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
6aaa4f154b652d3e4c0c5ef1a0399654d0785a0d
7,113
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use diem_api_types::{Error, LedgerInfo, MoveConverter, TransactionOnChainData}; use diem_config::config::{ApiConfig, JsonRpcConfig, RoleType}; use diem_crypto::HashValue; use diem_mempool::{MempoolClientRequest, MempoolClientSender, SubmissionStatus}; use diem_types::{ account_address::AccountAddress, account_state::AccountState, account_state_blob::AccountStateBlob, chain_id::ChainId, contract_event::ContractEvent, event::EventKey, ledger_info::LedgerInfoWithSignatures, transaction::SignedTransaction, }; use storage_interface::{MoveDbReader, Order}; use anyhow::{ensure, format_err, Result}; use futures::{channel::oneshot, SinkExt}; use std::{ borrow::Borrow, convert::{Infallible, TryFrom}, sync::Arc, }; use warp::{filters::BoxedFilter, Filter, Reply}; // Context holds application scope context #[derive(Clone)] pub struct Context { chain_id: ChainId, db: Arc<dyn MoveDbReader>, mp_sender: MempoolClientSender, role: RoleType, jsonrpc_config: JsonRpcConfig, api_config: ApiConfig, } impl Context { pub fn new( chain_id: ChainId, db: Arc<dyn MoveDbReader>, mp_sender: MempoolClientSender, role: RoleType, jsonrpc_config: JsonRpcConfig, api_config: ApiConfig, ) -> Self { Self { chain_id, db, mp_sender, role, jsonrpc_config, api_config, } } pub fn move_converter(&self) -> MoveConverter<dyn MoveDbReader + '_> { MoveConverter::new(self.db.borrow()) } pub fn chain_id(&self) -> ChainId { self.chain_id } pub fn content_length_limit(&self) -> u64 { self.api_config.content_length_limit() } pub fn filter(self) -> impl Filter<Extract = (Context,), Error = Infallible> + Clone { warp::any().map(move || self.clone()) } pub async fn submit_transaction(&self, txn: SignedTransaction) -> Result<SubmissionStatus> { let (req_sender, callback) = oneshot::channel(); self.mp_sender .clone() .send(MempoolClientRequest::SubmitTransaction(txn, req_sender)) .await?; callback.await? } pub fn get_latest_ledger_info(&self) -> Result<LedgerInfo, Error> { Ok(LedgerInfo::new( &self.chain_id(), &self.get_latest_ledger_info_with_signatures()?, )) } pub fn get_latest_ledger_info_with_signatures(&self) -> Result<LedgerInfoWithSignatures> { self.db.get_latest_ledger_info() } pub fn get_account_state( &self, address: AccountAddress, version: u64, ) -> Result<Option<AccountState>> { let state = self.get_account_state_blob(address, version)?; Ok(match state { Some(blob) => Some(AccountState::try_from(&blob)?), None => None, }) } pub fn get_account_state_blob( &self, account: AccountAddress, version: u64, ) -> Result<Option<AccountStateBlob>> { let (account_state_blob, _) = self .db .get_account_state_with_proof_by_version(account, version)?; Ok(account_state_blob) } pub fn get_block_timestamp(&self, version: u64) -> Result<u64> { self.db.get_block_timestamp(version) } pub fn get_transactions( &self, start_version: u64, limit: u16, ledger_version: u64, ) -> Result<Vec<TransactionOnChainData>> { let data = self .db .get_transactions(start_version, limit as u64, ledger_version, true)?; let txn_start_version = data .first_transaction_version .ok_or_else(|| format_err!("no start version from database"))?; ensure!( txn_start_version == start_version, "invalid start version from database: {} != {}", txn_start_version, start_version ); let txns = data.transactions; let infos = data.proof.transaction_infos; let events = data.events.unwrap_or_default(); ensure!( txns.len() == infos.len() && txns.len() == events.len(), "invalid data size from database: {}, {}, {}", txns.len(), infos.len(), events.len() ); Ok(txns .into_iter() .zip(infos.into_iter()) .zip(events.into_iter()) .enumerate() .map(|(i, ((txn, info), events))| (start_version + i as u64, txn, info, events).into()) .collect()) } pub fn get_account_transactions( &self, address: AccountAddress, start_seq_number: u64, limit: u16, ledger_version: u64, ) -> Result<Vec<TransactionOnChainData>> { let txns = self.db.get_account_transactions( address, start_seq_number, limit as u64, true, ledger_version, )?; Ok(txns.into_inner().into_iter().map(|t| t.into()).collect()) } pub fn get_transaction_by_hash( &self, hash: HashValue, ledger_version: u64, ) -> Result<Option<TransactionOnChainData>> { Ok(self .db .get_transaction_by_hash(hash, ledger_version, true)? .map(|t| t.into())) } pub async fn get_pending_transaction_by_hash( &self, hash: HashValue, ) -> Result<Option<SignedTransaction>> { let (req_sender, callback) = oneshot::channel(); self.mp_sender .clone() .send(MempoolClientRequest::GetTransactionByHash(hash, req_sender)) .await .map_err(anyhow::Error::from)?; callback.await.map_err(anyhow::Error::from) } pub fn get_transaction_by_version( &self, version: u64, ledger_version: u64, ) -> Result<TransactionOnChainData> { Ok(self .db .get_transaction_by_version(version, ledger_version, true)? .into()) } pub fn get_events( &self, event_key: &EventKey, start: u64, limit: u16, ledger_version: u64, ) -> Result<Vec<ContractEvent>> { let events = self .db .get_events(event_key, start, Order::Ascending, limit as u64)?; Ok(events .into_iter() .filter(|(version, _event)| version <= &ledger_version) .map(|(_, event)| event) .collect::<Vec<_>>()) } pub fn health_check_route(&self) -> BoxedFilter<(impl Reply,)> { diem_json_rpc::runtime::health_check_route(self.db.clone()) } pub fn jsonrpc_routes(&self) -> BoxedFilter<(impl Reply,)> { diem_json_rpc::runtime::jsonrpc_routes( self.db.clone(), self.mp_sender.clone(), self.role, self.chain_id, &self.jsonrpc_config, ) } }
29.271605
99
0.584985
bf1ab72c0c0329b5453819d5c243e09fe4b4735d
1,644
pub use either::Either; pub use swc_visit_macros::define; pub mod util; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Optional<V> { pub enabled: bool, pub visitor: V, } impl<V> Optional<V> { pub fn new(visitor: V, enabled: bool) -> Self { Self { enabled, visitor } } } pub trait Repeated { /// Should run again? fn changed(&self) -> bool; /// Reset. fn reset(&mut self); } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct AndThen<A, B> { pub first: A, pub second: B, } #[macro_export] macro_rules! chain { ($a:expr, $b:expr) => {{ use $crate::AndThen; AndThen { first: $a, second: $b, } }}; ($a:expr, $b:expr,) => { chain!($a, $b) }; ($a:expr, $b:expr, $($rest:tt)+) => {{ use $crate::AndThen; AndThen{ first: $a, second: chain!($b, $($rest)*), } }}; } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct Repeat<V> where V: Repeated, { pub pass: V, } impl<V> Repeat<V> where V: Repeated, { pub fn new(pass: V) -> Self { Self { pass } } } impl<V> Repeated for Repeat<V> where V: Repeated, { fn changed(&self) -> bool { self.pass.changed() } fn reset(&mut self) { self.pass.reset() } } impl<A, B> Repeated for AndThen<A, B> where A: Repeated, B: Repeated, { fn changed(&self) -> bool { self.first.changed() || self.second.changed() } fn reset(&mut self) { self.first.reset(); self.second.reset(); } }
16.277228
53
0.516423
b940df2ff4aa6c7dc32ce030c1cb33ad407c145c
17,735
use anyhow::Result; use crate::Client; pub struct Payroll { pub client: Client, } impl Payroll { #[doc(hidden)] pub fn new(client: Client) -> Self { Payroll { client } } /** * Get pay periods for a company. * * This function performs a `GET` to the `/v1/companies/{company_id_or_uuid}/pay_periods` endpoint. * * Pay periods are the foundation of payroll. Compensation, time & attendance, taxes, and expense reports all rely on when they happened. To begin submitting information for a given payroll, we need to agree on the time period. * * * By default, this endpoint returns every current and past pay period for a company. Since companies can process payroll as often as every week, there can be up to 53 pay periods a year. If a company has been running payroll with Gusto for five years, this endpoint could return up to 265 pay periods. Use the `start_date` and `end_date` parameters to reduce the scope of the response. * * **Parameters:** * * * `start_date: &str` * * `end_date: &str` */ pub async fn get_company_pay_periods( &self, company_id_or_uuid: &str, start_date: &str, end_date: &str, ) -> Result<Vec<crate::types::PayPeriod>> { let mut query_args: Vec<(String, String)> = Default::default(); if !end_date.is_empty() { query_args.push(("end_date".to_string(), end_date.to_string())); } if !start_date.is_empty() { query_args.push(("start_date".to_string(), start_date.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/v1/companies/{}/pay_periods?{}", crate::progenitor_support::encode_path(&company_id_or_uuid.to_string()), query_ ); self.client.get(&url, None).await } /** * Get pay periods for a company. * * This function performs a `GET` to the `/v1/companies/{company_id_or_uuid}/pay_periods` endpoint. * * As opposed to `get_company_pay_periods`, this function returns all the pages of the request at once. * * Pay periods are the foundation of payroll. Compensation, time & attendance, taxes, and expense reports all rely on when they happened. To begin submitting information for a given payroll, we need to agree on the time period. * * * By default, this endpoint returns every current and past pay period for a company. Since companies can process payroll as often as every week, there can be up to 53 pay periods a year. If a company has been running payroll with Gusto for five years, this endpoint could return up to 265 pay periods. Use the `start_date` and `end_date` parameters to reduce the scope of the response. */ pub async fn get_all_company_pay_periods( &self, company_id_or_uuid: &str, start_date: &str, end_date: &str, ) -> Result<Vec<crate::types::PayPeriod>> { let mut query_args: Vec<(String, String)> = Default::default(); if !end_date.is_empty() { query_args.push(("end_date".to_string(), end_date.to_string())); } if !start_date.is_empty() { query_args.push(("start_date".to_string(), start_date.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/v1/companies/{}/pay_periods?{}", crate::progenitor_support::encode_path(&company_id_or_uuid.to_string()), query_ ); self.client.get_all_pages(&url, None).await } /** * Get all payrolls for a company. * * This function performs a `GET` to the `/v1/companies/{company_id_or_uuid}/payrolls` endpoint. * * Returns all payrolls, current and past for a company. * * Notes: * * Hour and dollar amounts are returned as string representations of numeric decimals. * * Hours are represented to the thousands place; dollar amounts are represented to the cent. * * Every eligible compensation is returned for each employee. If no data has yet be inserted for a given field, it defaults to “0.00” (for fixed amounts) or “0.000” (for hours ). * * **Parameters:** * * * `processed: bool` -- Whether to return processed or unprocessed payrolls. * * `include_off_cycle: bool` -- Whether to include off cycle payrolls in the response. * * `include: &[String]` -- Include the requested attribute in the employee_compensations attribute in the response. * * `start_date: &str` -- Return payrolls whose pay period is after the start date. * * `end_date: &str` -- Return payrolls whose pay period is before the end date. */ pub async fn get_company( &self, company_id_or_uuid: &str, processed: bool, include_off_cycle: bool, include: &[String], start_date: &str, end_date: &str, ) -> Result<Vec<crate::types::PayrollData>> { let mut query_args: Vec<(String, String)> = Default::default(); if !end_date.is_empty() { query_args.push(("end_date".to_string(), end_date.to_string())); } if !include.is_empty() { query_args.push(("include".to_string(), include.join(" "))); } if include_off_cycle { query_args.push(( "include_off_cycle".to_string(), include_off_cycle.to_string(), )); } if processed { query_args.push(("processed".to_string(), processed.to_string())); } if !start_date.is_empty() { query_args.push(("start_date".to_string(), start_date.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/v1/companies/{}/payrolls?{}", crate::progenitor_support::encode_path(&company_id_or_uuid.to_string()), query_ ); self.client.get(&url, None).await } /** * Get all payrolls for a company. * * This function performs a `GET` to the `/v1/companies/{company_id_or_uuid}/payrolls` endpoint. * * As opposed to `get_company`, this function returns all the pages of the request at once. * * Returns all payrolls, current and past for a company. * * Notes: * * Hour and dollar amounts are returned as string representations of numeric decimals. * * Hours are represented to the thousands place; dollar amounts are represented to the cent. * * Every eligible compensation is returned for each employee. If no data has yet be inserted for a given field, it defaults to “0.00” (for fixed amounts) or “0.000” (for hours ). */ pub async fn get_all_company( &self, company_id_or_uuid: &str, processed: bool, include_off_cycle: bool, include: &[String], start_date: &str, end_date: &str, ) -> Result<Vec<crate::types::PayrollData>> { let mut query_args: Vec<(String, String)> = Default::default(); if !end_date.is_empty() { query_args.push(("end_date".to_string(), end_date.to_string())); } if !include.is_empty() { query_args.push(("include".to_string(), include.join(" "))); } if include_off_cycle { query_args.push(( "include_off_cycle".to_string(), include_off_cycle.to_string(), )); } if processed { query_args.push(("processed".to_string(), processed.to_string())); } if !start_date.is_empty() { query_args.push(("start_date".to_string(), start_date.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/v1/companies/{}/payrolls?{}", crate::progenitor_support::encode_path(&company_id_or_uuid.to_string()), query_ ); self.client.get_all_pages(&url, None).await } /** * Create an Off-Cycle Payroll (Beta). * * This function performs a `POST` to the `/v1/companies/{company_id_or_uuid}/payrolls` endpoint. * * This endpoint is in beta and intended for **[Gusto Embedded Payroll](https://gusto.com/embedded-payroll)** customers. Please [apply for early access](https://gusto-embedded-payroll.typeform.com/to/iomAQIj3?utm_source=docs) if you’d like to learn more and use it for production. Note, this endpoint will require you to enter a different agreement with Gusto. * * Creates a new, unprocessed, off-cycle payroll. */ pub async fn post_company( &self, company_id_or_uuid: &str, body: &crate::types::PostCompanyPayrollsRequest, ) -> Result<crate::types::PayrollData> { let url = format!( "/v1/companies/{}/payrolls", crate::progenitor_support::encode_path(&company_id_or_uuid.to_string()), ); self.client .post(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Get a single payroll. * * This function performs a `GET` to the `/v1/companies/{company_id_or_uuid}/payrolls/{payroll_id_or_uuid}` endpoint. * * Returns a payroll. * * Notes: * * Hour and dollar amounts are returned as string representations of numeric decimals. * * Hours are represented to the thousands place; dollar amounts are represented to the cent. * * Every eligible compensation is returned for each employee. If no data has yet be inserted for a given field, it defaults to “0.00” (for fixed amounts) or “0.000” (for hours ). * * **Parameters:** * * * `include: crate::types::GetCompanyPayrollsInclude` -- Include the requested attribute in the employee_compensations attribute in the response. * * `show_calculation: &str` -- with `include`, shows the tax, and/or benefit, and/or deduction details for a calculated, unprocessed payroll. . */ pub async fn get_company_payroll( &self, company_id_or_uuid: &str, payroll_id_or_uuid: &str, include: crate::types::GetCompanyPayrollsInclude, show_calculation: &str, ) -> Result<crate::types::PayrollData> { let mut query_args: Vec<(String, String)> = Default::default(); if !include.to_string().is_empty() { query_args.push(("include".to_string(), include.to_string())); } if !show_calculation.is_empty() { query_args.push(("show_calculation".to_string(), show_calculation.to_string())); } let query_ = serde_urlencoded::to_string(&query_args).unwrap(); let url = format!( "/v1/companies/{}/payrolls/{}?{}", crate::progenitor_support::encode_path(&company_id_or_uuid.to_string()), crate::progenitor_support::encode_path(&payroll_id_or_uuid.to_string()), query_ ); self.client.get(&url, None).await } /** * Update a payroll by ID. * * This function performs a `PUT` to the `/v1/companies/{company_id_or_uuid}/payrolls/{payroll_id_or_uuid}` endpoint. * * This endpoint allows you to update information for one or more employees for a specific **unprocessed** payroll. */ pub async fn put_company( &self, company_id_or_uuid: &str, payroll_id_or_uuid: &str, body: &crate::types::PutCompanyPayrollsRequest, ) -> Result<crate::types::PayrollData> { let url = format!( "/v1/companies/{}/payrolls/{}", crate::progenitor_support::encode_path(&company_id_or_uuid.to_string()), crate::progenitor_support::encode_path(&payroll_id_or_uuid.to_string()), ); self.client .put(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Update a payroll. * * This function performs a `PUT` to the `/v1/companies/{company_id_or_uuid}/payrolls/{pay_period_start_date}/{pay_period_end_date}` endpoint. * * This endpoint allows you to update information for one or more employees for a specific **unprocessed** payroll. * * The payrolls are identified by their pay periods’ start_date and end_date. Both are required and must correspond with an existing, unprocessed payroll. *If the dates do not match, the entire request will be rejected.* This was an explicit design decision to remove any assumptions around the timespan for data sent. */ pub async fn put_company_pay_period_start_date_end( &self, company_id_or_uuid: &str, pay_period_start_date: &str, pay_period_end_date: &str, body: &crate::types::PutCompanyPayrollsRequest, ) -> Result<crate::types::PayrollData> { let url = format!( "/v1/companies/{}/payrolls/{}/{}", crate::progenitor_support::encode_path(&company_id_or_uuid.to_string()), crate::progenitor_support::encode_path(&pay_period_start_date.to_string()), crate::progenitor_support::encode_path(&pay_period_end_date.to_string()), ); self.client .put(&url, Some(reqwest::Body::from(serde_json::to_vec(body)?))) .await } /** * Calculate a Payroll (Beta). * * This function performs a `PUT` to the `/v1/companies/{company_id}/payrolls/{payroll_id}/calculate` endpoint. * * This endpoint is in beta and intended for **[Gusto Embedded Payroll](https://gusto.com/embedded-payroll)** customers. Please [apply for early access](https://gusto-embedded-payroll.typeform.com/to/iomAQIj3?utm_source=docs) if you’d like to learn more and use it for production. Note, this endpoint will require you to enter a different agreement with Gusto. * * Performs calculations for taxes, benefits, and deductions for an unprocessed payroll. The calculated payroll details provide a preview of the actual values that will be used when the payroll is run. * * This endpoint is asynchronous and responds with only a 202 HTTP status. To view the details of the calculated payroll, use the GET /v1/companies/{company_id}/payrolls/{payroll_id} endpoint with the *show_calculation=true* and *include=taxes,benefits,deductions* params */ pub async fn put_company_calculate(&self, company_id: &str, payroll_id: &str) -> Result<()> { let url = format!( "/v1/companies/{}/payrolls/{}/calculate", crate::progenitor_support::encode_path(&company_id.to_string()), crate::progenitor_support::encode_path(&payroll_id.to_string()), ); self.client.put(&url, None).await } /** * Submit Payroll (Beta). * * This function performs a `PUT` to the `/v1/companies/{company_id}/payrolls/{payroll_Id}/submit` endpoint. * * This endpoint is in beta and intended for **[Gusto Embedded Payroll](https://gusto.com/embedded-payroll)** customers. Please [apply for early access](https://gusto-embedded-payroll.typeform.com/to/iomAQIj3?utm_source=docs) if you’d like to learn more and use it for production. Note, this endpoint will require you to enter a different agreement with Gusto. * * Submits an unprocessed payroll to be calculated and run. Upon success, transitions the payroll to the `processed` state. */ pub async fn put_company_submit(&self, company_id: &str, payroll_id: &str) -> Result<()> { let url = format!( "/v1/companies/{}/payrolls/{}/submit", crate::progenitor_support::encode_path(&company_id.to_string()), crate::progenitor_support::encode_path(&payroll_id.to_string()), ); self.client.put(&url, None).await } /** * Cancel a Payroll (Beta). * * This function performs a `PUT` to the `/v1/companies/{company_id}/payrolls/{payroll_id}/cancel` endpoint. * * This endpoint is in beta and intended for **[Gusto Embedded Payroll](https://gusto.com/embedded-payroll)** customers. Please [apply for early access](https://gusto-embedded-payroll.typeform.com/to/iomAQIj3?utm_source=docs) if you’d like to learn more and use it for production. Note, this endpoint will require you to enter a different agreement with Gusto. * * Transitions a `processed` payroll back to the `unprocessed` state. A payroll cannot be canceled once it has entered the `funded` state. * */ pub async fn put_company_cancel( &self, company_id: &str, payroll_id: &str, ) -> Result<crate::types::PayrollData> { let url = format!( "/v1/companies/{}/payrolls/{}/cancel", crate::progenitor_support::encode_path(&company_id.to_string()), crate::progenitor_support::encode_path(&payroll_id.to_string()), ); self.client.put(&url, None).await } /** * Get approved Payroll Reversals. * * This function performs a `GET` to the `/v1/companies/{company_id_or_uuid}/payroll_reversals` endpoint. * * Returns all approved Payroll Reversals for a Company. */ pub async fn get_company_or_reversals( &self, company_id_or_uuid: &str, ) -> Result<crate::types::GetCompanyPayrollReversalsResponse> { let url = format!( "/v1/companies/{}/payroll_reversals", crate::progenitor_support::encode_path(&company_id_or_uuid.to_string()), ); self.client.get(&url, None).await } }
44.448622
390
0.638173
298b7a20dca887342d90c2e75c468ba0e448b95e
2,476
// Copyright 2018-2019 Sebastian Wiesner <[email protected]> // 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. //! Access to resources referenced from markdown documents. #[cfg(feature = "resources")] use url::Url; /// What kind of resources mdcat may access when rendering. /// /// This struct denotes whether mdcat shows inline images from remote URLs or /// just from local files. #[derive(Debug, Copy, Clone)] pub enum ResourceAccess { /// Use only local files and prohibit remote resources. LocalOnly, /// Use local and remote resources alike. RemoteAllowed, } #[cfg(feature = "resources")] impl ResourceAccess { /// Whether the resource access permits access to the given `url`. pub fn permits(self, url: &Url) -> bool { match self { ResourceAccess::LocalOnly if is_local(url) => true, ResourceAccess::RemoteAllowed => true, _ => false, } } } /// Whether `url` is readable as local file:. #[cfg(feature = "resources")] fn is_local(url: &Url) -> bool { url.scheme() == "file" && url.to_file_path().is_ok() } #[cfg(all(test, feature = "resources"))] mod tests { pub use super::*; #[test] fn resource_access_permits_local_resource() { let resource = Url::parse("file:///foo/bar").unwrap(); assert!(ResourceAccess::LocalOnly.permits(&resource)); assert!(ResourceAccess::RemoteAllowed.permits(&resource)); } #[test] fn resource_access_permits_remote_file_url() { let resource = Url::parse("file://example.com/foo/bar").unwrap(); assert!(!ResourceAccess::LocalOnly.permits(&resource)); assert!(ResourceAccess::RemoteAllowed.permits(&resource)); } #[test] fn resource_access_permits_https_url() { let resource = Url::parse("https:///foo/bar").unwrap(); assert!(!ResourceAccess::LocalOnly.permits(&resource)); assert!(ResourceAccess::RemoteAllowed.permits(&resource)); } }
33.013333
77
0.674879
f86857f97f6546db85cadd6156d8e9d3e930638a
36,585
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /*! See doc.rs for documentation */ #![allow(non_camel_case_types)] pub use middle::ty::IntVarValue; pub use middle::typeck::infer::resolve::resolve_and_force_all_but_regions; pub use middle::typeck::infer::resolve::{force_all, not_regions}; pub use middle::typeck::infer::resolve::{force_ivar}; pub use middle::typeck::infer::resolve::{force_tvar, force_rvar}; pub use middle::typeck::infer::resolve::{resolve_ivar, resolve_all}; pub use middle::typeck::infer::resolve::{resolve_nested_tvar}; pub use middle::typeck::infer::resolve::{resolve_rvar}; use middle::subst; use middle::subst::Substs; use middle::ty::{TyVid, IntVid, FloatVid, RegionVid}; use middle::ty; use middle::ty_fold; use middle::ty_fold::TypeFolder; use middle::typeck::check::regionmanip::replace_late_bound_regions_in_fn_sig; use middle::typeck::infer::coercion::Coerce; use middle::typeck::infer::combine::{Combine, CombineFields}; use middle::typeck::infer::region_inference::{RegionVarBindings, RegionSnapshot}; use middle::typeck::infer::resolve::{resolver}; use middle::typeck::infer::equate::Equate; use middle::typeck::infer::sub::Sub; use middle::typeck::infer::lub::Lub; use middle::typeck::infer::unify::{UnificationTable}; use middle::typeck::infer::error_reporting::ErrorReporting; use std::cell::{RefCell}; use std::collections::HashMap; use std::rc::Rc; use syntax::ast; use syntax::codemap; use syntax::codemap::Span; use util::common::indent; use util::ppaux::{bound_region_to_string, ty_to_string, trait_ref_to_string, Repr}; pub mod coercion; pub mod combine; pub mod doc; pub mod equate; pub mod error_reporting; pub mod glb; pub mod lattice; pub mod lub; pub mod region_inference; pub mod resolve; pub mod sub; pub mod test; pub mod type_variable; pub mod unify; pub type Bound<T> = Option<T>; #[deriving(PartialEq,Clone)] pub struct Bounds<T> { pub lb: Bound<T>, pub ub: Bound<T> } pub type cres<T> = Result<T,ty::type_err>; // "combine result" pub type ures = cres<()>; // "unify result" pub type fres<T> = Result<T, fixup_err>; // "fixup result" pub type CoerceResult = cres<Option<ty::AutoAdjustment>>; pub struct InferCtxt<'a> { pub tcx: &'a ty::ctxt, // We instantiate UnificationTable with bounds<ty::t> because the // types that might instantiate a general type variable have an // order, represented by its upper and lower bounds. type_variables: RefCell<type_variable::TypeVariableTable>, // Map from integral variable to the kind of integer it represents int_unification_table: RefCell<UnificationTable<ty::IntVid, Option<IntVarValue>>>, // Map from floating variable to the kind of float it represents float_unification_table: RefCell<UnificationTable<ty::FloatVid, Option<ast::FloatTy>>>, // For region variables. region_vars: RegionVarBindings<'a>, } /// Why did we require that the two types be related? /// /// See `error_reporting.rs` for more details #[deriving(Clone)] pub enum TypeOrigin { // Not yet categorized in a better way Misc(Span), // Checking that method of impl is compatible with trait MethodCompatCheck(Span), // Checking that this expression can be assigned where it needs to be // FIXME(eddyb) #11161 is the original Expr required? ExprAssignable(Span), // Relating trait refs when resolving vtables RelateTraitRefs(Span), // Relating trait refs when resolving vtables RelateSelfType(Span), // Computing common supertype in the arms of a match expression MatchExpressionArm(Span, Span), // Computing common supertype in an if expression IfExpression(Span), } /// See `error_reporting.rs` for more details #[deriving(Clone)] pub enum ValuePairs { Types(ty::expected_found<ty::t>), TraitRefs(ty::expected_found<Rc<ty::TraitRef>>), } /// The trace designates the path through inference that we took to /// encounter an error or subtyping constraint. /// /// See `error_reporting.rs` for more details. #[deriving(Clone)] pub struct TypeTrace { origin: TypeOrigin, values: ValuePairs, } /// The origin of a `r1 <= r2` constraint. /// /// See `error_reporting.rs` for more details #[deriving(Clone)] pub enum SubregionOrigin { // Arose from a subtyping relation Subtype(TypeTrace), // Stack-allocated closures cannot outlive innermost loop // or function so as to ensure we only require finite stack InfStackClosure(Span), // Invocation of closure must be within its lifetime InvokeClosure(Span), // Dereference of reference must be within its lifetime DerefPointer(Span), // Closure bound must not outlive captured free variables FreeVariable(Span, ast::NodeId), // Proc upvars must be 'static ProcCapture(Span, ast::NodeId), // Index into slice must be within its lifetime IndexSlice(Span), // When casting `&'a T` to an `&'b Trait` object, // relating `'a` to `'b` RelateObjectBound(Span), // When closing over a variable in a closure/proc, ensure that the // type of the variable outlives the lifetime bound. RelateProcBound(Span, ast::NodeId, ty::t), // The given type parameter was instantiated with the given type, // and that type must outlive some region. RelateParamBound(Span, ty::ParamTy, ty::t), // The given region parameter was instantiated with a region // that must outlive some other region. RelateRegionParamBound(Span), // A bound placed on type parameters that states that must outlive // the moment of their instantiation. RelateDefaultParamBound(Span, ty::t), // Creating a pointer `b` to contents of another reference Reborrow(Span), // Creating a pointer `b` to contents of an upvar ReborrowUpvar(Span, ty::UpvarId), // (&'a &'b T) where a >= b ReferenceOutlivesReferent(ty::t, Span), // The type T of an expression E must outlive the lifetime for E. ExprTypeIsNotInScope(ty::t, Span), // A `ref b` whose region does not enclose the decl site BindingTypeIsNotValidAtDecl(Span), // Regions appearing in a method receiver must outlive method call CallRcvr(Span), // Regions appearing in a function argument must outlive func call CallArg(Span), // Region in return type of invoked fn must enclose call CallReturn(Span), // Region resulting from a `&` expr must enclose the `&` expr AddrOf(Span), // An auto-borrow that does not enclose the expr where it occurs AutoBorrow(Span), // Managed data cannot contain borrowed pointers. Managed(Span), } /// Reasons to create a region inference variable /// /// See `error_reporting.rs` for more details #[deriving(Clone)] pub enum RegionVariableOrigin { // Region variables created for ill-categorized reasons, // mostly indicates places in need of refactoring MiscVariable(Span), // Regions created by a `&P` or `[...]` pattern PatternRegion(Span), // Regions created by `&` operator AddrOfRegion(Span), // Regions created by `&[...]` literal AddrOfSlice(Span), // Regions created as part of an autoref of a method receiver Autoref(Span), // Regions created as part of an automatic coercion Coercion(TypeTrace), // Region variables created as the values for early-bound regions EarlyBoundRegion(Span, ast::Name), // Region variables created for bound regions // in a function or method that is called LateBoundRegion(Span, ty::BoundRegion), // Region variables created for bound regions // when doing subtyping/lub/glb computations BoundRegionInFnType(Span, ty::BoundRegion), UpvarRegion(ty::UpvarId, Span), BoundRegionInCoherence(ast::Name), } pub enum fixup_err { unresolved_int_ty(IntVid), unresolved_float_ty(FloatVid), unresolved_ty(TyVid), cyclic_ty(TyVid), unresolved_region(RegionVid), region_var_bound_by_region_var(RegionVid, RegionVid) } pub fn fixup_err_to_string(f: fixup_err) -> String { match f { unresolved_int_ty(_) => { "cannot determine the type of this integer; add a suffix to \ specify the type explicitly".to_string() } unresolved_float_ty(_) => { "cannot determine the type of this number; add a suffix to specify \ the type explicitly".to_string() } unresolved_ty(_) => "unconstrained type".to_string(), cyclic_ty(_) => "cyclic type of infinite size".to_string(), unresolved_region(_) => "unconstrained region".to_string(), region_var_bound_by_region_var(r1, r2) => { format!("region var {:?} bound by another region var {:?}; \ this is a bug in rustc", r1, r2) } } } pub fn new_infer_ctxt<'a>(tcx: &'a ty::ctxt) -> InferCtxt<'a> { InferCtxt { tcx: tcx, type_variables: RefCell::new(type_variable::TypeVariableTable::new()), int_unification_table: RefCell::new(UnificationTable::new()), float_unification_table: RefCell::new(UnificationTable::new()), region_vars: RegionVarBindings::new(tcx), } } pub fn common_supertype(cx: &InferCtxt, origin: TypeOrigin, a_is_expected: bool, a: ty::t, b: ty::t) -> ty::t { /*! * Computes the least upper-bound of `a` and `b`. If this is * not possible, reports an error and returns ty::err. */ debug!("common_supertype({}, {})", a.repr(cx.tcx), b.repr(cx.tcx)); let trace = TypeTrace { origin: origin, values: Types(expected_found(a_is_expected, a, b)) }; let result = cx.commit_if_ok(|| cx.lub(a_is_expected, trace.clone()).tys(a, b)); match result { Ok(t) => t, Err(ref err) => { cx.report_and_explain_type_error(trace, err); ty::mk_err() } } } pub fn mk_subty(cx: &InferCtxt, a_is_expected: bool, origin: TypeOrigin, a: ty::t, b: ty::t) -> ures { debug!("mk_subty({} <: {})", a.repr(cx.tcx), b.repr(cx.tcx)); indent(|| { cx.commit_if_ok(|| { let trace = TypeTrace { origin: origin, values: Types(expected_found(a_is_expected, a, b)) }; cx.sub(a_is_expected, trace).tys(a, b) }) }).to_ures() } pub fn can_mk_subty(cx: &InferCtxt, a: ty::t, b: ty::t) -> ures { debug!("can_mk_subty({} <: {})", a.repr(cx.tcx), b.repr(cx.tcx)); cx.probe(|| { let trace = TypeTrace { origin: Misc(codemap::DUMMY_SP), values: Types(expected_found(true, a, b)) }; cx.sub(true, trace).tys(a, b) }).to_ures() } pub fn mk_subr(cx: &InferCtxt, origin: SubregionOrigin, a: ty::Region, b: ty::Region) { debug!("mk_subr({} <: {})", a.repr(cx.tcx), b.repr(cx.tcx)); let snapshot = cx.region_vars.start_snapshot(); cx.region_vars.make_subregion(origin, a, b); cx.region_vars.commit(snapshot); } pub fn verify_param_bound(cx: &InferCtxt, origin: SubregionOrigin, param_ty: ty::ParamTy, a: ty::Region, bs: Vec<ty::Region>) { debug!("verify_param_bound({}, {} <: {})", param_ty.repr(cx.tcx), a.repr(cx.tcx), bs.repr(cx.tcx)); cx.region_vars.verify_param_bound(origin, param_ty, a, bs); } pub fn mk_eqty(cx: &InferCtxt, a_is_expected: bool, origin: TypeOrigin, a: ty::t, b: ty::t) -> ures { debug!("mk_eqty({} <: {})", a.repr(cx.tcx), b.repr(cx.tcx)); cx.commit_if_ok(|| { let trace = TypeTrace { origin: origin, values: Types(expected_found(a_is_expected, a, b)) }; try!(cx.equate(a_is_expected, trace).tys(a, b)); Ok(()) }) } pub fn mk_sub_trait_refs(cx: &InferCtxt, a_is_expected: bool, origin: TypeOrigin, a: Rc<ty::TraitRef>, b: Rc<ty::TraitRef>) -> ures { debug!("mk_sub_trait_refs({} <: {})", a.repr(cx.tcx), b.repr(cx.tcx)); indent(|| { cx.commit_if_ok(|| { let trace = TypeTrace { origin: origin, values: TraitRefs(expected_found(a_is_expected, a.clone(), b.clone())) }; let suber = cx.sub(a_is_expected, trace); suber.trait_refs(&*a, &*b) }) }).to_ures() } fn expected_found<T>(a_is_expected: bool, a: T, b: T) -> ty::expected_found<T> { if a_is_expected { ty::expected_found {expected: a, found: b} } else { ty::expected_found {expected: b, found: a} } } pub fn mk_coercety(cx: &InferCtxt, a_is_expected: bool, origin: TypeOrigin, a: ty::t, b: ty::t) -> CoerceResult { debug!("mk_coercety({} -> {})", a.repr(cx.tcx), b.repr(cx.tcx)); indent(|| { cx.commit_if_ok(|| { let trace = TypeTrace { origin: origin, values: Types(expected_found(a_is_expected, a, b)) }; Coerce(cx.combine_fields(a_is_expected, trace)).tys(a, b) }) }) } // See comment on the type `resolve_state` below pub fn resolve_type(cx: &InferCtxt, span: Option<Span>, a: ty::t, modes: uint) -> fres<ty::t> { let mut resolver = resolver(cx, modes, span); cx.commit_unconditionally(|| resolver.resolve_type_chk(a)) } pub fn resolve_region(cx: &InferCtxt, r: ty::Region, modes: uint) -> fres<ty::Region> { let mut resolver = resolver(cx, modes, None); resolver.resolve_region_chk(r) } trait then { fn then<T:Clone>(&self, f: || -> Result<T,ty::type_err>) -> Result<T,ty::type_err>; } impl then for ures { fn then<T:Clone>(&self, f: || -> Result<T,ty::type_err>) -> Result<T,ty::type_err> { self.and_then(|_i| f()) } } trait ToUres { fn to_ures(&self) -> ures; } impl<T> ToUres for cres<T> { fn to_ures(&self) -> ures { match *self { Ok(ref _v) => Ok(()), Err(ref e) => Err((*e)) } } } trait CresCompare<T> { fn compare(&self, t: T, f: || -> ty::type_err) -> cres<T>; } impl<T:Clone + PartialEq> CresCompare<T> for cres<T> { fn compare(&self, t: T, f: || -> ty::type_err) -> cres<T> { (*self).clone().and_then(|s| { if s == t { (*self).clone() } else { Err(f()) } }) } } pub fn uok() -> ures { Ok(()) } pub struct CombinedSnapshot { type_snapshot: type_variable::Snapshot, int_snapshot: unify::Snapshot<ty::IntVid>, float_snapshot: unify::Snapshot<ty::FloatVid>, region_vars_snapshot: RegionSnapshot, } impl<'a> InferCtxt<'a> { pub fn combine_fields<'a>(&'a self, a_is_expected: bool, trace: TypeTrace) -> CombineFields<'a> { CombineFields {infcx: self, a_is_expected: a_is_expected, trace: trace} } pub fn equate<'a>(&'a self, a_is_expected: bool, trace: TypeTrace) -> Equate<'a> { Equate(self.combine_fields(a_is_expected, trace)) } pub fn sub<'a>(&'a self, a_is_expected: bool, trace: TypeTrace) -> Sub<'a> { Sub(self.combine_fields(a_is_expected, trace)) } pub fn lub<'a>(&'a self, a_is_expected: bool, trace: TypeTrace) -> Lub<'a> { Lub(self.combine_fields(a_is_expected, trace)) } fn start_snapshot(&self) -> CombinedSnapshot { CombinedSnapshot { type_snapshot: self.type_variables.borrow_mut().snapshot(), int_snapshot: self.int_unification_table.borrow_mut().snapshot(), float_snapshot: self.float_unification_table.borrow_mut().snapshot(), region_vars_snapshot: self.region_vars.start_snapshot(), } } fn rollback_to(&self, snapshot: CombinedSnapshot) { debug!("rollback!"); let CombinedSnapshot { type_snapshot, int_snapshot, float_snapshot, region_vars_snapshot } = snapshot; self.type_variables .borrow_mut() .rollback_to(type_snapshot); self.int_unification_table .borrow_mut() .rollback_to(int_snapshot); self.float_unification_table .borrow_mut() .rollback_to(float_snapshot); self.region_vars .rollback_to(region_vars_snapshot); } fn commit_from(&self, snapshot: CombinedSnapshot) { debug!("commit_from!"); let CombinedSnapshot { type_snapshot, int_snapshot, float_snapshot, region_vars_snapshot } = snapshot; self.type_variables .borrow_mut() .commit(type_snapshot); self.int_unification_table .borrow_mut() .commit(int_snapshot); self.float_unification_table .borrow_mut() .commit(float_snapshot); self.region_vars .commit(region_vars_snapshot); } /// Execute `f` and commit the bindings pub fn commit_unconditionally<R>(&self, f: || -> R) -> R { debug!("commit()"); let snapshot = self.start_snapshot(); let r = f(); self.commit_from(snapshot); r } /// Execute `f` and commit the bindings if successful pub fn commit_if_ok<T,E>(&self, f: || -> Result<T,E>) -> Result<T,E> { self.commit_unconditionally(|| self.try(|| f())) } /// Execute `f`, unroll bindings on failure pub fn try<T,E>(&self, f: || -> Result<T,E>) -> Result<T,E> { debug!("try()"); let snapshot = self.start_snapshot(); let r = f(); debug!("try() -- r.is_ok() = {}", r.is_ok()); match r { Ok(_) => { self.commit_from(snapshot); } Err(_) => { self.rollback_to(snapshot); } } r } /// Execute `f` then unroll any bindings it creates pub fn probe<T,E>(&self, f: || -> Result<T,E>) -> Result<T,E> { debug!("probe()"); let snapshot = self.start_snapshot(); let r = f(); self.rollback_to(snapshot); r } pub fn add_given(&self, sub: ty::FreeRegion, sup: ty::RegionVid) { self.region_vars.add_given(sub, sup); } } impl<'a> InferCtxt<'a> { pub fn next_ty_var_id(&self) -> TyVid { self.type_variables .borrow_mut() .new_var() } pub fn next_ty_var(&self) -> ty::t { ty::mk_var(self.tcx, self.next_ty_var_id()) } pub fn next_ty_vars(&self, n: uint) -> Vec<ty::t> { Vec::from_fn(n, |_i| self.next_ty_var()) } pub fn next_int_var_id(&self) -> IntVid { self.int_unification_table .borrow_mut() .new_key(None) } pub fn next_float_var_id(&self) -> FloatVid { self.float_unification_table .borrow_mut() .new_key(None) } pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region { ty::ReInfer(ty::ReVar(self.region_vars.new_region_var(origin))) } pub fn region_vars_for_defs(&self, span: Span, defs: &[ty::RegionParameterDef]) -> Vec<ty::Region> { defs.iter() .map(|d| self.next_region_var(EarlyBoundRegion(span, d.name))) .collect() } pub fn fresh_substs_for_type(&self, span: Span, generics: &ty::Generics) -> subst::Substs { /*! * Given a set of generics defined on a type or impl, returns * a substitution mapping each type/region parameter to a * fresh inference variable. */ assert!(generics.types.len(subst::SelfSpace) == 0); assert!(generics.types.len(subst::FnSpace) == 0); assert!(generics.regions.len(subst::SelfSpace) == 0); assert!(generics.regions.len(subst::FnSpace) == 0); let type_parameter_count = generics.types.len(subst::TypeSpace); let region_param_defs = generics.regions.get_slice(subst::TypeSpace); let regions = self.region_vars_for_defs(span, region_param_defs); let type_parameters = self.next_ty_vars(type_parameter_count); subst::Substs::new_type(type_parameters, regions) } pub fn fresh_bound_region(&self, binder_id: ast::NodeId) -> ty::Region { self.region_vars.new_bound(binder_id) } pub fn resolve_regions_and_report_errors(&self) { let errors = self.region_vars.resolve_regions(); self.report_region_errors(&errors); // see error_reporting.rs } pub fn ty_to_string(&self, t: ty::t) -> String { ty_to_string(self.tcx, self.resolve_type_vars_if_possible(t)) } pub fn tys_to_string(&self, ts: &[ty::t]) -> String { let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect(); format!("({})", tstrs.connect(", ")) } pub fn trait_ref_to_string(&self, t: &ty::TraitRef) -> String { let t = self.resolve_type_vars_in_trait_ref_if_possible(t); trait_ref_to_string(self.tcx, &t) } pub fn resolve_type_vars_if_possible(&self, typ: ty::t) -> ty::t { match resolve_type(self, None, typ, resolve_nested_tvar | resolve_ivar) { Ok(new_type) => new_type, Err(_) => typ } } pub fn resolve_type_vars_in_trait_ref_if_possible(&self, trait_ref: &ty::TraitRef) -> ty::TraitRef { // make up a dummy type just to reuse/abuse the resolve machinery let dummy0 = ty::mk_trait(self.tcx, trait_ref.def_id, trait_ref.substs.clone(), ty::region_existential_bound(ty::ReStatic)); let dummy1 = self.resolve_type_vars_if_possible(dummy0); match ty::get(dummy1).sty { ty::ty_trait(box ty::TyTrait { ref def_id, ref substs, .. }) => { ty::TraitRef { def_id: *def_id, substs: (*substs).clone(), } } _ => { self.tcx.sess.bug( format!("resolve_type_vars_if_possible() yielded {} \ when supplied with {}", self.ty_to_string(dummy0), self.ty_to_string(dummy1)).as_slice()); } } } // [Note-Type-error-reporting] // An invariant is that anytime the expected or actual type is ty_err (the special // error type, meaning that an error occurred when typechecking this expression), // this is a derived error. The error cascaded from another error (that was already // reported), so it's not useful to display it to the user. // The following four methods -- type_error_message_str, type_error_message_str_with_expected, // type_error_message, and report_mismatched_types -- implement this logic. // They check if either the actual or expected type is ty_err, and don't print the error // in this case. The typechecker should only ever report type errors involving mismatched // types using one of these four methods, and should not call span_err directly for such // errors. pub fn type_error_message_str(&self, sp: Span, mk_msg: |Option<String>, String| -> String, actual_ty: String, err: Option<&ty::type_err>) { self.type_error_message_str_with_expected(sp, mk_msg, None, actual_ty, err) } pub fn type_error_message_str_with_expected(&self, sp: Span, mk_msg: |Option<String>, String| -> String, expected_ty: Option<ty::t>, actual_ty: String, err: Option<&ty::type_err>) { debug!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty, actual_ty); let error_str = err.map_or("".to_string(), |t_err| { format!(" ({})", ty::type_err_to_str(self.tcx, t_err)) }); let resolved_expected = expected_ty.map(|e_ty| { self.resolve_type_vars_if_possible(e_ty) }); if !resolved_expected.map_or(false, |e| { ty::type_is_error(e) }) { match resolved_expected { None => { self.tcx .sess .span_err(sp, format!("{}{}", mk_msg(None, actual_ty), error_str).as_slice()) } Some(e) => { self.tcx.sess.span_err(sp, format!("{}{}", mk_msg(Some(self.ty_to_string(e)), actual_ty), error_str).as_slice()); } } for err in err.iter() { ty::note_and_explain_type_err(self.tcx, *err) } } } pub fn type_error_message(&self, sp: Span, mk_msg: |String| -> String, actual_ty: ty::t, err: Option<&ty::type_err>) { let actual_ty = self.resolve_type_vars_if_possible(actual_ty); // Don't report an error if actual type is ty_err. if ty::type_is_error(actual_ty) { return; } self.type_error_message_str(sp, |_e, a| { mk_msg(a) }, self.ty_to_string(actual_ty), err); } pub fn report_mismatched_types(&self, sp: Span, e: ty::t, a: ty::t, err: &ty::type_err) { let resolved_expected = self.resolve_type_vars_if_possible(e); let mk_msg = match ty::get(resolved_expected).sty { // Don't report an error if expected is ty_err ty::ty_err => return, _ => { // if I leave out : String, it infers &str and complains |actual: String| { format!("mismatched types: expected `{}`, found `{}`", self.ty_to_string(resolved_expected), actual) } } }; self.type_error_message(sp, mk_msg, a, Some(err)); } pub fn replace_late_bound_regions_with_fresh_regions(&self, trace: TypeTrace, fsig: &ty::FnSig) -> (ty::FnSig, HashMap<ty::BoundRegion, ty::Region>) { let (map, fn_sig) = replace_late_bound_regions_in_fn_sig(self.tcx, fsig, |br| { let rvar = self.next_region_var( BoundRegionInFnType(trace.origin.span(), br)); debug!("Bound region {} maps to {:?}", bound_region_to_string(self.tcx, "", false, br), rvar); rvar }); (fn_sig, map) } } pub fn fold_regions_in_sig(tcx: &ty::ctxt, fn_sig: &ty::FnSig, fldr: |r: ty::Region| -> ty::Region) -> ty::FnSig { ty_fold::RegionFolder::regions(tcx, fldr).fold_sig(fn_sig) } impl TypeTrace { pub fn span(&self) -> Span { self.origin.span() } } impl Repr for TypeTrace { fn repr(&self, tcx: &ty::ctxt) -> String { format!("TypeTrace({})", self.origin.repr(tcx)) } } impl TypeOrigin { pub fn span(&self) -> Span { match *self { MethodCompatCheck(span) => span, ExprAssignable(span) => span, Misc(span) => span, RelateTraitRefs(span) => span, RelateSelfType(span) => span, MatchExpressionArm(match_span, _) => match_span, IfExpression(span) => span, } } } impl Repr for TypeOrigin { fn repr(&self, tcx: &ty::ctxt) -> String { match *self { MethodCompatCheck(a) => { format!("MethodCompatCheck({})", a.repr(tcx)) } ExprAssignable(a) => { format!("ExprAssignable({})", a.repr(tcx)) } Misc(a) => format!("Misc({})", a.repr(tcx)), RelateTraitRefs(a) => { format!("RelateTraitRefs({})", a.repr(tcx)) } RelateSelfType(a) => { format!("RelateSelfType({})", a.repr(tcx)) } MatchExpressionArm(a, b) => { format!("MatchExpressionArm({}, {})", a.repr(tcx), b.repr(tcx)) } IfExpression(a) => { format!("IfExpression({})", a.repr(tcx)) } } } } impl SubregionOrigin { pub fn span(&self) -> Span { match *self { Subtype(ref a) => a.span(), InfStackClosure(a) => a, InvokeClosure(a) => a, DerefPointer(a) => a, FreeVariable(a, _) => a, ProcCapture(a, _) => a, IndexSlice(a) => a, RelateObjectBound(a) => a, RelateProcBound(a, _, _) => a, RelateParamBound(a, _, _) => a, RelateRegionParamBound(a) => a, RelateDefaultParamBound(a, _) => a, Reborrow(a) => a, ReborrowUpvar(a, _) => a, ReferenceOutlivesReferent(_, a) => a, ExprTypeIsNotInScope(_, a) => a, BindingTypeIsNotValidAtDecl(a) => a, CallRcvr(a) => a, CallArg(a) => a, CallReturn(a) => a, AddrOf(a) => a, AutoBorrow(a) => a, Managed(a) => a, } } } impl Repr for SubregionOrigin { fn repr(&self, tcx: &ty::ctxt) -> String { match *self { Subtype(ref a) => { format!("Subtype({})", a.repr(tcx)) } InfStackClosure(a) => { format!("InfStackClosure({})", a.repr(tcx)) } InvokeClosure(a) => { format!("InvokeClosure({})", a.repr(tcx)) } DerefPointer(a) => { format!("DerefPointer({})", a.repr(tcx)) } FreeVariable(a, b) => { format!("FreeVariable({}, {})", a.repr(tcx), b) } ProcCapture(a, b) => { format!("ProcCapture({}, {})", a.repr(tcx), b) } IndexSlice(a) => { format!("IndexSlice({})", a.repr(tcx)) } RelateObjectBound(a) => { format!("RelateObjectBound({})", a.repr(tcx)) } RelateProcBound(a, b, c) => { format!("RelateProcBound({},{},{})", a.repr(tcx), b, c.repr(tcx)) } RelateParamBound(a, b, c) => { format!("RelateParamBound({},{},{})", a.repr(tcx), b.repr(tcx), c.repr(tcx)) } RelateRegionParamBound(a) => { format!("RelateRegionParamBound({})", a.repr(tcx)) } RelateDefaultParamBound(a, b) => { format!("RelateDefaultParamBound({},{})", a.repr(tcx), b.repr(tcx)) } Reborrow(a) => format!("Reborrow({})", a.repr(tcx)), ReborrowUpvar(a, b) => { format!("ReborrowUpvar({},{:?})", a.repr(tcx), b) } ReferenceOutlivesReferent(_, a) => { format!("ReferenceOutlivesReferent({})", a.repr(tcx)) } ExprTypeIsNotInScope(a, b) => { format!("ExprTypeIsNotInScope({}, {})", a.repr(tcx), b.repr(tcx)) } BindingTypeIsNotValidAtDecl(a) => { format!("BindingTypeIsNotValidAtDecl({})", a.repr(tcx)) } CallRcvr(a) => format!("CallRcvr({})", a.repr(tcx)), CallArg(a) => format!("CallArg({})", a.repr(tcx)), CallReturn(a) => format!("CallReturn({})", a.repr(tcx)), AddrOf(a) => format!("AddrOf({})", a.repr(tcx)), AutoBorrow(a) => format!("AutoBorrow({})", a.repr(tcx)), Managed(a) => format!("Managed({})", a.repr(tcx)), } } } impl RegionVariableOrigin { pub fn span(&self) -> Span { match *self { MiscVariable(a) => a, PatternRegion(a) => a, AddrOfRegion(a) => a, AddrOfSlice(a) => a, Autoref(a) => a, Coercion(ref a) => a.span(), EarlyBoundRegion(a, _) => a, LateBoundRegion(a, _) => a, BoundRegionInFnType(a, _) => a, BoundRegionInCoherence(_) => codemap::DUMMY_SP, UpvarRegion(_, a) => a } } } impl Repr for RegionVariableOrigin { fn repr(&self, tcx: &ty::ctxt) -> String { match *self { MiscVariable(a) => { format!("MiscVariable({})", a.repr(tcx)) } PatternRegion(a) => { format!("PatternRegion({})", a.repr(tcx)) } AddrOfRegion(a) => { format!("AddrOfRegion({})", a.repr(tcx)) } AddrOfSlice(a) => format!("AddrOfSlice({})", a.repr(tcx)), Autoref(a) => format!("Autoref({})", a.repr(tcx)), Coercion(ref a) => format!("Coercion({})", a.repr(tcx)), EarlyBoundRegion(a, b) => { format!("EarlyBoundRegion({},{})", a.repr(tcx), b.repr(tcx)) } LateBoundRegion(a, b) => { format!("LateBoundRegion({},{})", a.repr(tcx), b.repr(tcx)) } BoundRegionInFnType(a, b) => { format!("bound_regionInFnType({},{})", a.repr(tcx), b.repr(tcx)) } BoundRegionInCoherence(a) => { format!("bound_regionInCoherence({})", a.repr(tcx)) } UpvarRegion(a, b) => { format!("UpvarRegion({}, {})", a.repr(tcx), b.repr(tcx)) } } } }
33.656854
98
0.533333
d53a3dc3b9396ae18503ea6d2576d25c2be2551e
4,378
use std::env; use std::fs; use std::path::Path; //The following crates are used for testing extern crate tempfile; //Creates temp files and directories use assert_cmd::prelude::*; // Add methods on commands use predicates::prelude::*; use std::process::Command; // Run programs // Used for writing assertions fn main() { // This should be called with two command line arguments, // both file names. The first should be the name of a file // containing the text to disemvowel, and the second should // be the file we want to write the disemvoweled text to. let args: Vec<String> = env::args().collect(); //TODO: Panic if not enough arguments are provided //Panic should output the string "Not enough arguments" if args.len() != 3 { panic!("Not enough arguments"); } //TODO: // * Pass an argument to read_file to read the original text // * Pass that to disemvowel to remove the vowels // * Write the disemvoweled text using write_file let path = Path::new(&args[1]); let text = read_file(&path); // Replace String::from("test") with what you get from read_file let s = String::from(text); let s_disemvowel = disemvowel(&s); // Use command-line arguments for the name of the file, // and s_disemvowel for the text to write out. write_file(Path::new(&args[2]), &s_disemvowel); } fn read_file(path: &Path) -> String { fs::read_to_string(path).expect("Could not read the file") } fn write_file(path: &Path, s: &str) { fs::write(path, s).expect("Unable to write file"); } //TODO: Return the input string without vowels. fn disemvowel(s: &str) -> String { let s = s.replace(&['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'][..], ""); String::from(s) } // Everything from here down is Rust test code. You shouldn't need to // change any of this. // // Use `cargo test` to run all these tests. All the tests will initially // fail because there's no definition for the `disemvowel` function. Add // that up above and work to get the tests to pass. See the lab write-up // for some tips. #[cfg(test)] mod tests { use super::*; mod disemvowel { use super::*; #[test] fn hello_world() { let input = "Hello, world!"; let expected = "Hll, wrld!"; assert_eq!(expected, disemvowel(input)); } #[test] fn empty() { assert_eq!("", disemvowel("")); } #[test] fn no_vowels() { assert_eq!("pqrst", disemvowel("pqrst")); } #[test] fn all_vowels() { assert_eq!("", disemvowel("aeiouAEIOUOIEAuoiea")); } #[test] fn morris_minnesota() { assert_eq!("Mrrs, Mnnst", disemvowel("Morris, Minnesota")); } #[test] fn handle_punctuation() { assert_eq!( "n (nxplnd) lphnt!", disemvowel("An (Unexplained) Elephant!") ); } #[test] fn handle_unicode() { assert_eq!("Sm hrglyphs: 𒐁 𒐌 𒐥 𒑳", disemvowel("Some hieroglyphs: 𒐁 𒐌 𒐥 𒑳")); assert_eq!("Sm Lnr B: 𐂀 𐂚 𐃃 𐃺", disemvowel("Some Linear B: 𐂀 𐂚 𐃃 𐃺")); assert_eq!(" lttl Phncn: 𐤀 𐤈 𐤔 𐤕", disemvowel("A little Phoenician: 𐤀 𐤈 𐤔 𐤕")); assert_eq!( "W cn hndl mj s wll! 🤣😃👍", disemvowel("We can handle emoji as well! 🤣😃👍") ) } } // Tests that check that the correct panics are generated when // there aren't the correct number of command line arguments // or the input file isn't readable. mod panic_tests { use super::*; #[test] fn requires_two_arguments() { let mut cmd = Command::cargo_bin("disemvowel-in-rust").unwrap(); cmd.arg("1"); cmd.assert() .failure() .stderr(predicate::str::contains("Not enough arguments")); } #[test] fn requires_read_file() { let mut cmd = Command::cargo_bin("disemvowel-in-rust").unwrap(); cmd.arg("/this/path/does/not/exist") .arg("output/path/doesnt/matter"); cmd.assert() .failure() .stderr(predicate::str::contains("Could not read the file")); } } }
32.191176
91
0.566926
4bf7bbb3e4991fafc69605b8d2e507c12250ccca
953
use tonic::{transport::Server, Request, Response, Status}; pub mod hello_world { tonic::include_proto!("helloworld"); } use hello_world::{ server::{Greeter, GreeterServer}, HelloReply, HelloRequest, }; #[derive(Default)] pub struct MyGreeter {} #[tonic::async_trait] impl Greeter for MyGreeter { async fn say_hello( &self, request: Request<HelloRequest>, ) -> Result<Response<HelloReply>, Status> { println!("Got a request: {:?}", request); let reply = hello_world::HelloReply { message: format!("Hello {}!", request.into_inner().name).into(), }; Ok(Response::new(reply)) } } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let addr = "[::0]:50051".parse().unwrap(); let greeter = MyGreeter::default(); Server::builder() .add_service(GreeterServer::new(greeter)) .serve(addr) .await?; Ok(()) }
22.690476
76
0.598111
0e38bca6d5af7a82f7661ae4b79f3b49497e8212
1,377
use serde::Serialize; use std::{ default::Default, fmt::{Display, Formatter, Result as FmtResult}, }; #[derive(Debug, Serialize)] pub enum Orientation { Any, Natural, Landscape, LandscapePrimary, LandscapeSecondary, Portrait, PortraitPrimary, PortraitSecondary, } impl Orientation { pub fn all() -> Vec<Self> { vec![ Orientation::Any, Orientation::Natural, Orientation::Landscape, Orientation::LandscapePrimary, Orientation::LandscapeSecondary, Orientation::Portrait, Orientation::PortraitPrimary, Orientation::PortraitSecondary, ] } } impl Display for Orientation { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { use Orientation::*; match self { Any => write!(f, "any"), Natural => write!(f, "natural"), Landscape => write!(f, "landscape"), LandscapePrimary => write!(f, "landscape-primary"), LandscapeSecondary => write!(f, "landscape-secondary"), Portrait => write!(f, "portrait"), PortraitPrimary => write!(f, "portrait-primary"), PortraitSecondary => write!(f, "portrait-secondary"), } } } impl Default for Orientation { fn default() -> Self { Self::Any } }
24.589286
67
0.56427
e59cae0283e5983ce7a19244f156d257aadefa68
329
// Copyright (C) 2020 - 2022, J2 Innovations //! Zinc Haystack tag decoding use crate::haystack::val::Value; use super::id::*; use super::value::*; // Zinc tag pair #[derive(PartialEq, PartialOrd, Clone, Debug)] pub(super) struct TagPair { pub(super) name: String, pub(super) value: Value, } // Parse a Haystack tag
18.277778
46
0.671733
ac64a1531179caf79eda143fb94074f524a5cbc7
923
// TODO: try to pipeline queries mod utils; mod author; mod chapter; mod character; mod origin; mod pairing; mod story; mod tag; mod warning; mod worker; use { bb8::Pool, bb8_postgres::PostgresConnectionManager, std::sync::Arc, stry_common::LibraryDetails, stry_config::{BackendType, StorageType}, tokio_postgres::NoTls, }; pub const SCHEMA: &str = rewryte::schema!("postgresql", "../schema.dal"); #[derive(Clone, Debug)] pub struct PostgresBackend(Pool<PostgresConnectionManager<NoTls>>); #[cfg_attr(feature = "boxed-futures", stry_macros::box_async)] impl PostgresBackend { #[tracing::instrument(skip(_backend, _storage, _details), err)] pub async fn init( _backend: BackendType, _storage: StorageType, _details: Arc<Vec<LibraryDetails>>, ) -> anyhow::Result<Self> { todo!() } } pub fn library_details() -> Vec<LibraryDetails> { vec![] }
20.977273
73
0.678223
7580e79b1c8b3e90b9bd7413e7937143f65779bd
4,058
use crate::{ spaces::{discrete::Ordinal, real::Interval, ProductSpace}, Domain, Observation, Reward, }; const X_MIN: f64 = -1.2; const X_MAX: f64 = 0.6; const V_MIN: f64 = -0.07; const V_MAX: f64 = 0.07; const FORCE_G: f64 = -0.0025; const FORCE_CAR: f64 = 0.001; const HILL_FREQ: f64 = 3.0; const REWARD_STEP: f64 = -1.0; const REWARD_GOAL: f64 = 0.0; const ALL_ACTIONS: [f64; 3] = [-1.0, 0.0, 1.0]; /// Classic mountain car testing domain. /// /// This problem involves an under-powered car which must ascend a steep hill. /// Since gravity is stronger than the car's engine, even at full throttle, the /// car cannot simply accelerate up the steep slope. The car is situated in a /// valley and must learn to leverage potential energy by driving up the /// opposite hill before the car is able to make it to the goal at the top of /// the rightmost hill.[^1] /// /// [^1]: See [https://en.wikipedia.org/wiki/Mountain_car_problem](https://en.wikipedia.org/wiki/Mountain_car_problem) /// /// # Technical details /// The **state** is represented by a `Vec` with components: /// /// | Index | Name | Min | Max | /// | ----- | -------- | ----- | ----- | /// | 0 | Position | -1.2 | 0.6 | /// | 1 | Velocity | -0.07 | 0.07 | /// /// /// # References /// - Moore, A. W. (1990). Efficient memory-based learning for robot control. /// - Singh, S. P., & Sutton, R. S. (1996). Reinforcement learning with /// replacing eligibility traces. Recent Advances in Reinforcement Learning, /// 123-158. - Sutton, R. S., & Barto, A. G. (1998). Reinforcement learning: An /// introduction (Vol. 1, No. 1). Cambridge: MIT press. pub struct MountainCar { x: f64, v: f64, } impl MountainCar { pub fn new(x: f64, v: f64) -> MountainCar { MountainCar { x, v } } fn dv(x: f64, a: f64) -> f64 { FORCE_CAR * a + FORCE_G * (HILL_FREQ * x).cos() } fn update_state(&mut self, a: usize) { let a = ALL_ACTIONS[a]; self.v = clip!(V_MIN, self.v + Self::dv(self.x, a), V_MAX); self.x = clip!(X_MIN, self.x + self.v, X_MAX); } } impl Default for MountainCar { fn default() -> MountainCar { MountainCar::new(-0.5, 0.0) } } impl Domain for MountainCar { type StateSpace = ProductSpace<Interval>; type ActionSpace = Ordinal; fn emit(&self) -> Observation<Vec<f64>> { if self.x >= X_MAX { Observation::Terminal(vec![self.x, self.v]) } else { Observation::Full(vec![self.x, self.v]) } } fn step(&mut self, action: &usize) -> (Observation<Vec<f64>>, Reward) { self.update_state(*action); let to = self.emit(); let reward = if to.is_terminal() { REWARD_GOAL } else { REWARD_STEP }; (to, reward) } fn state_space(&self) -> Self::StateSpace { ProductSpace::empty() + Interval::bounded(X_MIN, X_MAX) + Interval::bounded(V_MIN, V_MAX) } fn action_space(&self) -> Ordinal { Ordinal::new(3) } } #[cfg(test)] mod tests { use super::*; use crate::{Domain, Observation}; #[test] fn test_initial_observation() { let m = MountainCar::default(); match m.emit() { Observation::Full(ref state) => { assert_eq!(state[0], -0.5); assert_eq!(state[1], 0.0); }, _ => panic!("Should yield a fully observable state."), } } #[test] fn test_is_terminal() { assert!(!MountainCar::default().emit().is_terminal()); assert!(!MountainCar::new(-0.5, 0.0).emit().is_terminal()); assert!(MountainCar::new(X_MAX, -0.05).emit().is_terminal()); assert!(MountainCar::new(X_MAX, 0.0).emit().is_terminal()); assert!(MountainCar::new(X_MAX, 0.05).emit().is_terminal()); assert!(!MountainCar::new(X_MAX - 0.0001 * X_MAX, 0.0) .emit() .is_terminal()); assert!(MountainCar::new(X_MAX + 0.0001 * X_MAX, 0.0) .emit() .is_terminal()); } }
29.194245
118
0.578117
56d6758209f19c8313c4b53cde6f1f1ed7af5f97
15,899
use std::str::from_utf8; use std::fmt; use nom; use nom::{IResult, ErrorKind, digit, space, alphanumeric, is_space}; use nom::IResult::{Error, Done, Incomplete}; #[derive(PartialEq)] #[derive(Debug)] #[derive(Clone)] pub enum CrontabSyntaxError { InvalidEnumField, ValueOutOfBounds { value: i32, min: i32, max: i32 }, InvalidNumericValue, InvalidPeriodField, InvalidFieldSeparator, InvalidUsername, InvalidCommandLine { reason: String }, } impl fmt::Display for CrontabSyntaxError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { CrontabSyntaxError::ValueOutOfBounds { value, min, max } => write!(f, "value {} out of bounds (accepted: {} to {})", value, min, max), CrontabSyntaxError::InvalidEnumField | CrontabSyntaxError::InvalidPeriodField => write!(f, "could not parse the field"), CrontabSyntaxError::InvalidNumericValue => write!(f, "invalid numeric value"), CrontabSyntaxError::InvalidFieldSeparator => write!(f, "expected a field separator (space or tab)"), CrontabSyntaxError::InvalidUsername => write!(f, "invalid username"), CrontabSyntaxError::InvalidCommandLine { ref reason } => write!(f, "invalid command line: {}", reason), } } } fn parse_within_bounds(input: &[u8], min: i32, max: i32) -> IResult<&[u8], (), CrontabSyntaxError> { let digits = digit(input); match digits { Done(remaining, result) => { from_utf8(result).ok().and_then(|x| x.parse::<i32>().ok() ).and_then(|int| if int < min || int > max { Some(Error(error_position!( ErrorKind::Custom(CrontabSyntaxError::ValueOutOfBounds { value: int, min: min, max: max }), input ))) } else { Some(Done(remaining, ())) } ).unwrap_or( Error(error_position!(ErrorKind::Custom(CrontabSyntaxError::InvalidNumericValue), input)) ) }, Error(..) => { Error(error_position!(ErrorKind::Custom(CrontabSyntaxError::InvalidNumericValue), input)) }, Incomplete(n) => Incomplete(n) } } // Basic values parsers (a value is either a day or month name ("mon", "jun") or a bounded integer ("2"), named!(minute_value_parser<&[u8], (), CrontabSyntaxError>, apply!(parse_within_bounds, 0, 59)); named!(hour_value_parser<&[u8], (), CrontabSyntaxError>, apply!(parse_within_bounds, 0, 24)); named!(day_of_month_value_parser<&[u8], (), CrontabSyntaxError>, apply!(parse_within_bounds, 0, 31)); fn month_value_parser(input: &[u8]) -> IResult<&[u8], (), CrontabSyntaxError> { let parsed = fix_error!(input, CrontabSyntaxError, alt_complete!( tag!("jan") | tag!("feb") | tag!("mar") | tag!("apr") | tag!("may") | tag!("jun") | tag!("jul") | tag!("aug") | tag!("sep") | tag!("oct") | tag!("nov") | tag!("dec") ) ); match parsed { Done(i, _) => Done(i, ()), Incomplete(inc) => Incomplete(inc), Error(..) => parse_within_bounds(input, 1, 12) } } fn day_of_week_value_parser(input: &[u8]) -> IResult<&[u8], (), CrontabSyntaxError> { let parsed = fix_error!(input, CrontabSyntaxError, alt_complete!( tag!("mon") | tag!("tue") | tag!("wed") | tag!("thu") | tag!("fri") | tag!("sat") | tag!("sun") ) ); match parsed { Done(i, _) => Done(i, ()), Incomplete(inc) => Incomplete(inc), Error(..) => parse_within_bounds(input, 0, 7) } } // parse '*/2' fn parse_period(input: &[u8], value_parser: fn(&[u8]) -> IResult<&[u8], (), CrontabSyntaxError>) -> IResult<&[u8], (), CrontabSyntaxError> { let out = tag!(input, "*"); match out { Done(i, _) => { let next = tag!(i, "/"); match next { Done(ii, _) => add_return_error!(ii, ErrorKind::Custom(CrontabSyntaxError::InvalidPeriodField), value_parser), _ => Done(i, ()), } }, _ => Error(error_position!(ErrorKind::Custom(CrontabSyntaxError::InvalidPeriodField), input)) } } fn parse_range_or_value(input: &[u8], value_parser: fn(&[u8]) -> IResult<&[u8], (), CrontabSyntaxError>) -> IResult<&[u8], (), CrontabSyntaxError> { let parsed_value = value_parser(input); match parsed_value { Error(..) | Incomplete(..) => parsed_value, Done(i, _) => { let separator = fix_error!(i, CrontabSyntaxError, tag!("-")); match separator { Error(..) => parsed_value, Incomplete(inc) => Incomplete(inc), Done(ii, _) => value_parser(ii) } } } } // parse 2,12-23 fn parse_enum(input: &[u8], value_parser: fn(&[u8]) -> IResult<&[u8], (), CrontabSyntaxError>) -> IResult<&[u8], (), CrontabSyntaxError> { add_return_error!(input, ErrorKind::Custom(CrontabSyntaxError::InvalidEnumField), do_parse!( separated_nonempty_list!(tag!(","), apply!(parse_range_or_value, value_parser)) >> () ) ) } // a field is either a frequency (*/2) or an enumeration (2-4,5) fn parse_field(input: &[u8], value_parser: fn(&[u8]) -> IResult<&[u8], (), CrontabSyntaxError>) -> IResult<&[u8], (), CrontabSyntaxError> { match peek!(input, tag!("*")) { IResult::Error(..) => apply!(input, parse_enum, value_parser), IResult::Done(..) => apply!(input, parse_period, value_parser), Incomplete(e) => Incomplete(e) } } fn parse_field_separator(input: &[u8]) -> IResult<&[u8], (), CrontabSyntaxError> { let parsed = space(input); match parsed { Done(i, _) => Done(i, ()), Error(_) => Error(error_position!(ErrorKind::Custom(CrontabSyntaxError::InvalidFieldSeparator), input)), Incomplete(i) => Incomplete(i) } } fn is_valid_username<T: AsRef<str>>(name: &str, allowed_usernames: Option<&[T]>) -> bool { if allowed_usernames.is_none() { return true; } (*(allowed_usernames.unwrap())).iter().any(|el| el.as_ref() == name) } fn parse_user<'a, 'b, T: AsRef<str> + 'b>(input: &'a[u8], allowed_usernames: Option<&'b[T]>) -> IResult<&'a[u8], (), CrontabSyntaxError> { let parsed = alphanumeric(input); match parsed { Done(i, o) => { from_utf8(o).ok().map(|name| is_valid_username(name, allowed_usernames)).map(|valid| if valid { Done(i, ()) } else { Error(error_position!(ErrorKind::Custom(CrontabSyntaxError::InvalidUsername), input)) }).unwrap_or(Error(error_position!(ErrorKind::Custom(CrontabSyntaxError::InvalidUsername), input))) }, Error(_) => Error(error_position!(ErrorKind::Custom(CrontabSyntaxError::InvalidUsername), input)), Incomplete(i) => Incomplete(i) } } pub struct CrontabParserOptions<'a, T: AsRef<str> + 'a> { pub allowed_usernames: Option<&'a [T]> } // consume all input, make sure there are not special characters in the command line fn parse_command_line(input: &[u8]) -> IResult<&[u8], (), CrontabSyntaxError> { // cron limitation // see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=686223 if (*input).len() > 999 { return Error(error_position!(ErrorKind::Custom( CrontabSyntaxError::InvalidCommandLine { reason: "command line can not exceed 999 characters".to_string() }), input )) } // FIXME: this is a dirty and inaccurate way of checking whether the '%' is escaped // TODO: give the correct error position let reason = "special char % should not be used unescaped".to_string(); let error = Error(error_position!(ErrorKind::Custom( CrontabSyntaxError::InvalidCommandLine { reason }), input )); if let Some(first_char) = input.first() { if *first_char == b'%' { return error; } } for slice in input.windows(2) { let c1 = slice[0]; let c2 = slice[1]; if c2 == b'%' && c1 != b'\\' { return error; } } Done(&[], ()) } fn parse_comment(input: &[u8]) -> IResult<&[u8], (), CrontabSyntaxError> { let out = fix_error!(input, CrontabSyntaxError, do_parse!( take_while_s!(is_space) >> tag!("#") >> () )); match out { Done(..) => Done(&[], ()), Error(e) => Error(e), Incomplete(e) => Incomplete(e) } } // TODO: more checks for this parser fn parse_environnment_variable(input: &[u8]) -> IResult<&[u8], (), CrontabSyntaxError> { let out = fix_error!(input, CrontabSyntaxError, do_parse!( alphanumeric >> tag!("=") >> () )); match out { Done(..) => Done(&[], ()), Error(e) => Error(e), Incomplete(e) => Incomplete(e) } } fn parse_empty_line(input: &[u8]) -> IResult<&[u8], (), CrontabSyntaxError> { for c in input { if !is_space(*c) { return Error(error_position!(ErrorKind::Space, input)); } } return Done(&[], ()); } // TODO: the caller should not have to depend on symbols exported by nom pub fn parse_crontab<'a, T: AsRef<str>>(input: &'a[u8], options: &CrontabParserOptions<T>) -> IResult<&'a[u8], (), CrontabSyntaxError> { // We do not use the alt_complete! combinator because we want to have nice error codes // Try to parse the line as an empty line, then if it fails as a comment, then as an // environment variable assignation, then as an actual crontab line let mut result = parse_empty_line(input); if let Done(..) = result { return result; } result = parse_comment(input); if let Done(..) = result { return result; } result = parse_environnment_variable(input); if let Done(..) = result { return result; } // actual crontab line return do_parse!(input, apply!(parse_field, minute_value_parser) >> parse_field_separator >> apply!(parse_field, hour_value_parser) >> parse_field_separator >> apply!(parse_field, day_of_month_value_parser) >> parse_field_separator >> apply!(parse_field, month_value_parser) >> parse_field_separator >> apply!(parse_field, day_of_week_value_parser) >> parse_field_separator >> apply!(parse_user, options.allowed_usernames) >> parse_field_separator >> parse_command_line >> () ) } fn format_error(error: &ErrorKind<CrontabSyntaxError>) -> String { match *error { ErrorKind::Custom(ref e) => e.to_string(), ref e => format!("error: {:?}", e).to_string() // this should not happen } } pub fn walk_errors(errs: &[nom::Err<&[u8], CrontabSyntaxError>]) -> String { let mut strings: Vec<String> = vec![]; for err in errs { let formatted = match *err { nom::Err::Code(ref kind) => format_error(kind), nom::Err::Node(ref kind, ref next_error) => format_error(kind) + "\nCaused by: " + &walk_errors(next_error), nom::Err::Position(ref kind, position) => format_error(kind) + " (at '" + format_position(position).as_str() + "')", nom::Err::NodePosition(ref kind, position, ref next_error) => format_error(kind) + " (at '" + format_position(position).as_str() + "')\nCaused by: " + &walk_errors(next_error), }; strings.push(formatted); } strings.join("\n\n") } fn format_position(pos: &[u8]) -> String { let mut s = from_utf8(pos).unwrap_or("(invalid UTF-8)").to_string(); s.truncate(15); s } #[cfg(test)] mod tests { use nom::IResult::{Error, Done}; use parser::*; #[test] fn test_format_errors() { let usernames = ["root"]; let options = &CrontabParserOptions { allowed_usernames: Some(&usernames) }; let parsed = parse_crontab("2-10 * */4 * mon root /usr/local/bin yay".as_bytes(), options); match parsed { Error(e) => { let errors = [e]; println!("{}", walk_errors(&errors)); }, _ => () }; } #[test] fn test_parse_valid_crontab() { let usernames = ["root"]; let options = &CrontabParserOptions { allowed_usernames: Some(&usernames) }; let out = parse_crontab("* * * * * root /usr/local/bin yay".as_bytes(), options); assert_eq!(out, Done("".as_bytes(), ())); let out = parse_crontab("8 * * * * root /usr/local/bin yay".as_bytes(), options); assert_eq!(out, Done("".as_bytes(), ())); let out = parse_crontab("*/3 2 * * * root /usr/local/bin yay".as_bytes(), options); assert_eq!(out, Done("".as_bytes(), ())); let out = parse_crontab("1-2 * * * * root /usr/local/bin yay".as_bytes(), options); assert_eq!(out, Done("".as_bytes(), ())); let out = parse_crontab("1-2 * * * mon,tue root /usr/local/bin yay".as_bytes(), options); assert_eq!(out, Done("".as_bytes(), ())); let out = parse_crontab("#This is a comment".as_bytes(), options); assert_eq!(out, Done("".as_bytes(), ())); let out = parse_crontab("VARIABLE=VALUE".as_bytes(), options); assert_eq!(out, Done("".as_bytes(), ())); let out = parse_crontab(" ".as_bytes(), options); assert_eq!(out, Done("".as_bytes(), ())); } #[test] fn test_parse_user() { assert_eq!(parse_user("whatever".as_bytes(), None as Option<&[String]>), Done("".as_bytes(), ())); let users = ["root"]; match parse_user("whatever".as_bytes(), Some(&users)) { Error(_) => (), _ => assert!(false) }; assert_eq!(parse_user("root /usr/bin/local".as_bytes(), None as Option<&[String]>), Done(" /usr/bin/local".as_bytes(), ())); } #[test] fn test_is_valid_username() { assert_eq!(true, is_valid_username("whatever", None as Option<&[String]>)); assert_eq!(true, is_valid_username("root", Some(&["root", "notroot"]))); assert_eq!(false, is_valid_username("bfaucon", Some(&["root", "notroot"]))); } #[test] fn test_day_of_week_value_parser() { assert_eq!(day_of_week_value_parser("mon".as_bytes()), Done("".as_bytes(), ())); assert_eq!(day_of_week_value_parser("mon ".as_bytes()), Done(" ".as_bytes(), ())); assert_eq!(day_of_week_value_parser("0 ".as_bytes()), Done(" ".as_bytes(), ())); assert_eq!(day_of_week_value_parser("1 ".as_bytes()), Done(" ".as_bytes(), ())); } #[test] fn test_parse_period() { assert_eq!(parse_period("* ".as_bytes(), minute_value_parser), Done(" ".as_bytes(), ())); assert_eq!(parse_period("*/2 ".as_bytes(), minute_value_parser), Done(" ".as_bytes(), ())); } #[test] fn test_parse_range_or_value() { assert_eq!(parse_range_or_value("1-2".as_bytes(), minute_value_parser), Done("".as_bytes(), ())); } #[test] fn test_parse_enum() { assert_eq!(parse_enum("1-2,3,4-5 *".as_bytes(), minute_value_parser), Done(" *".as_bytes(), ())); assert_eq!(parse_enum("mon-tue ".as_bytes(), day_of_week_value_parser), Done(" ".as_bytes(), ())); } #[test] fn test_parse_field() { assert_eq!(parse_field("mon-tue ".as_bytes(), day_of_week_value_parser), Done(" ".as_bytes(), ())); } }
36.803241
189
0.567331
1a56d888fb3b98a0fd12124cb9c5fb4ef5655458
521
// This powerful wrapper provides the ability to store a positive integer value. // Rewrite it using generics so that it supports wrapping ANY type. struct Wrapper<T> { value: T } impl Wrapper { pub fn new(value: u32) -> Self { Wrapper { value } } } #[cfg(test)] mod tests { use super::*; #[test] fn store_u32_in_wrapper() { assert_eq!(Wrapper::new(42).value, 42); } #[test] fn store_str_in_wrapper() { assert_eq!(Wrapper::new("Foo").value, "Foo"); } }
19.296296
80
0.602687
de37e1f37e5352d4c1337e24e372cad7c09a1a5d
3,789
#[derive(Clone)] pub struct VecMap<K, V> { vec: Vec<(K, V)>, } impl<K: PartialEq, V> VecMap<K, V> { #[inline] pub fn with_capacity(cap: usize) -> VecMap<K, V> { VecMap { vec: Vec::with_capacity(cap) } } #[inline] pub fn insert(&mut self, key: K, value: V) { // not using entry or find_mut because of borrowck for entry in &mut self.vec { if key == entry.0 { *entry = (key, value); return; } } self.vec.push((key, value)); } #[inline] pub fn append(&mut self, key: K, value: V) { self.vec.push((key, value)); } #[cfg(feature = "headers")] #[inline] pub fn entry(&mut self, key: K) -> Entry<K, V> { match self.pos(&key) { Some(pos) => Entry::Occupied(OccupiedEntry { vec: &mut self.vec, pos: pos, }), None => Entry::Vacant(VacantEntry { vec: &mut self.vec, key: key, }) } } #[inline] pub fn get<K2: PartialEq<K> + ?Sized>(&self, key: &K2) -> Option<&V> { self.find(key).map(|entry| &entry.1) } #[cfg(feature = "headers")] #[inline] pub fn get_mut<K2: PartialEq<K> + ?Sized>(&mut self, key: &K2) -> Option<&mut V> { self.find_mut(key).map(|entry| &mut entry.1) } #[cfg(feature = "headers")] #[inline] pub fn contains_key<K2: PartialEq<K> + ?Sized>(&self, key: &K2) -> bool { self.find(key).is_some() } #[inline] pub fn len(&self) -> usize { self.vec.len() } #[inline] pub fn iter(&self) -> ::std::slice::Iter<(K, V)> { self.vec.iter() } #[cfg(feature = "headers")] #[inline] pub fn remove<K2: PartialEq<K> + ?Sized>(&mut self, key: &K2) -> Option<V> { self.pos(key).map(|pos| self.vec.remove(pos)).map(|(_, v)| v) } #[inline] pub fn remove_all<K2: PartialEq<K> + ?Sized>(&mut self, key: &K2) { let len = self.vec.len(); for i in (0..len).rev() { if key == &self.vec[i].0 { self.vec.remove(i); } } } #[cfg(feature = "headers")] #[inline] pub fn clear(&mut self) { self.vec.clear(); } #[inline] fn find<K2: PartialEq<K> + ?Sized>(&self, key: &K2) -> Option<&(K, V)> { for entry in &self.vec { if key == &entry.0 { return Some(entry); } } None } #[cfg(feature = "headers")] #[inline] fn find_mut<K2: PartialEq<K> + ?Sized>(&mut self, key: &K2) -> Option<&mut (K, V)> { for entry in &mut self.vec { if key == &entry.0 { return Some(entry); } } None } #[cfg(feature = "headers")] #[inline] fn pos<K2: PartialEq<K> + ?Sized>(&self, key: &K2) -> Option<usize> { self.vec.iter().position(|entry| key == &entry.0) } } #[cfg(feature = "headers")] pub enum Entry<'a, K: 'a, V: 'a> { Vacant(VacantEntry<'a, K, V>), Occupied(OccupiedEntry<'a, K, V>) } #[cfg(feature = "headers")] pub struct VacantEntry<'a, K: 'a, V: 'a> { vec: &'a mut Vec<(K, V)>, key: K, } #[cfg(feature = "headers")] impl<'a, K, V> VacantEntry<'a, K, V> { pub fn insert(self, val: V) -> &'a mut V { self.vec.push((self.key, val)); let pos = self.vec.len() - 1; &mut self.vec[pos].1 } } #[cfg(feature = "headers")] pub struct OccupiedEntry<'a, K: 'a, V: 'a> { vec: &'a mut Vec<(K, V)>, pos: usize, } #[cfg(feature = "headers")] impl<'a, K, V> OccupiedEntry<'a, K, V> { pub fn into_mut(self) -> &'a mut V { &mut self.vec[self.pos].1 } }
24.603896
88
0.476115
e4370d230bbdbcc4cbc01cb3f355273c3cece563
16,686
// Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors // SPDX-License-Identifier: MIT use std::sync::Arc; use std::convert::TryFrom; use rocksdb::{Cache, ColumnFamilyDescriptor}; use serde::{Deserialize, Serialize}; use crypto::hash::{ChainId, HashType}; use tezos_messages::Head; use crate::database::tezedge_database::{KVStoreKeyValueSchema, TezedgeDatabaseWithIterator}; use crate::persistent::database::{default_table_options, RocksDbKeyValueSchema}; use crate::persistent::{BincodeEncoded, Decoder, Encoder, KeyValueSchema, SchemaError}; use crate::{PersistentStorage, StorageError}; pub type ChainMetaStorageKv = dyn TezedgeDatabaseWithIterator<ChainMetaStorage> + Sync + Send; pub trait ChainMetaStorageReader: Sync + Send { /// Load current head for chain_id from dedicated storage fn get_current_head(&self, chain_id: &ChainId) -> Result<Option<Head>, StorageError>; /// Load caboose for chain_id from dedicated storage /// /// `caboose` vs `save_point`: /// - save_point is the lowest block for which we also have the metadata information /// - caboose - so in particular it is the lowest block for which we have stored the context fn get_caboose(&self, chain_id: &ChainId) -> Result<Option<Head>, StorageError>; /// Load genesis for chain_id from dedicated storage fn get_genesis(&self, chain_id: &ChainId) -> Result<Option<Head>, StorageError>; } /// Represents storage of the chain metadata (current_head, test_chain, ...). /// Metadata are related to concrete chain_id, which is used as a part of key. /// /// Reason for this storage is that, for example current head cannot be easily selected from block_meta_storage (lets say by level), /// because there are some computations (with fitness) that need to be done... /// /// This storage differs from the other in regard that it is not exposing key-value pair /// but instead it provides get_ and set_ methods for each property prefixed with chain_id. /// /// Maybe this properties split is not very nice but, we need to access properties separatly, /// if we stored metadata grouped to struct K-V: <chain_id> - MetadataStruct, /// we need to all the time deserialize whole sturct. /// /// e.g. storage key-value will looks like: /// (<main_chain_id>, 'current_head') - block_hash_xyz /// (<main_chain_id>, 'test_chain_id') - chain_id_xyz /// #[derive(Clone)] pub struct ChainMetaStorage { kv: Arc<ChainMetaStorageKv>, } impl ChainMetaStorage { pub fn new(persistent_storage: &PersistentStorage) -> Self { Self { kv: persistent_storage.main_db(), } } #[inline] pub fn set_current_head(&self, chain_id: &ChainId, head: Head) -> Result<(), StorageError> { self.kv .put( &MetaKey::key_current_head(chain_id.clone()), &MetadataValue::Head(head), ) .map_err(StorageError::from) } #[inline] pub fn set_caboose(&self, chain_id: &ChainId, head: Head) -> Result<(), StorageError> { self.kv .put( &MetaKey::key_caboose(chain_id.clone()), &MetadataValue::Head(head), ) .map_err(StorageError::from) } #[inline] pub fn set_genesis(&self, chain_id: &ChainId, head: Head) -> Result<(), StorageError> { self.kv .put( &MetaKey::key_genesis(chain_id.clone()), &MetadataValue::Head(head), ) .map_err(StorageError::from) } #[inline] pub fn get_test_chain_id(&self, chain_id: &ChainId) -> Result<Option<ChainId>, StorageError> { self.kv .get(&MetaKey::key_test_chain_id(chain_id.clone())) .map(|result| match result { Some(MetadataValue::TestChainId(value)) => Some(value), _ => None, }) .map_err(StorageError::from) } #[inline] pub fn set_test_chain_id( &self, chain_id: &ChainId, test_chain_id: &ChainId, ) -> Result<(), StorageError> { self.kv .put( &MetaKey::key_test_chain_id(chain_id.clone()), &MetadataValue::TestChainId(test_chain_id.clone()), ) .map_err(StorageError::from) } #[inline] pub fn remove_test_chain_id(&self, chain_id: &ChainId) -> Result<(), StorageError> { self.kv .delete(&MetaKey::key_test_chain_id(chain_id.clone())) .map_err(StorageError::from) } } impl ChainMetaStorageReader for ChainMetaStorage { #[inline] fn get_current_head(&self, chain_id: &ChainId) -> Result<Option<Head>, StorageError> { self.kv .get(&MetaKey::key_current_head(chain_id.clone())) .map(|result| match result { Some(MetadataValue::Head(value)) => Some(value), _ => None, }) .map_err(StorageError::from) } #[inline] fn get_caboose(&self, chain_id: &ChainId) -> Result<Option<Head>, StorageError> { self.kv .get(&MetaKey::key_caboose(chain_id.clone())) .map(|result| match result { Some(MetadataValue::Head(value)) => Some(value), _ => None, }) .map_err(StorageError::from) } #[inline] fn get_genesis(&self, chain_id: &ChainId) -> Result<Option<Head>, StorageError> { self.kv .get(&MetaKey::key_genesis(chain_id.clone())) .map(|result| match result { Some(MetadataValue::Head(value)) => Some(value), _ => None, }) .map_err(StorageError::from) } } impl KeyValueSchema for ChainMetaStorage { type Key = MetaKey; type Value = MetadataValue; } impl RocksDbKeyValueSchema for ChainMetaStorage { fn descriptor(cache: &Cache) -> ColumnFamilyDescriptor { let cf_opts = default_table_options(cache); ColumnFamilyDescriptor::new(Self::name(), cf_opts) } #[inline] fn name() -> &'static str { "chain_meta_storage" } } impl KVStoreKeyValueSchema for ChainMetaStorage { fn column_name() -> &'static str { Self::name() } } #[derive(Serialize, Deserialize, Debug)] pub struct MetaKey { chain_id: ChainId, key: String, } impl MetaKey { const LEN_CHAIN_ID: usize = HashType::ChainId.size(); const IDX_CHAIN_ID: usize = 0; const IDX_KEY: usize = Self::IDX_CHAIN_ID + Self::LEN_CHAIN_ID; const KEY_CURRENT_HEAD: &'static str = "ch"; const KEY_CABOOSE: &'static str = "cbs"; const KEY_GENESIS: &'static str = "gns"; const KEY_TEST_CHAIN_ID: &'static str = "tcid"; fn key_current_head(chain_id: ChainId) -> MetaKey { MetaKey { chain_id, key: Self::KEY_CURRENT_HEAD.to_string(), } } fn key_caboose(chain_id: ChainId) -> MetaKey { MetaKey { chain_id, key: Self::KEY_CABOOSE.to_string(), } } fn key_genesis(chain_id: ChainId) -> MetaKey { MetaKey { chain_id, key: Self::KEY_GENESIS.to_string(), } } fn key_test_chain_id(chain_id: ChainId) -> MetaKey { MetaKey { chain_id, key: Self::KEY_TEST_CHAIN_ID.to_string(), } } } impl Encoder for MetaKey { fn encode(&self) -> Result<Vec<u8>, SchemaError> { if self.chain_id.as_ref().len() == Self::LEN_CHAIN_ID { let mut bytes = Vec::with_capacity(Self::LEN_CHAIN_ID); bytes.extend(self.chain_id.as_ref()); bytes.extend(self.key.encode()?); Ok(bytes) } else { Err(SchemaError::EncodeError) } } } impl Decoder for MetaKey { fn decode(bytes: &[u8]) -> Result<Self, SchemaError> { if bytes.len() > Self::LEN_CHAIN_ID { let chain_id = ChainId::try_from(&bytes[Self::IDX_CHAIN_ID..Self::IDX_KEY])?; let key = String::decode(&bytes[Self::IDX_KEY..])?; Ok(MetaKey { chain_id, key }) } else { Err(SchemaError::DecodeError) } } } #[derive(Serialize, Deserialize)] pub enum MetadataValue { Head(Head), TestChainId(ChainId), } impl BincodeEncoded for MetadataValue {} impl BincodeEncoded for Head {} #[cfg(test)] mod tests { use std::convert::TryInto; use anyhow::Error; use crate::tests_common::TmpStorage; use super::*; #[test] fn test_current_head() -> Result<(), Error> { let tmp_storage = TmpStorage::create_to_out_dir("__test_current_head")?; let index = ChainMetaStorage::new(tmp_storage.storage()); let chain_id1 = "NetXgtSLGNJvNye".try_into()?; let block_1 = Head::new( "BLockGenesisGenesisGenesisGenesisGenesisb83baZgbyZe".try_into()?, 1, vec![], ); let chain_id2 = "NetXjD3HPJJjmcd".try_into()?; let block_2 = Head::new( "BLockGenesisGenesisGenesisGenesisGenesisd6f5afWyME7".try_into()?, 2, vec![], ); // no current heads assert!(index.get_current_head(&chain_id1)?.is_none()); assert!(index.get_current_head(&chain_id2)?.is_none()); // set for chain_id1 index.set_current_head(&chain_id1, block_1.clone())?; assert!(index.get_current_head(&chain_id1)?.is_some()); assert_eq!( index.get_current_head(&chain_id1)?.unwrap().block_hash(), block_1.block_hash() ); assert!(index.get_current_head(&chain_id2)?.is_none()); // set for chain_id2 index.set_current_head(&chain_id2, block_2.clone())?; assert!(index.get_current_head(&chain_id1)?.is_some()); assert_eq!( index.get_current_head(&chain_id1)?.unwrap().block_hash(), block_1.block_hash() ); assert!(index.get_current_head(&chain_id2)?.is_some()); assert_eq!( index.get_current_head(&chain_id2)?.unwrap().block_hash(), block_2.block_hash() ); // update for chain_id1 index.set_current_head(&chain_id1, block_2.clone())?; assert!(index.get_current_head(&chain_id1)?.is_some()); assert_eq!( index.get_current_head(&chain_id1)?.unwrap().block_hash(), block_2.block_hash() ); assert!(index.get_current_head(&chain_id2)?.is_some()); assert_eq!( index.get_current_head(&chain_id2)?.unwrap().block_hash(), block_2.block_hash() ); Ok(()) } #[test] fn test_caboose() -> Result<(), Error> { let tmp_storage = TmpStorage::create_to_out_dir("__test_caboose")?; let index = ChainMetaStorage::new(tmp_storage.storage()); let chain_id1 = "NetXgtSLGNJvNye".try_into()?; let block_1 = Head::new( "BLockGenesisGenesisGenesisGenesisGenesisb83baZgbyZe".try_into()?, 1, vec![], ); let chain_id2 = "NetXjD3HPJJjmcd".try_into()?; let block_2 = Head::new( "BLockGenesisGenesisGenesisGenesisGenesisd6f5afWyME7".try_into()?, 2, vec![], ); // no current heads assert!(index.get_caboose(&chain_id1)?.is_none()); assert!(index.get_caboose(&chain_id2)?.is_none()); // set for chain_id1 index.set_caboose(&chain_id1, block_1.clone())?; assert!(index.get_caboose(&chain_id1)?.is_some()); assert_eq!( index.get_caboose(&chain_id1)?.unwrap().block_hash(), block_1.block_hash() ); assert!(index.get_caboose(&chain_id2)?.is_none()); // set for chain_id2 index.set_caboose(&chain_id2, block_2.clone())?; assert!(index.get_caboose(&chain_id1)?.is_some()); assert_eq!( index.get_caboose(&chain_id1)?.unwrap().block_hash(), block_1.block_hash() ); assert!(index.get_caboose(&chain_id2)?.is_some()); assert_eq!( index.get_caboose(&chain_id2)?.unwrap().block_hash(), block_2.block_hash() ); // update for chain_id1 index.set_caboose(&chain_id1, block_2.clone())?; assert!(index.get_caboose(&chain_id1)?.is_some()); assert_eq!( index.get_caboose(&chain_id1)?.unwrap().block_hash(), block_2.block_hash() ); assert!(index.get_caboose(&chain_id2)?.is_some()); assert_eq!( index.get_caboose(&chain_id2)?.unwrap().block_hash(), block_2.block_hash() ); Ok(()) } #[test] fn test_genesis() -> Result<(), Error> { let tmp_storage = TmpStorage::create_to_out_dir("__test_genesis")?; let index = ChainMetaStorage::new(tmp_storage.storage()); let chain_id1 = "NetXgtSLGNJvNye".try_into()?; let block_1 = Head::new( "BLockGenesisGenesisGenesisGenesisGenesisb83baZgbyZe".try_into()?, 1, vec![], ); let chain_id2 = "NetXjD3HPJJjmcd".try_into()?; let block_2 = Head::new( "BLockGenesisGenesisGenesisGenesisGenesisd6f5afWyME7".try_into()?, 2, vec![], ); // no current heads assert!(index.get_genesis(&chain_id1)?.is_none()); assert!(index.get_genesis(&chain_id2)?.is_none()); // set for chain_id1 index.set_genesis(&chain_id1, block_1.clone())?; assert!(index.get_genesis(&chain_id1)?.is_some()); assert_eq!( index.get_genesis(&chain_id1)?.unwrap().block_hash(), block_1.block_hash() ); assert!(index.get_genesis(&chain_id2)?.is_none()); // set for chain_id2 index.set_genesis(&chain_id2, block_2.clone())?; assert!(index.get_genesis(&chain_id1)?.is_some()); assert_eq!( index.get_genesis(&chain_id1)?.unwrap().block_hash(), block_1.block_hash() ); assert!(index.get_genesis(&chain_id2)?.is_some()); assert_eq!( index.get_genesis(&chain_id2)?.unwrap().block_hash(), block_2.block_hash() ); // update for chain_id1 index.set_genesis(&chain_id1, block_2.clone())?; assert!(index.get_genesis(&chain_id1)?.is_some()); assert_eq!( index.get_genesis(&chain_id1)?.unwrap().block_hash(), block_2.block_hash() ); assert!(index.get_genesis(&chain_id2)?.is_some()); assert_eq!( index.get_genesis(&chain_id2)?.unwrap().block_hash(), block_2.block_hash() ); Ok(()) } #[test] fn test_test_chain_id() -> Result<(), Error> { let tmp_storage = TmpStorage::create_to_out_dir("__test_test_chain_id")?; let index = ChainMetaStorage::new(tmp_storage.storage()); let chain_id1 = "NetXgtSLGNJvNye".try_into()?; let chain_id2 = "NetXjD3HPJJjmcd".try_into()?; let chain_id3 = "NetXjD3HPJJjmcd".try_into()?; assert!(index.get_test_chain_id(&chain_id1)?.is_none()); assert!(index.get_test_chain_id(&chain_id2)?.is_none()); // update for chain_id1 index.set_test_chain_id(&chain_id1, &chain_id3)?; assert!(index.get_test_chain_id(&chain_id1)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id1)?.unwrap(), chain_id3); assert!(index.get_test_chain_id(&chain_id2)?.is_none()); // update for chain_id2 index.set_test_chain_id(&chain_id2, &chain_id3)?; assert!(index.get_test_chain_id(&chain_id1)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id1)?.unwrap(), chain_id3); assert!(index.get_test_chain_id(&chain_id2)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id2)?.unwrap(), chain_id3); // update for chain_id1 index.set_test_chain_id(&chain_id1, &chain_id2)?; assert!(index.get_test_chain_id(&chain_id1)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id1)?.unwrap(), chain_id2); assert!(index.get_test_chain_id(&chain_id2)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id2)?.unwrap(), chain_id3); // remove for chain_id1 index.remove_test_chain_id(&chain_id1)?; assert!(index.get_test_chain_id(&chain_id1)?.is_none()); assert!(index.get_test_chain_id(&chain_id2)?.is_some()); assert_eq!(index.get_test_chain_id(&chain_id2)?.unwrap(), chain_id3); Ok(()) } }
33.372
132
0.604099
75dce5032884ebd66aefb38c8bb204663fbccb0a
1,990
use std::fs; use std::io; pub struct File { path: String, metadata: Option<fs::Metadata>, bytes: Option<Vec<u8>>, std_file: Option<std::fs::File> } pub fn new_file(path: &str) -> File { File { path: String::from(path), bytes: None, metadata: None, std_file: None } } impl File { pub fn get_bytes(&mut self) -> &Vec<u8> { let path = self.path.clone(); self.bytes.get_or_insert_with(|| { match fs::read(&path) { Ok(bytes) => { bytes } Err(e) => { if e.kind() == io::ErrorKind::PermissionDenied { eprintln!("please run again with appropriate permissions."); } panic!("{}", e); } } }) } pub fn get_metadata(&mut self) -> &fs::Metadata { let path = self.path.clone(); self.metadata.get_or_insert_with(|| { match fs::metadata(&path) { Ok(metadata) => { metadata } Err(e) => { panic!("{}", e); } } }) } pub fn get_std_file(&mut self) -> &std::fs::File { let path = self.path.clone(); self.std_file.get_or_insert_with(|| { match std::fs::File::open(path) { Ok(std_file) => { std_file } Err(e) => { panic!("{}", e); } } }) } pub fn new_std_file(&mut self) -> &std::fs::File { let path = self.path.clone(); self.std_file.get_or_insert_with(|| { match std::fs::File::create(path) { Ok(std_file) => { std_file } Err(e) => { panic!("{}", e); } } }) } }
25.512821
84
0.39196
f846d7d8c80af32c0dd2403d46fb7ce08359879c
4,555
use crate::drivers::NET_DRIVERS; use crate::drivers::Driver; use crate::drivers::net::virtio_net::VirtIONetDriver; use crate::net::SOCKETS; use crate::thread; use alloc::vec; use core::fmt::Write; use alloc::collections::BTreeMap; use alloc::sync::Arc; use smoltcp::socket::*; use smoltcp::wire::*; use smoltcp::iface::*; use smoltcp::time::Instant; pub extern "C" fn server(_arg: usize) -> ! { warn!("NET Server starting ... "); if NET_DRIVERS.read().len() < 1 { loop { //thread::yield_now(); } } warn!("NET_DRIVERS OK !"); let driver = { let ref_driver = Arc::clone(&NET_DRIVERS.write()[0]); // TODO: support multiple net drivers here ref_driver.as_any().downcast_ref::<VirtIONetDriver>().unwrap().clone() }; let ethernet_addr = driver.get_mac(); let ip_addrs = [IpCidr::new(IpAddress::v4(192, 168, 100, 15), 24)]; let neighbor_cache = NeighborCache::new(BTreeMap::new()); let mut iface = EthernetInterfaceBuilder::new(driver) .ethernet_addr(ethernet_addr) .ip_addrs(ip_addrs) .neighbor_cache(neighbor_cache) .finalize(); let udp_rx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 64]); let udp_tx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 128]); let udp_socket = UdpSocket::new(udp_rx_buffer, udp_tx_buffer); let tcp_rx_buffer = TcpSocketBuffer::new(vec![0; 1024]); let tcp_tx_buffer = TcpSocketBuffer::new(vec![0; 1024]); let tcp_socket = TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer); let tcp2_rx_buffer = TcpSocketBuffer::new(vec![0; 1024]); let tcp2_tx_buffer = TcpSocketBuffer::new(vec![0; 1024]); let tcp2_socket = TcpSocket::new(tcp2_rx_buffer, tcp2_tx_buffer); let mut sockets = SOCKETS.lock(); let udp_handle = sockets.add(udp_socket); let tcp_handle = sockets.add(tcp_socket); let tcp2_handle = sockets.add(tcp2_socket); loop { { let timestamp = Instant::from_millis(unsafe { crate::trap::TICK as i64 }); match iface.poll(&mut sockets, timestamp) { Ok(event) => { if (!event) { continue; } }, Err(e) => { println!("TICK: {}, iface.poll error: {}", unsafe { crate::trap::TICK }, e); } } // udp server { let mut socket = sockets.get::<UdpSocket>(udp_handle); if !socket.is_open() { socket.bind(6969).unwrap(); } let client = match socket.recv() { Ok((payload_buf, endpoint)) => { println!("{:?}", payload_buf); Some(endpoint) } Err(_) => None, }; if let Some(endpoint) = client { let hello = b"Hello from 6969\n"; socket.send_slice(hello, endpoint).unwrap(); } } // simple http server { let mut socket = sockets.get::<TcpSocket>(tcp_handle); if !socket.is_open() { socket.listen(80).unwrap(); warn!("HTTP Server, socket listen state: {:?}, local_endpoint: {:?}, remote_endpoint: {:?}", socket.state(), socket.local_endpoint(), socket.remote_endpoint()); } if socket.can_send() { write!(socket, "HTTP/1.1 200 OK\r\nServer: rCore\r\nContent-Length: 13\r\nContent-Type: text/html\r\nConnection: Closed\r\n\r\nHello World ! from rCore\r\n").unwrap(); socket.close(); } } // simple tcp server that just eats everything { let mut socket = sockets.get::<TcpSocket>(tcp2_handle); if !socket.is_open() { socket.listen(2222).unwrap(); } if socket.can_recv() { let mut data = [0u8; 2048]; let size = socket.recv_slice(&mut data).unwrap(); //let mut string = String::new(); /* for u in data.iter() { println!("{:?}", u); } */ } } } trace!("loop()\n"); //thread::yield_now(); } }
35.310078
187
0.512184
7565d7cb3fa1206cda7822f41599171295ec3002
19,334
// Copyright (c) 2021-present, Cruise LLC // // This source code is licensed under the Apache License, Version 2.0, // found in the LICENSE-APACHE file in the root directory of this source tree. // You may not use this file except in compliance with the License. //! Font drawing primitives. use std::sync::RwLock; use std::sync::RwLockReadGuard; use crate::*; use wrflib_vector::geometry::Trapezoid; use wrflib_vector::geometry::{AffineTransformation, Transform, Vector}; use wrflib_vector::internal_iter::*; use wrflib_vector::path::PathIterator; use wrflib_vector::trapezoidator::Trapezoidator; /// The default [Ubuntu font](https://design.ubuntu.com/font/). const FONT_UBUNTU_REGULAR: Font = Font { font_id: 0 }; /// The monospace [Liberation mono font](https://en.wikipedia.org/wiki/Liberation_fonts). const FONT_LIBERATION_MONO_REGULAR: Font = Font { font_id: 1 }; /// Actual font data; should match the font_ids above. #[cfg(not(feature = "disable-fonts"))] const FONTS_BYTES: &[&[u8]] = &[include_bytes!("../resources/Ubuntu-R.ttf"), include_bytes!("../resources/LiberationMono-Regular.ttf")]; /// The default [`TextStyle`]. pub const TEXT_STYLE_NORMAL: TextStyle = TextStyle { font: FONT_UBUNTU_REGULAR, font_size: 8.0, brightness: 1.0, curve: 0.6, line_spacing: 1.4, top_drop: 1.2, height_factor: 1.3, }; /// A monospace [`TextStyle`]. pub const TEXT_STYLE_MONO: TextStyle = TextStyle { font: FONT_LIBERATION_MONO_REGULAR, brightness: 1.1, font_size: 8.0, line_spacing: 1.8, top_drop: 1.3, ..TEXT_STYLE_NORMAL }; /// A pointer to a [`CxFont`] (indexed in [`CxFontsData::fonts`] using [`Font::font_id`]), #[derive(Copy, Clone, PartialEq, Debug)] pub struct Font { pub font_id: usize, } /// Style for how to render text. /// TODO(hernan): Should we include color and font scaling as part of the text style? #[derive(Clone, Debug, Copy)] pub struct TextStyle { pub font: Font, pub font_size: f32, pub brightness: f32, pub curve: f32, pub line_spacing: f32, pub top_drop: f32, pub height_factor: f32, } impl Default for TextStyle { fn default() -> Self { TextStyle { font: Font { font_id: 0 }, font_size: 8.0, brightness: 1.0, curve: 0.6, line_spacing: 1.4, top_drop: 1.1, height_factor: 1.3, } } } impl Cx { pub(crate) fn load_fonts(&mut self) { #[cfg(not(feature = "disable-fonts"))] { let mut write_fonts_data = self.fonts_data.write().unwrap(); write_fonts_data.fonts = Iterator::map(FONTS_BYTES.iter(), |bytes| { let font = wrflib_vector::ttf_parser::parse_ttf(bytes).expect("Error loading font"); CxFont { font_loaded: Some(font), atlas_pages: vec![] } }) .collect(); } } pub fn reset_font_atlas_and_redraw(&mut self) { { // Use a block here to constraint the lifetime of locks let mut write_fonts = self.fonts_data.write().unwrap(); for font in &mut write_fonts.fonts { font.atlas_pages.truncate(0); } write_fonts.fonts_atlas.alloc_xpos = 0.; write_fonts.fonts_atlas.alloc_ypos = 0.; write_fonts.fonts_atlas.alloc_hmax = 0.; write_fonts.fonts_atlas.clear_buffer = true; } self.request_draw(); } } static SHADER: Shader = Shader { build_geom: Some(QuadIns::build_geom), code_to_concatenate: &[ Cx::STD_SHADER, code_fragment!( r#" geometry geom: vec2; // trapezoid instance a_xs: vec2; instance a_ys: vec4; // index instance chan: float; varying v_p0: vec2; varying v_p1: vec2; varying v_p2: vec2; varying v_p3: vec2; varying v_pixel: vec2; fn intersect_line_segment_with_vertical_line(p0: vec2, p1: vec2, x: float) -> vec2 { return vec2( x, mix(p0.y, p1.y, (x - p0.x) / (p1.x - p0.x)) ); } fn intersect_line_segment_with_horizontal_line(p0: vec2, p1: vec2, y: float) -> vec2 { return vec2( mix(p0.x, p1.x, (y - p0.y) / (p1.y - p0.y)), y ); } fn compute_clamped_right_trapezoid_area(p0: vec2, p1: vec2, p_min: vec2, p_max: vec2) -> float { let x0 = clamp(p0.x, p_min.x, p_max.x); let x1 = clamp(p1.x, p_min.x, p_max.x); if (p0.x < p_min.x && p_min.x < p1.x) { p0 = intersect_line_segment_with_vertical_line(p0, p1, p_min.x); } if (p0.x < p_max.x && p_max.x < p1.x) { p1 = intersect_line_segment_with_vertical_line(p0, p1, p_max.x); } if (p0.y < p_min.y && p_min.y < p1.y) { p0 = intersect_line_segment_with_horizontal_line(p0, p1, p_min.y); } if (p1.y < p_min.y && p_min.y < p0.y) { p1 = intersect_line_segment_with_horizontal_line(p1, p0, p_min.y); } if (p0.y < p_max.y && p_max.y < p1.y) { p1 = intersect_line_segment_with_horizontal_line(p0, p1, p_max.y); } if (p1.y < p_max.y && p_max.y < p0.y) { p0 = intersect_line_segment_with_horizontal_line(p1, p0, p_max.y); } p0 = clamp(p0, p_min, p_max); p1 = clamp(p1, p_min, p_max); let h0 = p_max.y - p0.y; let h1 = p_max.y - p1.y; let a0 = (p0.x - x0) * h0; let a1 = (p1.x - p0.x) * (h0 + h1) * 0.5; let a2 = (x1 - p1.x) * h1; return a0 + a1 + a2; } fn compute_clamped_trapezoid_area(p_min: vec2, p_max: vec2) -> float { let a0 = compute_clamped_right_trapezoid_area(v_p0, v_p1, p_min, p_max); let a1 = compute_clamped_right_trapezoid_area(v_p2, v_p3, p_min, p_max); return a0 - a1; } fn pixel() -> vec4 { let p_min = v_pixel.xy - 0.5; let p_max = v_pixel.xy + 0.5; let t_area = compute_clamped_trapezoid_area(p_min, p_max); if chan < 0.5 { return vec4(t_area, 0., 0., 0.); } if chan < 1.5 { return vec4(0., t_area, 0., 0.); } if chan < 2.5 { return vec4(0., 0., t_area, 0.); } return vec4(t_area, t_area, t_area, 0.); } fn vertex() -> vec4 { let pos_min = vec2(a_xs.x, min(a_ys.x, a_ys.y)); let pos_max = vec2(a_xs.y, max(a_ys.z, a_ys.w)); let pos = mix(pos_min - 1.0, pos_max + 1.0, geom); // set the varyings v_p0 = vec2(a_xs.x, a_ys.x); v_p1 = vec2(a_xs.y, a_ys.y); v_p2 = vec2(a_xs.x, a_ys.z); v_p3 = vec2(a_xs.y, a_ys.w); v_pixel = pos; return camera_projection * vec4(pos, 0.0, 1.0); }"# ), ], ..Shader::DEFAULT }; #[derive(Clone, Default)] pub(crate) struct TrapezoidText { trapezoidator: Trapezoidator, } impl TrapezoidText { // test api for directly drawing a glyph /* pub(crate) fn draw_char(&mut self, cx: &mut Cx, c: char, font_id: usize, font_size: f32) { // now lets make a draw_character function let trapezoids = { let cxfont = &cx.fonts[font_id]; let font = cxfont.font_loaded.as_ref().unwrap(); let slot = if c < '\u{10000}' { cx.fonts[font_id].font_loaded.as_ref().unwrap().char_code_to_glyph_index_map[c as usize] } else { 0 }; if slot == 0 { return; } let glyph = &cx.fonts[font_id].font_loaded.as_ref().unwrap().glyphs[slot]; let dpi_factor = cx.current_dpi_factor; let pos = cx.get_draw_pos(); let font_scale_logical = font_size * 96.0 / (72.0 * font.units_per_em); let font_scale_pixels = font_scale_logical * dpi_factor; let mut trapezoids = Vec::new(); let trapezoidate = self.trapezoidator.trapezoidate( glyph .outline .commands() .map({ move |command| { command.transform( &AffineTransformation::identity() .translate(Vector::new(-glyph.bounds.p_min.x, -glyph.bounds.p_min.y)) .uniform_scale(font_scale_pixels) .translate(Vector::new(pos.x, pos.y)), ) } }) .linearize(0.5), ); if let Some(trapezoidate) = trapezoidate { trapezoids.extend_from_internal_iter(trapezoidate); } trapezoids }; for trapezoid in trapezoids { let data = [trapezoid.xs[0], trapezoid.xs[1], trapezoid.ys[0], trapezoid.ys[1], trapezoid.ys[2], trapezoid.ys[3], 3.0]; many.instances.extend_from_slice(&data); } } */ // atlas drawing function used by CxAfterDraw fn draw_todo(&mut self, cx: &mut Cx, todo: CxFontsAtlasTodo, instances: &mut Vec<(Trapezoid, f32)>) { let mut size = 1.0; for i in 0..3 { if i == 1 { size = 0.75; } if i == 2 { size = 0.6; } let read_fonts = cx.fonts_data.read().unwrap(); let trapezoids = { let cxfont = &read_fonts.fonts[todo.font_id]; let font = cxfont.font_loaded.as_ref().unwrap(); let atlas_page = &cxfont.atlas_pages[todo.atlas_page_id]; let glyph = &font.glyphs[todo.glyph_id]; if todo.glyph_id == font.char_code_to_glyph_index_map[10] || todo.glyph_id == font.char_code_to_glyph_index_map[9] || todo.glyph_id == font.char_code_to_glyph_index_map[13] { return; } let glyphtc = atlas_page.atlas_glyphs[todo.glyph_id][todo.subpixel_id].unwrap(); let texture_size = read_fonts.fonts_atlas.texture_size; let tx = glyphtc.tx1 * texture_size.x + todo.subpixel_x_fract * atlas_page.dpi_factor; let ty = 1.0 + glyphtc.ty1 * texture_size.y - todo.subpixel_y_fract * atlas_page.dpi_factor; let font_scale_logical = atlas_page.font_size * 96.0 / (72.0 * font.units_per_em); let font_scale_pixels = font_scale_logical * atlas_page.dpi_factor; assert!(font_scale_logical > 0.); assert!(font_scale_pixels > 0.); let mut trapezoids = Vec::new(); let trapezoidate = self.trapezoidator.trapezoidate( glyph .outline .commands() .map({ move |command| { command.transform( &AffineTransformation::identity() .translate(Vector::new(-glyph.bounds.p_min.x, -glyph.bounds.p_min.y)) .uniform_scale(font_scale_pixels * size) .translate(Vector::new(tx, ty)), ) } }) .linearize(0.5), ); if let Some(trapezoidate) = trapezoidate { trapezoidate.for_each(&mut |item| { trapezoids.push(item); true }); } trapezoids }; for trapezoid in trapezoids { instances.push((trapezoid, i as f32)); } } } } /// Some font-related stuff gets drawn at the end of each draw cycle. /// /// TODO(JP): This feels pretty arbitrary / one-off; find a way to better integrate this into the /// normal draw cycle. pub struct CxAfterDraw { pub(crate) trapezoid_text: TrapezoidText, pub(crate) atlas_pass: Pass, pub(crate) atlas_view: View, pub(crate) atlas_texture_handle: TextureHandle, pub(crate) counter: usize, } impl CxAfterDraw { pub fn new(cx: &mut Cx) -> Self { let atlas_texture_handle = { let mut texture = Texture::default(); let texture_handle = texture.get_color(cx); let mut fonts_atlas = &mut cx.fonts_data.write().unwrap().fonts_atlas; fonts_atlas.texture_size = Vec2 { x: 2048.0, y: 2048.0 }; fonts_atlas.texture_handle = Some(texture_handle); texture_handle }; Self { counter: 0, trapezoid_text: TrapezoidText::default(), atlas_pass: Pass::default(), atlas_view: View::default(), atlas_texture_handle, } } pub fn after_draw(&mut self, cx: &mut Cx) { //let start = Cx::profile_time_ns(); // we need to start a pass that just uses the texture if !cx.fonts_data.read().unwrap().fonts_atlas.atlas_todo.is_empty() { self.atlas_pass.begin_pass_without_textures(cx); let pass_size = cx.fonts_data.read().unwrap().fonts_atlas.texture_size; self.atlas_pass.set_size(cx, pass_size); let clear = if cx.fonts_data.read().unwrap().fonts_atlas.clear_buffer { cx.fonts_data.write().unwrap().fonts_atlas.clear_buffer = false; ClearColor::ClearWith(Vec4::default()) } else { ClearColor::InitWith(Vec4::default()) }; self.atlas_pass.add_color_texture(cx, self.atlas_texture_handle, clear); let _ = self.atlas_view.begin_view(cx, LayoutSize::FILL); let mut atlas_todo = Vec::new(); std::mem::swap(&mut cx.fonts_data.write().unwrap().fonts_atlas.atlas_todo, &mut atlas_todo); let mut instances = vec![]; for todo in atlas_todo { self.trapezoid_text.draw_todo(cx, todo, &mut instances); } cx.add_instances(&SHADER, &instances); self.counter += 1; self.atlas_view.end_view(cx); self.atlas_pass.end_pass(cx); } //println!("TOTALT TIME {}", Cx::profile_time_ns() - start); } } #[derive(Default, Debug, Clone)] pub(crate) struct CxFont { pub(crate) font_loaded: Option<wrflib_vector::font::VectorFont>, pub(crate) atlas_pages: Vec<CxFontAtlasPage>, } const ATLAS_SUBPIXEL_SLOTS: usize = 64; #[derive(Clone, Debug)] pub(crate) struct CxFontAtlasPage { dpi_factor: f32, font_size: f32, pub(crate) atlas_glyphs: Vec<[Option<CxFontAtlasGlyph>; ATLAS_SUBPIXEL_SLOTS]>, } #[derive(Clone, Copy, Debug)] pub(crate) struct CxFontAtlasGlyph { pub(crate) tx1: f32, pub(crate) ty1: f32, pub(crate) tx2: f32, pub(crate) ty2: f32, } #[derive(Default, Debug)] pub(crate) struct CxFontsAtlasTodo { pub(crate) subpixel_x_fract: f32, pub(crate) subpixel_y_fract: f32, pub(crate) font_id: usize, pub(crate) atlas_page_id: usize, pub(crate) glyph_id: usize, pub(crate) subpixel_id: usize, } /// An "atlas" for font glyphs, which is like a cached version of glyphs. #[derive(Debug, Default)] pub(crate) struct CxFontsAtlas { texture_handle: Option<TextureHandle>, texture_size: Vec2, clear_buffer: bool, alloc_xpos: f32, alloc_ypos: f32, alloc_hmax: f32, pub(crate) atlas_todo: Vec<CxFontsAtlasTodo>, } /// Get the page id for a particular font_id/dpi_factor/font_size combination. /// /// Returns a read lock in addition to the page id, since you typically need to read more stuff out of /// `fonts_data`, and this avoids you having to get another lock after this. pub fn get_font_atlas_page_id( fonts_data: &RwLock<CxFontsData>, font_id: usize, dpi_factor: f32, font_size: f32, ) -> (usize, RwLockReadGuard<CxFontsData>) { let fonts_data_read_lock = fonts_data.read().unwrap(); for (index, sg) in fonts_data_read_lock.fonts[font_id].atlas_pages.iter().enumerate() { #[allow(clippy::float_cmp)] if sg.dpi_factor == dpi_factor && sg.font_size == font_size { return (index, fonts_data_read_lock); } } let glyphs_len = match &fonts_data_read_lock.fonts[font_id].font_loaded { Some(font) => font.glyphs.len(), _ => panic!("Font not loaded {}", font_id), }; drop(fonts_data_read_lock); let glyph_index = { let write_fonts_atlas_pages = &mut fonts_data.write().unwrap().fonts[font_id].atlas_pages; write_fonts_atlas_pages.push(CxFontAtlasPage { dpi_factor, font_size, atlas_glyphs: { let mut v = Vec::new(); v.resize(glyphs_len, [None; ATLAS_SUBPIXEL_SLOTS]); v }, }); write_fonts_atlas_pages.len() - 1 }; (glyph_index, fonts_data.read().unwrap()) } impl CxFontsAtlas { pub fn alloc_atlas_glyph(&mut self, w: f32, h: f32) -> CxFontAtlasGlyph { if w + self.alloc_xpos >= self.texture_size.x { self.alloc_xpos = 0.0; self.alloc_ypos += self.alloc_hmax + 1.0; self.alloc_hmax = 0.0; } if h + self.alloc_ypos >= self.texture_size.y { println!("FONT ATLAS FULL, TODO FIX THIS"); } if h > self.alloc_hmax { self.alloc_hmax = h; } let tx1 = self.alloc_xpos / self.texture_size.x; let ty1 = self.alloc_ypos / self.texture_size.y; self.alloc_xpos += w + 1.0; if h > self.alloc_hmax { self.alloc_hmax = h; } CxFontAtlasGlyph { tx1, ty1, tx2: tx1 + (w / self.texture_size.x), ty2: ty1 + (h / self.texture_size.y) } } } /// A context object containing everything font releated. This is used in different places to render text /// and also #[derive(Debug, Default)] pub struct CxFontsData { /// List of actual [`CxFont`] objects. [`Font::font_id`] represents an index in this list. pub(crate) fonts: Vec<CxFont>, /// See [`CxFontsAtlas`]. pub(crate) fonts_atlas: CxFontsAtlas, } impl CxFontsData { pub fn get_fonts_atlas_texture_handle(&self) -> TextureHandle { self.fonts_atlas.texture_handle.unwrap() } pub fn new_dummy_for_tests() -> Self { CxFontsData::default() } }
35.671587
124
0.546343
f719ce150924f0652d28bdb55657a72923dbaeb5
32,261
// Copyright 2017 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. //! This module contains `HashStable` implementations for various data types //! from rustc::ty in no particular order. use ich::{StableHashingContext, NodeIdHashingMode}; use rustc_data_structures::stable_hasher::{HashStable, ToStableHashKey, StableHasher, StableHasherResult}; use std::hash as std_hash; use std::mem; use middle::region; use traits; use ty; impl<'gcx, T> HashStable<StableHashingContext<'gcx>> for &'gcx ty::Slice<T> where T: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { (&self[..]).hash_stable(hcx, hasher); } } impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::subst::Kind<'gcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { self.as_type().hash_stable(hcx, hasher); self.as_region().hash_stable(hcx, hasher); } } impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::RegionKind { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::ReErased | ty::ReStatic | ty::ReEmpty => { // No variant fields to hash for these ... } ty::ReLateBound(db, ty::BrAnon(i)) => { db.depth.hash_stable(hcx, hasher); i.hash_stable(hcx, hasher); } ty::ReLateBound(db, ty::BrNamed(def_id, name)) => { db.depth.hash_stable(hcx, hasher); def_id.hash_stable(hcx, hasher); name.hash_stable(hcx, hasher); } ty::ReLateBound(db, ty::BrEnv) => { db.depth.hash_stable(hcx, hasher); } ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, index, name }) => { def_id.hash_stable(hcx, hasher); index.hash_stable(hcx, hasher); name.hash_stable(hcx, hasher); } ty::ReScope(scope) => { scope.hash_stable(hcx, hasher); } ty::ReFree(ref free_region) => { free_region.hash_stable(hcx, hasher); } ty::ReLateBound(..) | ty::ReVar(..) | ty::ReSkolemized(..) => { bug!("TypeIdHasher: unexpected region {:?}", *self) } } } } impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::adjustment::AutoBorrow<'gcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::adjustment::AutoBorrow::Ref(ref region, mutability) => { region.hash_stable(hcx, hasher); mutability.hash_stable(hcx, hasher); } ty::adjustment::AutoBorrow::RawPtr(mutability) => { mutability.hash_stable(hcx, hasher); } } } } impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::adjustment::Adjust<'gcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::adjustment::Adjust::NeverToAny | ty::adjustment::Adjust::ReifyFnPointer | ty::adjustment::Adjust::UnsafeFnPointer | ty::adjustment::Adjust::ClosureFnPointer | ty::adjustment::Adjust::MutToConstPointer | ty::adjustment::Adjust::Unsize => {} ty::adjustment::Adjust::Deref(ref overloaded) => { overloaded.hash_stable(hcx, hasher); } ty::adjustment::Adjust::Borrow(ref autoref) => { autoref.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(struct ty::adjustment::Adjustment<'tcx> { kind, target }); impl_stable_hash_for!(struct ty::adjustment::OverloadedDeref<'tcx> { region, mutbl }); impl_stable_hash_for!(struct ty::UpvarBorrow<'tcx> { kind, region }); impl_stable_hash_for!(struct ty::UpvarId { var_id, closure_expr_id }); impl_stable_hash_for!(enum ty::BorrowKind { ImmBorrow, UniqueImmBorrow, MutBorrow }); impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::UpvarCapture<'gcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::UpvarCapture::ByValue => {} ty::UpvarCapture::ByRef(ref up_var_borrow) => { up_var_borrow.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(struct ty::GenSig<'tcx> { yield_ty, return_ty }); impl_stable_hash_for!(struct ty::FnSig<'tcx> { inputs_and_output, variadic, unsafety, abi }); impl<'gcx, T> HashStable<StableHashingContext<'gcx>> for ty::Binder<T> where T: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let ty::Binder(ref inner) = *self; inner.hash_stable(hcx, hasher); } } impl_stable_hash_for!(enum ty::ClosureKind { Fn, FnMut, FnOnce }); impl_stable_hash_for!(enum ty::Visibility { Public, Restricted(def_id), Invisible }); impl_stable_hash_for!(struct ty::TraitRef<'tcx> { def_id, substs }); impl_stable_hash_for!(struct ty::TraitPredicate<'tcx> { trait_ref }); impl_stable_hash_for!(tuple_struct ty::EquatePredicate<'tcx> { t1, t2 }); impl_stable_hash_for!(struct ty::SubtypePredicate<'tcx> { a_is_expected, a, b }); impl<'gcx, A, B> HashStable<StableHashingContext<'gcx>> for ty::OutlivesPredicate<A, B> where A: HashStable<StableHashingContext<'gcx>>, B: HashStable<StableHashingContext<'gcx>>, { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let ty::OutlivesPredicate(ref a, ref b) = *self; a.hash_stable(hcx, hasher); b.hash_stable(hcx, hasher); } } impl_stable_hash_for!(struct ty::ProjectionPredicate<'tcx> { projection_ty, ty }); impl_stable_hash_for!(struct ty::ProjectionTy<'tcx> { substs, item_def_id }); impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::Predicate<'gcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::Predicate::Trait(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::Equate(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::Subtype(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::RegionOutlives(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::TypeOutlives(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::Projection(ref pred) => { pred.hash_stable(hcx, hasher); } ty::Predicate::WellFormed(ty) => { ty.hash_stable(hcx, hasher); } ty::Predicate::ObjectSafe(def_id) => { def_id.hash_stable(hcx, hasher); } ty::Predicate::ClosureKind(def_id, closure_kind) => { def_id.hash_stable(hcx, hasher); closure_kind.hash_stable(hcx, hasher); } ty::Predicate::ConstEvaluatable(def_id, substs) => { def_id.hash_stable(hcx, hasher); substs.hash_stable(hcx, hasher); } } } } impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::AdtFlags { fn hash_stable<W: StableHasherResult>(&self, _: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { std_hash::Hash::hash(self, hasher); } } impl_stable_hash_for!(struct ty::VariantDef { did, name, discr, fields, ctor_kind }); impl_stable_hash_for!(enum ty::VariantDiscr { Explicit(def_id), Relative(distance) }); impl_stable_hash_for!(struct ty::FieldDef { did, name, vis }); impl<'gcx> HashStable<StableHashingContext<'gcx>> for ::middle::const_val::ConstVal<'gcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { use middle::const_val::ConstVal::*; use middle::const_val::ConstAggregate::*; mem::discriminant(self).hash_stable(hcx, hasher); match *self { Integral(ref value) => { value.hash_stable(hcx, hasher); } Float(ref value) => { value.hash_stable(hcx, hasher); } Str(ref value) => { value.hash_stable(hcx, hasher); } ByteStr(ref value) => { value.hash_stable(hcx, hasher); } Bool(value) => { value.hash_stable(hcx, hasher); } Char(value) => { value.hash_stable(hcx, hasher); } Variant(def_id) => { def_id.hash_stable(hcx, hasher); } Function(def_id, substs) => { def_id.hash_stable(hcx, hasher); hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| { substs.hash_stable(hcx, hasher); }); } Aggregate(Struct(ref name_values)) => { let mut values = name_values.to_vec(); values.sort_unstable_by_key(|&(ref name, _)| name.clone()); values.hash_stable(hcx, hasher); } Aggregate(Tuple(ref value)) => { value.hash_stable(hcx, hasher); } Aggregate(Array(ref value)) => { value.hash_stable(hcx, hasher); } Aggregate(Repeat(ref value, times)) => { value.hash_stable(hcx, hasher); times.hash_stable(hcx, hasher); } Unevaluated(def_id, substs) => { def_id.hash_stable(hcx, hasher); substs.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(struct ::middle::const_val::ByteArray<'tcx> { data }); impl_stable_hash_for!(struct ty::Const<'tcx> { ty, val }); impl_stable_hash_for!(struct ::middle::const_val::ConstEvalErr<'tcx> { span, kind }); impl<'gcx> HashStable<StableHashingContext<'gcx>> for ::middle::const_val::ErrKind<'gcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { use middle::const_val::ErrKind::*; mem::discriminant(self).hash_stable(hcx, hasher); match *self { CannotCast | MissingStructField | NonConstPath | ExpectedConstTuple | ExpectedConstStruct | IndexedNonVec | IndexNotUsize | MiscBinaryOp | MiscCatchAll | IndexOpFeatureGated | TypeckError => { // nothing to do } UnimplementedConstVal(s) => { s.hash_stable(hcx, hasher); } IndexOutOfBounds { len, index } => { len.hash_stable(hcx, hasher); index.hash_stable(hcx, hasher); } Math(ref const_math_err) => { const_math_err.hash_stable(hcx, hasher); } LayoutError(ref layout_error) => { layout_error.hash_stable(hcx, hasher); } ErroneousReferencedConstant(ref const_val) => { const_val.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(struct ty::ClosureSubsts<'tcx> { substs }); impl_stable_hash_for!(struct ty::GeneratorInterior<'tcx> { witness }); impl_stable_hash_for!(struct ty::GenericPredicates<'tcx> { parent, predicates }); impl_stable_hash_for!(enum ty::Variance { Covariant, Invariant, Contravariant, Bivariant }); impl_stable_hash_for!(enum ty::adjustment::CustomCoerceUnsized { Struct(index) }); impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::Generics { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let ty::Generics { parent, parent_regions, parent_types, ref regions, ref types, // Reverse map to each `TypeParameterDef`'s `index` field, from // `def_id.index` (`def_id.krate` is the same as the item's). type_param_to_index: _, // Don't hash this has_self, has_late_bound_regions, } = *self; parent.hash_stable(hcx, hasher); parent_regions.hash_stable(hcx, hasher); parent_types.hash_stable(hcx, hasher); regions.hash_stable(hcx, hasher); types.hash_stable(hcx, hasher); has_self.hash_stable(hcx, hasher); has_late_bound_regions.hash_stable(hcx, hasher); } } impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::RegionParameterDef { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let ty::RegionParameterDef { name, def_id, index, pure_wrt_drop } = *self; name.hash_stable(hcx, hasher); def_id.hash_stable(hcx, hasher); index.hash_stable(hcx, hasher); pure_wrt_drop.hash_stable(hcx, hasher); } } impl_stable_hash_for!(struct ty::TypeParameterDef { name, def_id, index, has_default, object_lifetime_default, pure_wrt_drop, synthetic }); impl<'gcx, T> HashStable<StableHashingContext<'gcx>> for ::middle::resolve_lifetime::Set1<T> where T: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { use middle::resolve_lifetime::Set1; mem::discriminant(self).hash_stable(hcx, hasher); match *self { Set1::Empty | Set1::Many => { // Nothing to do. } Set1::One(ref value) => { value.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(enum ::middle::resolve_lifetime::Region { Static, EarlyBound(index, decl), LateBound(db_index, decl), LateBoundAnon(db_index, anon_index), Free(call_site_scope_data, decl) }); impl_stable_hash_for!(struct ty::DebruijnIndex { depth }); impl_stable_hash_for!(enum ty::cast::CastKind { CoercionCast, PtrPtrCast, PtrAddrCast, AddrPtrCast, NumericCast, EnumCast, PrimIntCast, U8CharCast, ArrayPtrCast, FnPtrPtrCast, FnPtrAddrCast }); impl_stable_hash_for!(struct ::middle::region::FirstStatementIndex { idx }); impl_stable_hash_for!(struct ::middle::region::Scope { id, code }); impl<'gcx> ToStableHashKey<StableHashingContext<'gcx>> for region::Scope { type KeyType = region::Scope; #[inline] fn to_stable_hash_key(&self, _: &StableHashingContext<'gcx>) -> region::Scope { *self } } impl_stable_hash_for!(struct ::middle::region::BlockRemainder { block, first_statement_index }); impl_stable_hash_for!(struct ty::adjustment::CoerceUnsizedInfo { custom_kind }); impl_stable_hash_for!(struct ty::FreeRegion { scope, bound_region }); impl_stable_hash_for!(enum ty::BoundRegion { BrAnon(index), BrNamed(def_id, name), BrFresh(index), BrEnv }); impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::TypeVariants<'gcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { use ty::TypeVariants::*; mem::discriminant(self).hash_stable(hcx, hasher); match *self { TyBool | TyChar | TyStr | TyError | TyNever => { // Nothing more to hash. } TyInt(int_ty) => { int_ty.hash_stable(hcx, hasher); } TyUint(uint_ty) => { uint_ty.hash_stable(hcx, hasher); } TyFloat(float_ty) => { float_ty.hash_stable(hcx, hasher); } TyAdt(adt_def, substs) => { adt_def.hash_stable(hcx, hasher); substs.hash_stable(hcx, hasher); } TyArray(inner_ty, len) => { inner_ty.hash_stable(hcx, hasher); len.hash_stable(hcx, hasher); } TySlice(inner_ty) => { inner_ty.hash_stable(hcx, hasher); } TyRawPtr(pointee_ty) => { pointee_ty.hash_stable(hcx, hasher); } TyRef(region, pointee_ty) => { region.hash_stable(hcx, hasher); pointee_ty.hash_stable(hcx, hasher); } TyFnDef(def_id, substs) => { def_id.hash_stable(hcx, hasher); substs.hash_stable(hcx, hasher); } TyFnPtr(ref sig) => { sig.hash_stable(hcx, hasher); } TyDynamic(ref existential_predicates, region) => { existential_predicates.hash_stable(hcx, hasher); region.hash_stable(hcx, hasher); } TyClosure(def_id, closure_substs) => { def_id.hash_stable(hcx, hasher); closure_substs.hash_stable(hcx, hasher); } TyGenerator(def_id, closure_substs, interior) => { def_id.hash_stable(hcx, hasher); closure_substs.hash_stable(hcx, hasher); interior.hash_stable(hcx, hasher); } TyTuple(inner_tys, from_diverging_type_var) => { inner_tys.hash_stable(hcx, hasher); from_diverging_type_var.hash_stable(hcx, hasher); } TyProjection(ref projection_ty) => { projection_ty.hash_stable(hcx, hasher); } TyAnon(def_id, substs) => { def_id.hash_stable(hcx, hasher); substs.hash_stable(hcx, hasher); } TyParam(param_ty) => { param_ty.hash_stable(hcx, hasher); } TyInfer(..) => { bug!("ty::TypeVariants::hash_stable() - Unexpected variant {:?}.", *self) } } } } impl_stable_hash_for!(struct ty::ParamTy { idx, name }); impl_stable_hash_for!(struct ty::TypeAndMut<'tcx> { ty, mutbl }); impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::ExistentialPredicate<'gcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::ExistentialPredicate::Trait(ref trait_ref) => { trait_ref.hash_stable(hcx, hasher); } ty::ExistentialPredicate::Projection(ref projection) => { projection.hash_stable(hcx, hasher); } ty::ExistentialPredicate::AutoTrait(def_id) => { def_id.hash_stable(hcx, hasher); } } } } impl_stable_hash_for!(struct ty::ExistentialTraitRef<'tcx> { def_id, substs }); impl_stable_hash_for!(struct ty::ExistentialProjection<'tcx> { item_def_id, substs, ty }); impl_stable_hash_for!(struct ty::Instance<'tcx> { def, substs }); impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::InstanceDef<'gcx> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { mem::discriminant(self).hash_stable(hcx, hasher); match *self { ty::InstanceDef::Item(def_id) => { def_id.hash_stable(hcx, hasher); } ty::InstanceDef::Intrinsic(def_id) => { def_id.hash_stable(hcx, hasher); } ty::InstanceDef::FnPtrShim(def_id, ty) => { def_id.hash_stable(hcx, hasher); ty.hash_stable(hcx, hasher); } ty::InstanceDef::Virtual(def_id, n) => { def_id.hash_stable(hcx, hasher); n.hash_stable(hcx, hasher); } ty::InstanceDef::ClosureOnceShim { call_once } => { call_once.hash_stable(hcx, hasher); } ty::InstanceDef::DropGlue(def_id, t) => { def_id.hash_stable(hcx, hasher); t.hash_stable(hcx, hasher); } ty::InstanceDef::CloneShim(def_id, t) => { def_id.hash_stable(hcx, hasher); t.hash_stable(hcx, hasher); } } } } impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::TraitDef { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let ty::TraitDef { // We already have the def_path_hash below, no need to hash it twice def_id: _, unsafety, paren_sugar, has_default_impl, def_path_hash, } = *self; unsafety.hash_stable(hcx, hasher); paren_sugar.hash_stable(hcx, hasher); has_default_impl.hash_stable(hcx, hasher); def_path_hash.hash_stable(hcx, hasher); } } impl_stable_hash_for!(struct ty::Destructor { did }); impl_stable_hash_for!(struct ty::DtorckConstraint<'tcx> { outlives, dtorck_types }); impl<'gcx> HashStable<StableHashingContext<'gcx>> for ty::CrateVariancesMap { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let ty::CrateVariancesMap { ref dependencies, ref variances, // This is just an irrelevant helper value. empty_variance: _, } = *self; dependencies.hash_stable(hcx, hasher); variances.hash_stable(hcx, hasher); } } impl_stable_hash_for!(struct ty::AssociatedItem { def_id, name, kind, vis, defaultness, container, method_has_self_argument }); impl_stable_hash_for!(enum ty::AssociatedKind { Const, Method, Type }); impl_stable_hash_for!(enum ty::AssociatedItemContainer { TraitContainer(def_id), ImplContainer(def_id) }); impl<'gcx, T> HashStable<StableHashingContext<'gcx>> for ty::steal::Steal<T> where T: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { self.borrow().hash_stable(hcx, hasher); } } impl_stable_hash_for!(struct ty::ParamEnv<'tcx> { caller_bounds, reveal }); impl_stable_hash_for!(enum traits::Reveal { UserFacing, All }); impl_stable_hash_for!(enum ::middle::privacy::AccessLevel { Reachable, Exported, Public }); impl<'gcx> HashStable<StableHashingContext<'gcx>> for ::middle::privacy::AccessLevels { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| { let ::middle::privacy::AccessLevels { ref map } = *self; map.hash_stable(hcx, hasher); }); } } impl_stable_hash_for!(struct ty::CrateInherentImpls { inherent_impls }); impl_stable_hash_for!(enum ::session::CompileIncomplete { Stopped, Errored(error_reported) }); impl_stable_hash_for!(struct ::util::common::ErrorReported {}); impl_stable_hash_for!(tuple_struct ::middle::reachable::ReachableSet { reachable_set }); impl<'gcx, N> HashStable<StableHashingContext<'gcx>> for traits::Vtable<'gcx, N> where N: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { use traits::Vtable::*; mem::discriminant(self).hash_stable(hcx, hasher); match self { &VtableImpl(ref table_impl) => table_impl.hash_stable(hcx, hasher), &VtableDefaultImpl(ref table_def_impl) => table_def_impl.hash_stable(hcx, hasher), &VtableParam(ref table_param) => table_param.hash_stable(hcx, hasher), &VtableObject(ref table_obj) => table_obj.hash_stable(hcx, hasher), &VtableBuiltin(ref table_builtin) => table_builtin.hash_stable(hcx, hasher), &VtableClosure(ref table_closure) => table_closure.hash_stable(hcx, hasher), &VtableFnPointer(ref table_fn_pointer) => table_fn_pointer.hash_stable(hcx, hasher), &VtableGenerator(ref table_generator) => table_generator.hash_stable(hcx, hasher), } } } impl<'gcx, N> HashStable<StableHashingContext<'gcx>> for traits::VtableImplData<'gcx, N> where N: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let traits::VtableImplData { impl_def_id, substs, ref nested, } = *self; impl_def_id.hash_stable(hcx, hasher); substs.hash_stable(hcx, hasher); nested.hash_stable(hcx, hasher); } } impl<'gcx, N> HashStable<StableHashingContext<'gcx>> for traits::VtableDefaultImplData<N> where N: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let traits::VtableDefaultImplData { trait_def_id, ref nested, } = *self; trait_def_id.hash_stable(hcx, hasher); nested.hash_stable(hcx, hasher); } } impl<'gcx, N> HashStable<StableHashingContext<'gcx>> for traits::VtableObjectData<'gcx, N> where N: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let traits::VtableObjectData { upcast_trait_ref, vtable_base, ref nested, } = *self; upcast_trait_ref.hash_stable(hcx, hasher); vtable_base.hash_stable(hcx, hasher); nested.hash_stable(hcx, hasher); } } impl<'gcx, N> HashStable<StableHashingContext<'gcx>> for traits::VtableBuiltinData<N> where N: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let traits::VtableBuiltinData { ref nested, } = *self; nested.hash_stable(hcx, hasher); } } impl<'gcx, N> HashStable<StableHashingContext<'gcx>> for traits::VtableClosureData<'gcx, N> where N: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let traits::VtableClosureData { closure_def_id, substs, ref nested, } = *self; closure_def_id.hash_stable(hcx, hasher); substs.hash_stable(hcx, hasher); nested.hash_stable(hcx, hasher); } } impl<'gcx, N> HashStable<StableHashingContext<'gcx>> for traits::VtableFnPointerData<'gcx, N> where N: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let traits::VtableFnPointerData { fn_ty, ref nested, } = *self; fn_ty.hash_stable(hcx, hasher); nested.hash_stable(hcx, hasher); } } impl<'gcx, N> HashStable<StableHashingContext<'gcx>> for traits::VtableGeneratorData<'gcx, N> where N: HashStable<StableHashingContext<'gcx>> { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'gcx>, hasher: &mut StableHasher<W>) { let traits::VtableGeneratorData { closure_def_id, substs, ref nested, } = *self; closure_def_id.hash_stable(hcx, hasher); substs.hash_stable(hcx, hasher); nested.hash_stable(hcx, hasher); } }
33.156218
96
0.54958
e9e9fcff5b75e7f0965a0fb5aa34fffe65c4d7f2
10,879
//! `core_arch` #![cfg_attr(not(bootstrap), allow(automatic_links))] #[macro_use] mod macros; #[cfg(any(target_arch = "arm", target_arch = "aarch64", doc))] mod acle; mod simd; #[doc(include = "core_arch_docs.md")] #[stable(feature = "simd_arch", since = "1.27.0")] pub mod arch { /// Platform-specific intrinsics for the `x86` platform. /// /// See the [module documentation](../index.html) for more details. #[cfg(any(target_arch = "x86", doc))] #[doc(cfg(target_arch = "x86"))] #[stable(feature = "simd_x86", since = "1.27.0")] pub mod x86 { #[stable(feature = "simd_x86", since = "1.27.0")] pub use crate::core_arch::x86::*; } /// Platform-specific intrinsics for the `x86_64` platform. /// /// See the [module documentation](../index.html) for more details. #[cfg(any(target_arch = "x86_64", doc))] #[doc(cfg(target_arch = "x86_64"))] #[stable(feature = "simd_x86", since = "1.27.0")] pub mod x86_64 { #[stable(feature = "simd_x86", since = "1.27.0")] pub use crate::core_arch::x86::*; #[stable(feature = "simd_x86", since = "1.27.0")] pub use crate::core_arch::x86_64::*; } /// Platform-specific intrinsics for the `arm` platform. /// /// See the [module documentation](../index.html) for more details. #[cfg(any(target_arch = "arm", doc))] #[doc(cfg(target_arch = "arm"))] #[unstable(feature = "stdsimd", issue = "27731")] pub mod arm { pub use crate::core_arch::arm::*; } /// Platform-specific intrinsics for the `aarch64` platform. /// /// See the [module documentation](../index.html) for more details. #[cfg(any(target_arch = "aarch64", doc))] #[doc(cfg(target_arch = "aarch64"))] #[unstable(feature = "stdsimd", issue = "27731")] pub mod aarch64 { pub use crate::core_arch::{aarch64::*, arm::*}; } /// Platform-specific intrinsics for the `wasm32` platform. /// /// This module provides intrinsics specific to the WebAssembly /// architecture. Here you'll find intrinsics necessary for leveraging /// WebAssembly proposals such as [atomics] and [simd]. These proposals are /// evolving over time and as such the support here is unstable and requires /// the nightly channel. As WebAssembly proposals stabilize these functions /// will also become stable. /// /// [atomics]: https://github.com/webassembly/threads /// [simd]: https://github.com/webassembly/simd /// /// See the [module documentation](../index.html) for general information /// about the `arch` module and platform intrinsics. /// /// ## Atomics /// /// The [threads proposal][atomics] for WebAssembly adds a number of /// instructions for dealing with multithreaded programs. Atomic /// instructions can all be generated through `std::sync::atomic` types, but /// some instructions have no equivalent in Rust such as /// `memory.atomic.notify` so this module will provide these intrinsics. /// /// At this time, however, these intrinsics are only available **when the /// standard library itself is compiled with atomics**. Compiling with /// atomics is not enabled by default and requires passing /// `-Ctarget-feature=+atomics` to rustc. The standard library shipped via /// `rustup` is not compiled with atomics. To get access to these intrinsics /// you'll need to compile the standard library from source with the /// requisite compiler flags. /// /// ## SIMD /// /// The [simd proposal][simd] for WebAssembly adds a new `v128` type for a /// 128-bit SIMD register. It also adds a large array of instructions to /// operate on the `v128` type to perform data processing. The SIMD proposal /// has been in progress for quite some time and many instructions have come /// and gone. This module attempts to keep up with the proposal, but if you /// notice anything awry please feel free to [open an /// issue](https://github.com/rust-lang/stdarch/issues/new). /// /// It's important to be aware that the current state of development of SIMD /// in WebAssembly is still somewhat early days. There's lots of pieces to /// demo and prototype with, but discussions and support are still in /// progress. There's a number of pitfalls and gotchas in various places, /// which will attempt to be documented here, but there may be others /// lurking! /// /// Using SIMD is intended to be similar to as you would on `x86_64`, for /// example. You'd write a function such as: /// /// ```rust,ignore /// #[cfg(target_arch = "wasm32")] /// #[target_feature(enable = "simd128")] /// unsafe fn uses_simd() { /// use std::arch::wasm32::*; /// // ... /// } /// ``` /// /// Unlike `x86_64`, however, WebAssembly does not currently have dynamic /// detection at runtime as to whether SIMD is supported (this is one of the /// motivators for the [conditional sections proposal][condsections], but /// that is still pretty early days). This means that your binary will /// either have SIMD and can only run on engines which support SIMD, or it /// will not have SIMD at all. For compatibility the standard library itself /// does not use any SIMD internally. Determining how best to ship your /// WebAssembly binary with SIMD is largely left up to you as it can can be /// pretty nuanced depending on your situation. /// /// [condsections]: https://github.com/webassembly/conditional-sections /// /// To enable SIMD support at compile time you need to do one of two things: /// /// * First you can annotate functions with `#[target_feature(enable = /// "simd128")]`. This causes just that one function to have SIMD support /// available to it, and intrinsics will get inlined as usual in this /// situation. /// /// * Second you can compile your program with `-Ctarget-feature=+simd128`. /// This compilation flag blanket enables SIMD support for your entire /// compilation. Note that this does not include the standard library /// unless you recompile the standard library. /// /// If you enable SIMD via either of these routes then you'll have a /// WebAssembly binary that uses SIMD instructions, and you'll need to ship /// that accordingly. Also note that if you call SIMD intrinsics but don't /// enable SIMD via either of these mechanisms, you'll still have SIMD /// generated in your program. This means to generate a binary without SIMD /// you'll need to avoid both options above plus calling into any intrinsics /// in this module. /// /// > **Note**: Due to /// > [rust-lang/rust#74320](https://github.com/rust-lang/rust/issues/74320) /// > it's recommended to compile your entire program with SIMD support /// > (using `RUSTFLAGS`) or otherwise functions may not be inlined /// > correctly. /// /// > **Note**: LLVM's SIMD support is actually split into two features: /// > `simd128` and `unimplemented-simd128`. Rust code can enable `simd128` /// > with `#[target_feature]` (and test for it with `#[cfg(target_feature = /// > "simd128")]`, but it cannot enable `unimplemented-simd128`. The only /// > way to enable this feature is to compile with /// > `-Ctarget-feature=+simd128,+unimplemented-simd128`. This second /// > feature enables more recent instructions implemented in LLVM which /// > haven't always had enough time to make their way to runtimes. #[cfg(any(target_arch = "wasm32", doc))] #[doc(cfg(target_arch = "wasm32"))] #[stable(feature = "simd_wasm32", since = "1.33.0")] pub mod wasm32 { #[stable(feature = "simd_wasm32", since = "1.33.0")] pub use crate::core_arch::wasm32::*; } /// Platform-specific intrinsics for the `mips` platform. /// /// See the [module documentation](../index.html) for more details. #[cfg(any(target_arch = "mips", doc))] #[doc(cfg(target_arch = "mips"))] #[unstable(feature = "stdsimd", issue = "27731")] pub mod mips { pub use crate::core_arch::mips::*; } /// Platform-specific intrinsics for the `mips64` platform. /// /// See the [module documentation](../index.html) for more details. #[cfg(any(target_arch = "mips64", doc))] #[doc(cfg(target_arch = "mips64"))] #[unstable(feature = "stdsimd", issue = "27731")] pub mod mips64 { pub use crate::core_arch::mips::*; } /// Platform-specific intrinsics for the `PowerPC` platform. /// /// See the [module documentation](../index.html) for more details. #[cfg(any(target_arch = "powerpc", doc))] #[doc(cfg(target_arch = "powerpc"))] #[unstable(feature = "stdsimd", issue = "27731")] pub mod powerpc { pub use crate::core_arch::powerpc::*; } /// Platform-specific intrinsics for the `PowerPC64` platform. /// /// See the [module documentation](../index.html) for more details. #[cfg(any(target_arch = "powerpc64", doc))] #[doc(cfg(target_arch = "powerpc64"))] #[unstable(feature = "stdsimd", issue = "27731")] pub mod powerpc64 { pub use crate::core_arch::powerpc64::*; } /// Platform-specific intrinsics for the `NVPTX` platform. /// /// See the [module documentation](../index.html) for more details. #[cfg(any(target_arch = "nvptx", target_arch = "nvptx64", doc))] #[doc(cfg(any(target_arch = "nvptx", target_arch = "nvptx64")))] #[unstable(feature = "stdsimd", issue = "27731")] pub mod nvptx { pub use crate::core_arch::nvptx::*; } } mod simd_llvm; #[cfg(any(target_arch = "x86", target_arch = "x86_64", doc))] #[doc(cfg(any(target_arch = "x86", target_arch = "x86_64")))] mod x86; #[cfg(any(target_arch = "x86_64", doc))] #[doc(cfg(target_arch = "x86_64"))] mod x86_64; #[cfg(any(target_arch = "aarch64", doc))] #[doc(cfg(target_arch = "aarch64"))] mod aarch64; #[cfg(any(target_arch = "arm", target_arch = "aarch64", doc))] #[doc(cfg(any(target_arch = "arm", target_arch = "aarch64")))] mod arm; #[cfg(any(target_arch = "wasm32", doc))] #[doc(cfg(target_arch = "wasm32"))] mod wasm32; #[cfg(any(target_arch = "mips", target_arch = "mips64", doc))] #[doc(cfg(any(target_arch = "mips", target_arch = "mips64")))] mod mips; #[cfg(any(target_arch = "powerpc", target_arch = "powerpc64", doc))] #[doc(cfg(any(target_arch = "powerpc", target_arch = "powerpc64")))] mod powerpc; #[cfg(any(target_arch = "powerpc64", doc))] #[doc(cfg(target_arch = "powerpc64"))] mod powerpc64; #[cfg(any(target_arch = "nvptx", target_arch = "nvptx64", doc))] #[doc(cfg(any(target_arch = "nvptx", target_arch = "nvptx64")))] mod nvptx;
42.003861
80
0.640776
dd357c083de6013fd42e9f385e3a2284b5c5febf
13,449
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - OTG_FS host configuration register (OTG_FS_HCFG)"] pub fs_hcfg: FS_HCFG, #[doc = "0x04 - OTG_FS Host frame interval register"] pub hfir: HFIR, #[doc = "0x08 - OTG_FS host frame number/frame time remaining register (OTG_FS_HFNUM)"] pub fs_hfnum: FS_HFNUM, _reserved0: [u8; 4usize], #[doc = "0x10 - OTG_FS_Host periodic transmit FIFO/queue status register (OTG_FS_HPTXSTS)"] pub fs_hptxsts: FS_HPTXSTS, #[doc = "0x14 - OTG_FS Host all channels interrupt register"] pub haint: HAINT, #[doc = "0x18 - OTG_FS host all channels interrupt mask register"] pub haintmsk: HAINTMSK, _reserved1: [u8; 36usize], #[doc = "0x40 - OTG_FS host port control and status register (OTG_FS_HPRT)"] pub fs_hprt: FS_HPRT, _reserved2: [u8; 188usize], #[doc = "0x100 - OTG_FS host channel-0 characteristics register (OTG_FS_HCCHAR0)"] pub fs_hcchar0: FS_HCCHAR0, _reserved3: [u8; 4usize], #[doc = "0x108 - OTG_FS host channel-0 interrupt register (OTG_FS_HCINT0)"] pub fs_hcint0: FS_HCINT0, #[doc = "0x10c - OTG_FS host channel-0 mask register (OTG_FS_HCINTMSK0)"] pub fs_hcintmsk0: FS_HCINTMSK0, #[doc = "0x110 - OTG_FS host channel-0 transfer size register"] pub fs_hctsiz0: FS_HCTSIZ0, _reserved4: [u8; 12usize], #[doc = "0x120 - OTG_FS host channel-1 characteristics register (OTG_FS_HCCHAR1)"] pub fs_hcchar1: FS_HCCHAR1, _reserved5: [u8; 4usize], #[doc = "0x128 - OTG_FS host channel-1 interrupt register (OTG_FS_HCINT1)"] pub fs_hcint1: FS_HCINT1, #[doc = "0x12c - OTG_FS host channel-1 mask register (OTG_FS_HCINTMSK1)"] pub fs_hcintmsk1: FS_HCINTMSK1, #[doc = "0x130 - OTG_FS host channel-1 transfer size register"] pub fs_hctsiz1: FS_HCTSIZ1, _reserved6: [u8; 12usize], #[doc = "0x140 - OTG_FS host channel-2 characteristics register (OTG_FS_HCCHAR2)"] pub fs_hcchar2: FS_HCCHAR2, _reserved7: [u8; 4usize], #[doc = "0x148 - OTG_FS host channel-2 interrupt register (OTG_FS_HCINT2)"] pub fs_hcint2: FS_HCINT2, #[doc = "0x14c - OTG_FS host channel-2 mask register (OTG_FS_HCINTMSK2)"] pub fs_hcintmsk2: FS_HCINTMSK2, #[doc = "0x150 - OTG_FS host channel-2 transfer size register"] pub fs_hctsiz2: FS_HCTSIZ2, _reserved8: [u8; 12usize], #[doc = "0x160 - OTG_FS host channel-3 characteristics register (OTG_FS_HCCHAR3)"] pub fs_hcchar3: FS_HCCHAR3, _reserved9: [u8; 4usize], #[doc = "0x168 - OTG_FS host channel-3 interrupt register (OTG_FS_HCINT3)"] pub fs_hcint3: FS_HCINT3, #[doc = "0x16c - OTG_FS host channel-3 mask register (OTG_FS_HCINTMSK3)"] pub fs_hcintmsk3: FS_HCINTMSK3, #[doc = "0x170 - OTG_FS host channel-3 transfer size register"] pub fs_hctsiz3: FS_HCTSIZ3, _reserved10: [u8; 12usize], #[doc = "0x180 - OTG_FS host channel-4 characteristics register (OTG_FS_HCCHAR4)"] pub fs_hcchar4: FS_HCCHAR4, _reserved11: [u8; 4usize], #[doc = "0x188 - OTG_FS host channel-4 interrupt register (OTG_FS_HCINT4)"] pub fs_hcint4: FS_HCINT4, #[doc = "0x18c - OTG_FS host channel-4 mask register (OTG_FS_HCINTMSK4)"] pub fs_hcintmsk4: FS_HCINTMSK4, #[doc = "0x190 - OTG_FS host channel-x transfer size register"] pub fs_hctsiz4: FS_HCTSIZ4, _reserved12: [u8; 12usize], #[doc = "0x1a0 - OTG_FS host channel-5 characteristics register (OTG_FS_HCCHAR5)"] pub fs_hcchar5: FS_HCCHAR5, _reserved13: [u8; 4usize], #[doc = "0x1a8 - OTG_FS host channel-5 interrupt register (OTG_FS_HCINT5)"] pub fs_hcint5: FS_HCINT5, #[doc = "0x1ac - OTG_FS host channel-5 mask register (OTG_FS_HCINTMSK5)"] pub fs_hcintmsk5: FS_HCINTMSK5, #[doc = "0x1b0 - OTG_FS host channel-5 transfer size register"] pub fs_hctsiz5: FS_HCTSIZ5, _reserved14: [u8; 12usize], #[doc = "0x1c0 - OTG_FS host channel-6 characteristics register (OTG_FS_HCCHAR6)"] pub fs_hcchar6: FS_HCCHAR6, _reserved15: [u8; 4usize], #[doc = "0x1c8 - OTG_FS host channel-6 interrupt register (OTG_FS_HCINT6)"] pub fs_hcint6: FS_HCINT6, #[doc = "0x1cc - OTG_FS host channel-6 mask register (OTG_FS_HCINTMSK6)"] pub fs_hcintmsk6: FS_HCINTMSK6, #[doc = "0x1d0 - OTG_FS host channel-6 transfer size register"] pub fs_hctsiz6: FS_HCTSIZ6, _reserved16: [u8; 12usize], #[doc = "0x1e0 - OTG_FS host channel-7 characteristics register (OTG_FS_HCCHAR7)"] pub fs_hcchar7: FS_HCCHAR7, _reserved17: [u8; 4usize], #[doc = "0x1e8 - OTG_FS host channel-7 interrupt register (OTG_FS_HCINT7)"] pub fs_hcint7: FS_HCINT7, #[doc = "0x1ec - OTG_FS host channel-7 mask register (OTG_FS_HCINTMSK7)"] pub fs_hcintmsk7: FS_HCINTMSK7, #[doc = "0x1f0 - OTG_FS host channel-7 transfer size register"] pub fs_hctsiz7: FS_HCTSIZ7, } #[doc = "OTG_FS host configuration register (OTG_FS_HCFG)"] pub struct FS_HCFG { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host configuration register (OTG_FS_HCFG)"] pub mod fs_hcfg; #[doc = "OTG_FS Host frame interval register"] pub struct HFIR { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS Host frame interval register"] pub mod hfir; #[doc = "OTG_FS host frame number/frame time remaining register (OTG_FS_HFNUM)"] pub struct FS_HFNUM { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host frame number/frame time remaining register (OTG_FS_HFNUM)"] pub mod fs_hfnum; #[doc = "OTG_FS_Host periodic transmit FIFO/queue status register (OTG_FS_HPTXSTS)"] pub struct FS_HPTXSTS { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS_Host periodic transmit FIFO/queue status register (OTG_FS_HPTXSTS)"] pub mod fs_hptxsts; #[doc = "OTG_FS Host all channels interrupt register"] pub struct HAINT { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS Host all channels interrupt register"] pub mod haint; #[doc = "OTG_FS host all channels interrupt mask register"] pub struct HAINTMSK { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host all channels interrupt mask register"] pub mod haintmsk; #[doc = "OTG_FS host port control and status register (OTG_FS_HPRT)"] pub struct FS_HPRT { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host port control and status register (OTG_FS_HPRT)"] pub mod fs_hprt; #[doc = "OTG_FS host channel-0 characteristics register (OTG_FS_HCCHAR0)"] pub struct FS_HCCHAR0 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-0 characteristics register (OTG_FS_HCCHAR0)"] pub mod fs_hcchar0; #[doc = "OTG_FS host channel-1 characteristics register (OTG_FS_HCCHAR1)"] pub struct FS_HCCHAR1 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-1 characteristics register (OTG_FS_HCCHAR1)"] pub mod fs_hcchar1; #[doc = "OTG_FS host channel-2 characteristics register (OTG_FS_HCCHAR2)"] pub struct FS_HCCHAR2 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-2 characteristics register (OTG_FS_HCCHAR2)"] pub mod fs_hcchar2; #[doc = "OTG_FS host channel-3 characteristics register (OTG_FS_HCCHAR3)"] pub struct FS_HCCHAR3 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-3 characteristics register (OTG_FS_HCCHAR3)"] pub mod fs_hcchar3; #[doc = "OTG_FS host channel-4 characteristics register (OTG_FS_HCCHAR4)"] pub struct FS_HCCHAR4 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-4 characteristics register (OTG_FS_HCCHAR4)"] pub mod fs_hcchar4; #[doc = "OTG_FS host channel-5 characteristics register (OTG_FS_HCCHAR5)"] pub struct FS_HCCHAR5 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-5 characteristics register (OTG_FS_HCCHAR5)"] pub mod fs_hcchar5; #[doc = "OTG_FS host channel-6 characteristics register (OTG_FS_HCCHAR6)"] pub struct FS_HCCHAR6 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-6 characteristics register (OTG_FS_HCCHAR6)"] pub mod fs_hcchar6; #[doc = "OTG_FS host channel-7 characteristics register (OTG_FS_HCCHAR7)"] pub struct FS_HCCHAR7 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-7 characteristics register (OTG_FS_HCCHAR7)"] pub mod fs_hcchar7; #[doc = "OTG_FS host channel-0 interrupt register (OTG_FS_HCINT0)"] pub struct FS_HCINT0 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-0 interrupt register (OTG_FS_HCINT0)"] pub mod fs_hcint0; #[doc = "OTG_FS host channel-1 interrupt register (OTG_FS_HCINT1)"] pub struct FS_HCINT1 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-1 interrupt register (OTG_FS_HCINT1)"] pub mod fs_hcint1; #[doc = "OTG_FS host channel-2 interrupt register (OTG_FS_HCINT2)"] pub struct FS_HCINT2 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-2 interrupt register (OTG_FS_HCINT2)"] pub mod fs_hcint2; #[doc = "OTG_FS host channel-3 interrupt register (OTG_FS_HCINT3)"] pub struct FS_HCINT3 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-3 interrupt register (OTG_FS_HCINT3)"] pub mod fs_hcint3; #[doc = "OTG_FS host channel-4 interrupt register (OTG_FS_HCINT4)"] pub struct FS_HCINT4 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-4 interrupt register (OTG_FS_HCINT4)"] pub mod fs_hcint4; #[doc = "OTG_FS host channel-5 interrupt register (OTG_FS_HCINT5)"] pub struct FS_HCINT5 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-5 interrupt register (OTG_FS_HCINT5)"] pub mod fs_hcint5; #[doc = "OTG_FS host channel-6 interrupt register (OTG_FS_HCINT6)"] pub struct FS_HCINT6 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-6 interrupt register (OTG_FS_HCINT6)"] pub mod fs_hcint6; #[doc = "OTG_FS host channel-7 interrupt register (OTG_FS_HCINT7)"] pub struct FS_HCINT7 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-7 interrupt register (OTG_FS_HCINT7)"] pub mod fs_hcint7; #[doc = "OTG_FS host channel-0 mask register (OTG_FS_HCINTMSK0)"] pub struct FS_HCINTMSK0 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-0 mask register (OTG_FS_HCINTMSK0)"] pub mod fs_hcintmsk0; #[doc = "OTG_FS host channel-1 mask register (OTG_FS_HCINTMSK1)"] pub struct FS_HCINTMSK1 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-1 mask register (OTG_FS_HCINTMSK1)"] pub mod fs_hcintmsk1; #[doc = "OTG_FS host channel-2 mask register (OTG_FS_HCINTMSK2)"] pub struct FS_HCINTMSK2 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-2 mask register (OTG_FS_HCINTMSK2)"] pub mod fs_hcintmsk2; #[doc = "OTG_FS host channel-3 mask register (OTG_FS_HCINTMSK3)"] pub struct FS_HCINTMSK3 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-3 mask register (OTG_FS_HCINTMSK3)"] pub mod fs_hcintmsk3; #[doc = "OTG_FS host channel-4 mask register (OTG_FS_HCINTMSK4)"] pub struct FS_HCINTMSK4 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-4 mask register (OTG_FS_HCINTMSK4)"] pub mod fs_hcintmsk4; #[doc = "OTG_FS host channel-5 mask register (OTG_FS_HCINTMSK5)"] pub struct FS_HCINTMSK5 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-5 mask register (OTG_FS_HCINTMSK5)"] pub mod fs_hcintmsk5; #[doc = "OTG_FS host channel-6 mask register (OTG_FS_HCINTMSK6)"] pub struct FS_HCINTMSK6 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-6 mask register (OTG_FS_HCINTMSK6)"] pub mod fs_hcintmsk6; #[doc = "OTG_FS host channel-7 mask register (OTG_FS_HCINTMSK7)"] pub struct FS_HCINTMSK7 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-7 mask register (OTG_FS_HCINTMSK7)"] pub mod fs_hcintmsk7; #[doc = "OTG_FS host channel-0 transfer size register"] pub struct FS_HCTSIZ0 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-0 transfer size register"] pub mod fs_hctsiz0; #[doc = "OTG_FS host channel-1 transfer size register"] pub struct FS_HCTSIZ1 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-1 transfer size register"] pub mod fs_hctsiz1; #[doc = "OTG_FS host channel-2 transfer size register"] pub struct FS_HCTSIZ2 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-2 transfer size register"] pub mod fs_hctsiz2; #[doc = "OTG_FS host channel-3 transfer size register"] pub struct FS_HCTSIZ3 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-3 transfer size register"] pub mod fs_hctsiz3; #[doc = "OTG_FS host channel-x transfer size register"] pub struct FS_HCTSIZ4 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-x transfer size register"] pub mod fs_hctsiz4; #[doc = "OTG_FS host channel-5 transfer size register"] pub struct FS_HCTSIZ5 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-5 transfer size register"] pub mod fs_hctsiz5; #[doc = "OTG_FS host channel-6 transfer size register"] pub struct FS_HCTSIZ6 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-6 transfer size register"] pub mod fs_hctsiz6; #[doc = "OTG_FS host channel-7 transfer size register"] pub struct FS_HCTSIZ7 { register: ::vcell::VolatileCell<u32>, } #[doc = "OTG_FS host channel-7 transfer size register"] pub mod fs_hctsiz7;
40.146269
95
0.7205
e22a291323f6a46c5a998a59e12ffc4385ae43e4
1,073
use super::{log1pf, logf, sqrtf}; const LN2: f32 = 0.693147180559945309417232121458176568; /* asinh(x) = sign(x)*log(|x|+sqrt(x*x+1)) ~= x - x^3/6 + o(x^5) */ /// Inverse hyperbolic sine (f32) /// /// Calculates the inverse hyperbolic sine of `x`. /// Is defined as `sgn(x)*log(|x|+sqrt(x*x+1))`. pub fn asinhf(mut x: f32) -> f32 { let u = x.to_bits(); let i = u & 0x7fffffff; let sign = (u >> 31) != 0; /* |x| */ x = f32::from_bits(i); if i >= 0x3f800000 + (12 << 23) { /* |x| >= 0x1p12 or inf or nan */ x = logf(x) + LN2; } else if i >= 0x3f800000 + (1 << 23) { /* |x| >= 2 */ x = logf(2.0 * x + 1.0 / (sqrtf(x * x + 1.0) + x)); } else if i >= 0x3f800000 - (12 << 23) { /* |x| >= 0x1p-12, up to 1.6ulp error in [0.125,0.5] */ x = log1pf(x + x * x / (sqrtf(x * x + 1.0) + 1.0)); } else { /* |x| < 0x1p-12, raise inexact if x!=0 */ let x1p120 = f32::from_bits(0x7b800000); force_eval!(x + x1p120); } if sign { -x } else { x } }
27.512821
67
0.469711
eda0fe81abbbc400e1d6adf5535a9c117f925633
831
#![no_main] use libfuzzer_sys::arbitrary::Arbitrary; use libfuzzer_sys::fuzz_target; #[derive(Debug, Arbitrary)] struct TransportHeaderSpec { uri: Vec<u8>, header_name: Vec<u8>, header_value: Vec<u8>, http_method: bool, } fuzz_target!(|inp: TransportHeaderSpec| { if let Ok(uri) = std::str::from_utf8(&inp.uri[..]) { if let Ok(header_name) = std::str::from_utf8(&inp.header_name[..]) { if let Ok(header_value) = std::str::from_utf8(&inp.header_value[..]) { let rt = tokio::runtime::Runtime::new().unwrap(); rt.block_on(linkerd_app_inbound::http::fuzz_logic::fuzz_entry_raw( uri, header_name, header_value, inp.http_method, )); } } } });
29.678571
82
0.552347
fe9a17a72e0c4b140fb639fa7e701f6d9efe7401
29,495
use std::cmp; use std::collections::BTreeMap; use std::fmt; use std::io::Read; use std::path; use gfx_glyph::FontId; use image; use image::RgbaImage; use rusttype; use super::*; /// A font that defines the shape of characters drawn on the screen. /// Can be created from a .ttf file or from an image (bitmap fonts). #[derive(Clone)] pub enum Font { /// A truetype font TTFFont { /// The actual font data font: rusttype::Font<'static>, /// The size of the font points: u32, /// Scale information for the font scale: rusttype::Scale, }, /// A bitmap font where letter widths are infered BitmapFontVariant(BitmapFont), /// A TrueType font stored in `GraphicsContext::glyph_brush` GlyphFont(FontId), } /// A bitmap font where letter widths are infered #[derive(Clone, Debug)] pub struct BitmapFont { /// The original glyph image bytes: Vec<u8>, /// Width of the image width: usize, /// Height of the image (same as the height of a glyph) height: usize, /// Glyph to horizontal position (in pixels) and span (in pixels) (does not include space) glyphs: BTreeMap<char, (usize, usize)>, /// Width in pixels of the space space_width: usize, letter_separation: usize, } impl BitmapFont { fn span_for(&self, c: char) -> usize { match self.glyphs.get(&c) { Some(&(_, span)) => span, None => { if c == ' ' { self.space_width } else { 0 //No span is defined for this char. // We could error here, but I don't see the point. // We will just render the missing char as nothing and move on, // and the user will see that there is a nothing and if they // do not understand, they will certainly feel silly when // we and ask them what they expected to happen when they // told the system to render a char they never specified. I t // hink I would kind of prefer an implementation that is // guaranteed not to error for any string. // TODO: While this is a perfectly valid preference, I would // prefer fail-noisily to fail-invisibly; we should possibly have // options for either behavior. } } } } } impl Font { /// Load a new TTF font from the given file. pub fn new<P>(context: &mut Context, path: P, points: u32) -> GameResult<Font> where P: AsRef<path::Path> + fmt::Debug, { let mut stream = context.filesystem.open(path.as_ref())?; let mut buf = Vec::new(); stream.read_to_end(&mut buf)?; let name = format!("{:?}", path); // Get the proper DPI to scale font size accordingly let (_diag_dpi, x_dpi, y_dpi) = context.gfx_context.dpi; Font::from_bytes(&name, &buf, points, (x_dpi, y_dpi)) } /// Load a new TTF font from the given file, returning a font that draws /// lines that are the given number of pixels high. pub fn new_px<P>(context: &mut Context, path: P, pixels: u32) -> GameResult<Font> where P: AsRef<path::Path> + fmt::Debug, { let mut stream = context.filesystem.open(path.as_ref())?; let mut buf = Vec::new(); stream.read_to_end(&mut buf)?; let name = format!("{:?}", path); Font::from_bytes_px(&name, &buf, pixels) } /// Loads a new TTF font from data copied out of the given buffer. pub fn from_bytes(name: &str, bytes: &[u8], points: u32, dpi: (f32, f32)) -> GameResult<Font> { let font_collection_err = &|_| { GameError::ResourceLoadError(format!( "Could not load font collection for \ font {:?}", name )) }; let collection = rusttype::FontCollection::from_bytes(bytes.to_vec()).map_err(font_collection_err)?; let font_err = &|_| { GameError::ResourceLoadError(format!( "Could not retrieve font from collection for \ font {:?}", name )) }; let font = collection.into_font().map_err(font_err)?; let (x_dpi, y_dpi) = dpi; // println!("DPI: {}, {}", x_dpi, y_dpi); let scale = display_independent_scale(points, x_dpi, y_dpi); Ok(Font::TTFFont { font, points, scale, }) } /// Loads a new TTF font from data copied out of the given buffer, taking font size in pixels pub fn from_bytes_px(name: &str, bytes: &[u8], pixels: u32) -> GameResult<Font> { let font_collection_err = &|_| { GameError::ResourceLoadError(format!( "Could not load font collection for \ font {:?}", name )) }; let collection = rusttype::FontCollection::from_bytes(bytes.to_vec()).map_err(font_collection_err)?; let font_err = &|_| { GameError::ResourceLoadError(format!( "Could not retrieve font from collection for \ font {:?}", name )) }; let font = collection.into_font().map_err(font_err)?; let scale = rusttype::Scale { x: pixels as f32, y: pixels as f32, }; Ok(Font::TTFFont { points: 0, // Pretty sure points is unused apart from display, so font, scale, }) } /// Creates a bitmap font from a long image of its alphabet, specified by `path`. /// The width of each individual chars is assumed to be to be /// image(path).width/glyphs.chars().count() pub fn new_bitmap<P: AsRef<path::Path>>( context: &mut Context, path: P, glyphs: &str, ) -> GameResult<Font> { let img = { let mut buf = Vec::new(); let mut reader = context.filesystem.open(path)?; reader.read_to_end(&mut buf)?; image::load_from_memory(&buf)?.to_rgba() }; let (image_width, image_height) = img.dimensions(); let glyph_width = (image_width as usize) / glyphs.len(); let mut glyphs_map: BTreeMap<char, (usize, usize)> = BTreeMap::new(); for (i, c) in glyphs.chars().enumerate() { glyphs_map.insert(c, (i * glyph_width, glyph_width)); } Ok(Font::BitmapFontVariant(BitmapFont { bytes: img.into_vec(), width: image_width as usize, height: image_height as usize, glyphs: glyphs_map, space_width: glyph_width, letter_separation: 0, })) } /// Creates a bitmap font from a long image of its alphabet. /// Each letter must be separated from the last by a fully transparent column of pixels. /// The width of each letter is infered from these letter boundaries. pub fn new_variable_width_bitmap_font<P: AsRef<path::Path>>( context: &mut Context, path: P, glyphs: &str, space_width: usize, //in addition to letter_separation letter_separation: usize, ) -> GameResult<Font> { let img = { let mut buf = Vec::new(); let mut reader = context.filesystem.open(path)?; reader.read_to_end(&mut buf)?; image::load_from_memory(&buf)?.to_rgba() }; let (image_width, image_height) = img.dimensions(); let mut glyphs_map: BTreeMap<char, (usize, usize)> = BTreeMap::new(); let mut start = 0usize; let mut glyphos = glyphs.chars().enumerate(); let column_has_content = |offset: usize, image: &RgbaImage| { //iff any pixel herein has an alpha greater than 0 (0..image_height).any(|ir| image.get_pixel(offset as u32, ir).data[3] > 0) }; while start < image_width as usize { if column_has_content(start, &img) { let mut span = 1; while start + span < image_width as usize && column_has_content(start + span, &img) { span += 1; } let next_char: char = glyphos .next() .ok_or_else(|| { GameError::FontError("I counted more glyphs in the font bitmap than there were chars in the glyphs string. Note, glyphs must not have gaps. A glyph with a transparent column in the middle will read as two glyphs.".into()) })? .1; glyphs_map.insert(next_char, (start, span)); start += span; } start += 1; } let (lb, _) = glyphos.size_hint(); if lb > 0 { return Err(GameError::FontError( "There were more chars in glyphs than I counted in the bitmap!".into(), )); } Ok(Font::BitmapFontVariant(BitmapFont { bytes: img.into_vec(), width: image_width as usize, height: image_height as usize, glyphs: glyphs_map, space_width, letter_separation, })) } /// Loads a new TrueType font from given file and into `GraphicsContext::glyph_brush`. pub fn new_glyph_font<P>(context: &mut Context, path: P) -> GameResult<Self> where P: AsRef<path::Path> + fmt::Debug, { let mut stream = context.filesystem.open(path.as_ref())?; let mut buf = Vec::new(); stream.read_to_end(&mut buf)?; let font_id = context.gfx_context.glyph_brush.add_font_bytes(buf); Ok(Font::GlyphFont(font_id)) } /// Retrieves a loaded font from `GraphicsContext::glyph_brush`. pub fn get_glyph_font_by_id(context: &mut Context, font_id: FontId) -> GameResult<Self> { if context .gfx_context .glyph_brush .fonts() .contains_key(&font_id) { Ok(Font::GlyphFont(font_id)) } else { Err(GameError::FontError( format!("Font {:?} not found!", font_id).into(), )) } } /// Returns the baked-in bytes of default font (currently DejaVuSerif.ttf). pub(crate) fn default_font_bytes() -> &'static [u8] { include_bytes!(concat!( env!("CARGO_MANIFEST_DIR"), "/resources/DejaVuSerif.ttf" )) } /// Returns baked-in default font (currently DejaVuSerif.ttf). /// Note it does create a new `Font` object with every call; /// although the actual data should be shared. pub fn default_font() -> GameResult<Self> { let size = 16; // BUGGO: fix DPI. Get from Context? If we do that we can basically // just make Context always keep the default Font itself... hmm. // TODO: ^^^ is that still relevant? Nah, it will probably be replaced by // the `gfx_glyph` interation. Font::from_bytes("default", Font::default_font_bytes(), size, (75.0, 75.0)) } /// Get the height of the Font in pixels. /// /// The height of the font includes any spacing, it will be the total height /// a line needs. pub fn get_height(&self) -> usize { match *self { Font::BitmapFontVariant(BitmapFont { height, .. }) => height, Font::TTFFont { scale, .. } => scale.y.ceil() as usize, Font::GlyphFont(_) => 0, } } /// Returns the width a line of text needs, in pixels. /// Does not handle line-breaks. pub fn get_width(&self, text: &str) -> usize { match *self { Font::BitmapFontVariant(ref font) => { compute_variable_bitmap_text_rendering_span(text, font) } Font::TTFFont { ref font, scale, .. } => { let v_metrics = font.v_metrics(scale); let offset = rusttype::point(0.0, v_metrics.ascent); let glyphs: Vec<rusttype::PositionedGlyph> = font.layout(text, scale, offset).collect(); text_width(&glyphs).ceil() as usize } Font::GlyphFont(_) => 0, } } /// Breaks the given text into lines that will not exceed `wrap_limit` pixels /// in length when drawn with the given font. /// It accounts for newlines correctly but does not /// try to break words or handle hyphenated words; it just breaks /// at whitespace. (It also doesn't preserve whitespace.) /// /// Returns a tuple of maximum line width and a `Vec` of wrapped `String`s. pub fn get_wrap(&self, text: &str, wrap_limit: usize) -> (usize, Vec<String>) { let mut broken_lines = Vec::new(); for line in text.lines() { let mut current_line = Vec::new(); for word in line.split_whitespace() { // I'm sick of trying to do things the clever way and // build up a line word by word while tracking how // long it should be, so instead I just re-render the whole // line, incrementally adding a word at a time until it // becomes too long. // This is not the most efficient way but it is simple and // it works. let mut prospective_line = current_line.clone(); prospective_line.push(word); let text = prospective_line.join(" "); let prospective_line_width = self.get_width(&text); if prospective_line_width > wrap_limit { // Current line is long enough, keep it broken_lines.push(current_line.join(" ")); // and overflow the current word onto the next line. current_line.clear(); current_line.push(word); } else { // Current line with the added word is still short enough current_line.push(word); } } // Push the last line of the text broken_lines.push(current_line.join(" ")); } // If we have a line with only whitespace on it, // this results in the unwrap_or value. // And we can't create a texture of size 0, so // we put 1 here. // Not entirely sure what this will actually result // in though; hopefully a blank line. let max_line_length = broken_lines .iter() .map(|line| self.get_width(line)) .max() .unwrap_or(1); (max_line_length, broken_lines) } } impl fmt::Debug for Font { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Font::TTFFont { .. } => write!(f, "<TTFFont: {:p}>", &self), Font::BitmapFontVariant(BitmapFont { .. }) => write!(f, "<BitmapFont: {:p}>", &self), Font::GlyphFont { .. } => write!(f, "<GlyphFont: {:p}>", &self), } } } /// Drawable text created from a `Font`. #[derive(Clone)] pub struct Text { texture: Image, contents: String, blend_mode: Option<BlendMode>, } /// Compute a scale for a font of a given size. // This basically does the points->pixels unit conversion, // taking the display DPI into account. fn display_independent_scale(points: u32, dpi_w: f32, dpi_h: f32) -> rusttype::Scale { // Calculate pixels per point let points = points as f32; let points_per_inch = 72.0; let pixels_per_point_w = dpi_w * (1.0 / points_per_inch); let pixels_per_point_h = dpi_h * (1.0 / points_per_inch); // rusttype::Scale is in units of pixels, so. rusttype::Scale { x: pixels_per_point_w * points, y: pixels_per_point_h * points, } } fn text_width(glyphs: &[rusttype::PositionedGlyph]) -> f32 { glyphs .iter() .rev() .filter_map(|g| { g.pixel_bounding_box() .map(|b| b.min.x as f32 + g.unpositioned().h_metrics().advance_width) }) .next() .unwrap_or(0.0) } fn render_ttf( context: &mut Context, text: &str, font: &rusttype::Font<'static>, scale: rusttype::Scale, ) -> GameResult<Text> { // Ripped almost wholesale from // https://github.com/dylanede/rusttype/blob/master/examples/simple.rs let text_height_pixels = scale.y.ceil() as usize; let v_metrics = font.v_metrics(scale); let offset = rusttype::point(0.0, v_metrics.ascent); // Then turn them into an array of positioned glyphs... // `layout()` turns an abstract glyph, which contains no concrete // size or position information, into a PositionedGlyph, which does. let glyphs: Vec<rusttype::PositionedGlyph> = font.layout(text, scale, offset).collect(); // If the string is empty or only whitespace, we end up trying to create a 0-width // texture which is invalid. Instead we create a texture 1 texel wide, with everything // set to zero, which probably isn't ideal but is 100% consistent and doesn't require // special-casing things like get_filter(). // See issue #109 let text_width_pixels = cmp::max(text_width(&glyphs).ceil() as usize, 1); let bytes_per_pixel = 4; let mut pixel_data = vec![0; text_width_pixels * text_height_pixels * bytes_per_pixel]; let pitch = text_width_pixels * bytes_per_pixel; // Now we actually render the glyphs to a bitmap... for g in glyphs { if let Some(bb) = g.pixel_bounding_box() { // v is the amount of the pixel covered // by the glyph, in the range 0.0 to 1.0 g.draw(|x, y, v| { let c = (v * 255.0) as u8; let x = x as i32 + bb.min.x; let y = y as i32 + bb.min.y; // There's still a possibility that the glyph clips the boundaries of the bitmap if x >= 0 && x < text_width_pixels as i32 && y >= 0 && y < text_height_pixels as i32 { let x = x as usize * bytes_per_pixel; let y = y as usize; pixel_data[(x + y * pitch)] = 255; pixel_data[(x + y * pitch + 1)] = 255; pixel_data[(x + y * pitch + 2)] = 255; pixel_data[(x + y * pitch + 3)] = c; } }) } } // Copy the bitmap into an image, and we're basically done! assert!(text_width_pixels < u16::MAX as usize); assert!(text_height_pixels < u16::MAX as usize); let image = Image::from_rgba8( context, text_width_pixels as u16, text_height_pixels as u16, &pixel_data, )?; let text_string = text.to_string(); Ok(Text { texture: image, contents: text_string, blend_mode: None, }) } /// Treats src and dst as row-major 2D arrays, and blits the given rect from src to dst. /// Does no bounds checking or anything; if you feed it invalid bounds it will just panic. /// Generally, you shouldn't need to use this directly. #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))] fn blit( dst: &mut [u8], dst_dims: (usize, usize), dst_point: (usize, usize), src: &[u8], src_dims: (usize, usize), src_point: (usize, usize), rect_size: (usize, usize), pitch: usize, ) { // The rect properties are all f32's; we truncate them down to integers. let area_row_width = rect_size.0 * pitch; let src_row_width = src_dims.0 * pitch; let dst_row_width = dst_dims.0 * pitch; for row_idx in 0..rect_size.1 { let src_row = row_idx + src_point.1; let dst_row = row_idx + dst_point.1; let src_offset = src_row * src_row_width + (src_point.0 * pitch); let dst_offset = dst_row * dst_row_width + (dst_point.0 * pitch); // println!("from {} to {}, width {}", // dst_offset, // src_offset, // area_row_width); let dst_slice = &mut dst[dst_offset..(dst_offset + area_row_width)]; let src_slice = &src[src_offset..(src_offset + area_row_width)]; dst_slice.copy_from_slice(src_slice); } } struct VariableFontCharIter<'a> { font: &'a BitmapFont, iter: ::std::str::Chars<'a>, offset: usize, } impl<'a> Iterator for VariableFontCharIter<'a> { // iterates over each char in a line of text, finding the horizontal // offsets at which they will appear on the screen, relative to the origin. type Item = (char, usize, usize); //(letter, offset, letter_render_span) fn next(&mut self) -> Option<Self::Item> { if let Some(c) = self.iter.next() { let char_span = self.font.span_for(c); let this_offset = self.offset; self.offset += char_span + self.font.letter_separation; Some((c, this_offset, char_span)) } else { None } } } impl<'a> VariableFontCharIter<'a> { fn new(text: &'a str, font: &'a BitmapFont) -> VariableFontCharIter<'a> { VariableFontCharIter { font, iter: text.chars(), offset: 0, } } } fn compute_variable_bitmap_text_rendering_span(text: &str, font: &BitmapFont) -> usize { VariableFontCharIter::new(text, font) .last() .map(|(_, offset, span)| offset + span) .unwrap_or(0) } fn render_dynamic_bitmap(context: &mut Context, text: &str, font: &BitmapFont) -> GameResult<Text> { let image_span = compute_variable_bitmap_text_rendering_span(text, font); // Same at-least-one-pixel-wide constraint here as with TTF fonts. let buf_len = cmp::max(image_span * font.height * 4, 1); let mut dest_buf = Vec::with_capacity(buf_len); dest_buf.resize(buf_len, 0u8); for (c, offset, _) in VariableFontCharIter::new(text, font) { let (coffset, cspan) = *font.glyphs.get(&c).unwrap_or(&(0, 0)); blit( &mut dest_buf, (image_span, font.height), (offset, 0), &font.bytes, (font.width, font.height), (coffset, 0), (cspan, font.height), 4, ); } let image = Image::from_rgba8(context, image_span as u16, font.height as u16, &dest_buf)?; let text_string = text.to_string(); Ok(Text { texture: image, contents: text_string, blend_mode: None, }) } impl Text { /// Renders a new `Text` from the given `Font`. /// /// Note that this is relatively computationally expensive; /// if you want to draw text every frame you probably want to save /// it and only update it when the text changes. pub fn new(context: &mut Context, text: &str, font: &Font) -> GameResult<Text> { match *font { Font::TTFFont { font: ref f, scale, .. } => render_ttf(context, text, f, scale), Font::BitmapFontVariant(ref font) => render_dynamic_bitmap(context, text, font), Font::GlyphFont(_) => Err(GameError::FontError( "`Text` can't be created with a `Font::GlyphFont` (yet)!".into(), )), } } /// Returns the width of the rendered text, in pixels. pub fn width(&self) -> u32 { self.texture.width() } /// Returns the height of the rendered text, in pixels. pub fn height(&self) -> u32 { self.texture.height() } /// Returns the string that the text represents. pub fn contents(&self) -> &str { &self.contents } /// Returns the dimensions of the rendered text. pub fn get_dimensions(&self) -> Rect { self.texture.get_dimensions() } /// Get the filter mode for the the rendered text. pub fn get_filter(&self) -> FilterMode { self.texture.get_filter() } /// Set the filter mode for the the rendered text. pub fn set_filter(&mut self, mode: FilterMode) { self.texture.set_filter(mode); } /// Returns a reference to the `Image` contained /// by the `Text` object. pub fn get_image(&self) -> &Image { &self.texture } /// Returns a mutable reference to the `Image` contained /// by the `Text` object. pub fn get_image_mut(&mut self) -> &mut Image { &mut self.texture } /// Unwraps the `Image` contained /// by the `Text` object. pub fn into_inner(self) -> Image { self.texture } } impl Drawable for Text { fn draw_ex(&self, ctx: &mut Context, param: DrawParam) -> GameResult<()> { draw_ex(ctx, &self.texture, param) } fn set_blend_mode(&mut self, mode: Option<BlendMode>) { self.blend_mode = mode; } fn get_blend_mode(&self) -> Option<BlendMode> { self.blend_mode } } impl fmt::Debug for Text { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "<Text: {}x{}, {:p}>", self.texture.width, self.texture.height, &self ) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_blit() { let dst = &mut [0; 125][..]; let src = &[ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ][..]; assert_eq!(src.len(), 25 * 5); // Test just blitting the whole thing let rect_dims = (25, 5); blit(dst, rect_dims, (0, 0), src, rect_dims, (0, 0), (25, 5), 1); //println!("{:?}", src); //println!("{:?}", dst); assert_eq!(dst, src); for i in 0..dst.len() { dst[i] = 0; } // Test blitting the whole thing with a non-1 pitch let rect_dims = (5, 5); blit(dst, rect_dims, (0, 0), src, rect_dims, (0, 0), (5, 5), 5); assert_eq!(dst, src); } #[test] fn test_metrics() { let f = Font::default_font().expect("Could not get default font"); assert_eq!(f.get_height(), 17); assert_eq!(f.get_width("Foo!"), 34); // http://www.catipsum.com/index.php let text_to_wrap = "Walk on car leaving trail of paw prints on hood and windshield sniff \ other cat's butt and hang jaw half open thereafter for give attitude. \ Annoy kitten\nbrother with poking. Mrow toy mouse squeak roll over. \ Human give me attention meow."; let (len, v) = f.get_wrap(text_to_wrap, 250); println!("{} {:?}", len, v); assert_eq!(len, 250); /* let wrapped_text = vec![ "Walk on car leaving trail of paw prints", "on hood and windshield sniff other", "cat\'s butt and hang jaw half open", "thereafter for give attitude. Annoy", "kitten", "brother with poking. Mrow toy", "mouse squeak roll over. Human give", "me attention meow." ]; */ let wrapped_text = vec![ "Walk on car leaving trail of paw", "prints on hood and windshield", "sniff other cat\'s butt and hang jaw", "half open thereafter for give", "attitude. Annoy kitten", "brother with poking. Mrow toy", "mouse squeak roll over. Human", "give me attention meow.", ]; assert_eq!(&v, &wrapped_text); } // We sadly can't have this test in the general case because it needs to create a Context, // which creates a window, which fails on a headless server like our CI systems. :/ //#[test] #[allow(dead_code)] fn test_wrapping() { use conf; let c = conf::Conf::new(); let ctx = &mut Context::load_from_conf("test_wrapping", "ggez", c) .expect("Could not create context?"); let font = Font::default_font().expect("Could not get default font"); let text_to_wrap = "Walk on car leaving trail of paw prints on hood and windshield sniff \ other cat's butt and hang jaw half open thereafter for give attitude. \ Annoy kitten\nbrother with poking. Mrow toy mouse squeak roll over. \ Human give me attention meow."; let wrap_length = 250; let (len, v) = font.get_wrap(text_to_wrap, wrap_length); assert!(len < wrap_length); for line in &v { let t = Text::new(ctx, line, &font).unwrap(); println!( "Width is claimed to be <= {}, should be <= {}, is {}", len, wrap_length, t.width() ); // Why does this not match? x_X //assert!(t.width() as usize <= len); assert!(t.width() as usize <= wrap_length); } } }
36.503713
245
0.555891
670e44f20b52b833b51fe1163fd4d3759119847e
1,442
macro_rules! alu { ($name: ident, $op:tt) => { fn $name(mem: &mut [usize], pc: usize) -> Option<usize> { let pa = *mem.get(pc + 1)?; let a = *mem.get(pa)?; let pb = *mem.get(pc + 2)?; let b = *mem.get(pb)?; let pres = *mem.get(pc + 3)?; let res = mem.get_mut(pres)?; *res = a $op b; Some(4) } }; } alu!(add, +); alu!(mul, *); pub fn intcode(mem: &mut [usize]) -> Option<usize> { let mut pc = 0usize; loop { match mem.get(pc) { Some(1) => pc += add(mem, pc)?, Some(2) => pc += mul(mem, pc)?, Some(99) => break, _ => return None, } } mem.get(0).map(|p| *p) } pub fn init_and_run(mem: &[usize], noun: usize, verb: usize) -> Option<usize> { let mut mem = mem.to_vec(); mem[1] = noun; mem[2] = verb; intcode(&mut mem) } #[cfg(test)] mod tests { use super::*; #[test] fn test_small() { let mem = &mut [1, 0, 0, 0, 99]; assert_eq!(intcode(mem), Some(2)); let mem = &mut [1, 1, 1, 4, 99, 5, 6, 0, 99]; assert_eq!(intcode(mem), Some(30)); let mem = &mut [2, 3, 0, 3, 99]; assert_eq!(intcode(mem), Some(2)); assert_eq!(mem[3], 6); let mem = &mut [2, 4, 4, 5, 99, 0]; assert_eq!(intcode(mem), Some(2)); assert_eq!(mem[5], 9801); } }
22.888889
79
0.441748
2980d0f78fd74d644c35e16601e2a3cfe03f3124
586
use protobuf::*; use protobuf::prelude::*; use super::test_required_pb::*; #[test] #[should_panic] fn test_write_missing_required() { TestRequired::new().write_to_bytes().unwrap(); } #[test] #[should_panic] fn test_read_missing_required() { parse_from_bytes::<TestRequired>(&[]).unwrap(); } #[test] fn test_is_initialized_is_recursive() { let mut m = TestRequiredOuter::new(); assert!(!m.is_initialized()); m.inner.set_message(Default::default()); assert!(!m.is_initialized()); m.inner.as_mut().unwrap().set_b(false); assert!(m.is_initialized()); }
20.928571
51
0.679181
eb9c0185af794a4e5794b5da89a8a2438dd0ff4f
14,335
// 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. use crate::{ decimal::Decimal, duration::Duration, schema::Schema, types::Value, util::{safe_len, zag_i32, zag_i64}, AvroResult, Error, }; use std::{ collections::HashMap, convert::TryFrom, io::{ErrorKind, Read}, str::FromStr, }; use uuid::Uuid; #[inline] fn decode_long<R: Read>(reader: &mut R) -> AvroResult<Value> { zag_i64(reader).map(Value::Long) } #[inline] fn decode_int<R: Read>(reader: &mut R) -> AvroResult<Value> { zag_i32(reader).map(Value::Int) } #[inline] fn decode_len<R: Read>(reader: &mut R) -> AvroResult<usize> { let len = zag_i64(reader)?; safe_len(usize::try_from(len).map_err(|e| Error::ConvertI64ToUsize(e, len))?) } /// Decode the length of a sequence. /// /// Maps and arrays are 0-terminated, 0i64 is also encoded as 0 in Avro reading a length of 0 means /// the end of the map or array. fn decode_seq_len<R: Read>(reader: &mut R) -> AvroResult<usize> { let raw_len = zag_i64(reader)?; safe_len( usize::try_from(match raw_len.cmp(&0) { std::cmp::Ordering::Equal => return Ok(0), std::cmp::Ordering::Less => { let _size = zag_i64(reader)?; -raw_len } std::cmp::Ordering::Greater => raw_len, }) .map_err(|e| Error::ConvertI64ToUsize(e, raw_len))?, ) } /// Decode a `Value` from avro format given its `Schema`. pub fn decode<R: Read>(schema: &Schema, reader: &mut R) -> AvroResult<Value> { fn decode0<R: Read>( schema: &Schema, reader: &mut R, schemas_by_name: &mut HashMap<String, Schema>, ) -> AvroResult<Value> { match *schema { Schema::Null => Ok(Value::Null), Schema::Boolean => { let mut buf = [0u8; 1]; match reader.read_exact(&mut buf[..]) { Ok(_) => match buf[0] { 0u8 => Ok(Value::Boolean(false)), 1u8 => Ok(Value::Boolean(true)), _ => Err(Error::BoolValue(buf[0])), }, Err(io_err) => { if let ErrorKind::UnexpectedEof = io_err.kind() { Ok(Value::Null) } else { Err(Error::ReadBoolean(io_err)) } } } } Schema::Decimal { ref inner, .. } => match &**inner { Schema::Fixed { .. } => match decode0(inner, reader, schemas_by_name)? { Value::Fixed(_, bytes) => Ok(Value::Decimal(Decimal::from(bytes))), value => Err(Error::FixedValue(value.into())), }, Schema::Bytes => match decode0(inner, reader, schemas_by_name)? { Value::Bytes(bytes) => Ok(Value::Decimal(Decimal::from(bytes))), value => Err(Error::BytesValue(value.into())), }, schema => Err(Error::ResolveDecimalSchema(schema.into())), }, Schema::Uuid => Ok(Value::Uuid( Uuid::from_str(match decode0(&Schema::String, reader, schemas_by_name)? { Value::String(ref s) => s, value => return Err(Error::GetUuidFromStringValue(value.into())), }) .map_err(Error::ConvertStrToUuid)?, )), Schema::Int => decode_int(reader), Schema::Date => zag_i32(reader).map(Value::Date), Schema::TimeMillis => zag_i32(reader).map(Value::TimeMillis), Schema::Long => decode_long(reader), Schema::TimeMicros => zag_i64(reader).map(Value::TimeMicros), Schema::TimestampMillis => zag_i64(reader).map(Value::TimestampMillis), Schema::TimestampMicros => zag_i64(reader).map(Value::TimestampMicros), Schema::Duration => { let mut buf = [0u8; 12]; reader.read_exact(&mut buf).map_err(Error::ReadDuration)?; Ok(Value::Duration(Duration::from(buf))) } Schema::Float => { let mut buf = [0u8; std::mem::size_of::<f32>()]; reader.read_exact(&mut buf[..]).map_err(Error::ReadFloat)?; Ok(Value::Float(f32::from_le_bytes(buf))) } Schema::Double => { let mut buf = [0u8; std::mem::size_of::<f64>()]; reader.read_exact(&mut buf[..]).map_err(Error::ReadDouble)?; Ok(Value::Double(f64::from_le_bytes(buf))) } Schema::Bytes => { let len = decode_len(reader)?; let mut buf = vec![0u8; len]; reader.read_exact(&mut buf).map_err(Error::ReadBytes)?; Ok(Value::Bytes(buf)) } Schema::String => { let len = decode_len(reader)?; let mut buf = vec![0u8; len]; match reader.read_exact(&mut buf) { Ok(_) => Ok(Value::String( String::from_utf8(buf).map_err(Error::ConvertToUtf8)?, )), Err(io_err) => { if let ErrorKind::UnexpectedEof = io_err.kind() { Ok(Value::Null) } else { Err(Error::ReadString(io_err)) } } } } Schema::Fixed { ref name, size, .. } => { schemas_by_name.insert(name.name.clone(), schema.clone()); let mut buf = vec![0u8; size]; reader .read_exact(&mut buf) .map_err(|e| Error::ReadFixed(e, size))?; Ok(Value::Fixed(size, buf)) } Schema::Array(ref inner) => { let mut items = Vec::new(); loop { let len = decode_seq_len(reader)?; if len == 0 { break; } items.reserve(len); for _ in 0..len { items.push(decode0(inner, reader, schemas_by_name)?); } } Ok(Value::Array(items)) } Schema::Map(ref inner) => { let mut items = HashMap::new(); loop { let len = decode_seq_len(reader)?; if len == 0 { break; } items.reserve(len); for _ in 0..len { match decode0(&Schema::String, reader, schemas_by_name)? { Value::String(key) => { let value = decode0(inner, reader, schemas_by_name)?; items.insert(key, value); } value => return Err(Error::MapKeyType(value.into())), } } } Ok(Value::Map(items)) } Schema::Union(ref inner) => match zag_i64(reader) { Ok(index) => { let variants = inner.variants(); let variant = variants .get( usize::try_from(index) .map_err(|e| Error::ConvertI64ToUsize(e, index))?, ) .ok_or_else(|| Error::GetUnionVariant { index, num_variants: variants.len(), })?; let value = decode0(variant, reader, schemas_by_name)?; Ok(Value::Union(index as i32, Box::new(value))) } Err(Error::ReadVariableIntegerBytes(io_err)) => { if let ErrorKind::UnexpectedEof = io_err.kind() { Ok(Value::Union(0, Box::new(Value::Null))) } else { Err(Error::ReadVariableIntegerBytes(io_err)) } } Err(io_err) => Err(io_err), }, Schema::Record { ref name, ref fields, .. } => { schemas_by_name.insert(name.name.clone(), schema.clone()); // Benchmarks indicate ~10% improvement using this method. let mut items = Vec::with_capacity(fields.len()); for field in fields { // TODO: This clone is also expensive. See if we can do away with it... items.push(( field.name.clone(), decode0(&field.schema, reader, schemas_by_name)?, )); } Ok(Value::Record(items)) } Schema::Enum { ref name, ref symbols, .. } => { schemas_by_name.insert(name.name.clone(), schema.clone()); Ok(if let Value::Int(raw_index) = decode_int(reader)? { let index = usize::try_from(raw_index) .map_err(|e| Error::ConvertI32ToUsize(e, raw_index))?; if (0..=symbols.len()).contains(&index) { let symbol = symbols[index].clone(); Value::Enum(raw_index, symbol) } else { return Err(Error::GetEnumValue { index, nsymbols: symbols.len(), }); } } else { return Err(Error::GetEnumSymbol); }) } Schema::Ref { ref name } => { let name = &name.name; if let Some(resolved) = schemas_by_name.get(name.as_str()) { decode0(resolved, reader, &mut schemas_by_name.clone()) } else { Err(Error::SchemaResolutionError(name.clone())) } } } } let mut schemas_by_name: HashMap<String, Schema> = HashMap::new(); decode0(schema, reader, &mut schemas_by_name) } #[cfg(test)] mod tests { use crate::{ decode::decode, schema::Schema, types::{ Value, Value::{Array, Int, Map}, }, Decimal, }; use std::collections::HashMap; #[test] fn test_decode_array_without_size() { let mut input: &[u8] = &[6, 2, 4, 6, 0]; let result = decode(&Schema::Array(Box::new(Schema::Int)), &mut input); assert_eq!(Array(vec!(Int(1), Int(2), Int(3))), result.unwrap()); } #[test] fn test_decode_array_with_size() { let mut input: &[u8] = &[5, 6, 2, 4, 6, 0]; let result = decode(&Schema::Array(Box::new(Schema::Int)), &mut input); assert_eq!(Array(vec!(Int(1), Int(2), Int(3))), result.unwrap()); } #[test] fn test_decode_map_without_size() { let mut input: &[u8] = &[0x02, 0x08, 0x74, 0x65, 0x73, 0x74, 0x02, 0x00]; let result = decode(&Schema::Map(Box::new(Schema::Int)), &mut input); let mut expected = HashMap::new(); expected.insert(String::from("test"), Int(1)); assert_eq!(Map(expected), result.unwrap()); } #[test] fn test_decode_map_with_size() { let mut input: &[u8] = &[0x01, 0x0C, 0x08, 0x74, 0x65, 0x73, 0x74, 0x02, 0x00]; let result = decode(&Schema::Map(Box::new(Schema::Int)), &mut input); let mut expected = HashMap::new(); expected.insert(String::from("test"), Int(1)); assert_eq!(Map(expected), result.unwrap()); } #[test] fn test_negative_decimal_value() { use crate::{encode::encode, schema::Name}; use num_bigint::ToBigInt; let inner = Box::new(Schema::Fixed { size: 2, doc: None, name: Name::new("decimal"), }); let schema = Schema::Decimal { inner, precision: 4, scale: 2, }; let bigint = (-423).to_bigint().unwrap(); let value = Value::Decimal(Decimal::from(bigint.to_signed_bytes_be())); let mut buffer = Vec::new(); encode(&value, &schema, &mut buffer); let mut bytes = &buffer[..]; let result = decode(&schema, &mut bytes).unwrap(); assert_eq!(result, value); } #[test] fn test_decode_decimal_with_bigger_than_necessary_size() { use crate::{encode::encode, schema::Name}; use num_bigint::ToBigInt; let inner = Box::new(Schema::Fixed { size: 13, name: Name::new("decimal"), doc: None, }); let schema = Schema::Decimal { inner, precision: 4, scale: 2, }; let value = Value::Decimal(Decimal::from( ((-423).to_bigint().unwrap()).to_signed_bytes_be(), )); let mut buffer = Vec::<u8>::new(); encode(&value, &schema, &mut buffer); let mut bytes: &[u8] = &buffer[..]; let result = decode(&schema, &mut bytes).unwrap(); assert_eq!(result, value); } }
37.92328
99
0.476177
edfe9d6910ec5f78d089136188d88d0d6133afda
6,754
//! A crate containing various basic types that are especially useful when //! writing Rust canisters. use candid::CandidType; use ic_protobuf::proxy::ProxyDecodeError; use ic_protobuf::state::system_metadata::v1 as pb_metadata; use ic_protobuf::types::v1 as pb; use phantom_newtype::{AmountOf, DisplayerOf, Id}; use serde::{Deserialize, Serialize}; use std::{convert::TryFrom, fmt, slice::Iter}; use strum_macros::EnumString; mod canister_id; mod pb_internal; mod principal_id; pub use candid::types::ic_types; pub use canister_id::{CanisterId, CanisterIdError, CanisterIdError as CanisterIdBlobParseError}; pub use principal_id::{ PrincipalId, PrincipalIdError, PrincipalIdError as PrincipalIdBlobParseError, PrincipalIdError as PrincipalIdParseError, }; pub struct RegistryVersionTag {} /// A type representing the registry's version. pub type RegistryVersion = AmountOf<RegistryVersionTag, u64>; pub struct NodeTag {} /// A type representing a node's [`PrincipalId`]. pub type NodeId = Id<NodeTag, PrincipalId>; pub struct SubnetTag {} /// A type representing a subnet's [`PrincipalId`]. pub type SubnetId = Id<SubnetTag, PrincipalId>; pub struct NumSecondsTag; /// Models a non-negative number of seconds. pub type NumSeconds = AmountOf<NumSecondsTag, u64>; pub struct NumBytesTag; /// This type models a non-negative number of bytes. /// /// This type is primarily useful in the context of tracking the memory usage /// and allocation of a Canister. pub type NumBytes = AmountOf<NumBytesTag, u64>; impl DisplayerOf<NumBytes> for NumBytesTag { /// Formats the number of bytes using the most appropriate binary power unit /// (kiB, MiB, GiB, etc), with up 2 decimals (e.g., 123.45 MiB). /// /// There will be no decimals iff the chosen unit is 'bytes'. fn display(num_bytes: &NumBytes, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", byte_unit::Byte::from_bytes(num_bytes.get().into()) .get_appropriate_unit(true) .format(2) ) } } /// Indicates whether the canister is running, stopping, or stopped. /// /// Unlike `CanisterStatus`, it contains no additional metadata. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, CandidType)] pub enum CanisterStatusType { #[serde(rename = "running")] Running, #[serde(rename = "stopping")] Stopping, #[serde(rename = "stopped")] Stopped, } /// These strings are used to generate metrics -- changing any existing entries /// will invalidate monitoring dashboards. impl fmt::Display for CanisterStatusType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { CanisterStatusType::Running => write!(f, "running"), CanisterStatusType::Stopping => write!(f, "stopping"), CanisterStatusType::Stopped => write!(f, "stopped"), } } } /// The mode with which a canister is installed. #[derive( Clone, Debug, Deserialize, PartialEq, Serialize, Eq, EnumString, Hash, CandidType, Copy, )] pub enum CanisterInstallMode { /// A fresh install of a new canister. #[serde(rename = "install")] #[strum(serialize = "install")] Install, /// Reinstalling a canister that was already installed. #[serde(rename = "reinstall")] #[strum(serialize = "reinstall")] Reinstall, /// Upgrade an existing canister. #[serde(rename = "upgrade")] #[strum(serialize = "upgrade")] Upgrade, } impl Default for CanisterInstallMode { fn default() -> Self { CanisterInstallMode::Install } } impl CanisterInstallMode { pub fn iter() -> Iter<'static, CanisterInstallMode> { static MODES: [CanisterInstallMode; 3] = [ CanisterInstallMode::Install, CanisterInstallMode::Reinstall, CanisterInstallMode::Upgrade, ]; MODES.iter() } } /// A type to represent an error that can occur when installing a canister. #[derive(Debug)] pub struct CanisterInstallModeError(pub String); impl TryFrom<String> for CanisterInstallMode { type Error = CanisterInstallModeError; fn try_from(mode: String) -> Result<Self, Self::Error> { let mode = mode.as_str(); match mode { "install" => Ok(CanisterInstallMode::Install), "reinstall" => Ok(CanisterInstallMode::Reinstall), "upgrade" => Ok(CanisterInstallMode::Upgrade), _ => Err(CanisterInstallModeError(mode.to_string())), } } } impl From<CanisterInstallMode> for String { fn from(mode: CanisterInstallMode) -> Self { let res = match mode { CanisterInstallMode::Install => "install", CanisterInstallMode::Reinstall => "reinstall", CanisterInstallMode::Upgrade => "upgrade", }; res.to_string() } } /// Converts a SubnetId into its protobuf definition. Normally, we would use /// `impl From<SubnetId> for pb::SubnetId` here however we cannot as both /// `Id` and `pb::SubnetId` are defined in other crates. pub fn subnet_id_into_protobuf(id: SubnetId) -> pb::SubnetId { pb::SubnetId { principal_id: Some(pb::PrincipalId::from(id.get())), } } /// From its protobuf definition convert to a SubnetId. Normally, we would /// use `impl TryFrom<pb::SubnetId> for SubnetId` here however we cannot as /// both `Id` and `pb::SubnetId` are defined in other crates. pub fn subnet_id_try_from_protobuf(value: pb::SubnetId) -> Result<SubnetId, ProxyDecodeError> { let principal_id = PrincipalId::try_from( value .principal_id .ok_or(ProxyDecodeError::MissingField("SubnetId::principal_id"))?, )?; Ok(SubnetId::from(principal_id)) } impl From<PrincipalIdError> for ProxyDecodeError { fn from(err: PrincipalIdError) -> Self { Self::InvalidPrincipalId(Box::new(err)) } } impl From<CanisterIdError> for ProxyDecodeError { fn from(err: CanisterIdError) -> Self { Self::InvalidCanisterId(Box::new(err)) } } #[derive(Clone, Debug, PartialEq, CandidType, Eq, Hash, Serialize, Deserialize)] pub enum HttpMethodType { GET, } impl From<&HttpMethodType> for pb_metadata::HttpMethodType { fn from(http_method_type: &HttpMethodType) -> Self { match http_method_type { HttpMethodType::GET => pb_metadata::HttpMethodType::Get, } } } impl From<pb_metadata::HttpMethodType> for HttpMethodType { fn from(http_method_type: pb_metadata::HttpMethodType) -> Self { match http_method_type { pb_metadata::HttpMethodType::Unspecified | pb_metadata::HttpMethodType::Get => { HttpMethodType::GET } } } }
32.315789
96
0.669825
d73a6a4ab5412c46fa7d28e47a70c6e7e451b771
28,432
use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send}; use mpstthree::role::broadcast::RoleBroadcast; use mpstthree::role::end::RoleEnd; use mpstthree::{ bundle_struct_fork_close_multi, create_fn_choose_mpst_multi_to_all_bundle, create_multiple_normal_role_short, create_recv_mpst_session_bundle, create_send_mpst_session_bundle, offer_mpst, }; use std::error::Error; // Create the new MeshedChannels for ten participants and the close and fork functions bundle_struct_fork_close_multi!(close_mpst_multi, fork_mpst, MeshedChannelsTen, 10); // Create new roles // normal create_multiple_normal_role_short!(A, B, C, D, E, F, G, H, I, J); // Create new send functions // A create_send_mpst_session_bundle!( send_mpst_a_to_b, RoleB, 1 | send_mpst_a_to_c, RoleC, 2 | send_mpst_a_to_d, RoleD, 3 | send_mpst_a_to_e, RoleE, 4 | send_mpst_a_to_f, RoleF, 5 | send_mpst_a_to_g, RoleG, 6 | send_mpst_a_to_h, RoleH, 7 | send_mpst_a_to_i, RoleI, 8 | send_mpst_a_to_j, RoleJ, 9 | => RoleA, MeshedChannelsTen, 10 ); // B create_send_mpst_session_bundle!( send_mpst_b_to_a, RoleA, 1 | send_mpst_b_to_c, RoleC, 2 | send_mpst_b_to_d, RoleD, 3 | send_mpst_b_to_e, RoleE, 4 | send_mpst_b_to_f, RoleF, 5 | send_mpst_b_to_g, RoleG, 6 | send_mpst_b_to_h, RoleH, 7 | send_mpst_b_to_i, RoleI, 8 | send_mpst_b_to_j, RoleJ, 9 | => RoleB, MeshedChannelsTen, 10 ); // C create_send_mpst_session_bundle!( send_mpst_c_to_a, RoleA, 1 | send_mpst_c_to_b, RoleB, 2 | send_mpst_c_to_d, RoleD, 3 | send_mpst_c_to_e, RoleE, 4 | send_mpst_c_to_f, RoleF, 5 | send_mpst_c_to_g, RoleG, 6 | send_mpst_c_to_h, RoleH, 7 | send_mpst_c_to_i, RoleI, 8 | send_mpst_c_to_j, RoleJ, 9 | => RoleC, MeshedChannelsTen, 10 ); // D create_send_mpst_session_bundle!( send_mpst_d_to_a, RoleA, 1 | send_mpst_d_to_b, RoleB, 2 | send_mpst_d_to_c, RoleC, 3 | send_mpst_d_to_e, RoleE, 4 | send_mpst_d_to_f, RoleF, 5 | send_mpst_d_to_g, RoleG, 6 | send_mpst_d_to_h, RoleH, 7 | send_mpst_d_to_i, RoleI, 8 | send_mpst_d_to_j, RoleJ, 9 | => RoleD, MeshedChannelsTen, 10 ); // E create_send_mpst_session_bundle!( send_mpst_e_to_a, RoleA, 1 | send_mpst_e_to_b, RoleB, 2 | send_mpst_e_to_c, RoleC, 3 | send_mpst_e_to_d, RoleD, 4 | send_mpst_e_to_f, RoleF, 5 | send_mpst_e_to_g, RoleG, 6 | send_mpst_e_to_h, RoleH, 7 | send_mpst_e_to_i, RoleI, 8 | send_mpst_e_to_j, RoleJ, 9 | => RoleE, MeshedChannelsTen, 10 ); // F create_send_mpst_session_bundle!( send_mpst_f_to_a, RoleA, 1 | send_mpst_f_to_b, RoleB, 2 | send_mpst_f_to_c, RoleC, 3 | send_mpst_f_to_d, RoleD, 4 | send_mpst_f_to_e, RoleE, 5 | send_mpst_f_to_g, RoleG, 6 | send_mpst_f_to_h, RoleH, 7 | send_mpst_f_to_i, RoleI, 8 | send_mpst_f_to_j, RoleJ, 9 | => RoleF, MeshedChannelsTen, 10 ); // G create_send_mpst_session_bundle!( send_mpst_g_to_a, RoleA, 1 | send_mpst_g_to_b, RoleB, 2 | send_mpst_g_to_c, RoleC, 3 | send_mpst_g_to_d, RoleD, 4 | send_mpst_g_to_e, RoleE, 5 | send_mpst_g_to_f, RoleF, 6 | send_mpst_g_to_h, RoleH, 7 | send_mpst_g_to_i, RoleI, 8 | send_mpst_g_to_j, RoleJ, 9 | => RoleG, MeshedChannelsTen, 10 ); // H create_send_mpst_session_bundle!( send_mpst_h_to_a, RoleA, 1 | send_mpst_h_to_b, RoleB, 2 | send_mpst_h_to_c, RoleC, 3 | send_mpst_h_to_d, RoleD, 4 | send_mpst_h_to_e, RoleE, 5 | send_mpst_h_to_f, RoleF, 6 | send_mpst_h_to_g, RoleG, 7 | send_mpst_h_to_i, RoleI, 8 | send_mpst_h_to_j, RoleJ, 9 | => RoleH, MeshedChannelsTen, 10 ); // I create_send_mpst_session_bundle!( send_mpst_i_to_a, RoleA, 1 | send_mpst_i_to_b, RoleB, 2 | send_mpst_i_to_c, RoleC, 3 | send_mpst_i_to_d, RoleD, 4 | send_mpst_i_to_e, RoleE, 5 | send_mpst_i_to_f, RoleF, 6 | send_mpst_i_to_g, RoleG, 7 | send_mpst_i_to_h, RoleH, 8 | send_mpst_i_to_j, RoleJ, 9 | => RoleI, MeshedChannelsTen, 10 ); // J create_send_mpst_session_bundle!( send_mpst_j_to_a, RoleA, 1 | send_mpst_j_to_b, RoleB, 2 | send_mpst_j_to_c, RoleC, 3 | send_mpst_j_to_d, RoleD, 4 | send_mpst_j_to_e, RoleE, 5 | send_mpst_j_to_f, RoleF, 6 | send_mpst_j_to_g, RoleG, 7 | send_mpst_j_to_h, RoleH, 8 | send_mpst_j_to_i, RoleI, 9 | => RoleJ, MeshedChannelsTen, 10 ); // Create new recv functions and related types // A create_recv_mpst_session_bundle!( recv_mpst_a_from_b, RoleB, 1 | recv_mpst_a_from_c, RoleC, 2 | recv_mpst_a_from_d, RoleD, 3 | recv_mpst_a_from_e, RoleE, 4 | recv_mpst_a_from_f, RoleF, 5 | recv_mpst_a_from_g, RoleG, 6 | recv_mpst_a_from_h, RoleH, 7 | recv_mpst_a_from_i, RoleI, 8 | recv_mpst_a_from_j, RoleJ, 9 | => RoleA, MeshedChannelsTen, 10 ); // B create_recv_mpst_session_bundle!( recv_mpst_b_from_a, RoleA, 1 | recv_mpst_b_from_c, RoleC, 2 | recv_mpst_b_from_d, RoleD, 3 | recv_mpst_b_from_e, RoleE, 4 | recv_mpst_b_from_f, RoleF, 5 | recv_mpst_b_from_g, RoleG, 6 | recv_mpst_b_from_h, RoleH, 7 | recv_mpst_b_from_i, RoleI, 8 | recv_mpst_b_from_j, RoleJ, 9 | => RoleB, MeshedChannelsTen, 10 ); // C create_recv_mpst_session_bundle!( recv_mpst_c_from_a, RoleA, 1 | recv_mpst_c_from_b, RoleB, 2 | recv_mpst_c_from_d, RoleD, 3 | recv_mpst_c_from_e, RoleE, 4 | recv_mpst_c_from_f, RoleF, 5 | recv_mpst_c_from_g, RoleG, 6 | recv_mpst_c_from_h, RoleH, 7 | recv_mpst_c_from_i, RoleI, 8 | recv_mpst_c_from_j, RoleJ, 9 | => RoleC, MeshedChannelsTen, 10 ); // D create_recv_mpst_session_bundle!( recv_mpst_d_from_a, RoleA, 1 | recv_mpst_d_from_b, RoleB, 2 | recv_mpst_d_from_c, RoleC, 3 | recv_mpst_d_from_e, RoleE, 4 | recv_mpst_d_from_f, RoleF, 5 | recv_mpst_d_from_g, RoleG, 6 | recv_mpst_d_from_h, RoleH, 7 | recv_mpst_d_from_i, RoleI, 8 | recv_mpst_d_from_j, RoleJ, 9 | => RoleD, MeshedChannelsTen, 10 ); // E create_recv_mpst_session_bundle!( recv_mpst_e_from_a, RoleA, 1 | recv_mpst_e_from_b, RoleB, 2 | recv_mpst_e_from_c, RoleC, 3 | recv_mpst_e_from_d, RoleD, 4 | recv_mpst_e_from_f, RoleF, 5 | recv_mpst_e_from_g, RoleG, 6 | recv_mpst_e_from_h, RoleH, 7 | recv_mpst_e_from_i, RoleI, 8 | recv_mpst_e_from_j, RoleJ, 9 | => RoleE, MeshedChannelsTen, 10 ); // F create_recv_mpst_session_bundle!( recv_mpst_f_from_a, RoleA, 1 | recv_mpst_f_from_b, RoleB, 2 | recv_mpst_f_from_c, RoleC, 3 | recv_mpst_f_from_d, RoleD, 4 | recv_mpst_f_from_e, RoleE, 5 | recv_mpst_f_from_g, RoleG, 6 | recv_mpst_f_from_h, RoleH, 7 | recv_mpst_f_from_i, RoleI, 8 | recv_mpst_f_from_j, RoleJ, 9 | => RoleF, MeshedChannelsTen, 10 ); // G create_recv_mpst_session_bundle!( recv_mpst_g_from_a, RoleA, 1 | recv_mpst_g_from_b, RoleB, 2 | recv_mpst_g_from_c, RoleC, 3 | recv_mpst_g_from_d, RoleD, 4 | recv_mpst_g_from_e, RoleE, 5 | recv_mpst_g_from_f, RoleF, 6 | recv_mpst_g_from_h, RoleH, 7 | recv_mpst_g_from_i, RoleI, 8 | recv_mpst_g_from_j, RoleJ, 9 | => RoleG, MeshedChannelsTen, 10 ); // H create_recv_mpst_session_bundle!( recv_mpst_h_from_a, RoleA, 1 | recv_mpst_h_from_b, RoleB, 2 | recv_mpst_h_from_c, RoleC, 3 | recv_mpst_h_from_d, RoleD, 4 | recv_mpst_h_from_e, RoleE, 5 | recv_mpst_h_from_f, RoleF, 6 | recv_mpst_h_from_g, RoleG, 7 | recv_mpst_h_from_i, RoleI, 8 | recv_mpst_h_from_j, RoleJ, 9 | => RoleH, MeshedChannelsTen, 10 ); // I create_recv_mpst_session_bundle!( recv_mpst_i_from_a, RoleA, 1 | recv_mpst_i_from_b, RoleB, 2 | recv_mpst_i_from_c, RoleC, 3 | recv_mpst_i_from_d, RoleD, 4 | recv_mpst_i_from_e, RoleE, 5 | recv_mpst_i_from_f, RoleF, 6 | recv_mpst_i_from_g, RoleG, 7 | recv_mpst_i_from_h, RoleH, 8 | recv_mpst_i_from_j, RoleJ, 9 | => RoleI, MeshedChannelsTen, 10 ); // J create_recv_mpst_session_bundle!( recv_mpst_j_from_a, RoleA, 1 | recv_mpst_j_from_b, RoleB, 2 | recv_mpst_j_from_c, RoleC, 3 | recv_mpst_j_from_d, RoleD, 4 | recv_mpst_j_from_e, RoleE, 5 | recv_mpst_j_from_f, RoleF, 6 | recv_mpst_j_from_g, RoleG, 7 | recv_mpst_j_from_h, RoleH, 8 | recv_mpst_j_from_i, RoleI, 9 | => RoleJ, MeshedChannelsTen, 10 ); // Names type NameA = RoleA<RoleEnd>; type NameB = RoleB<RoleEnd>; type NameC = RoleC<RoleEnd>; type NameD = RoleD<RoleEnd>; type NameE = RoleE<RoleEnd>; type NameF = RoleF<RoleEnd>; type NameG = RoleG<RoleEnd>; type NameH = RoleH<RoleEnd>; type NameI = RoleI<RoleEnd>; type NameJ = RoleJ<RoleEnd>; // Types // Send/Recv type RS = Recv<(), Send<(), End>>; type SR = Send<(), Recv<(), End>>; // Roles type R2A<R> = RoleA<RoleA<R>>; type R2B<R> = RoleB<RoleB<R>>; type R2C<R> = RoleC<RoleC<R>>; type R2D<R> = RoleD<RoleD<R>>; type R2E<R> = RoleE<RoleE<R>>; type R2F<R> = RoleF<RoleF<R>>; type R2G<R> = RoleG<RoleG<R>>; type R2H<R> = RoleH<RoleH<R>>; type R2I<R> = RoleI<RoleI<R>>; type R2J<R> = RoleJ<RoleJ<R>>; // A enum Branching0fromJtoA { More( MeshedChannelsTen< RS, RS, RS, RS, RS, RS, RS, RS, Recv<(), Send<(), RecursAtoJ>>, R2J<R2B<R2C<R2D<R2E<R2F<R2G<R2H<R2I<RoleJ<RoleEnd>>>>>>>>>>, NameA, >, ), Done(MeshedChannelsTen<End, End, End, End, End, End, End, End, End, RoleEnd, NameA>), } type RecursAtoJ = Recv<Branching0fromJtoA, End>; // B enum Branching0fromJtoB { More( MeshedChannelsTen< SR, RS, RS, RS, RS, RS, RS, RS, Recv<(), Send<(), RecursBtoJ>>, R2J<R2A<R2C<R2D<R2E<R2F<R2G<R2H<R2I<RoleJ<RoleEnd>>>>>>>>>>, NameB, >, ), Done(MeshedChannelsTen<End, End, End, End, End, End, End, End, End, RoleEnd, NameB>), } type RecursBtoJ = Recv<Branching0fromJtoB, End>; // C enum Branching0fromJtoC { More( MeshedChannelsTen< SR, SR, RS, RS, RS, RS, RS, RS, Recv<(), Send<(), RecursCtoJ>>, R2J<R2A<R2B<R2D<R2E<R2F<R2G<R2H<R2I<RoleJ<RoleEnd>>>>>>>>>>, NameC, >, ), Done(MeshedChannelsTen<End, End, End, End, End, End, End, End, End, RoleEnd, NameC>), } type RecursCtoJ = Recv<Branching0fromJtoC, End>; // D enum Branching0fromJtoD { More( MeshedChannelsTen< SR, SR, SR, RS, RS, RS, RS, RS, Recv<(), Send<(), RecursDtoJ>>, R2J<R2A<R2B<R2C<R2E<R2F<R2G<R2H<R2I<RoleJ<RoleEnd>>>>>>>>>>, NameD, >, ), Done(MeshedChannelsTen<End, End, End, End, End, End, End, End, End, RoleEnd, NameD>), } type RecursDtoJ = Recv<Branching0fromJtoD, End>; // E enum Branching0fromJtoE { More( MeshedChannelsTen< SR, SR, SR, SR, RS, RS, RS, RS, Recv<(), Send<(), RecursEtoJ>>, R2J<R2A<R2B<R2C<R2D<R2F<R2G<R2H<R2I<RoleJ<RoleEnd>>>>>>>>>>, NameE, >, ), Done(MeshedChannelsTen<End, End, End, End, End, End, End, End, End, RoleEnd, NameE>), } type RecursEtoJ = Recv<Branching0fromJtoE, End>; // F enum Branching0fromJtoF { More( MeshedChannelsTen< SR, SR, SR, SR, SR, RS, RS, RS, Recv<(), Send<(), RecursFtoJ>>, R2J<R2A<R2B<R2C<R2D<R2E<R2G<R2H<R2I<RoleJ<RoleEnd>>>>>>>>>>, NameF, >, ), Done(MeshedChannelsTen<End, End, End, End, End, End, End, End, End, RoleEnd, NameF>), } type RecursFtoJ = Recv<Branching0fromJtoF, End>; // G enum Branching0fromJtoG { More( MeshedChannelsTen< SR, SR, SR, SR, SR, SR, RS, RS, Recv<(), Send<(), RecursGtoJ>>, R2J<R2A<R2B<R2C<R2D<R2E<R2F<R2H<R2I<RoleJ<RoleEnd>>>>>>>>>>, NameG, >, ), Done(MeshedChannelsTen<End, End, End, End, End, End, End, End, End, RoleEnd, NameG>), } type RecursGtoJ = Recv<Branching0fromJtoG, End>; // H enum Branching0fromJtoH { More( MeshedChannelsTen< SR, SR, SR, SR, SR, SR, SR, RS, Recv<(), Send<(), RecursHtoJ>>, R2J<R2A<R2B<R2C<R2D<R2E<R2F<R2G<R2I<RoleJ<RoleEnd>>>>>>>>>>, NameH, >, ), Done(MeshedChannelsTen<End, End, End, End, End, End, End, End, End, RoleEnd, NameH>), } type RecursHtoJ = Recv<Branching0fromJtoH, End>; // I enum Branching0fromJtoI { More( MeshedChannelsTen< SR, SR, SR, SR, SR, SR, SR, SR, Recv<(), Send<(), RecursItoJ>>, R2J<R2A<R2B<R2C<R2D<R2E<R2F<R2G<R2H<RoleJ<RoleEnd>>>>>>>>>>, NameI, >, ), Done(MeshedChannelsTen<End, End, End, End, End, End, End, End, End, RoleEnd, NameI>), } type RecursItoJ = Recv<Branching0fromJtoI, End>; // J type Choose0fromJtoA = Send<Branching0fromJtoA, End>; type Choose0fromJtoB = Send<Branching0fromJtoB, End>; type Choose0fromJtoC = Send<Branching0fromJtoC, End>; type Choose0fromJtoD = Send<Branching0fromJtoD, End>; type Choose0fromJtoE = Send<Branching0fromJtoE, End>; type Choose0fromJtoF = Send<Branching0fromJtoF, End>; type Choose0fromJtoG = Send<Branching0fromJtoG, End>; type Choose0fromJtoH = Send<Branching0fromJtoH, End>; type Choose0fromJtoI = Send<Branching0fromJtoI, End>; type EndpointDoneJ = MeshedChannelsTen<End, End, End, End, End, End, End, End, End, RoleEnd, NameJ>; type EndpointMoreJ = MeshedChannelsTen< Send<(), Recv<(), Choose0fromJtoA>>, Send<(), Recv<(), Choose0fromJtoB>>, Send<(), Recv<(), Choose0fromJtoC>>, Send<(), Recv<(), Choose0fromJtoD>>, Send<(), Recv<(), Choose0fromJtoE>>, Send<(), Recv<(), Choose0fromJtoF>>, Send<(), Recv<(), Choose0fromJtoG>>, Send<(), Recv<(), Choose0fromJtoH>>, Send<(), Recv<(), Choose0fromJtoI>>, R2A<R2B<R2C<R2D<R2E<R2F<R2G<R2H<R2I<RoleBroadcast>>>>>>>>>, NameJ, >; // Creating the MP sessions type EndpointA = MeshedChannelsTen<End, End, End, End, End, End, End, End, RecursAtoJ, RoleJ<RoleEnd>, NameA>; type EndpointB = MeshedChannelsTen<End, End, End, End, End, End, End, End, RecursBtoJ, RoleJ<RoleEnd>, NameB>; type EndpointC = MeshedChannelsTen<End, End, End, End, End, End, End, End, RecursCtoJ, RoleJ<RoleEnd>, NameC>; type EndpointD = MeshedChannelsTen<End, End, End, End, End, End, End, End, RecursDtoJ, RoleJ<RoleEnd>, NameD>; type EndpointE = MeshedChannelsTen<End, End, End, End, End, End, End, End, RecursEtoJ, RoleJ<RoleEnd>, NameE>; type EndpointF = MeshedChannelsTen<End, End, End, End, End, End, End, End, RecursFtoJ, RoleJ<RoleEnd>, NameF>; type EndpointG = MeshedChannelsTen<End, End, End, End, End, End, End, End, RecursGtoJ, RoleJ<RoleEnd>, NameG>; type EndpointH = MeshedChannelsTen<End, End, End, End, End, End, End, End, RecursHtoJ, RoleJ<RoleEnd>, NameH>; type EndpointI = MeshedChannelsTen<End, End, End, End, End, End, End, End, RecursItoJ, RoleJ<RoleEnd>, NameI>; type EndpointJ = MeshedChannelsTen< Choose0fromJtoA, Choose0fromJtoB, Choose0fromJtoC, Choose0fromJtoD, Choose0fromJtoE, Choose0fromJtoF, Choose0fromJtoG, Choose0fromJtoH, Choose0fromJtoI, RoleBroadcast, NameJ, >; create_fn_choose_mpst_multi_to_all_bundle!( done_from_j_to_all, more_from_j_to_all, => Done, More, => EndpointDoneJ, EndpointMoreJ, => Branching0fromJtoA, Branching0fromJtoB, Branching0fromJtoC, Branching0fromJtoD, Branching0fromJtoE, Branching0fromJtoF, Branching0fromJtoG, Branching0fromJtoH, Branching0fromJtoI, => RoleA, RoleB, RoleC, RoleD, RoleE, RoleF, RoleG, RoleH, RoleI, => RoleJ, MeshedChannelsTen, 10 ); fn endpoint_a(s: EndpointA) -> Result<(), Box<dyn Error>> { offer_mpst!(s, recv_mpst_a_from_j, { Branching0fromJtoA::Done(s) => { close_mpst_multi(s) }, Branching0fromJtoA::More(s) => { let (_, s) = recv_mpst_a_from_j(s)?; let s = send_mpst_a_to_j((), s); let (_, s) = recv_mpst_a_from_b(s)?; let s = send_mpst_a_to_b((), s); let (_, s) = recv_mpst_a_from_c(s)?; let s = send_mpst_a_to_c((), s); let (_, s) = recv_mpst_a_from_d(s)?; let s = send_mpst_a_to_d((), s); let (_, s) = recv_mpst_a_from_e(s)?; let s = send_mpst_a_to_e((), s); let (_, s) = recv_mpst_a_from_f(s)?; let s = send_mpst_a_to_f((), s); let (_, s) = recv_mpst_a_from_g(s)?; let s = send_mpst_a_to_g((), s); let (_, s) = recv_mpst_a_from_h(s)?; let s = send_mpst_a_to_h((), s); let (_, s) = recv_mpst_a_from_i(s)?; let s = send_mpst_a_to_i((), s); endpoint_a(s) }, }) } fn endpoint_b(s: EndpointB) -> Result<(), Box<dyn Error>> { offer_mpst!(s, recv_mpst_b_from_j, { Branching0fromJtoB::Done(s) => { close_mpst_multi(s) }, Branching0fromJtoB::More(s) => { let (_, s) = recv_mpst_b_from_j(s)?; let s = send_mpst_b_to_j((), s); let s = send_mpst_b_to_a((), s); let (_, s) = recv_mpst_b_from_a(s)?; let (_, s) = recv_mpst_b_from_c(s)?; let s = send_mpst_b_to_c((), s); let (_, s) = recv_mpst_b_from_d(s)?; let s = send_mpst_b_to_d((), s); let (_, s) = recv_mpst_b_from_e(s)?; let s = send_mpst_b_to_e((), s); let (_, s) = recv_mpst_b_from_f(s)?; let s = send_mpst_b_to_f((), s); let (_, s) = recv_mpst_b_from_g(s)?; let s = send_mpst_b_to_g((), s); let (_, s) = recv_mpst_b_from_h(s)?; let s = send_mpst_b_to_h((), s); let (_, s) = recv_mpst_b_from_i(s)?; let s = send_mpst_b_to_i((), s); endpoint_b(s) }, }) } fn endpoint_c(s: EndpointC) -> Result<(), Box<dyn Error>> { offer_mpst!(s, recv_mpst_c_from_j, { Branching0fromJtoC::Done(s) => { close_mpst_multi(s) }, Branching0fromJtoC::More(s) => { let (_, s) = recv_mpst_c_from_j(s)?; let s = send_mpst_c_to_j((), s); let s = send_mpst_c_to_a((), s); let (_, s) = recv_mpst_c_from_a(s)?; let s = send_mpst_c_to_b((), s); let (_, s) = recv_mpst_c_from_b(s)?; let (_, s) = recv_mpst_c_from_d(s)?; let s = send_mpst_c_to_d((), s); let (_, s) = recv_mpst_c_from_e(s)?; let s = send_mpst_c_to_e((), s); let (_, s) = recv_mpst_c_from_f(s)?; let s = send_mpst_c_to_f((), s); let (_, s) = recv_mpst_c_from_g(s)?; let s = send_mpst_c_to_g((), s); let (_, s) = recv_mpst_c_from_h(s)?; let s = send_mpst_c_to_h((), s); let (_, s) = recv_mpst_c_from_i(s)?; let s = send_mpst_c_to_i((), s); endpoint_c(s) }, }) } fn endpoint_d(s: EndpointD) -> Result<(), Box<dyn Error>> { offer_mpst!(s, recv_mpst_d_from_j, { Branching0fromJtoD::Done(s) => { close_mpst_multi(s) }, Branching0fromJtoD::More(s) => { let (_, s) = recv_mpst_d_from_j(s)?; let s = send_mpst_d_to_j((), s); let s = send_mpst_d_to_a((), s); let (_, s) = recv_mpst_d_from_a(s)?; let s = send_mpst_d_to_b((), s); let (_, s) = recv_mpst_d_from_b(s)?; let s = send_mpst_d_to_c((), s); let (_, s) = recv_mpst_d_from_c(s)?; let (_, s) = recv_mpst_d_from_e(s)?; let s = send_mpst_d_to_e((), s); let (_, s) = recv_mpst_d_from_f(s)?; let s = send_mpst_d_to_f((), s); let (_, s) = recv_mpst_d_from_g(s)?; let s = send_mpst_d_to_g((), s); let (_, s) = recv_mpst_d_from_h(s)?; let s = send_mpst_d_to_h((), s); let (_, s) = recv_mpst_d_from_i(s)?; let s = send_mpst_d_to_i((), s); endpoint_d(s) }, }) } fn endpoint_e(s: EndpointE) -> Result<(), Box<dyn Error>> { offer_mpst!(s, recv_mpst_e_from_j, { Branching0fromJtoE::Done(s) => { close_mpst_multi(s) }, Branching0fromJtoE::More(s) => { let (_, s) = recv_mpst_e_from_j(s)?; let s = send_mpst_e_to_j((), s); let s = send_mpst_e_to_a((), s); let (_, s) = recv_mpst_e_from_a(s)?; let s = send_mpst_e_to_b((), s); let (_, s) = recv_mpst_e_from_b(s)?; let s = send_mpst_e_to_c((), s); let (_, s) = recv_mpst_e_from_c(s)?; let s = send_mpst_e_to_d((), s); let (_, s) = recv_mpst_e_from_d(s)?; let (_, s) = recv_mpst_e_from_f(s)?; let s = send_mpst_e_to_f((), s); let (_, s) = recv_mpst_e_from_g(s)?; let s = send_mpst_e_to_g((), s); let (_, s) = recv_mpst_e_from_h(s)?; let s = send_mpst_e_to_h((), s); let (_, s) = recv_mpst_e_from_i(s)?; let s = send_mpst_e_to_i((), s); endpoint_e(s) }, }) } fn endpoint_f(s: EndpointF) -> Result<(), Box<dyn Error>> { offer_mpst!(s, recv_mpst_f_from_j, { Branching0fromJtoF::Done(s) => { close_mpst_multi(s) }, Branching0fromJtoF::More(s) => { let (_, s) = recv_mpst_f_from_j(s)?; let s = send_mpst_f_to_j((), s); let s = send_mpst_f_to_a((), s); let (_, s) = recv_mpst_f_from_a(s)?; let s = send_mpst_f_to_b((), s); let (_, s) = recv_mpst_f_from_b(s)?; let s = send_mpst_f_to_c((), s); let (_, s) = recv_mpst_f_from_c(s)?; let s = send_mpst_f_to_d((), s); let (_, s) = recv_mpst_f_from_d(s)?; let s = send_mpst_f_to_e((), s); let (_, s) = recv_mpst_f_from_e(s)?; let (_, s) = recv_mpst_f_from_g(s)?; let s = send_mpst_f_to_g((), s); let (_, s) = recv_mpst_f_from_h(s)?; let s = send_mpst_f_to_h((), s); let (_, s) = recv_mpst_f_from_i(s)?; let s = send_mpst_f_to_i((), s); endpoint_f(s) }, }) } fn endpoint_g(s: EndpointG) -> Result<(), Box<dyn Error>> { offer_mpst!(s, recv_mpst_g_from_j, { Branching0fromJtoG::Done(s) => { close_mpst_multi(s) }, Branching0fromJtoG::More(s) => { let (_, s) = recv_mpst_g_from_j(s)?; let s = send_mpst_g_to_j((), s); let s = send_mpst_g_to_a((), s); let (_, s) = recv_mpst_g_from_a(s)?; let s = send_mpst_g_to_b((), s); let (_, s) = recv_mpst_g_from_b(s)?; let s = send_mpst_g_to_c((), s); let (_, s) = recv_mpst_g_from_c(s)?; let s = send_mpst_g_to_d((), s); let (_, s) = recv_mpst_g_from_d(s)?; let s = send_mpst_g_to_e((), s); let (_, s) = recv_mpst_g_from_e(s)?; let s = send_mpst_g_to_f((), s); let (_, s) = recv_mpst_g_from_f(s)?; let (_, s) = recv_mpst_g_from_h(s)?; let s = send_mpst_g_to_h((), s); let (_, s) = recv_mpst_g_from_i(s)?; let s = send_mpst_g_to_i((), s); endpoint_g(s) }, }) } fn endpoint_h(s: EndpointH) -> Result<(), Box<dyn Error>> { offer_mpst!(s, recv_mpst_h_from_j, { Branching0fromJtoH::Done(s) => { close_mpst_multi(s) }, Branching0fromJtoH::More(s) => { let (_, s) = recv_mpst_h_from_j(s)?; let s = send_mpst_h_to_j((), s); let s = send_mpst_h_to_a((), s); let (_, s) = recv_mpst_h_from_a(s)?; let s = send_mpst_h_to_b((), s); let (_, s) = recv_mpst_h_from_b(s)?; let s = send_mpst_h_to_c((), s); let (_, s) = recv_mpst_h_from_c(s)?; let s = send_mpst_h_to_d((), s); let (_, s) = recv_mpst_h_from_d(s)?; let s = send_mpst_h_to_e((), s); let (_, s) = recv_mpst_h_from_e(s)?; let s = send_mpst_h_to_f((), s); let (_, s) = recv_mpst_h_from_f(s)?; let s = send_mpst_h_to_g((), s); let (_, s) = recv_mpst_h_from_g(s)?; let (_, s) = recv_mpst_h_from_i(s)?; let s = send_mpst_h_to_i((), s); endpoint_h(s) }, }) } fn endpoint_i(s: EndpointI) -> Result<(), Box<dyn Error>> { offer_mpst!(s, recv_mpst_i_from_j, { Branching0fromJtoI::Done(s) => { close_mpst_multi(s) }, Branching0fromJtoI::More(s) => { let (_, s) = recv_mpst_i_from_j(s)?; let s = send_mpst_i_to_j((), s); let s = send_mpst_i_to_a((), s); let (_, s) = recv_mpst_i_from_a(s)?; let s = send_mpst_i_to_b((), s); let (_, s) = recv_mpst_i_from_b(s)?; let s = send_mpst_i_to_c((), s); let (_, s) = recv_mpst_i_from_c(s)?; let s = send_mpst_i_to_d((), s); let (_, s) = recv_mpst_i_from_d(s)?; let s = send_mpst_i_to_e((), s); let (_, s) = recv_mpst_i_from_e(s)?; let s = send_mpst_i_to_f((), s); let (_, s) = recv_mpst_i_from_f(s)?; let s = send_mpst_i_to_g((), s); let (_, s) = recv_mpst_i_from_g(s)?; let s = send_mpst_i_to_h((), s); let (_, s) = recv_mpst_i_from_h(s)?; endpoint_i(s) }, }) } fn endpoint_j(s: EndpointJ) -> Result<(), Box<dyn Error>> { recurs_j(s, 100) } fn recurs_j(s: EndpointJ, index: i64) -> Result<(), Box<dyn Error>> { match index { 0 => { let s = done_from_j_to_all(s); close_mpst_multi(s) } i => { let s = more_from_j_to_all(s); let s = send_mpst_j_to_a((), s); let (_, s) = recv_mpst_j_from_a(s)?; let s = send_mpst_j_to_b((), s); let (_, s) = recv_mpst_j_from_b(s)?; let s = send_mpst_j_to_c((), s); let (_, s) = recv_mpst_j_from_c(s)?; let s = send_mpst_j_to_d((), s); let (_, s) = recv_mpst_j_from_d(s)?; let s = send_mpst_j_to_e((), s); let (_, s) = recv_mpst_j_from_e(s)?; let s = send_mpst_j_to_f((), s); let (_, s) = recv_mpst_j_from_f(s)?; let s = send_mpst_j_to_g((), s); let (_, s) = recv_mpst_j_from_g(s)?; let s = send_mpst_j_to_h((), s); let (_, s) = recv_mpst_j_from_h(s)?; let s = send_mpst_j_to_i((), s); let (_, s) = recv_mpst_j_from_i(s)?; recurs_j(s, i - 1) } } } fn main() { let ( thread_a, thread_b, thread_c, thread_d, thread_e, thread_f, thread_g, thread_h, thread_i, thread_j, ) = fork_mpst( endpoint_a, endpoint_b, endpoint_c, endpoint_d, endpoint_e, endpoint_f, endpoint_g, endpoint_h, endpoint_i, endpoint_j, ); thread_a.join().unwrap(); thread_b.join().unwrap(); thread_c.join().unwrap(); thread_d.join().unwrap(); thread_e.join().unwrap(); thread_f.join().unwrap(); thread_g.join().unwrap(); thread_h.join().unwrap(); thread_i.join().unwrap(); thread_j.join().unwrap(); }
31.591111
100
0.570203
91e40de69b90635fa31983fb7f17d6e5c4d2a5fd
963
use std::fmt::Display; use hex::FromHex; use beserial::{Deserialize, Serialize}; #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Serialize, Deserialize, Display)] #[repr(u8)] pub enum AccountType { Basic = 0, Vesting = 1, HTLC = 2, } impl AccountType { pub fn from_int(x: u8) -> Option<AccountType> { match x { 0 => Some(AccountType::Basic), 1 => Some(AccountType::Vesting), 2 => Some(AccountType::HTLC), _ => None } } } #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Serialize, Deserialize)] #[repr(u8)] pub enum HashAlgorithm { Blake2b = 1, Sha256 = 3 } #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Serialize, Deserialize)] #[repr(u8)] pub enum ProofType { RegularTransfer = 1, EarlyResolve = 2, TimeoutResolve = 3 } create_typed_array!(AnyHash, u8, 32); add_hex_io_fns_typed_arr!(AnyHash, AnyHash::SIZE);
21.886364
94
0.626168
bb271651de5e3b249c33998615f87ac6927b7443
1,399
// 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 parser::{ lexable_token::LexableToken, positioned_trivia::PositionedTrivium, source_text::SourceText, syntax_by_ref::positioned_token::PositionedToken, token_kind::TokenKind, }; pub trait RescanTrivia<Trivium> { fn scan_leading(&self, source_text: &SourceText<'_>) -> Vec<Trivium>; fn scan_trailing(&self, source_text: &SourceText<'_>) -> Vec<Trivium>; } impl RescanTrivia<PositionedTrivium> for PositionedToken<'_> { fn scan_leading(&self, source_text: &SourceText<'_>) -> Vec<PositionedTrivium> { let f = if self.kind() == TokenKind::XHPBody { positioned_parser::scan_leading_xhp_trivia } else { positioned_parser::scan_leading_php_trivia }; f( source_text, self.leading_start_offset().unwrap(), self.leading_width(), ) } fn scan_trailing(&self, source_text: &SourceText<'_>) -> Vec<PositionedTrivium> { let f = if self.kind() == TokenKind::XHPBody { positioned_parser::scan_trailing_xhp_trivia } else { positioned_parser::scan_trailing_php_trivia }; f(source_text, self.leading_start_offset().unwrap()) } }
34.975
95
0.659757
5676ce5bda946817c7728cd98514ac59cf541e41
1,512
//! This module contains the macros //! for creating close functions for interleaved sessions. //! //! *This module is available only if MultiCrusty is built with //! the `"interleaved"` feature.* use crate::binary::struct_trait::end::End; use crate::binary::struct_trait::end::Signal; use crate::meshedchannels::MeshedChannels; use crate::role::end::RoleEnd; use crate::role::Role; use std::error::Error; #[doc(hidden)] pub fn close_mpst_interleaved<R1, R2, R3>( s_1: MeshedChannels<End, End, RoleEnd, R1>, s_2: MeshedChannels<End, End, RoleEnd, R2>, s_3: MeshedChannels<End, End, RoleEnd, R3>, ) -> Result<(), Box<dyn Error>> where R1: Role, R2: Role, R3: Role, { s_1.session1.sender.send(Signal::Stop).unwrap_or(()); s_1.session2.sender.send(Signal::Stop).unwrap_or(()); s_2.session1.sender.send(Signal::Stop).unwrap_or(()); s_2.session2.sender.send(Signal::Stop).unwrap_or(()); s_3.session1.sender.send(Signal::Stop).unwrap_or(()); s_3.session2.sender.send(Signal::Stop).unwrap_or(()); s_1.session1.receiver.recv()?; s_1.session2.receiver.recv()?; s_2.session1.receiver.recv()?; s_2.session2.receiver.recv()?; s_3.session1.receiver.recv()?; s_3.session2.receiver.recv()?; Ok(()) } #[macro_export] #[doc(hidden)] macro_rules! close_mpst_interleaved { ($func_name:ident, $meshedchannels_name:ident, $n_sessions:literal) => { mpst_seq::close_mpst_interleaved!($func_name, $meshedchannels_name, $n_sessions); }; }
30.24
89
0.685185
f96b5a91fca7f24e09eb4f7593704fdb26384570
12,869
#[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::BMXCONSET { #[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 BMXARBR { bits: u8, } impl BMXARBR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct BMXWSDRMR { bits: bool, } impl BMXWSDRMR { #[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 BMXERRISR { bits: bool, } impl BMXERRISR { #[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 BMXERRDSR { bits: bool, } impl BMXERRDSR { #[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 BMXERRDMAR { bits: bool, } impl BMXERRDMAR { #[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 BMXERRICDR { bits: bool, } impl BMXERRICDR { #[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 BMXERRIXIR { bits: bool, } impl BMXERRIXIR { #[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 BMXCHEDMAR { bits: bool, } impl BMXCHEDMAR { #[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 _BMXARBW<'a> { w: &'a mut W, } impl<'a> _BMXARBW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 7; 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 _BMXWSDRMW<'a> { w: &'a mut W, } impl<'a> _BMXWSDRMW<'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 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BMXERRISW<'a> { w: &'a mut W, } impl<'a> _BMXERRISW<'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 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BMXERRDSW<'a> { w: &'a mut W, } impl<'a> _BMXERRDSW<'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 = 17; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BMXERRDMAW<'a> { w: &'a mut W, } impl<'a> _BMXERRDMAW<'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 = 18; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BMXERRICDW<'a> { w: &'a mut W, } impl<'a> _BMXERRICDW<'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 = 19; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BMXERRIXIW<'a> { w: &'a mut W, } impl<'a> _BMXERRIXIW<'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 = 20; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BMXCHEDMAW<'a> { w: &'a mut W, } impl<'a> _BMXCHEDMAW<'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 = 26; 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:2"] #[inline] pub fn bmxarb(&self) -> BMXARBR { let bits = { const MASK: u8 = 7; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; BMXARBR { bits } } #[doc = "Bit 6"] #[inline] pub fn bmxwsdrm(&self) -> BMXWSDRMR { let bits = { const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BMXWSDRMR { bits } } #[doc = "Bit 16"] #[inline] pub fn bmxerris(&self) -> BMXERRISR { let bits = { const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BMXERRISR { bits } } #[doc = "Bit 17"] #[inline] pub fn bmxerrds(&self) -> BMXERRDSR { let bits = { const MASK: bool = true; const OFFSET: u8 = 17; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BMXERRDSR { bits } } #[doc = "Bit 18"] #[inline] pub fn bmxerrdma(&self) -> BMXERRDMAR { let bits = { const MASK: bool = true; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BMXERRDMAR { bits } } #[doc = "Bit 19"] #[inline] pub fn bmxerricd(&self) -> BMXERRICDR { let bits = { const MASK: bool = true; const OFFSET: u8 = 19; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BMXERRICDR { bits } } #[doc = "Bit 20"] #[inline] pub fn bmxerrixi(&self) -> BMXERRIXIR { let bits = { const MASK: bool = true; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BMXERRIXIR { bits } } #[doc = "Bit 26"] #[inline] pub fn bmxchedma(&self) -> BMXCHEDMAR { let bits = { const MASK: bool = true; const OFFSET: u8 = 26; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BMXCHEDMAR { 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:2"] #[inline] pub fn bmxarb(&mut self) -> _BMXARBW { _BMXARBW { w: self } } #[doc = "Bit 6"] #[inline] pub fn bmxwsdrm(&mut self) -> _BMXWSDRMW { _BMXWSDRMW { w: self } } #[doc = "Bit 16"] #[inline] pub fn bmxerris(&mut self) -> _BMXERRISW { _BMXERRISW { w: self } } #[doc = "Bit 17"] #[inline] pub fn bmxerrds(&mut self) -> _BMXERRDSW { _BMXERRDSW { w: self } } #[doc = "Bit 18"] #[inline] pub fn bmxerrdma(&mut self) -> _BMXERRDMAW { _BMXERRDMAW { w: self } } #[doc = "Bit 19"] #[inline] pub fn bmxerricd(&mut self) -> _BMXERRICDW { _BMXERRICDW { w: self } } #[doc = "Bit 20"] #[inline] pub fn bmxerrixi(&mut self) -> _BMXERRIXIW { _BMXERRIXIW { w: self } } #[doc = "Bit 26"] #[inline] pub fn bmxchedma(&mut self) -> _BMXCHEDMAW { _BMXCHEDMAW { w: self } } }
24.795761
59
0.494522
11193784dafe88c1dc74b5bc23d746eac5176967
131
fn main() -> Result<(), Box<dyn std::error::Error>> { tonic_build::compile_protos("proto/commandservice.proto")?; Ok(()) }
26.2
63
0.625954
386f140c69750c368d005fe1c21a03fed2d54150
1,898
use fibers; use futures::{Future, Poll}; use raftlog::election::Role; use raftlog::{Error as RaftError, ErrorKind as RaftErrorKind}; use rand::{self, Rng}; use std::time::Duration; use trackable::error::ErrorKindExt; /// Raft用のタイマー実装. /// /// このタイマーは、パラメータとして「最小タイムアウト時間」と「最大タイムアウト時間」を受け取り、 /// 以下のルールに従って、各ロール用のタイムアウト時間を決定する. /// /// - `Role::Follower`: 常に最大タイムアウト時間 /// - `Role::Leader`: 常に最小タイムアウト時間 /// - `Role::Candidate`: 最小と最大の間のいずれかの値を無作為に選択 #[derive(Debug, Clone)] pub struct Timer { min_timeout: Duration, max_timeout: Duration, } impl Timer { /// 新しい`Timer`インスタンスを生成する. pub fn new(min_timeout: Duration, max_timeout: Duration) -> Self { assert!(min_timeout <= max_timeout); Timer { min_timeout, max_timeout, } } pub(crate) fn create_timeout(&self, role: Role) -> Timeout { let duration = match role { Role::Follower => self.max_timeout, Role::Candidate => { let min = duration_to_millis(self.min_timeout); let max = duration_to_millis(self.max_timeout); let millis = rand::thread_rng().gen_range(min, max); Duration::from_millis(millis) } Role::Leader => self.min_timeout, }; let inner = fibers::time::timer::timeout(duration); Timeout(inner) } } fn duration_to_millis(duration: Duration) -> u64 { duration.as_secs() * 1000 + u64::from(duration.subsec_nanos()) / 1_000_000 } /// タイムアウトを表現した`Future`実装. /// /// `Timer`によって内部的に生成される. #[derive(Debug)] pub struct Timeout(fibers::time::timer::Timeout); impl Future for Timeout { type Item = (); type Error = RaftError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { track!(self .0 .poll() .map_err(|e| RaftErrorKind::Other.cause(e).into(),)) } }
28.328358
78
0.608008
0926cf4832e21e13558c28ea48c0b3b661b8e53c
394
pub mod connection; pub mod event; pub mod gdi; mod wgl; pub mod window; pub use self::window::*; pub use connection::*; pub use event::*; pub use gdi::*; /// Convert a rust string to a windows wide string fn wide_string(s: &str) -> Vec<u16> { use std::os::windows::ffi::OsStrExt; std::ffi::OsStr::new(s) .encode_wide() .chain(std::iter::once(0)) .collect() }
19.7
50
0.616751
648211dd5cf51075754330f2f92f4760b51595bc
5,178
//! This library takes a [`Serialize`](deser::ser::Serialize) and //! formats it with [`std::fmt`] to debug representation. use std::fmt; use std::sync::atomic::{self, AtomicUsize}; use deser::ser::{Serialize, SerializeDriver}; use deser::{Atom, Event}; /// Serializes a serializable value to `Debug` format. pub struct ToDebug { events: Vec<(Event<'static>, Option<String>)>, } impl fmt::Display for ToDebug { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&Helper(&self.events, AtomicUsize::default()), f) } } impl fmt::Debug for ToDebug { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&Helper(&self.events, AtomicUsize::default()), f) } } impl ToDebug { /// Creates a new [`ToDebug`] object from a serializable value. pub fn new(value: &dyn Serialize) -> ToDebug { let mut events = Vec::new(); let mut driver = SerializeDriver::new(value); while let Some((event, descriptor, _)) = driver.next().unwrap() { events.push((event.to_static(), descriptor.name().map(|x| x.to_string()))); } ToDebug { events } } } fn dump<'a, 'f>( tokens: &'a [(Event<'a>, Option<String>)], f: &'f mut fmt::Formatter<'_>, ) -> Result<&'a [(Event<'a>, Option<String>)], fmt::Error> { if let Some((first, mut rest)) = tokens.split_first() { match first.0 { Event::Atom(Atom::Null) => fmt::Debug::fmt(&(), f)?, Event::Atom(Atom::Bool(v)) => fmt::Debug::fmt(&v, f)?, Event::Atom(Atom::Str(ref v)) => fmt::Debug::fmt(v, f)?, Event::Atom(Atom::Bytes(ref v)) => { write!(f, "b\"")?; for &b in &v[..] { if b == b'\n' { write!(f, "\\n")?; } else if b == b'\r' { write!(f, "\\r")?; } else if b == b'\t' { write!(f, "\\t")?; } else if b == b'\\' || b == b'"' { write!(f, "\\{}", b as char)?; } else if b == b'\0' { write!(f, "\\0")?; } else if (0x20..0x7f).contains(&b) { write!(f, "{}", b as char)?; } else { write!(f, "\\x{:02x}", b)?; } } write!(f, "\"")?; } Event::Atom(Atom::Char(v)) => fmt::Debug::fmt(&v, f)?, Event::Atom(Atom::U64(v)) => fmt::Debug::fmt(&v, f)?, Event::Atom(Atom::I64(v)) => fmt::Debug::fmt(&v, f)?, Event::Atom(Atom::F64(v)) => fmt::Debug::fmt(&v, f)?, Event::Atom(..) => f.debug_struct("?").finish()?, Event::MapStart => { if let Some(ref name) = first.1 { write!(f, "{} ", name)?; } let mut map = f.debug_map(); let mut is_key = true; loop { if rest.get(0).map_or(false, |x| matches!(x.0, Event::MapEnd)) { rest = &rest[1..]; break; } let inner = Helper(rest, AtomicUsize::default()); if is_key { map.key(&inner); } else { map.value(&inner); } is_key = !is_key; rest = &rest[inner.1.load(atomic::Ordering::Relaxed)..]; } map.finish()?; } Event::MapEnd => unreachable!(), Event::SeqStart => { if let Some(ref name) = first.1 { if name != "Vec" && name != "slice" { write!(f, "{} ", name)?; } } let mut list = f.debug_list(); loop { if rest.get(0).map_or(false, |x| matches!(x.0, Event::SeqEnd)) { rest = &rest[1..]; break; } let inner = Helper(rest, AtomicUsize::default()); list.entry(&inner); rest = &rest[inner.1.load(atomic::Ordering::Relaxed)..]; } list.finish()?; } Event::SeqEnd => unreachable!(), } Ok(rest) } else { Ok(tokens) } } struct Helper<'a>(&'a [(Event<'a>, Option<String>)], AtomicUsize); impl<'a> fmt::Debug for Helper<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let new = dump(self.0, f)?; self.1 .store(self.0.len() - new.len(), atomic::Ordering::Relaxed); Ok(()) } } #[test] fn test_debug_format() { let mut m = std::collections::BTreeMap::new(); m.insert(true, vec![vec![&b"x"[..], b"yyy"], vec![b"zzzz\x00\x01"]]); m.insert(false, vec![]); assert_eq!( ToDebug::new(&m).to_string(), "BTreeMap {false: [], true: [[b\"x\", b\"yyy\"], [b\"zzzz\\0\\x01\"]]}" ); }
35.958333
87
0.422171
216dad0772668fc51f538592a57d4b254f8287e4
4,074
use std::{env, process::exit}; use matrix_sdk::{ self, async_trait, events::{ room::message::{MessageEventContent, MessageType, TextMessageEventContent}, AnyMessageEventContent, SyncMessageEvent, }, Client, ClientConfig, EventHandler, Room, RoomType, SyncSettings, }; use url::Url; struct CommandBot { /// This clone of the `Client` will send requests to the server, /// while the other keeps us in sync with the server using `sync`. client: Client, } impl CommandBot { pub fn new(client: Client) -> Self { Self { client } } } #[async_trait] impl EventHandler for CommandBot { async fn on_room_message(&self, room: Room, event: &SyncMessageEvent<MessageEventContent>) { if room.room_type() == RoomType::Joined { let msg_body = if let SyncMessageEvent { content: MessageEventContent { msgtype: MessageType::Text(TextMessageEventContent { body: msg_body, .. }), .. }, .. } = event { msg_body } else { return; }; if msg_body.contains("!party") { let content = AnyMessageEventContent::RoomMessage(MessageEventContent::text_plain( "🎉🎊🥳 let's PARTY!! 🥳🎊🎉", )); println!("sending"); self.client // send our message to the room we found the "!party" command in // the last parameter is an optional Uuid which we don't care about. .room_send(room.room_id(), content, None) .await .unwrap(); println!("message sent"); } } } } async fn login_and_sync( homeserver_url: String, username: String, password: String, ) -> Result<(), matrix_sdk::Error> { // the location for `JsonStore` to save files to let mut home = dirs::home_dir().expect("no home directory found"); home.push("party_bot"); let client_config = ClientConfig::new().store_path(home); let homeserver_url = Url::parse(&homeserver_url).expect("Couldn't parse the homeserver URL"); // create a new Client with the given homeserver url and config let client = Client::new_with_config(homeserver_url, client_config).unwrap(); client .login(&username, &password, None, Some("command bot")) .await?; println!("logged in as {}", username); // An initial sync to set up state and so our bot doesn't respond to old messages. // If the `StateStore` finds saved state in the location given the initial sync will // be skipped in favor of loading state from the store client.sync_once(SyncSettings::default()).await.unwrap(); // add our CommandBot to be notified of incoming messages, we do this after the initial // sync to avoid responding to messages before the bot was running. client .set_event_handler(Box::new(CommandBot::new(client.clone()))) .await; // since we called `sync_once` before we entered our sync loop we must pass // that sync token to `sync` let settings = SyncSettings::default().token(client.sync_token().await.unwrap()); // this keeps state from the server streaming in to CommandBot via the EventHandler trait client.sync(settings).await; Ok(()) } #[tokio::main] async fn main() -> Result<(), matrix_sdk::Error> { tracing_subscriber::fmt::init(); let (homeserver_url, username, password) = match (env::args().nth(1), env::args().nth(2), env::args().nth(3)) { (Some(a), Some(b), Some(c)) => (a, b, c), _ => { eprintln!( "Usage: {} <homeserver_url> <username> <password>", env::args().next().unwrap() ); exit(1) } }; login_and_sync(homeserver_url, username, password).await?; Ok(()) }
33.393443
99
0.579038
115c242deedefebdba1225ff3b0a3705835dd7f2
802
impl super::AsyncWriteUnpin for tokio::io::Stdout {} impl super::AsyncWriteUnpin for tokio::io::Stderr {} #[derive(new)] pub struct TokioProcess; impl super::Process for TokioProcess { fn stdout(&self) -> Box<dyn super::AsyncWriteUnpin> { Box::new(tokio::io::stdout()) } fn stderr(&self) -> Box<dyn super::AsyncWriteUnpin> { Box::new(tokio::io::stderr()) } } #[cfg(test)] impl super::AsyncWriteUnpin for Vec<u8> {} #[cfg(test)] pub struct StubProcess { pub stdout: Vec<u8>, pub stderr: Vec<u8>, } #[cfg(test)] impl super::Process for StubProcess { fn stdout(&self) -> Box<dyn super::AsyncWriteUnpin> { Box::new(self.stdout.clone()) } fn stderr(&self) -> Box<dyn super::AsyncWriteUnpin> { Box::new(self.stderr.clone()) } }
21.675676
57
0.628429
fb84e91458a44f56c00a5af4b038933f97f8cddc
3,082
// Copyright 2019. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use std::time::Duration; use tokio::time::delay_for; /// The structure can be initialized with some state and an internal Delay future. The struct will resolve to the /// internal state when the delay elapses. /// This allows for one to create unique delays that can be await'ed upon in a collection like FuturesUnordered pub struct StateDelay<T> { state: T, period: Duration, } impl<T> StateDelay<T> { pub fn new(period: Duration, state: T) -> Self { Self { state, period } } /// The future that will delay for the specified time and then return the internal state pub async fn delay(self) -> T { delay_for(self.period).await; self.state } } #[cfg(test)] mod test { use crate::util::futures::StateDelay; use chrono::{Duration as ChronoDuration, Utc}; use std::time::Duration; use tokio::runtime::Runtime; #[derive(Clone, Debug, PartialEq)] struct Dummy { a: i32, b: String, } #[test] fn test_state_delay() { let mut runtime = Runtime::new().unwrap(); let state = Dummy { a: 22, b: "Testing".to_string(), }; let delay = 1; let state_delay_future = StateDelay::new(Duration::from_secs(delay), state.clone()); let tick = Utc::now().naive_utc(); let result = runtime.block_on(state_delay_future.delay()); let tock = Utc::now().naive_utc(); assert!(tock.signed_duration_since(tick) > ChronoDuration::seconds(0i64)); assert_eq!(result, state); } }
41.093333
118
0.703764
87ca410dece0dcee116b43653044c586653712f5
18,631
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! # Representation of Algebraic Data Types //! //! This module determines how to represent enums, structs, and tuples //! based on their monomorphized types; it is responsible both for //! choosing a representation and translating basic operations on //! values of those types. (Note: exporting the representations for //! debuggers is handled in debuginfo.rs, not here.) //! //! Note that the interface treats everything as a general case of an //! enum, so structs/tuples/etc. have one pseudo-variant with //! discriminant 0; i.e., as if they were a univariant enum. //! //! Having everything in one place will enable improvements to data //! structure representation; possibilities include: //! //! - User-specified alignment (e.g., cacheline-aligning parts of //! concurrently accessed data structures); LLVM can't represent this //! directly, so we'd have to insert padding fields in any structure //! that might contain one and adjust GEP indices accordingly. See //! issue #4578. //! //! - Store nested enums' discriminants in the same word. Rather, if //! some variants start with enums, and those enums representations //! have unused alignment padding between discriminant and body, the //! outer enum's discriminant can be stored there and those variants //! can start at offset 0. Kind of fancy, and might need work to //! make copies of the inner enum type cooperate, but it could help //! with `Option` or `Result` wrapped around another enum. //! //! - Tagged pointers would be neat, but given that any type can be //! used unboxed and any field can have pointers (including mutable) //! taken to it, implementing them for Rust seems difficult. use std; use llvm::{ValueRef, True, IntEQ, IntNE}; use rustc::ty::{self, Ty}; use rustc::ty::layout::{self, LayoutTyper}; use common::*; use builder::Builder; use base; use machine; use monomorphize; use type_::Type; use type_of; use mir::lvalue::Alignment; /// Given an enum, struct, closure, or tuple, extracts fields. /// Treats closures as a struct with one variant. /// `empty_if_no_variants` is a switch to deal with empty enums. /// If true, `variant_index` is disregarded and an empty Vec returned in this case. pub fn compute_fields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, variant_index: usize, empty_if_no_variants: bool) -> Vec<Ty<'tcx>> { match t.sty { ty::TyAdt(ref def, _) if def.variants.len() == 0 && empty_if_no_variants => { Vec::default() }, ty::TyAdt(ref def, ref substs) => { def.variants[variant_index].fields.iter().map(|f| { monomorphize::field_ty(cx.tcx(), substs, f) }).collect::<Vec<_>>() }, ty::TyTuple(fields, _) => fields.to_vec(), ty::TyClosure(def_id, substs) => { if variant_index > 0 { bug!("{} is a closure, which only has one variant", t);} substs.upvar_tys(def_id, cx.tcx()).collect() }, _ => bug!("{} is not a type that can have fields.", t) } } /// LLVM-level types are a little complicated. /// /// C-like enums need to be actual ints, not wrapped in a struct, /// because that changes the ABI on some platforms (see issue #10308). /// /// For nominal types, in some cases, we need to use LLVM named structs /// and fill in the actual contents in a second pass to prevent /// unbounded recursion; see also the comments in `trans::type_of`. pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { generic_type_of(cx, t, None, false, false) } pub fn incomplete_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, name: &str) -> Type { generic_type_of(cx, t, Some(name), false, false) } pub fn finish_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, llty: &mut Type) { let l = cx.layout_of(t); debug!("finish_type_of: {} with layout {:#?}", t, l); match *l { layout::CEnum { .. } | layout::General { .. } | layout::UntaggedUnion { .. } | layout::RawNullablePointer { .. } => { } layout::Univariant { ..} | layout::StructWrappedNullablePointer { .. } => { let (nonnull_variant_index, nonnull_variant, packed) = match *l { layout::Univariant { ref variant, .. } => (0, variant, variant.packed), layout::StructWrappedNullablePointer { nndiscr, ref nonnull, .. } => (nndiscr, nonnull, nonnull.packed), _ => unreachable!() }; let fields = compute_fields(cx, t, nonnull_variant_index as usize, true); llty.set_struct_body(&struct_llfields(cx, &fields, nonnull_variant, false, false), packed) }, _ => bug!("This function cannot handle {} with layout {:#?}", t, l) } } fn generic_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, name: Option<&str>, sizing: bool, dst: bool) -> Type { let l = cx.layout_of(t); debug!("adt::generic_type_of t: {:?} name: {:?} sizing: {} dst: {}", t, name, sizing, dst); match *l { layout::CEnum { discr, .. } => Type::from_integer(cx, discr), layout::RawNullablePointer { nndiscr, .. } => { let (def, substs) = match t.sty { ty::TyAdt(d, s) => (d, s), _ => bug!("{} is not an ADT", t) }; let nnty = monomorphize::field_ty(cx.tcx(), substs, &def.variants[nndiscr as usize].fields[0]); if let layout::Scalar { value: layout::Pointer, .. } = *cx.layout_of(nnty) { Type::i8p(cx) } else { type_of::type_of(cx, nnty) } } layout::StructWrappedNullablePointer { nndiscr, ref nonnull, .. } => { let fields = compute_fields(cx, t, nndiscr as usize, false); match name { None => { Type::struct_(cx, &struct_llfields(cx, &fields, nonnull, sizing, dst), nonnull.packed) } Some(name) => { assert_eq!(sizing, false); Type::named_struct(cx, name) } } } layout::Univariant { ref variant, .. } => { // Note that this case also handles empty enums. // Thus the true as the final parameter here. let fields = compute_fields(cx, t, 0, true); match name { None => { let fields = struct_llfields(cx, &fields, &variant, sizing, dst); Type::struct_(cx, &fields, variant.packed) } Some(name) => { // Hypothesis: named_struct's can never need a // drop flag. (... needs validation.) assert_eq!(sizing, false); Type::named_struct(cx, name) } } } layout::UntaggedUnion { ref variants, .. }=> { // Use alignment-sized ints to fill all the union storage. let size = variants.stride().bytes(); let align = variants.align.abi(); let fill = union_fill(cx, size, align); match name { None => { Type::struct_(cx, &[fill], variants.packed) } Some(name) => { let mut llty = Type::named_struct(cx, name); llty.set_struct_body(&[fill], variants.packed); llty } } } layout::General { discr, size, align, .. } => { // We need a representation that has: // * The alignment of the most-aligned field // * The size of the largest variant (rounded up to that alignment) // * No alignment padding anywhere any variant has actual data // (currently matters only for enums small enough to be immediate) // * The discriminant in an obvious place. // // So we start with the discriminant, pad it up to the alignment with // more of its own type, then use alignment-sized ints to get the rest // of the size. let size = size.bytes(); let align = align.abi(); assert!(align <= std::u32::MAX as u64); let discr_ty = Type::from_integer(cx, discr); let discr_size = discr.size().bytes(); let padded_discr_size = roundup(discr_size, align as u32); let variant_part_size = size-padded_discr_size; let variant_fill = union_fill(cx, variant_part_size, align); assert_eq!(machine::llalign_of_min(cx, variant_fill), align as u32); assert_eq!(padded_discr_size % discr_size, 0); // Ensure discr_ty can fill pad evenly let fields: Vec<Type> = [discr_ty, Type::array(&discr_ty, (padded_discr_size - discr_size)/discr_size), variant_fill].iter().cloned().collect(); match name { None => { Type::struct_(cx, &fields, false) } Some(name) => { let mut llty = Type::named_struct(cx, name); llty.set_struct_body(&fields, false); llty } } } _ => bug!("Unsupported type {} represented as {:#?}", t, l) } } fn union_fill(cx: &CrateContext, size: u64, align: u64) -> Type { assert_eq!(size%align, 0); assert_eq!(align.count_ones(), 1, "Alignment must be a power fof 2. Got {}", align); let align_units = size/align; let layout_align = layout::Align::from_bytes(align, align).unwrap(); if let Some(ity) = layout::Integer::for_abi_align(cx, layout_align) { Type::array(&Type::from_integer(cx, ity), align_units) } else { Type::array(&Type::vector(&Type::i32(cx), align/4), align_units) } } fn struct_llfields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, fields: &Vec<Ty<'tcx>>, variant: &layout::Struct, sizing: bool, _dst: bool) -> Vec<Type> { let fields = variant.field_index_by_increasing_offset().map(|i| fields[i as usize]); if sizing { bug!() } else { fields.map(|ty| type_of::in_memory_type_of(cx, ty)).collect() } } pub fn is_discr_signed<'tcx>(l: &layout::Layout) -> bool { match *l { layout::CEnum { signed, .. }=> signed, _ => false, } } /// Obtain the actual discriminant of a value. pub fn trans_get_discr<'a, 'tcx>( bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, scrutinee: ValueRef, alignment: Alignment, cast_to: Option<Type>, range_assert: bool ) -> ValueRef { debug!("trans_get_discr t: {:?}", t); let l = bcx.ccx.layout_of(t); let val = match *l { layout::CEnum { discr, min, max, .. } => { load_discr(bcx, discr, scrutinee, alignment, min, max, range_assert) } layout::General { discr, ref variants, .. } => { let ptr = bcx.struct_gep(scrutinee, 0); load_discr(bcx, discr, ptr, alignment, 0, variants.len() as u64 - 1, range_assert) } layout::Univariant { .. } | layout::UntaggedUnion { .. } => C_u8(bcx.ccx, 0), layout::RawNullablePointer { nndiscr, .. } => { let cmp = if nndiscr == 0 { IntEQ } else { IntNE }; let discr = bcx.load(scrutinee, alignment.to_align()); bcx.icmp(cmp, discr, C_null(val_ty(discr))) } layout::StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => { struct_wrapped_nullable_bitdiscr(bcx, nndiscr, discrfield, scrutinee, alignment) }, _ => bug!("{} is not an enum", t) }; match cast_to { None => val, Some(llty) => bcx.intcast(val, llty, is_discr_signed(&l)) } } fn struct_wrapped_nullable_bitdiscr( bcx: &Builder, nndiscr: u64, discrfield: &layout::FieldPath, scrutinee: ValueRef, alignment: Alignment, ) -> ValueRef { let llptrptr = bcx.gepi(scrutinee, &discrfield.iter().map(|f| *f as usize).collect::<Vec<_>>()); let llptr = bcx.load(llptrptr, alignment.to_align()); let cmp = if nndiscr == 0 { IntEQ } else { IntNE }; bcx.icmp(cmp, llptr, C_null(val_ty(llptr))) } /// Helper for cases where the discriminant is simply loaded. fn load_discr(bcx: &Builder, ity: layout::Integer, ptr: ValueRef, alignment: Alignment, min: u64, max: u64, range_assert: bool) -> ValueRef { let llty = Type::from_integer(bcx.ccx, ity); assert_eq!(val_ty(ptr), llty.ptr_to()); let bits = ity.size().bits(); assert!(bits <= 64); let bits = bits as usize; let mask = !0u64 >> (64 - bits); // For a (max) discr of -1, max will be `-1 as usize`, which overflows. // However, that is fine here (it would still represent the full range), if max.wrapping_add(1) & mask == min & mask || !range_assert { // i.e., if the range is everything. The lo==hi case would be // rejected by the LLVM verifier (it would mean either an // empty set, which is impossible, or the entire range of the // type, which is pointless). bcx.load(ptr, alignment.to_align()) } else { // llvm::ConstantRange can deal with ranges that wrap around, // so an overflow on (max + 1) is fine. bcx.load_range_assert(ptr, min, max.wrapping_add(1), /* signed: */ True, alignment.to_align()) } } /// Set the discriminant for a new value of the given case of the given /// representation. pub fn trans_set_discr<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, t: Ty<'tcx>, val: ValueRef, to: u64) { let l = bcx.ccx.layout_of(t); match *l { layout::CEnum{ discr, min, max, .. } => { assert_discr_in_range(min, max, to); bcx.store(C_integral(Type::from_integer(bcx.ccx, discr), to, true), val, None); } layout::General{ discr, .. } => { bcx.store(C_integral(Type::from_integer(bcx.ccx, discr), to, true), bcx.struct_gep(val, 0), None); } layout::Univariant { .. } | layout::UntaggedUnion { .. } | layout::Vector { .. } => { assert_eq!(to, 0); } layout::RawNullablePointer { nndiscr, .. } => { if to != nndiscr { let llptrty = val_ty(val).element_type(); bcx.store(C_null(llptrty), val, None); } } layout::StructWrappedNullablePointer { nndiscr, ref discrfield, ref nonnull, .. } => { if to != nndiscr { if target_sets_discr_via_memset(bcx) { // Issue #34427: As workaround for LLVM bug on // ARM, use memset of 0 on whole struct rather // than storing null to single target field. let llptr = bcx.pointercast(val, Type::i8(bcx.ccx).ptr_to()); let fill_byte = C_u8(bcx.ccx, 0); let size = C_uint(bcx.ccx, nonnull.stride().bytes()); let align = C_i32(bcx.ccx, nonnull.align.abi() as i32); base::call_memset(bcx, llptr, fill_byte, size, align, false); } else { let path = discrfield.iter().map(|&i| i as usize).collect::<Vec<_>>(); let llptrptr = bcx.gepi(val, &path); let llptrty = val_ty(llptrptr).element_type(); bcx.store(C_null(llptrty), llptrptr, None); } } } _ => bug!("Cannot handle {} represented as {:#?}", t, l) } } fn target_sets_discr_via_memset<'a, 'tcx>(bcx: &Builder<'a, 'tcx>) -> bool { bcx.sess().target.target.arch == "arm" || bcx.sess().target.target.arch == "aarch64" } pub fn assert_discr_in_range<D: PartialOrd>(min: D, max: D, discr: D) { if min <= max { assert!(min <= discr && discr <= max) } else { assert!(min <= discr || discr <= max) } } // FIXME this utility routine should be somewhere more general #[inline] fn roundup(x: u64, a: u32) -> u64 { let a = a as u64; ((x + (a - 1)) / a) * a } /// Extract a field of a constant value, as appropriate for its /// representation. /// /// (Not to be confused with `common::const_get_elt`, which operates on /// raw LLVM-level structs and arrays.) pub fn const_get_field<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>, val: ValueRef, ix: usize) -> ValueRef { let l = ccx.layout_of(t); match *l { layout::CEnum { .. } => bug!("element access in C-like enum const"), layout::Univariant { ref variant, .. } => { const_struct_field(val, variant.memory_index[ix] as usize) } layout::Vector { .. } => const_struct_field(val, ix), layout::UntaggedUnion { .. } => const_struct_field(val, 0), _ => bug!("{} does not have fields.", t) } } /// Extract field of struct-like const, skipping our alignment padding. fn const_struct_field(val: ValueRef, ix: usize) -> ValueRef { // Get the ix-th non-undef element of the struct. let mut real_ix = 0; // actual position in the struct let mut ix = ix; // logical index relative to real_ix let mut field; loop { loop { field = const_get_elt(val, &[real_ix]); if !is_undef(field) { break; } real_ix = real_ix + 1; } if ix == 0 { return field; } ix = ix - 1; real_ix = real_ix + 1; } }
41.310421
97
0.555418
71dbd1d24bcdd26f8b56ba96793b8c4b5d900e39
21,284
//! Contains the `Error` and `Result` types that `mongodb` uses. use std::{ collections::{HashMap, HashSet}, fmt::{self, Debug}, sync::Arc, }; use bson::Bson; use serde::Deserialize; use thiserror::Error; use crate::{bson::Document, options::ServerAddress}; const RECOVERING_CODES: [i32; 5] = [11600, 11602, 13436, 189, 91]; const NOTMASTER_CODES: [i32; 3] = [10107, 13435, 10058]; const SHUTTING_DOWN_CODES: [i32; 2] = [11600, 91]; const RETRYABLE_READ_CODES: [i32; 11] = [11600, 11602, 10107, 13435, 13436, 189, 91, 7, 6, 89, 9001]; const RETRYABLE_WRITE_CODES: [i32; 12] = [ 11600, 11602, 10107, 13435, 13436, 189, 91, 7, 6, 89, 9001, 262, ]; const UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL_CODES: [i32; 3] = [50, 64, 91]; /// Retryable write error label. This label will be added to an error when the error is /// write-retryable. pub const RETRYABLE_WRITE_ERROR: &str = "RetryableWriteError"; /// Transient transaction error label. This label will be added to a network error or server /// selection error that occurs during a transaction. pub const TRANSIENT_TRANSACTION_ERROR: &str = "TransientTransactionError"; /// Unknown transaction commit result error label. This label will be added to a server selection /// error, network error, write-retryable error, MaxTimeMSExpired error, or write concern /// failed/timeout during a commitTransaction. pub const UNKNOWN_TRANSACTION_COMMIT_RESULT: &str = "UnknownTransactionCommitResult"; /// The result type for all methods that can return an error in the `mongodb` crate. pub type Result<T> = std::result::Result<T, Error>; /// An error that can occur in the `mongodb` crate. The inner /// [`ErrorKind`](enum.ErrorKind.html) is wrapped in an `Arc` to allow the errors to be /// cloned. #[derive(Clone, Debug, Error)] #[error("{kind}")] #[non_exhaustive] pub struct Error { /// The type of error that occurred. pub kind: Box<ErrorKind>, pub(crate) labels: HashSet<String>, } impl Error { pub(crate) fn new(kind: ErrorKind, labels: Option<impl IntoIterator<Item = String>>) -> Self { Self { kind: Box::new(kind), labels: labels .map(|labels| labels.into_iter().collect()) .unwrap_or_default(), } } pub(crate) fn pool_cleared_error(address: &ServerAddress, cause: &Error) -> Self { ErrorKind::ConnectionPoolCleared { message: format!( "Connection pool for {} cleared because another operation failed with: {}", address, cause ), } .into() } /// Creates an `AuthenticationError` for the given mechanism with the provided reason. pub(crate) fn authentication_error(mechanism_name: &str, reason: &str) -> Self { ErrorKind::Authentication { message: format!("{} failure: {}", mechanism_name, reason), } .into() } /// Creates an `AuthenticationError` for the given mechanism with a generic "unknown" message. pub(crate) fn unknown_authentication_error(mechanism_name: &str) -> Error { Error::authentication_error(mechanism_name, "internal error") } /// Creates an `AuthenticationError` for the given mechanism when the server response is /// invalid. pub(crate) fn invalid_authentication_response(mechanism_name: &str) -> Error { Error::authentication_error(mechanism_name, "invalid server response") } pub(crate) fn internal(message: impl Into<String>) -> Error { ErrorKind::Internal { message: message.into(), } .into() } pub(crate) fn invalid_argument(message: impl Into<String>) -> Error { ErrorKind::InvalidArgument { message: message.into(), } .into() } pub(crate) fn is_state_change_error(&self) -> bool { self.is_recovering() || self.is_not_master() } pub(crate) fn is_auth_error(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::Authentication { .. }) } pub(crate) fn is_command_error(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::Command(_)) } pub(crate) fn is_network_timeout(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::Io(ref io_err) if io_err.kind() == std::io::ErrorKind::TimedOut) } /// Whether this error is an "ns not found" error or not. pub(crate) fn is_ns_not_found(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::Command(ref err) if err.code == 26) } pub(crate) fn is_server_selection_error(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::ServerSelection { .. }) } /// Whether a read operation should be retried if this error occurs. pub(crate) fn is_read_retryable(&self) -> bool { if self.is_network_error() { return true; } match self.code() { Some(code) => RETRYABLE_READ_CODES.contains(&code), None => false, } } pub(crate) fn is_write_retryable(&self) -> bool { self.contains_label(RETRYABLE_WRITE_ERROR) } /// Whether a "RetryableWriteError" label should be added to this error. If max_wire_version /// indicates a 4.4+ server, a label should only be added if the error is a network error. /// Otherwise, a label should be added if the error is a network error or the error code /// matches one of the retryable write codes. pub(crate) fn should_add_retryable_write_label(&self, max_wire_version: i32) -> bool { if max_wire_version > 8 { return self.is_network_error(); } if self.is_network_error() { return true; } match &self.code() { Some(code) => RETRYABLE_WRITE_CODES.contains(code), None => false, } } pub(crate) fn should_add_unknown_transaction_commit_result_label(&self) -> bool { if self.contains_label(TRANSIENT_TRANSACTION_ERROR) { return false; } if self.is_network_error() || self.is_server_selection_error() || self.is_write_retryable() { return true; } match self.code() { Some(code) => UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL_CODES.contains(&code), None => false, } } /// Whether an error originated from the server. pub(crate) fn is_server_error(&self) -> bool { matches!( self.kind.as_ref(), ErrorKind::Authentication { .. } | ErrorKind::BulkWrite(_) | ErrorKind::Command(_) | ErrorKind::Write(_) ) } /// Returns the labels for this error. pub fn labels(&self) -> &HashSet<String> { &self.labels } /// Whether this error contains the specified label. pub fn contains_label<T: AsRef<str>>(&self, label: T) -> bool { self.labels().contains(label.as_ref()) } /// Adds the given label to this error. pub(crate) fn add_label<T: AsRef<str>>(&mut self, label: T) { let label = label.as_ref().to_string(); self.labels.insert(label); } pub(crate) fn from_resolve_error(error: trust_dns_resolver::error::ResolveError) -> Self { ErrorKind::DnsResolve { message: error.to_string(), } .into() } pub(crate) fn is_non_timeout_network_error(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::Io(ref io_err) if io_err.kind() != std::io::ErrorKind::TimedOut) } pub(crate) fn is_network_error(&self) -> bool { matches!( self.kind.as_ref(), ErrorKind::Io(..) | ErrorKind::ConnectionPoolCleared { .. } ) } /// Gets the code from this error for performing SDAM updates, if applicable. /// Any codes contained in WriteErrors are ignored. pub(crate) fn code(&self) -> Option<i32> { match self.kind.as_ref() { ErrorKind::Command(command_error) => Some(command_error.code), // According to SDAM spec, write concern error codes MUST also be checked, and // writeError codes MUST NOT be checked. ErrorKind::BulkWrite(BulkWriteFailure { write_concern_error: Some(wc_error), .. }) => Some(wc_error.code), ErrorKind::Write(WriteFailure::WriteConcernError(wc_error)) => Some(wc_error.code), _ => None, } } /// Gets the message for this error, if applicable, for use in testing. /// If this error is a BulkWriteError, the messages are concatenated. #[cfg(test)] pub(crate) fn message(&self) -> Option<String> { match self.kind.as_ref() { ErrorKind::Command(command_error) => Some(command_error.message.clone()), // since this is used primarily for errorMessageContains assertions in the unified // runner, we just concatenate all the relevant server messages into one for // bulk errors. ErrorKind::BulkWrite(BulkWriteFailure { write_concern_error, write_errors, inserted_ids: _, }) => { let mut msg = "".to_string(); if let Some(wc_error) = write_concern_error { msg.push_str(wc_error.message.as_str()); } if let Some(write_errors) = write_errors { for we in write_errors { msg.push_str(we.message.as_str()); } } Some(msg) } ErrorKind::Write(WriteFailure::WriteConcernError(wc_error)) => { Some(wc_error.message.clone()) } ErrorKind::Write(WriteFailure::WriteError(write_error)) => { Some(write_error.message.clone()) } ErrorKind::Transaction { message } => Some(message.clone()), ErrorKind::IncompatibleServer { message } => Some(message.clone()), _ => None, } } /// Gets the code name from this error, if applicable. #[cfg(test)] pub(crate) fn code_name(&self) -> Option<&str> { match self.kind.as_ref() { ErrorKind::Command(ref cmd_err) => Some(cmd_err.code_name.as_str()), ErrorKind::Write(ref failure) => match failure { WriteFailure::WriteConcernError(ref wce) => Some(wce.code_name.as_str()), WriteFailure::WriteError(ref we) => we.code_name.as_deref(), }, ErrorKind::BulkWrite(ref bwe) => bwe .write_concern_error .as_ref() .map(|wce| wce.code_name.as_str()), _ => None, } } /// If this error corresponds to a "not master" error as per the SDAM spec. pub(crate) fn is_not_master(&self) -> bool { self.code() .map(|code| NOTMASTER_CODES.contains(&code)) .unwrap_or(false) } /// If this error corresponds to a "node is recovering" error as per the SDAM spec. pub(crate) fn is_recovering(&self) -> bool { self.code() .map(|code| RECOVERING_CODES.contains(&code)) .unwrap_or(false) } /// If this error corresponds to a "node is shutting down" error as per the SDAM spec. pub(crate) fn is_shutting_down(&self) -> bool { self.code() .map(|code| SHUTTING_DOWN_CODES.contains(&code)) .unwrap_or(false) } pub(crate) fn is_pool_cleared(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::ConnectionPoolCleared { .. }) } } impl<E> From<E> for Error where ErrorKind: From<E>, { fn from(err: E) -> Self { Self { kind: Box::new(err.into()), labels: Default::default(), } } } impl From<bson::de::Error> for ErrorKind { fn from(err: bson::de::Error) -> Self { Self::BsonDeserialization(err) } } impl From<bson::ser::Error> for ErrorKind { fn from(err: bson::ser::Error) -> Self { Self::BsonSerialization(err) } } impl From<std::io::Error> for ErrorKind { fn from(err: std::io::Error) -> Self { Self::Io(Arc::new(err)) } } impl From<std::io::ErrorKind> for ErrorKind { fn from(err: std::io::ErrorKind) -> Self { Self::Io(Arc::new(err.into())) } } /// The types of errors that can occur. #[allow(missing_docs)] #[derive(Clone, Debug, Error)] #[non_exhaustive] pub enum ErrorKind { /// An invalid argument was provided. #[error("An invalid argument was provided: {message}")] #[non_exhaustive] InvalidArgument { message: String }, /// An error occurred while the [`Client`](../struct.Client.html) attempted to authenticate a /// connection. #[error("{message}")] #[non_exhaustive] Authentication { message: String }, /// Wrapper around `bson::de::Error`. #[error("{0}")] BsonDeserialization(crate::bson::de::Error), /// Wrapper around `bson::ser::Error`. #[error("{0}")] BsonSerialization(crate::bson::ser::Error), /// An error occurred when trying to execute a write operation consisting of multiple writes. #[error("An error occurred when trying to execute a write operation: {0:?}")] BulkWrite(BulkWriteFailure), /// The server returned an error to an attempted operation. #[error("Command failed {0}")] Command(CommandError), /// An error occurred during DNS resolution. #[error("An error occurred during DNS resolution: {message}")] #[non_exhaustive] DnsResolve { message: String }, #[error("Internal error: {message}")] #[non_exhaustive] Internal { message: String }, /// Wrapper around [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html). #[error("{0}")] Io(Arc<std::io::Error>), /// The connection pool for a server was cleared during operation execution due to /// a concurrent error, causing the operation to fail. #[error("{message}")] #[non_exhaustive] ConnectionPoolCleared { message: String }, /// The server returned an invalid reply to a database operation. #[error("The server returned an invalid reply to a database operation: {message}")] #[non_exhaustive] InvalidResponse { message: String }, /// The Client was not able to select a server for the operation. #[error("{message}")] #[non_exhaustive] ServerSelection { message: String }, /// The Client does not support sessions. #[error("Attempted to start a session on a deployment that does not support sessions")] SessionsNotSupported, #[error("{message}")] #[non_exhaustive] InvalidTlsConfig { message: String }, /// An error occurred when trying to execute a write operation. #[error("An error occurred when trying to execute a write operation: {0:?}")] Write(WriteFailure), /// An error occurred during a transaction. #[error("{message}")] #[non_exhaustive] Transaction { message: String }, /// The server does not support the operation. #[error("The server does not support a database operation: {message}")] #[non_exhaustive] IncompatibleServer { message: String }, } /// An error that occurred due to a database command failing. #[derive(Clone, Debug, Deserialize)] #[non_exhaustive] pub struct CommandError { /// Identifies the type of error. pub code: i32, /// The name associated with the error code. #[serde(rename = "codeName", default)] pub code_name: String, /// A description of the error that occurred. #[serde(rename = "errmsg")] pub message: String, } impl fmt::Display for CommandError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "({}): {})", self.code_name, self.message) } } /// An error that occurred due to not being able to satisfy a write concern. #[derive(Clone, Debug, Deserialize, PartialEq)] #[non_exhaustive] pub struct WriteConcernError { /// Identifies the type of write concern error. pub code: i32, /// The name associated with the error code. #[serde(rename = "codeName", default)] pub code_name: String, /// A description of the error that occurred. #[serde(rename = "errmsg")] pub message: String, /// A document identifying the write concern setting related to the error. #[serde(rename = "errInfo")] pub details: Option<Document>, } /// An error that occurred during a write operation that wasn't due to being unable to satisfy a /// write concern. #[derive(Clone, Debug, PartialEq, Deserialize)] #[non_exhaustive] pub struct WriteError { /// Identifies the type of write error. pub code: i32, /// The name associated with the error code. /// /// Note that the server will not return this in some cases, hence `code_name` being an /// `Option`. #[serde(rename = "codeName", default)] pub code_name: Option<String>, /// A description of the error that occurred. #[serde(rename = "errmsg")] pub message: String, /// A document providing more information about the write error (e.g. details /// pertaining to document validation). #[serde(rename = "errInfo")] pub details: Option<Document>, } /// An error that occurred during a write operation consisting of multiple writes that wasn't due to /// being unable to satisfy a write concern. #[derive(Debug, PartialEq, Clone, Deserialize)] #[non_exhaustive] pub struct BulkWriteError { /// Index into the list of operations that this error corresponds to. #[serde(default)] pub index: usize, /// Identifies the type of write concern error. pub code: i32, /// The name associated with the error code. /// /// Note that the server will not return this in some cases, hence `code_name` being an /// `Option`. #[serde(rename = "codeName", default)] pub code_name: Option<String>, /// A description of the error that occurred. #[serde(rename = "errmsg")] pub message: String, /// A document providing more information about the write error (e.g. details /// pertaining to document validation). #[serde(rename = "errInfo")] pub details: Option<Document>, } /// The set of errors that occurred during a write operation. #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct BulkWriteFailure { /// The error(s) that occurred on account of a non write concern failure. pub write_errors: Option<Vec<BulkWriteError>>, /// The error that occurred on account of write concern failure. pub write_concern_error: Option<WriteConcernError>, #[serde(skip)] pub(crate) inserted_ids: HashMap<usize, Bson>, } impl BulkWriteFailure { pub(crate) fn new() -> Self { BulkWriteFailure { write_errors: None, write_concern_error: None, inserted_ids: Default::default(), } } } /// An error that occurred when trying to execute a write operation. #[derive(Clone, Debug)] #[non_exhaustive] pub enum WriteFailure { /// An error that occurred due to not being able to satisfy a write concern. WriteConcernError(WriteConcernError), /// An error that occurred during a write operation that wasn't due to being unable to satisfy /// a write concern. WriteError(WriteError), } impl WriteFailure { fn from_bulk_failure(bulk: BulkWriteFailure) -> Result<Self> { if let Some(bulk_write_error) = bulk.write_errors.and_then(|es| es.into_iter().next()) { let write_error = WriteError { code: bulk_write_error.code, code_name: bulk_write_error.code_name, message: bulk_write_error.message, details: bulk_write_error.details, }; Ok(WriteFailure::WriteError(write_error)) } else if let Some(wc_error) = bulk.write_concern_error { Ok(WriteFailure::WriteConcernError(wc_error)) } else { Err(ErrorKind::InvalidResponse { message: "error missing write errors and write concern errors".to_string(), } .into()) } } } /// Translates ErrorKind::BulkWriteError cases to ErrorKind::WriteErrors, leaving all other errors /// untouched. pub(crate) fn convert_bulk_errors(error: Error) -> Error { match *error.kind { ErrorKind::BulkWrite(bulk_failure) => match WriteFailure::from_bulk_failure(bulk_failure) { Ok(failure) => Error::new(ErrorKind::Write(failure), Some(error.labels)), Err(e) => e, }, _ => error, } } /// Flag a load-balanced mode mismatch. With debug assertions enabled, it will panic; otherwise, /// it will return the argument, or `()` if none is given. // TODO RUST-230 Log an error in the non-panic branch for mode mismatch. macro_rules! load_balanced_mode_mismatch { ($e:expr) => {{ if cfg!(debug_assertions) { panic!("load-balanced mode mismatch") } return $e; }}; () => { load_balanced_mode_mismatch!(()) }; } pub(crate) use load_balanced_mode_mismatch;
34.440129
112
0.62399
f9748c764d2c1046a668f2d36dd2baba0b840893
855,872
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. use std::fmt::Write; /// See [`CreateConfigurationSetInput`](crate::input::CreateConfigurationSetInput) pub mod create_configuration_set_input { /// A builder for [`CreateConfigurationSetInput`](crate::input::CreateConfigurationSetInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, pub(crate) tracking_options: std::option::Option<crate::model::TrackingOptions>, pub(crate) delivery_options: std::option::Option<crate::model::DeliveryOptions>, pub(crate) reputation_options: std::option::Option<crate::model::ReputationOptions>, pub(crate) sending_options: std::option::Option<crate::model::SendingOptions>, pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, pub(crate) suppression_options: std::option::Option<crate::model::SuppressionOptions>, } impl Builder { /// <p>The name of the configuration set. The name can contain up to 64 alphanumeric /// characters, including letters, numbers, hyphens (-) and underscores (_) only.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set. The name can contain up to 64 alphanumeric /// characters, including letters, numbers, hyphens (-) and underscores (_) only.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// <p>An object that defines the open and click tracking options for emails that you send /// using the configuration set.</p> pub fn tracking_options(mut self, input: crate::model::TrackingOptions) -> Self { self.tracking_options = Some(input); self } /// <p>An object that defines the open and click tracking options for emails that you send /// using the configuration set.</p> pub fn set_tracking_options( mut self, input: std::option::Option<crate::model::TrackingOptions>, ) -> Self { self.tracking_options = input; self } /// <p>An object that defines the dedicated IP pool that is used to send emails that you send /// using the configuration set.</p> pub fn delivery_options(mut self, input: crate::model::DeliveryOptions) -> Self { self.delivery_options = Some(input); self } /// <p>An object that defines the dedicated IP pool that is used to send emails that you send /// using the configuration set.</p> pub fn set_delivery_options( mut self, input: std::option::Option<crate::model::DeliveryOptions>, ) -> Self { self.delivery_options = input; self } /// <p>An object that defines whether or not Amazon SES collects reputation metrics for the emails /// that you send that use the configuration set.</p> pub fn reputation_options(mut self, input: crate::model::ReputationOptions) -> Self { self.reputation_options = Some(input); self } /// <p>An object that defines whether or not Amazon SES collects reputation metrics for the emails /// that you send that use the configuration set.</p> pub fn set_reputation_options( mut self, input: std::option::Option<crate::model::ReputationOptions>, ) -> Self { self.reputation_options = input; self } /// <p>An object that defines whether or not Amazon SES can send email that you send using the /// configuration set.</p> pub fn sending_options(mut self, input: crate::model::SendingOptions) -> Self { self.sending_options = Some(input); self } /// <p>An object that defines whether or not Amazon SES can send email that you send using the /// configuration set.</p> pub fn set_sending_options( mut self, input: std::option::Option<crate::model::SendingOptions>, ) -> Self { self.sending_options = input; self } /// Appends an item to `tags`. /// /// To override the contents of this collection use [`set_tags`](Self::set_tags). /// /// <p>An array of objects that define the tags (keys and values) to associate with the /// configuration set.</p> pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self { let mut v = self.tags.unwrap_or_default(); v.push(input.into()); self.tags = Some(v); self } /// <p>An array of objects that define the tags (keys and values) to associate with the /// configuration set.</p> pub fn set_tags( mut self, input: std::option::Option<std::vec::Vec<crate::model::Tag>>, ) -> Self { self.tags = input; self } /// <p>An object that contains information about the suppression list preferences for your /// account.</p> pub fn suppression_options(mut self, input: crate::model::SuppressionOptions) -> Self { self.suppression_options = Some(input); self } /// <p>An object that contains information about the suppression list preferences for your /// account.</p> pub fn set_suppression_options( mut self, input: std::option::Option<crate::model::SuppressionOptions>, ) -> Self { self.suppression_options = input; self } /// Consumes the builder and constructs a [`CreateConfigurationSetInput`](crate::input::CreateConfigurationSetInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateConfigurationSetInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateConfigurationSetInput { configuration_set_name: self.configuration_set_name, tracking_options: self.tracking_options, delivery_options: self.delivery_options, reputation_options: self.reputation_options, sending_options: self.sending_options, tags: self.tags, suppression_options: self.suppression_options, }) } } } #[doc(hidden)] pub type CreateConfigurationSetInputOperationOutputAlias = crate::operation::CreateConfigurationSet; #[doc(hidden)] pub type CreateConfigurationSetInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateConfigurationSetInput { /// Consumes the builder and constructs an Operation<[`CreateConfigurationSet`](crate::operation::CreateConfigurationSet)> #[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::CreateConfigurationSet, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateConfigurationSetInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/configuration-sets").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateConfigurationSetInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateConfigurationSetInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_configuration_set( &self, )?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::CreateConfigurationSet::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateConfigurationSet", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateConfigurationSetInput`](crate::input::CreateConfigurationSetInput) pub fn builder() -> crate::input::create_configuration_set_input::Builder { crate::input::create_configuration_set_input::Builder::default() } } /// See [`CreateConfigurationSetEventDestinationInput`](crate::input::CreateConfigurationSetEventDestinationInput) pub mod create_configuration_set_event_destination_input { /// A builder for [`CreateConfigurationSetEventDestinationInput`](crate::input::CreateConfigurationSetEventDestinationInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, pub(crate) event_destination_name: std::option::Option<std::string::String>, pub(crate) event_destination: std::option::Option<crate::model::EventDestinationDefinition>, } impl Builder { /// <p>The name of the configuration set .</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set .</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// <p>A name that identifies the event destination within the configuration set.</p> pub fn event_destination_name(mut self, input: impl Into<std::string::String>) -> Self { self.event_destination_name = Some(input.into()); self } /// <p>A name that identifies the event destination within the configuration set.</p> pub fn set_event_destination_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.event_destination_name = input; self } /// <p>An object that defines the event destination.</p> pub fn event_destination( mut self, input: crate::model::EventDestinationDefinition, ) -> Self { self.event_destination = Some(input); self } /// <p>An object that defines the event destination.</p> pub fn set_event_destination( mut self, input: std::option::Option<crate::model::EventDestinationDefinition>, ) -> Self { self.event_destination = input; self } /// Consumes the builder and constructs a [`CreateConfigurationSetEventDestinationInput`](crate::input::CreateConfigurationSetEventDestinationInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateConfigurationSetEventDestinationInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateConfigurationSetEventDestinationInput { configuration_set_name: self.configuration_set_name, event_destination_name: self.event_destination_name, event_destination: self.event_destination, }) } } } #[doc(hidden)] pub type CreateConfigurationSetEventDestinationInputOperationOutputAlias = crate::operation::CreateConfigurationSetEventDestination; #[doc(hidden)] pub type CreateConfigurationSetEventDestinationInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateConfigurationSetEventDestinationInput { /// Consumes the builder and constructs an Operation<[`CreateConfigurationSetEventDestination`](crate::operation::CreateConfigurationSetEventDestination)> #[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::CreateConfigurationSetEventDestination, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateConfigurationSetEventDestinationInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_1 = &_input.configuration_set_name; let input_1 = input_1 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", })?; let configuration_set_name = aws_smithy_http::label::fmt_string(input_1, false); if configuration_set_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/configuration-sets/{ConfigurationSetName}/event-destinations", ConfigurationSetName = configuration_set_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateConfigurationSetEventDestinationInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateConfigurationSetEventDestinationInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_configuration_set_event_destination(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::CreateConfigurationSetEventDestination::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateConfigurationSetEventDestination", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateConfigurationSetEventDestinationInput`](crate::input::CreateConfigurationSetEventDestinationInput) pub fn builder() -> crate::input::create_configuration_set_event_destination_input::Builder { crate::input::create_configuration_set_event_destination_input::Builder::default() } } /// See [`CreateContactInput`](crate::input::CreateContactInput) pub mod create_contact_input { /// A builder for [`CreateContactInput`](crate::input::CreateContactInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) contact_list_name: std::option::Option<std::string::String>, pub(crate) email_address: std::option::Option<std::string::String>, pub(crate) topic_preferences: std::option::Option<std::vec::Vec<crate::model::TopicPreference>>, pub(crate) unsubscribe_all: std::option::Option<bool>, pub(crate) attributes_data: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the contact list to which the contact should be added.</p> pub fn contact_list_name(mut self, input: impl Into<std::string::String>) -> Self { self.contact_list_name = Some(input.into()); self } /// <p>The name of the contact list to which the contact should be added.</p> pub fn set_contact_list_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.contact_list_name = input; self } /// <p>The contact's email address.</p> pub fn email_address(mut self, input: impl Into<std::string::String>) -> Self { self.email_address = Some(input.into()); self } /// <p>The contact's email address.</p> pub fn set_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_address = input; self } /// Appends an item to `topic_preferences`. /// /// To override the contents of this collection use [`set_topic_preferences`](Self::set_topic_preferences). /// /// <p>The contact's preferences for being opted-in to or opted-out of topics.</p> pub fn topic_preferences( mut self, input: impl Into<crate::model::TopicPreference>, ) -> Self { let mut v = self.topic_preferences.unwrap_or_default(); v.push(input.into()); self.topic_preferences = Some(v); self } /// <p>The contact's preferences for being opted-in to or opted-out of topics.</p> pub fn set_topic_preferences( mut self, input: std::option::Option<std::vec::Vec<crate::model::TopicPreference>>, ) -> Self { self.topic_preferences = input; self } /// <p>A boolean value status noting if the contact is unsubscribed from all contact list /// topics.</p> pub fn unsubscribe_all(mut self, input: bool) -> Self { self.unsubscribe_all = Some(input); self } /// <p>A boolean value status noting if the contact is unsubscribed from all contact list /// topics.</p> pub fn set_unsubscribe_all(mut self, input: std::option::Option<bool>) -> Self { self.unsubscribe_all = input; self } /// <p>The attribute data attached to a contact.</p> pub fn attributes_data(mut self, input: impl Into<std::string::String>) -> Self { self.attributes_data = Some(input.into()); self } /// <p>The attribute data attached to a contact.</p> pub fn set_attributes_data( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.attributes_data = input; self } /// Consumes the builder and constructs a [`CreateContactInput`](crate::input::CreateContactInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateContactInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateContactInput { contact_list_name: self.contact_list_name, email_address: self.email_address, topic_preferences: self.topic_preferences, unsubscribe_all: self.unsubscribe_all.unwrap_or_default(), attributes_data: self.attributes_data, }) } } } #[doc(hidden)] pub type CreateContactInputOperationOutputAlias = crate::operation::CreateContact; #[doc(hidden)] pub type CreateContactInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateContactInput { /// Consumes the builder and constructs an Operation<[`CreateContact`](crate::operation::CreateContact)> #[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::CreateContact, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateContactInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_2 = &_input.contact_list_name; let input_2 = input_2 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", })?; let contact_list_name = aws_smithy_http::label::fmt_string(input_2, false); if contact_list_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/contact-lists/{ContactListName}/contacts", ContactListName = contact_list_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateContactInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateContactInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_contact(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::CreateContact::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateContact", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateContactInput`](crate::input::CreateContactInput) pub fn builder() -> crate::input::create_contact_input::Builder { crate::input::create_contact_input::Builder::default() } } /// See [`CreateContactListInput`](crate::input::CreateContactListInput) pub mod create_contact_list_input { /// A builder for [`CreateContactListInput`](crate::input::CreateContactListInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) contact_list_name: std::option::Option<std::string::String>, pub(crate) topics: std::option::Option<std::vec::Vec<crate::model::Topic>>, pub(crate) description: std::option::Option<std::string::String>, pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl Builder { /// <p>The name of the contact list.</p> pub fn contact_list_name(mut self, input: impl Into<std::string::String>) -> Self { self.contact_list_name = Some(input.into()); self } /// <p>The name of the contact list.</p> pub fn set_contact_list_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.contact_list_name = input; self } /// Appends an item to `topics`. /// /// To override the contents of this collection use [`set_topics`](Self::set_topics). /// /// <p>An interest group, theme, or label within a list. A contact list can have multiple /// topics.</p> pub fn topics(mut self, input: impl Into<crate::model::Topic>) -> Self { let mut v = self.topics.unwrap_or_default(); v.push(input.into()); self.topics = Some(v); self } /// <p>An interest group, theme, or label within a list. A contact list can have multiple /// topics.</p> pub fn set_topics( mut self, input: std::option::Option<std::vec::Vec<crate::model::Topic>>, ) -> Self { self.topics = input; self } /// <p>A description of what the contact list is about.</p> pub fn description(mut self, input: impl Into<std::string::String>) -> Self { self.description = Some(input.into()); self } /// <p>A description of what the contact list is about.</p> pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self { self.description = input; self } /// Appends an item to `tags`. /// /// To override the contents of this collection use [`set_tags`](Self::set_tags). /// /// <p>The tags associated with a contact list.</p> pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self { let mut v = self.tags.unwrap_or_default(); v.push(input.into()); self.tags = Some(v); self } /// <p>The tags associated with a contact list.</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 [`CreateContactListInput`](crate::input::CreateContactListInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateContactListInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateContactListInput { contact_list_name: self.contact_list_name, topics: self.topics, description: self.description, tags: self.tags, }) } } } #[doc(hidden)] pub type CreateContactListInputOperationOutputAlias = crate::operation::CreateContactList; #[doc(hidden)] pub type CreateContactListInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateContactListInput { /// Consumes the builder and constructs an Operation<[`CreateContactList`](crate::operation::CreateContactList)> #[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::CreateContactList, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateContactListInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/contact-lists").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateContactListInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateContactListInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_contact_list(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::CreateContactList::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateContactList", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateContactListInput`](crate::input::CreateContactListInput) pub fn builder() -> crate::input::create_contact_list_input::Builder { crate::input::create_contact_list_input::Builder::default() } } /// See [`CreateCustomVerificationEmailTemplateInput`](crate::input::CreateCustomVerificationEmailTemplateInput) pub mod create_custom_verification_email_template_input { /// A builder for [`CreateCustomVerificationEmailTemplateInput`](crate::input::CreateCustomVerificationEmailTemplateInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) template_name: std::option::Option<std::string::String>, pub(crate) from_email_address: std::option::Option<std::string::String>, pub(crate) template_subject: std::option::Option<std::string::String>, pub(crate) template_content: std::option::Option<std::string::String>, pub(crate) success_redirection_url: std::option::Option<std::string::String>, pub(crate) failure_redirection_url: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the custom verification email template.</p> pub fn template_name(mut self, input: impl Into<std::string::String>) -> Self { self.template_name = Some(input.into()); self } /// <p>The name of the custom verification email template.</p> pub fn set_template_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_name = input; self } /// <p>The email address that the custom verification email is sent from.</p> pub fn from_email_address(mut self, input: impl Into<std::string::String>) -> Self { self.from_email_address = Some(input.into()); self } /// <p>The email address that the custom verification email is sent from.</p> pub fn set_from_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.from_email_address = input; self } /// <p>The subject line of the custom verification email.</p> pub fn template_subject(mut self, input: impl Into<std::string::String>) -> Self { self.template_subject = Some(input.into()); self } /// <p>The subject line of the custom verification email.</p> pub fn set_template_subject( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_subject = input; self } /// <p>The content of the custom verification email. The total size of the email must be less /// than 10 MB. The message body may contain HTML, with some limitations. For more /// information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-verify-address-custom.html#custom-verification-emails-faq">Custom Verification Email Frequently Asked Questions</a> in the <i>Amazon SES /// Developer Guide</i>.</p> pub fn template_content(mut self, input: impl Into<std::string::String>) -> Self { self.template_content = Some(input.into()); self } /// <p>The content of the custom verification email. The total size of the email must be less /// than 10 MB. The message body may contain HTML, with some limitations. For more /// information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-verify-address-custom.html#custom-verification-emails-faq">Custom Verification Email Frequently Asked Questions</a> in the <i>Amazon SES /// Developer Guide</i>.</p> pub fn set_template_content( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_content = input; self } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is successfully verified.</p> pub fn success_redirection_url(mut self, input: impl Into<std::string::String>) -> Self { self.success_redirection_url = Some(input.into()); self } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is successfully verified.</p> pub fn set_success_redirection_url( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.success_redirection_url = input; self } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is not successfully verified.</p> pub fn failure_redirection_url(mut self, input: impl Into<std::string::String>) -> Self { self.failure_redirection_url = Some(input.into()); self } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is not successfully verified.</p> pub fn set_failure_redirection_url( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.failure_redirection_url = input; self } /// Consumes the builder and constructs a [`CreateCustomVerificationEmailTemplateInput`](crate::input::CreateCustomVerificationEmailTemplateInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateCustomVerificationEmailTemplateInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateCustomVerificationEmailTemplateInput { template_name: self.template_name, from_email_address: self.from_email_address, template_subject: self.template_subject, template_content: self.template_content, success_redirection_url: self.success_redirection_url, failure_redirection_url: self.failure_redirection_url, }) } } } #[doc(hidden)] pub type CreateCustomVerificationEmailTemplateInputOperationOutputAlias = crate::operation::CreateCustomVerificationEmailTemplate; #[doc(hidden)] pub type CreateCustomVerificationEmailTemplateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateCustomVerificationEmailTemplateInput { /// Consumes the builder and constructs an Operation<[`CreateCustomVerificationEmailTemplate`](crate::operation::CreateCustomVerificationEmailTemplate)> #[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::CreateCustomVerificationEmailTemplate, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateCustomVerificationEmailTemplateInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/custom-verification-email-templates") .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateCustomVerificationEmailTemplateInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateCustomVerificationEmailTemplateInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_custom_verification_email_template(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::CreateCustomVerificationEmailTemplate::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateCustomVerificationEmailTemplate", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateCustomVerificationEmailTemplateInput`](crate::input::CreateCustomVerificationEmailTemplateInput) pub fn builder() -> crate::input::create_custom_verification_email_template_input::Builder { crate::input::create_custom_verification_email_template_input::Builder::default() } } /// See [`CreateDedicatedIpPoolInput`](crate::input::CreateDedicatedIpPoolInput) pub mod create_dedicated_ip_pool_input { /// A builder for [`CreateDedicatedIpPoolInput`](crate::input::CreateDedicatedIpPoolInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) pool_name: std::option::Option<std::string::String>, pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl Builder { /// <p>The name of the dedicated IP pool.</p> pub fn pool_name(mut self, input: impl Into<std::string::String>) -> Self { self.pool_name = Some(input.into()); self } /// <p>The name of the dedicated IP pool.</p> pub fn set_pool_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.pool_name = input; self } /// Appends an item to `tags`. /// /// To override the contents of this collection use [`set_tags`](Self::set_tags). /// /// <p>An object that defines the tags (keys and values) that you want to associate with the /// pool.</p> pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self { let mut v = self.tags.unwrap_or_default(); v.push(input.into()); self.tags = Some(v); self } /// <p>An object that defines the tags (keys and values) that you want to associate with the /// pool.</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 [`CreateDedicatedIpPoolInput`](crate::input::CreateDedicatedIpPoolInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateDedicatedIpPoolInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateDedicatedIpPoolInput { pool_name: self.pool_name, tags: self.tags, }) } } } #[doc(hidden)] pub type CreateDedicatedIpPoolInputOperationOutputAlias = crate::operation::CreateDedicatedIpPool; #[doc(hidden)] pub type CreateDedicatedIpPoolInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateDedicatedIpPoolInput { /// Consumes the builder and constructs an Operation<[`CreateDedicatedIpPool`](crate::operation::CreateDedicatedIpPool)> #[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::CreateDedicatedIpPool, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateDedicatedIpPoolInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/dedicated-ip-pools").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateDedicatedIpPoolInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateDedicatedIpPoolInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_dedicated_ip_pool( &self, )?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::CreateDedicatedIpPool::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateDedicatedIpPool", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateDedicatedIpPoolInput`](crate::input::CreateDedicatedIpPoolInput) pub fn builder() -> crate::input::create_dedicated_ip_pool_input::Builder { crate::input::create_dedicated_ip_pool_input::Builder::default() } } /// See [`CreateDeliverabilityTestReportInput`](crate::input::CreateDeliverabilityTestReportInput) pub mod create_deliverability_test_report_input { /// A builder for [`CreateDeliverabilityTestReportInput`](crate::input::CreateDeliverabilityTestReportInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) report_name: std::option::Option<std::string::String>, pub(crate) from_email_address: std::option::Option<std::string::String>, pub(crate) content: std::option::Option<crate::model::EmailContent>, pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl Builder { /// <p>A unique name that helps you to identify the predictive inbox placement test when you retrieve the /// results.</p> pub fn report_name(mut self, input: impl Into<std::string::String>) -> Self { self.report_name = Some(input.into()); self } /// <p>A unique name that helps you to identify the predictive inbox placement test when you retrieve the /// results.</p> pub fn set_report_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.report_name = input; self } /// <p>The email address that the predictive inbox placement test email was sent from.</p> pub fn from_email_address(mut self, input: impl Into<std::string::String>) -> Self { self.from_email_address = Some(input.into()); self } /// <p>The email address that the predictive inbox placement test email was sent from.</p> pub fn set_from_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.from_email_address = input; self } /// <p>The HTML body of the message that you sent when you performed the predictive inbox placement test.</p> pub fn content(mut self, input: crate::model::EmailContent) -> Self { self.content = Some(input); self } /// <p>The HTML body of the message that you sent when you performed the predictive inbox placement test.</p> pub fn set_content( mut self, input: std::option::Option<crate::model::EmailContent>, ) -> Self { self.content = input; self } /// Appends an item to `tags`. /// /// To override the contents of this collection use [`set_tags`](Self::set_tags). /// /// <p>An array of objects that define the tags (keys and values) that you want to associate /// with the predictive inbox placement test.</p> pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self { let mut v = self.tags.unwrap_or_default(); v.push(input.into()); self.tags = Some(v); self } /// <p>An array of objects that define the tags (keys and values) that you want to associate /// with the predictive inbox placement test.</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 [`CreateDeliverabilityTestReportInput`](crate::input::CreateDeliverabilityTestReportInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateDeliverabilityTestReportInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateDeliverabilityTestReportInput { report_name: self.report_name, from_email_address: self.from_email_address, content: self.content, tags: self.tags, }) } } } #[doc(hidden)] pub type CreateDeliverabilityTestReportInputOperationOutputAlias = crate::operation::CreateDeliverabilityTestReport; #[doc(hidden)] pub type CreateDeliverabilityTestReportInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateDeliverabilityTestReportInput { /// Consumes the builder and constructs an Operation<[`CreateDeliverabilityTestReport`](crate::operation::CreateDeliverabilityTestReport)> #[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::CreateDeliverabilityTestReport, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateDeliverabilityTestReportInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/deliverability-dashboard/test") .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateDeliverabilityTestReportInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateDeliverabilityTestReportInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_deliverability_test_report(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::CreateDeliverabilityTestReport::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateDeliverabilityTestReport", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateDeliverabilityTestReportInput`](crate::input::CreateDeliverabilityTestReportInput) pub fn builder() -> crate::input::create_deliverability_test_report_input::Builder { crate::input::create_deliverability_test_report_input::Builder::default() } } /// See [`CreateEmailIdentityInput`](crate::input::CreateEmailIdentityInput) pub mod create_email_identity_input { /// A builder for [`CreateEmailIdentityInput`](crate::input::CreateEmailIdentityInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, pub(crate) dkim_signing_attributes: std::option::Option<crate::model::DkimSigningAttributes>, pub(crate) configuration_set_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The email address or domain to verify.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The email address or domain to verify.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// Appends an item to `tags`. /// /// To override the contents of this collection use [`set_tags`](Self::set_tags). /// /// <p>An array of objects that define the tags (keys and values) to associate with the email /// identity.</p> pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self { let mut v = self.tags.unwrap_or_default(); v.push(input.into()); self.tags = Some(v); self } /// <p>An array of objects that define the tags (keys and values) to associate with the email /// identity.</p> pub fn set_tags( mut self, input: std::option::Option<std::vec::Vec<crate::model::Tag>>, ) -> Self { self.tags = input; self } /// <p>If your request includes this object, Amazon SES configures the identity to use Bring Your /// Own DKIM (BYODKIM) for DKIM authentication purposes, or, configures the key length to be used for /// <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy DKIM</a>.</p> /// <p>You can only specify this object if the email identity is a domain, as opposed to an /// address.</p> pub fn dkim_signing_attributes( mut self, input: crate::model::DkimSigningAttributes, ) -> Self { self.dkim_signing_attributes = Some(input); self } /// <p>If your request includes this object, Amazon SES configures the identity to use Bring Your /// Own DKIM (BYODKIM) for DKIM authentication purposes, or, configures the key length to be used for /// <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy DKIM</a>.</p> /// <p>You can only specify this object if the email identity is a domain, as opposed to an /// address.</p> pub fn set_dkim_signing_attributes( mut self, input: std::option::Option<crate::model::DkimSigningAttributes>, ) -> Self { self.dkim_signing_attributes = input; self } /// <p>The configuration set to use by default when sending from this identity. Note that any /// configuration set defined in the email sending request takes precedence. </p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The configuration set to use by default when sending from this identity. Note that any /// configuration set defined in the email sending request takes precedence. </p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// Consumes the builder and constructs a [`CreateEmailIdentityInput`](crate::input::CreateEmailIdentityInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateEmailIdentityInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateEmailIdentityInput { email_identity: self.email_identity, tags: self.tags, dkim_signing_attributes: self.dkim_signing_attributes, configuration_set_name: self.configuration_set_name, }) } } } #[doc(hidden)] pub type CreateEmailIdentityInputOperationOutputAlias = crate::operation::CreateEmailIdentity; #[doc(hidden)] pub type CreateEmailIdentityInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateEmailIdentityInput { /// Consumes the builder and constructs an Operation<[`CreateEmailIdentity`](crate::operation::CreateEmailIdentity)> #[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::CreateEmailIdentity, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateEmailIdentityInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/identities").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateEmailIdentityInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateEmailIdentityInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_email_identity(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::CreateEmailIdentity::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateEmailIdentity", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateEmailIdentityInput`](crate::input::CreateEmailIdentityInput) pub fn builder() -> crate::input::create_email_identity_input::Builder { crate::input::create_email_identity_input::Builder::default() } } /// See [`CreateEmailIdentityPolicyInput`](crate::input::CreateEmailIdentityPolicyInput) pub mod create_email_identity_policy_input { /// A builder for [`CreateEmailIdentityPolicyInput`](crate::input::CreateEmailIdentityPolicyInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, pub(crate) policy_name: std::option::Option<std::string::String>, pub(crate) policy: std::option::Option<std::string::String>, } impl Builder { /// <p>The email identity.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The email identity.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub fn policy_name(mut self, input: impl Into<std::string::String>) -> Self { self.policy_name = Some(input.into()); self } /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub fn set_policy_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.policy_name = input; self } /// <p>The text of the policy in JSON format. The policy cannot exceed 4 KB.</p> /// <p>For information about the syntax of sending authorization policies, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES Developer /// Guide</a>.</p> pub fn policy(mut self, input: impl Into<std::string::String>) -> Self { self.policy = Some(input.into()); self } /// <p>The text of the policy in JSON format. The policy cannot exceed 4 KB.</p> /// <p>For information about the syntax of sending authorization policies, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES Developer /// Guide</a>.</p> pub fn set_policy(mut self, input: std::option::Option<std::string::String>) -> Self { self.policy = input; self } /// Consumes the builder and constructs a [`CreateEmailIdentityPolicyInput`](crate::input::CreateEmailIdentityPolicyInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateEmailIdentityPolicyInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateEmailIdentityPolicyInput { email_identity: self.email_identity, policy_name: self.policy_name, policy: self.policy, }) } } } #[doc(hidden)] pub type CreateEmailIdentityPolicyInputOperationOutputAlias = crate::operation::CreateEmailIdentityPolicy; #[doc(hidden)] pub type CreateEmailIdentityPolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateEmailIdentityPolicyInput { /// Consumes the builder and constructs an Operation<[`CreateEmailIdentityPolicy`](crate::operation::CreateEmailIdentityPolicy)> #[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::CreateEmailIdentityPolicy, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateEmailIdentityPolicyInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_3 = &_input.email_identity; let input_3 = input_3 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", })?; let email_identity = aws_smithy_http::label::fmt_string(input_3, false); if email_identity.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", }); } let input_4 = &_input.policy_name; let input_4 = input_4 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "policy_name", details: "cannot be empty or unset", })?; let policy_name = aws_smithy_http::label::fmt_string(input_4, false); if policy_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "policy_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/identities/{EmailIdentity}/policies/{PolicyName}", EmailIdentity = email_identity, PolicyName = policy_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateEmailIdentityPolicyInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateEmailIdentityPolicyInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_email_identity_policy( &self, )?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::CreateEmailIdentityPolicy::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateEmailIdentityPolicy", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateEmailIdentityPolicyInput`](crate::input::CreateEmailIdentityPolicyInput) pub fn builder() -> crate::input::create_email_identity_policy_input::Builder { crate::input::create_email_identity_policy_input::Builder::default() } } /// See [`CreateEmailTemplateInput`](crate::input::CreateEmailTemplateInput) pub mod create_email_template_input { /// A builder for [`CreateEmailTemplateInput`](crate::input::CreateEmailTemplateInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) template_name: std::option::Option<std::string::String>, pub(crate) template_content: std::option::Option<crate::model::EmailTemplateContent>, } impl Builder { /// <p>The name of the template.</p> pub fn template_name(mut self, input: impl Into<std::string::String>) -> Self { self.template_name = Some(input.into()); self } /// <p>The name of the template.</p> pub fn set_template_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_name = input; self } /// <p>The content of the email template, composed of a subject line, an HTML part, and a /// text-only part.</p> pub fn template_content(mut self, input: crate::model::EmailTemplateContent) -> Self { self.template_content = Some(input); self } /// <p>The content of the email template, composed of a subject line, an HTML part, and a /// text-only part.</p> pub fn set_template_content( mut self, input: std::option::Option<crate::model::EmailTemplateContent>, ) -> Self { self.template_content = input; self } /// Consumes the builder and constructs a [`CreateEmailTemplateInput`](crate::input::CreateEmailTemplateInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateEmailTemplateInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateEmailTemplateInput { template_name: self.template_name, template_content: self.template_content, }) } } } #[doc(hidden)] pub type CreateEmailTemplateInputOperationOutputAlias = crate::operation::CreateEmailTemplate; #[doc(hidden)] pub type CreateEmailTemplateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateEmailTemplateInput { /// Consumes the builder and constructs an Operation<[`CreateEmailTemplate`](crate::operation::CreateEmailTemplate)> #[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::CreateEmailTemplate, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateEmailTemplateInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/templates").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateEmailTemplateInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateEmailTemplateInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_email_template(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::CreateEmailTemplate::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateEmailTemplate", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateEmailTemplateInput`](crate::input::CreateEmailTemplateInput) pub fn builder() -> crate::input::create_email_template_input::Builder { crate::input::create_email_template_input::Builder::default() } } /// See [`CreateImportJobInput`](crate::input::CreateImportJobInput) pub mod create_import_job_input { /// A builder for [`CreateImportJobInput`](crate::input::CreateImportJobInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) import_destination: std::option::Option<crate::model::ImportDestination>, pub(crate) import_data_source: std::option::Option<crate::model::ImportDataSource>, } impl Builder { /// <p>The destination for the import job.</p> pub fn import_destination(mut self, input: crate::model::ImportDestination) -> Self { self.import_destination = Some(input); self } /// <p>The destination for the import job.</p> pub fn set_import_destination( mut self, input: std::option::Option<crate::model::ImportDestination>, ) -> Self { self.import_destination = input; self } /// <p>The data source for the import job.</p> pub fn import_data_source(mut self, input: crate::model::ImportDataSource) -> Self { self.import_data_source = Some(input); self } /// <p>The data source for the import job.</p> pub fn set_import_data_source( mut self, input: std::option::Option<crate::model::ImportDataSource>, ) -> Self { self.import_data_source = input; self } /// Consumes the builder and constructs a [`CreateImportJobInput`](crate::input::CreateImportJobInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateImportJobInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::CreateImportJobInput { import_destination: self.import_destination, import_data_source: self.import_data_source, }) } } } #[doc(hidden)] pub type CreateImportJobInputOperationOutputAlias = crate::operation::CreateImportJob; #[doc(hidden)] pub type CreateImportJobInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateImportJobInput { /// Consumes the builder and constructs an Operation<[`CreateImportJob`](crate::operation::CreateImportJob)> #[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::CreateImportJob, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::CreateImportJobInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/import-jobs").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::CreateImportJobInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::CreateImportJobInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_create_import_job(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::CreateImportJob::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "CreateImportJob", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateImportJobInput`](crate::input::CreateImportJobInput) pub fn builder() -> crate::input::create_import_job_input::Builder { crate::input::create_import_job_input::Builder::default() } } /// See [`DeleteConfigurationSetInput`](crate::input::DeleteConfigurationSetInput) pub mod delete_configuration_set_input { /// A builder for [`DeleteConfigurationSetInput`](crate::input::DeleteConfigurationSetInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the configuration set.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// Consumes the builder and constructs a [`DeleteConfigurationSetInput`](crate::input::DeleteConfigurationSetInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteConfigurationSetInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteConfigurationSetInput { configuration_set_name: self.configuration_set_name, }) } } } #[doc(hidden)] pub type DeleteConfigurationSetInputOperationOutputAlias = crate::operation::DeleteConfigurationSet; #[doc(hidden)] pub type DeleteConfigurationSetInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteConfigurationSetInput { /// Consumes the builder and constructs an Operation<[`DeleteConfigurationSet`](crate::operation::DeleteConfigurationSet)> #[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::DeleteConfigurationSet, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteConfigurationSetInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_5 = &_input.configuration_set_name; let input_5 = input_5 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", })?; let configuration_set_name = aws_smithy_http::label::fmt_string(input_5, false); if configuration_set_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/configuration-sets/{ConfigurationSetName}", ConfigurationSetName = configuration_set_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteConfigurationSetInput, 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("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteConfigurationSetInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::DeleteConfigurationSet::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteConfigurationSet", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteConfigurationSetInput`](crate::input::DeleteConfigurationSetInput) pub fn builder() -> crate::input::delete_configuration_set_input::Builder { crate::input::delete_configuration_set_input::Builder::default() } } /// See [`DeleteConfigurationSetEventDestinationInput`](crate::input::DeleteConfigurationSetEventDestinationInput) pub mod delete_configuration_set_event_destination_input { /// A builder for [`DeleteConfigurationSetEventDestinationInput`](crate::input::DeleteConfigurationSetEventDestinationInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, pub(crate) event_destination_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the configuration set that contains the event destination to /// delete.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set that contains the event destination to /// delete.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// <p>The name of the event destination to delete.</p> pub fn event_destination_name(mut self, input: impl Into<std::string::String>) -> Self { self.event_destination_name = Some(input.into()); self } /// <p>The name of the event destination to delete.</p> pub fn set_event_destination_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.event_destination_name = input; self } /// Consumes the builder and constructs a [`DeleteConfigurationSetEventDestinationInput`](crate::input::DeleteConfigurationSetEventDestinationInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteConfigurationSetEventDestinationInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteConfigurationSetEventDestinationInput { configuration_set_name: self.configuration_set_name, event_destination_name: self.event_destination_name, }) } } } #[doc(hidden)] pub type DeleteConfigurationSetEventDestinationInputOperationOutputAlias = crate::operation::DeleteConfigurationSetEventDestination; #[doc(hidden)] pub type DeleteConfigurationSetEventDestinationInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteConfigurationSetEventDestinationInput { /// Consumes the builder and constructs an Operation<[`DeleteConfigurationSetEventDestination`](crate::operation::DeleteConfigurationSetEventDestination)> #[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::DeleteConfigurationSetEventDestination, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteConfigurationSetEventDestinationInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_6 = &_input.configuration_set_name; let input_6 = input_6 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", })?; let configuration_set_name = aws_smithy_http::label::fmt_string(input_6, false); if configuration_set_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", }); } let input_7 = &_input.event_destination_name; let input_7 = input_7 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "event_destination_name", details: "cannot be empty or unset", })?; let event_destination_name = aws_smithy_http::label::fmt_string(input_7, false); if event_destination_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "event_destination_name", details: "cannot be empty or unset", }); } write!(output, "/v2/email/configuration-sets/{ConfigurationSetName}/event-destinations/{EventDestinationName}", ConfigurationSetName = configuration_set_name, EventDestinationName = event_destination_name).expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteConfigurationSetEventDestinationInput, 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("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteConfigurationSetEventDestinationInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::DeleteConfigurationSetEventDestination::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteConfigurationSetEventDestination", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteConfigurationSetEventDestinationInput`](crate::input::DeleteConfigurationSetEventDestinationInput) pub fn builder() -> crate::input::delete_configuration_set_event_destination_input::Builder { crate::input::delete_configuration_set_event_destination_input::Builder::default() } } /// See [`DeleteContactInput`](crate::input::DeleteContactInput) pub mod delete_contact_input { /// A builder for [`DeleteContactInput`](crate::input::DeleteContactInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) contact_list_name: std::option::Option<std::string::String>, pub(crate) email_address: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the contact list from which the contact should be removed.</p> pub fn contact_list_name(mut self, input: impl Into<std::string::String>) -> Self { self.contact_list_name = Some(input.into()); self } /// <p>The name of the contact list from which the contact should be removed.</p> pub fn set_contact_list_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.contact_list_name = input; self } /// <p>The contact's email address.</p> pub fn email_address(mut self, input: impl Into<std::string::String>) -> Self { self.email_address = Some(input.into()); self } /// <p>The contact's email address.</p> pub fn set_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_address = input; self } /// Consumes the builder and constructs a [`DeleteContactInput`](crate::input::DeleteContactInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteContactInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteContactInput { contact_list_name: self.contact_list_name, email_address: self.email_address, }) } } } #[doc(hidden)] pub type DeleteContactInputOperationOutputAlias = crate::operation::DeleteContact; #[doc(hidden)] pub type DeleteContactInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteContactInput { /// Consumes the builder and constructs an Operation<[`DeleteContact`](crate::operation::DeleteContact)> #[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::DeleteContact, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteContactInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_8 = &_input.contact_list_name; let input_8 = input_8 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", })?; let contact_list_name = aws_smithy_http::label::fmt_string(input_8, false); if contact_list_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", }); } let input_9 = &_input.email_address; let input_9 = input_9 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_address", details: "cannot be empty or unset", })?; let email_address = aws_smithy_http::label::fmt_string(input_9, false); if email_address.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_address", details: "cannot be empty or unset", }); } write!( output, "/v2/email/contact-lists/{ContactListName}/contacts/{EmailAddress}", ContactListName = contact_list_name, EmailAddress = email_address ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteContactInput, 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("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteContactInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::DeleteContact::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteContact", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteContactInput`](crate::input::DeleteContactInput) pub fn builder() -> crate::input::delete_contact_input::Builder { crate::input::delete_contact_input::Builder::default() } } /// See [`DeleteContactListInput`](crate::input::DeleteContactListInput) pub mod delete_contact_list_input { /// A builder for [`DeleteContactListInput`](crate::input::DeleteContactListInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) contact_list_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the contact list.</p> pub fn contact_list_name(mut self, input: impl Into<std::string::String>) -> Self { self.contact_list_name = Some(input.into()); self } /// <p>The name of the contact list.</p> pub fn set_contact_list_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.contact_list_name = input; self } /// Consumes the builder and constructs a [`DeleteContactListInput`](crate::input::DeleteContactListInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteContactListInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteContactListInput { contact_list_name: self.contact_list_name, }) } } } #[doc(hidden)] pub type DeleteContactListInputOperationOutputAlias = crate::operation::DeleteContactList; #[doc(hidden)] pub type DeleteContactListInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteContactListInput { /// Consumes the builder and constructs an Operation<[`DeleteContactList`](crate::operation::DeleteContactList)> #[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::DeleteContactList, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteContactListInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_10 = &_input.contact_list_name; let input_10 = input_10 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", })?; let contact_list_name = aws_smithy_http::label::fmt_string(input_10, false); if contact_list_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/contact-lists/{ContactListName}", ContactListName = contact_list_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteContactListInput, 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("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteContactListInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::DeleteContactList::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteContactList", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteContactListInput`](crate::input::DeleteContactListInput) pub fn builder() -> crate::input::delete_contact_list_input::Builder { crate::input::delete_contact_list_input::Builder::default() } } /// See [`DeleteCustomVerificationEmailTemplateInput`](crate::input::DeleteCustomVerificationEmailTemplateInput) pub mod delete_custom_verification_email_template_input { /// A builder for [`DeleteCustomVerificationEmailTemplateInput`](crate::input::DeleteCustomVerificationEmailTemplateInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) template_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the custom verification email template that you want to delete.</p> pub fn template_name(mut self, input: impl Into<std::string::String>) -> Self { self.template_name = Some(input.into()); self } /// <p>The name of the custom verification email template that you want to delete.</p> pub fn set_template_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_name = input; self } /// Consumes the builder and constructs a [`DeleteCustomVerificationEmailTemplateInput`](crate::input::DeleteCustomVerificationEmailTemplateInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteCustomVerificationEmailTemplateInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteCustomVerificationEmailTemplateInput { template_name: self.template_name, }) } } } #[doc(hidden)] pub type DeleteCustomVerificationEmailTemplateInputOperationOutputAlias = crate::operation::DeleteCustomVerificationEmailTemplate; #[doc(hidden)] pub type DeleteCustomVerificationEmailTemplateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteCustomVerificationEmailTemplateInput { /// Consumes the builder and constructs an Operation<[`DeleteCustomVerificationEmailTemplate`](crate::operation::DeleteCustomVerificationEmailTemplate)> #[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::DeleteCustomVerificationEmailTemplate, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteCustomVerificationEmailTemplateInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_11 = &_input.template_name; let input_11 = input_11 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", })?; let template_name = aws_smithy_http::label::fmt_string(input_11, false); if template_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/custom-verification-email-templates/{TemplateName}", TemplateName = template_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteCustomVerificationEmailTemplateInput, 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("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteCustomVerificationEmailTemplateInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::DeleteCustomVerificationEmailTemplate::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteCustomVerificationEmailTemplate", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteCustomVerificationEmailTemplateInput`](crate::input::DeleteCustomVerificationEmailTemplateInput) pub fn builder() -> crate::input::delete_custom_verification_email_template_input::Builder { crate::input::delete_custom_verification_email_template_input::Builder::default() } } /// See [`DeleteDedicatedIpPoolInput`](crate::input::DeleteDedicatedIpPoolInput) pub mod delete_dedicated_ip_pool_input { /// A builder for [`DeleteDedicatedIpPoolInput`](crate::input::DeleteDedicatedIpPoolInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) pool_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the dedicated IP pool that you want to delete.</p> pub fn pool_name(mut self, input: impl Into<std::string::String>) -> Self { self.pool_name = Some(input.into()); self } /// <p>The name of the dedicated IP pool that you want to delete.</p> pub fn set_pool_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.pool_name = input; self } /// Consumes the builder and constructs a [`DeleteDedicatedIpPoolInput`](crate::input::DeleteDedicatedIpPoolInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteDedicatedIpPoolInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteDedicatedIpPoolInput { pool_name: self.pool_name, }) } } } #[doc(hidden)] pub type DeleteDedicatedIpPoolInputOperationOutputAlias = crate::operation::DeleteDedicatedIpPool; #[doc(hidden)] pub type DeleteDedicatedIpPoolInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteDedicatedIpPoolInput { /// Consumes the builder and constructs an Operation<[`DeleteDedicatedIpPool`](crate::operation::DeleteDedicatedIpPool)> #[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::DeleteDedicatedIpPool, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteDedicatedIpPoolInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_12 = &_input.pool_name; let input_12 = input_12 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "pool_name", details: "cannot be empty or unset", })?; let pool_name = aws_smithy_http::label::fmt_string(input_12, false); if pool_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "pool_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/dedicated-ip-pools/{PoolName}", PoolName = pool_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteDedicatedIpPoolInput, 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("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteDedicatedIpPoolInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::DeleteDedicatedIpPool::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteDedicatedIpPool", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteDedicatedIpPoolInput`](crate::input::DeleteDedicatedIpPoolInput) pub fn builder() -> crate::input::delete_dedicated_ip_pool_input::Builder { crate::input::delete_dedicated_ip_pool_input::Builder::default() } } /// See [`DeleteEmailIdentityInput`](crate::input::DeleteEmailIdentityInput) pub mod delete_email_identity_input { /// A builder for [`DeleteEmailIdentityInput`](crate::input::DeleteEmailIdentityInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, } impl Builder { /// <p>The identity (that is, the email address or domain) to delete.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The identity (that is, the email address or domain) to delete.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// Consumes the builder and constructs a [`DeleteEmailIdentityInput`](crate::input::DeleteEmailIdentityInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteEmailIdentityInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteEmailIdentityInput { email_identity: self.email_identity, }) } } } #[doc(hidden)] pub type DeleteEmailIdentityInputOperationOutputAlias = crate::operation::DeleteEmailIdentity; #[doc(hidden)] pub type DeleteEmailIdentityInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteEmailIdentityInput { /// Consumes the builder and constructs an Operation<[`DeleteEmailIdentity`](crate::operation::DeleteEmailIdentity)> #[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::DeleteEmailIdentity, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteEmailIdentityInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_13 = &_input.email_identity; let input_13 = input_13 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", })?; let email_identity = aws_smithy_http::label::fmt_string(input_13, false); if email_identity.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", }); } write!( output, "/v2/email/identities/{EmailIdentity}", EmailIdentity = email_identity ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteEmailIdentityInput, 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("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteEmailIdentityInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::DeleteEmailIdentity::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteEmailIdentity", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteEmailIdentityInput`](crate::input::DeleteEmailIdentityInput) pub fn builder() -> crate::input::delete_email_identity_input::Builder { crate::input::delete_email_identity_input::Builder::default() } } /// See [`DeleteEmailIdentityPolicyInput`](crate::input::DeleteEmailIdentityPolicyInput) pub mod delete_email_identity_policy_input { /// A builder for [`DeleteEmailIdentityPolicyInput`](crate::input::DeleteEmailIdentityPolicyInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, pub(crate) policy_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The email identity.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The email identity.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub fn policy_name(mut self, input: impl Into<std::string::String>) -> Self { self.policy_name = Some(input.into()); self } /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub fn set_policy_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.policy_name = input; self } /// Consumes the builder and constructs a [`DeleteEmailIdentityPolicyInput`](crate::input::DeleteEmailIdentityPolicyInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteEmailIdentityPolicyInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteEmailIdentityPolicyInput { email_identity: self.email_identity, policy_name: self.policy_name, }) } } } #[doc(hidden)] pub type DeleteEmailIdentityPolicyInputOperationOutputAlias = crate::operation::DeleteEmailIdentityPolicy; #[doc(hidden)] pub type DeleteEmailIdentityPolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteEmailIdentityPolicyInput { /// Consumes the builder and constructs an Operation<[`DeleteEmailIdentityPolicy`](crate::operation::DeleteEmailIdentityPolicy)> #[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::DeleteEmailIdentityPolicy, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteEmailIdentityPolicyInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_14 = &_input.email_identity; let input_14 = input_14 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", })?; let email_identity = aws_smithy_http::label::fmt_string(input_14, false); if email_identity.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", }); } let input_15 = &_input.policy_name; let input_15 = input_15 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "policy_name", details: "cannot be empty or unset", })?; let policy_name = aws_smithy_http::label::fmt_string(input_15, false); if policy_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "policy_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/identities/{EmailIdentity}/policies/{PolicyName}", EmailIdentity = email_identity, PolicyName = policy_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteEmailIdentityPolicyInput, 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("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteEmailIdentityPolicyInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::DeleteEmailIdentityPolicy::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteEmailIdentityPolicy", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteEmailIdentityPolicyInput`](crate::input::DeleteEmailIdentityPolicyInput) pub fn builder() -> crate::input::delete_email_identity_policy_input::Builder { crate::input::delete_email_identity_policy_input::Builder::default() } } /// See [`DeleteEmailTemplateInput`](crate::input::DeleteEmailTemplateInput) pub mod delete_email_template_input { /// A builder for [`DeleteEmailTemplateInput`](crate::input::DeleteEmailTemplateInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) template_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the template to be deleted.</p> pub fn template_name(mut self, input: impl Into<std::string::String>) -> Self { self.template_name = Some(input.into()); self } /// <p>The name of the template to be deleted.</p> pub fn set_template_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_name = input; self } /// Consumes the builder and constructs a [`DeleteEmailTemplateInput`](crate::input::DeleteEmailTemplateInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteEmailTemplateInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteEmailTemplateInput { template_name: self.template_name, }) } } } #[doc(hidden)] pub type DeleteEmailTemplateInputOperationOutputAlias = crate::operation::DeleteEmailTemplate; #[doc(hidden)] pub type DeleteEmailTemplateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteEmailTemplateInput { /// Consumes the builder and constructs an Operation<[`DeleteEmailTemplate`](crate::operation::DeleteEmailTemplate)> #[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::DeleteEmailTemplate, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteEmailTemplateInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_16 = &_input.template_name; let input_16 = input_16 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", })?; let template_name = aws_smithy_http::label::fmt_string(input_16, false); if template_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/templates/{TemplateName}", TemplateName = template_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteEmailTemplateInput, 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("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteEmailTemplateInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::DeleteEmailTemplate::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteEmailTemplate", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteEmailTemplateInput`](crate::input::DeleteEmailTemplateInput) pub fn builder() -> crate::input::delete_email_template_input::Builder { crate::input::delete_email_template_input::Builder::default() } } /// See [`DeleteSuppressedDestinationInput`](crate::input::DeleteSuppressedDestinationInput) pub mod delete_suppressed_destination_input { /// A builder for [`DeleteSuppressedDestinationInput`](crate::input::DeleteSuppressedDestinationInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_address: std::option::Option<std::string::String>, } impl Builder { /// <p>The suppressed email destination to remove from the account suppression list.</p> pub fn email_address(mut self, input: impl Into<std::string::String>) -> Self { self.email_address = Some(input.into()); self } /// <p>The suppressed email destination to remove from the account suppression list.</p> pub fn set_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_address = input; self } /// Consumes the builder and constructs a [`DeleteSuppressedDestinationInput`](crate::input::DeleteSuppressedDestinationInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteSuppressedDestinationInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::DeleteSuppressedDestinationInput { email_address: self.email_address, }) } } } #[doc(hidden)] pub type DeleteSuppressedDestinationInputOperationOutputAlias = crate::operation::DeleteSuppressedDestination; #[doc(hidden)] pub type DeleteSuppressedDestinationInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteSuppressedDestinationInput { /// Consumes the builder and constructs an Operation<[`DeleteSuppressedDestination`](crate::operation::DeleteSuppressedDestination)> #[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::DeleteSuppressedDestination, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::DeleteSuppressedDestinationInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_17 = &_input.email_address; let input_17 = input_17 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_address", details: "cannot be empty or unset", })?; let email_address = aws_smithy_http::label::fmt_string(input_17, false); if email_address.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_address", details: "cannot be empty or unset", }); } write!( output, "/v2/email/suppression/addresses/{EmailAddress}", EmailAddress = email_address ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::DeleteSuppressedDestinationInput, 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("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::DeleteSuppressedDestinationInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::DeleteSuppressedDestination::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "DeleteSuppressedDestination", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteSuppressedDestinationInput`](crate::input::DeleteSuppressedDestinationInput) pub fn builder() -> crate::input::delete_suppressed_destination_input::Builder { crate::input::delete_suppressed_destination_input::Builder::default() } } /// See [`GetAccountInput`](crate::input::GetAccountInput) pub mod get_account_input { /// A builder for [`GetAccountInput`](crate::input::GetAccountInput) #[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 [`GetAccountInput`](crate::input::GetAccountInput) pub fn build( self, ) -> std::result::Result< crate::input::GetAccountInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetAccountInput {}) } } } #[doc(hidden)] pub type GetAccountInputOperationOutputAlias = crate::operation::GetAccount; #[doc(hidden)] pub type GetAccountInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetAccountInput { /// Consumes the builder and constructs an Operation<[`GetAccount`](crate::operation::GetAccount)> #[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::GetAccount, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetAccountInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/account").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetAccountInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetAccountInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetAccount::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetAccount", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetAccountInput`](crate::input::GetAccountInput) pub fn builder() -> crate::input::get_account_input::Builder { crate::input::get_account_input::Builder::default() } } /// See [`GetBlacklistReportsInput`](crate::input::GetBlacklistReportsInput) pub mod get_blacklist_reports_input { /// A builder for [`GetBlacklistReportsInput`](crate::input::GetBlacklistReportsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) blacklist_item_names: std::option::Option<std::vec::Vec<std::string::String>>, } impl Builder { /// Appends an item to `blacklist_item_names`. /// /// To override the contents of this collection use [`set_blacklist_item_names`](Self::set_blacklist_item_names). /// /// <p>A list of IP addresses that you want to retrieve blacklist information about. You can /// only specify the dedicated IP addresses that you use to send email using Amazon SES or /// Amazon Pinpoint.</p> pub fn blacklist_item_names(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.blacklist_item_names.unwrap_or_default(); v.push(input.into()); self.blacklist_item_names = Some(v); self } /// <p>A list of IP addresses that you want to retrieve blacklist information about. You can /// only specify the dedicated IP addresses that you use to send email using Amazon SES or /// Amazon Pinpoint.</p> pub fn set_blacklist_item_names( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.blacklist_item_names = input; self } /// Consumes the builder and constructs a [`GetBlacklistReportsInput`](crate::input::GetBlacklistReportsInput) pub fn build( self, ) -> std::result::Result< crate::input::GetBlacklistReportsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetBlacklistReportsInput { blacklist_item_names: self.blacklist_item_names, }) } } } #[doc(hidden)] pub type GetBlacklistReportsInputOperationOutputAlias = crate::operation::GetBlacklistReports; #[doc(hidden)] pub type GetBlacklistReportsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetBlacklistReportsInput { /// Consumes the builder and constructs an Operation<[`GetBlacklistReports`](crate::operation::GetBlacklistReports)> #[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::GetBlacklistReports, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetBlacklistReportsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!( output, "/v2/email/deliverability-dashboard/blacklist-report" ) .expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::GetBlacklistReportsInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_18) = &_input.blacklist_item_names { for inner_19 in inner_18 { query.push_kv( "BlacklistItemNames", &aws_smithy_http::query::fmt_string(&inner_19), ); } } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetBlacklistReportsInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetBlacklistReportsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetBlacklistReports::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetBlacklistReports", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetBlacklistReportsInput`](crate::input::GetBlacklistReportsInput) pub fn builder() -> crate::input::get_blacklist_reports_input::Builder { crate::input::get_blacklist_reports_input::Builder::default() } } /// See [`GetConfigurationSetInput`](crate::input::GetConfigurationSetInput) pub mod get_configuration_set_input { /// A builder for [`GetConfigurationSetInput`](crate::input::GetConfigurationSetInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the configuration set.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// Consumes the builder and constructs a [`GetConfigurationSetInput`](crate::input::GetConfigurationSetInput) pub fn build( self, ) -> std::result::Result< crate::input::GetConfigurationSetInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetConfigurationSetInput { configuration_set_name: self.configuration_set_name, }) } } } #[doc(hidden)] pub type GetConfigurationSetInputOperationOutputAlias = crate::operation::GetConfigurationSet; #[doc(hidden)] pub type GetConfigurationSetInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetConfigurationSetInput { /// Consumes the builder and constructs an Operation<[`GetConfigurationSet`](crate::operation::GetConfigurationSet)> #[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::GetConfigurationSet, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetConfigurationSetInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_20 = &_input.configuration_set_name; let input_20 = input_20 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", })?; let configuration_set_name = aws_smithy_http::label::fmt_string(input_20, false); if configuration_set_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/configuration-sets/{ConfigurationSetName}", ConfigurationSetName = configuration_set_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetConfigurationSetInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetConfigurationSetInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetConfigurationSet::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetConfigurationSet", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetConfigurationSetInput`](crate::input::GetConfigurationSetInput) pub fn builder() -> crate::input::get_configuration_set_input::Builder { crate::input::get_configuration_set_input::Builder::default() } } /// See [`GetConfigurationSetEventDestinationsInput`](crate::input::GetConfigurationSetEventDestinationsInput) pub mod get_configuration_set_event_destinations_input { /// A builder for [`GetConfigurationSetEventDestinationsInput`](crate::input::GetConfigurationSetEventDestinationsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the configuration set that contains the event destination.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set that contains the event destination.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// Consumes the builder and constructs a [`GetConfigurationSetEventDestinationsInput`](crate::input::GetConfigurationSetEventDestinationsInput) pub fn build( self, ) -> std::result::Result< crate::input::GetConfigurationSetEventDestinationsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetConfigurationSetEventDestinationsInput { configuration_set_name: self.configuration_set_name, }) } } } #[doc(hidden)] pub type GetConfigurationSetEventDestinationsInputOperationOutputAlias = crate::operation::GetConfigurationSetEventDestinations; #[doc(hidden)] pub type GetConfigurationSetEventDestinationsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetConfigurationSetEventDestinationsInput { /// Consumes the builder and constructs an Operation<[`GetConfigurationSetEventDestinations`](crate::operation::GetConfigurationSetEventDestinations)> #[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::GetConfigurationSetEventDestinations, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetConfigurationSetEventDestinationsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_21 = &_input.configuration_set_name; let input_21 = input_21 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", })?; let configuration_set_name = aws_smithy_http::label::fmt_string(input_21, false); if configuration_set_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/configuration-sets/{ConfigurationSetName}/event-destinations", ConfigurationSetName = configuration_set_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetConfigurationSetEventDestinationsInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetConfigurationSetEventDestinationsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetConfigurationSetEventDestinations::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetConfigurationSetEventDestinations", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetConfigurationSetEventDestinationsInput`](crate::input::GetConfigurationSetEventDestinationsInput) pub fn builder() -> crate::input::get_configuration_set_event_destinations_input::Builder { crate::input::get_configuration_set_event_destinations_input::Builder::default() } } /// See [`GetContactInput`](crate::input::GetContactInput) pub mod get_contact_input { /// A builder for [`GetContactInput`](crate::input::GetContactInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) contact_list_name: std::option::Option<std::string::String>, pub(crate) email_address: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the contact list to which the contact belongs.</p> pub fn contact_list_name(mut self, input: impl Into<std::string::String>) -> Self { self.contact_list_name = Some(input.into()); self } /// <p>The name of the contact list to which the contact belongs.</p> pub fn set_contact_list_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.contact_list_name = input; self } /// <p>The contact's email addres.</p> pub fn email_address(mut self, input: impl Into<std::string::String>) -> Self { self.email_address = Some(input.into()); self } /// <p>The contact's email addres.</p> pub fn set_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_address = input; self } /// Consumes the builder and constructs a [`GetContactInput`](crate::input::GetContactInput) pub fn build( self, ) -> std::result::Result< crate::input::GetContactInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetContactInput { contact_list_name: self.contact_list_name, email_address: self.email_address, }) } } } #[doc(hidden)] pub type GetContactInputOperationOutputAlias = crate::operation::GetContact; #[doc(hidden)] pub type GetContactInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetContactInput { /// Consumes the builder and constructs an Operation<[`GetContact`](crate::operation::GetContact)> #[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::GetContact, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetContactInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_22 = &_input.contact_list_name; let input_22 = input_22 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", })?; let contact_list_name = aws_smithy_http::label::fmt_string(input_22, false); if contact_list_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", }); } let input_23 = &_input.email_address; let input_23 = input_23 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_address", details: "cannot be empty or unset", })?; let email_address = aws_smithy_http::label::fmt_string(input_23, false); if email_address.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_address", details: "cannot be empty or unset", }); } write!( output, "/v2/email/contact-lists/{ContactListName}/contacts/{EmailAddress}", ContactListName = contact_list_name, EmailAddress = email_address ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetContactInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetContactInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetContact::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetContact", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetContactInput`](crate::input::GetContactInput) pub fn builder() -> crate::input::get_contact_input::Builder { crate::input::get_contact_input::Builder::default() } } /// See [`GetContactListInput`](crate::input::GetContactListInput) pub mod get_contact_list_input { /// A builder for [`GetContactListInput`](crate::input::GetContactListInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) contact_list_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the contact list.</p> pub fn contact_list_name(mut self, input: impl Into<std::string::String>) -> Self { self.contact_list_name = Some(input.into()); self } /// <p>The name of the contact list.</p> pub fn set_contact_list_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.contact_list_name = input; self } /// Consumes the builder and constructs a [`GetContactListInput`](crate::input::GetContactListInput) pub fn build( self, ) -> std::result::Result< crate::input::GetContactListInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetContactListInput { contact_list_name: self.contact_list_name, }) } } } #[doc(hidden)] pub type GetContactListInputOperationOutputAlias = crate::operation::GetContactList; #[doc(hidden)] pub type GetContactListInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetContactListInput { /// Consumes the builder and constructs an Operation<[`GetContactList`](crate::operation::GetContactList)> #[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::GetContactList, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetContactListInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_24 = &_input.contact_list_name; let input_24 = input_24 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", })?; let contact_list_name = aws_smithy_http::label::fmt_string(input_24, false); if contact_list_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/contact-lists/{ContactListName}", ContactListName = contact_list_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetContactListInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetContactListInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetContactList::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetContactList", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetContactListInput`](crate::input::GetContactListInput) pub fn builder() -> crate::input::get_contact_list_input::Builder { crate::input::get_contact_list_input::Builder::default() } } /// See [`GetCustomVerificationEmailTemplateInput`](crate::input::GetCustomVerificationEmailTemplateInput) pub mod get_custom_verification_email_template_input { /// A builder for [`GetCustomVerificationEmailTemplateInput`](crate::input::GetCustomVerificationEmailTemplateInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) template_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the custom verification email template that you want to retrieve.</p> pub fn template_name(mut self, input: impl Into<std::string::String>) -> Self { self.template_name = Some(input.into()); self } /// <p>The name of the custom verification email template that you want to retrieve.</p> pub fn set_template_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_name = input; self } /// Consumes the builder and constructs a [`GetCustomVerificationEmailTemplateInput`](crate::input::GetCustomVerificationEmailTemplateInput) pub fn build( self, ) -> std::result::Result< crate::input::GetCustomVerificationEmailTemplateInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetCustomVerificationEmailTemplateInput { template_name: self.template_name, }) } } } #[doc(hidden)] pub type GetCustomVerificationEmailTemplateInputOperationOutputAlias = crate::operation::GetCustomVerificationEmailTemplate; #[doc(hidden)] pub type GetCustomVerificationEmailTemplateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetCustomVerificationEmailTemplateInput { /// Consumes the builder and constructs an Operation<[`GetCustomVerificationEmailTemplate`](crate::operation::GetCustomVerificationEmailTemplate)> #[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::GetCustomVerificationEmailTemplate, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetCustomVerificationEmailTemplateInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_25 = &_input.template_name; let input_25 = input_25 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", })?; let template_name = aws_smithy_http::label::fmt_string(input_25, false); if template_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/custom-verification-email-templates/{TemplateName}", TemplateName = template_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetCustomVerificationEmailTemplateInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetCustomVerificationEmailTemplateInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetCustomVerificationEmailTemplate::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetCustomVerificationEmailTemplate", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetCustomVerificationEmailTemplateInput`](crate::input::GetCustomVerificationEmailTemplateInput) pub fn builder() -> crate::input::get_custom_verification_email_template_input::Builder { crate::input::get_custom_verification_email_template_input::Builder::default() } } /// See [`GetDedicatedIpInput`](crate::input::GetDedicatedIpInput) pub mod get_dedicated_ip_input { /// A builder for [`GetDedicatedIpInput`](crate::input::GetDedicatedIpInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) ip: std::option::Option<std::string::String>, } impl Builder { /// <p>The IP address that you want to obtain more information about. The value you specify /// has to be a dedicated IP address that's assocaited with your Amazon Web Services account.</p> pub fn ip(mut self, input: impl Into<std::string::String>) -> Self { self.ip = Some(input.into()); self } /// <p>The IP address that you want to obtain more information about. The value you specify /// has to be a dedicated IP address that's assocaited with your Amazon Web Services account.</p> pub fn set_ip(mut self, input: std::option::Option<std::string::String>) -> Self { self.ip = input; self } /// Consumes the builder and constructs a [`GetDedicatedIpInput`](crate::input::GetDedicatedIpInput) pub fn build( self, ) -> std::result::Result< crate::input::GetDedicatedIpInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetDedicatedIpInput { ip: self.ip }) } } } #[doc(hidden)] pub type GetDedicatedIpInputOperationOutputAlias = crate::operation::GetDedicatedIp; #[doc(hidden)] pub type GetDedicatedIpInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetDedicatedIpInput { /// Consumes the builder and constructs an Operation<[`GetDedicatedIp`](crate::operation::GetDedicatedIp)> #[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::GetDedicatedIp, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetDedicatedIpInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_26 = &_input.ip; let input_26 = input_26 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "ip", details: "cannot be empty or unset", })?; let ip = aws_smithy_http::label::fmt_string(input_26, false); if ip.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "ip", details: "cannot be empty or unset", }); } write!(output, "/v2/email/dedicated-ips/{Ip}", Ip = ip) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetDedicatedIpInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetDedicatedIpInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetDedicatedIp::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetDedicatedIp", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetDedicatedIpInput`](crate::input::GetDedicatedIpInput) pub fn builder() -> crate::input::get_dedicated_ip_input::Builder { crate::input::get_dedicated_ip_input::Builder::default() } } /// See [`GetDedicatedIpsInput`](crate::input::GetDedicatedIpsInput) pub mod get_dedicated_ips_input { /// A builder for [`GetDedicatedIpsInput`](crate::input::GetDedicatedIpsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) pool_name: std::option::Option<std::string::String>, pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) page_size: std::option::Option<i32>, } impl Builder { /// <p>The name of the IP pool that the dedicated IP address is associated with.</p> pub fn pool_name(mut self, input: impl Into<std::string::String>) -> Self { self.pool_name = Some(input.into()); self } /// <p>The name of the IP pool that the dedicated IP address is associated with.</p> pub fn set_pool_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.pool_name = input; self } /// <p>A token returned from a previous call to <code>GetDedicatedIps</code> to indicate the /// position of the dedicated IP pool in the list of IP pools.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A token returned from a previous call to <code>GetDedicatedIps</code> to indicate the /// position of the dedicated IP pool in the list of IP pools.</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 results to show in a single call to <code>GetDedicatedIpsRequest</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>The number of results to show in a single call to <code>GetDedicatedIpsRequest</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// Consumes the builder and constructs a [`GetDedicatedIpsInput`](crate::input::GetDedicatedIpsInput) pub fn build( self, ) -> std::result::Result< crate::input::GetDedicatedIpsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetDedicatedIpsInput { pool_name: self.pool_name, next_token: self.next_token, page_size: self.page_size, }) } } } #[doc(hidden)] pub type GetDedicatedIpsInputOperationOutputAlias = crate::operation::GetDedicatedIps; #[doc(hidden)] pub type GetDedicatedIpsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetDedicatedIpsInput { /// Consumes the builder and constructs an Operation<[`GetDedicatedIps`](crate::operation::GetDedicatedIps)> #[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::GetDedicatedIps, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetDedicatedIpsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/dedicated-ips").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::GetDedicatedIpsInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_27) = &_input.pool_name { query.push_kv("PoolName", &aws_smithy_http::query::fmt_string(&inner_27)); } if let Some(inner_28) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_28)); } if let Some(inner_29) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_29).encode(), ); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetDedicatedIpsInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetDedicatedIpsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetDedicatedIps::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetDedicatedIps", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetDedicatedIpsInput`](crate::input::GetDedicatedIpsInput) pub fn builder() -> crate::input::get_dedicated_ips_input::Builder { crate::input::get_dedicated_ips_input::Builder::default() } } /// See [`GetDeliverabilityDashboardOptionsInput`](crate::input::GetDeliverabilityDashboardOptionsInput) pub mod get_deliverability_dashboard_options_input { /// A builder for [`GetDeliverabilityDashboardOptionsInput`](crate::input::GetDeliverabilityDashboardOptionsInput) #[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 [`GetDeliverabilityDashboardOptionsInput`](crate::input::GetDeliverabilityDashboardOptionsInput) pub fn build( self, ) -> std::result::Result< crate::input::GetDeliverabilityDashboardOptionsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetDeliverabilityDashboardOptionsInput {}) } } } #[doc(hidden)] pub type GetDeliverabilityDashboardOptionsInputOperationOutputAlias = crate::operation::GetDeliverabilityDashboardOptions; #[doc(hidden)] pub type GetDeliverabilityDashboardOptionsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetDeliverabilityDashboardOptionsInput { /// Consumes the builder and constructs an Operation<[`GetDeliverabilityDashboardOptions`](crate::operation::GetDeliverabilityDashboardOptions)> #[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::GetDeliverabilityDashboardOptions, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetDeliverabilityDashboardOptionsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/deliverability-dashboard") .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetDeliverabilityDashboardOptionsInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetDeliverabilityDashboardOptionsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetDeliverabilityDashboardOptions::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetDeliverabilityDashboardOptions", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetDeliverabilityDashboardOptionsInput`](crate::input::GetDeliverabilityDashboardOptionsInput) pub fn builder() -> crate::input::get_deliverability_dashboard_options_input::Builder { crate::input::get_deliverability_dashboard_options_input::Builder::default() } } /// See [`GetDeliverabilityTestReportInput`](crate::input::GetDeliverabilityTestReportInput) pub mod get_deliverability_test_report_input { /// A builder for [`GetDeliverabilityTestReportInput`](crate::input::GetDeliverabilityTestReportInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) report_id: std::option::Option<std::string::String>, } impl Builder { /// <p>A unique string that identifies the predictive inbox placement test.</p> pub fn report_id(mut self, input: impl Into<std::string::String>) -> Self { self.report_id = Some(input.into()); self } /// <p>A unique string that identifies the predictive inbox placement test.</p> pub fn set_report_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.report_id = input; self } /// Consumes the builder and constructs a [`GetDeliverabilityTestReportInput`](crate::input::GetDeliverabilityTestReportInput) pub fn build( self, ) -> std::result::Result< crate::input::GetDeliverabilityTestReportInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetDeliverabilityTestReportInput { report_id: self.report_id, }) } } } #[doc(hidden)] pub type GetDeliverabilityTestReportInputOperationOutputAlias = crate::operation::GetDeliverabilityTestReport; #[doc(hidden)] pub type GetDeliverabilityTestReportInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetDeliverabilityTestReportInput { /// Consumes the builder and constructs an Operation<[`GetDeliverabilityTestReport`](crate::operation::GetDeliverabilityTestReport)> #[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::GetDeliverabilityTestReport, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetDeliverabilityTestReportInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_30 = &_input.report_id; let input_30 = input_30 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "report_id", details: "cannot be empty or unset", })?; let report_id = aws_smithy_http::label::fmt_string(input_30, false); if report_id.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "report_id", details: "cannot be empty or unset", }); } write!( output, "/v2/email/deliverability-dashboard/test-reports/{ReportId}", ReportId = report_id ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetDeliverabilityTestReportInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetDeliverabilityTestReportInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetDeliverabilityTestReport::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetDeliverabilityTestReport", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetDeliverabilityTestReportInput`](crate::input::GetDeliverabilityTestReportInput) pub fn builder() -> crate::input::get_deliverability_test_report_input::Builder { crate::input::get_deliverability_test_report_input::Builder::default() } } /// See [`GetDomainDeliverabilityCampaignInput`](crate::input::GetDomainDeliverabilityCampaignInput) pub mod get_domain_deliverability_campaign_input { /// A builder for [`GetDomainDeliverabilityCampaignInput`](crate::input::GetDomainDeliverabilityCampaignInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) campaign_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The unique identifier for the campaign. The Deliverability dashboard automatically generates /// and assigns this identifier to a campaign.</p> pub fn campaign_id(mut self, input: impl Into<std::string::String>) -> Self { self.campaign_id = Some(input.into()); self } /// <p>The unique identifier for the campaign. The Deliverability dashboard automatically generates /// and assigns this identifier to a campaign.</p> pub fn set_campaign_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.campaign_id = input; self } /// Consumes the builder and constructs a [`GetDomainDeliverabilityCampaignInput`](crate::input::GetDomainDeliverabilityCampaignInput) pub fn build( self, ) -> std::result::Result< crate::input::GetDomainDeliverabilityCampaignInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetDomainDeliverabilityCampaignInput { campaign_id: self.campaign_id, }) } } } #[doc(hidden)] pub type GetDomainDeliverabilityCampaignInputOperationOutputAlias = crate::operation::GetDomainDeliverabilityCampaign; #[doc(hidden)] pub type GetDomainDeliverabilityCampaignInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetDomainDeliverabilityCampaignInput { /// Consumes the builder and constructs an Operation<[`GetDomainDeliverabilityCampaign`](crate::operation::GetDomainDeliverabilityCampaign)> #[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::GetDomainDeliverabilityCampaign, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetDomainDeliverabilityCampaignInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_31 = &_input.campaign_id; let input_31 = input_31 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "campaign_id", details: "cannot be empty or unset", })?; let campaign_id = aws_smithy_http::label::fmt_string(input_31, false); if campaign_id.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "campaign_id", details: "cannot be empty or unset", }); } write!( output, "/v2/email/deliverability-dashboard/campaigns/{CampaignId}", CampaignId = campaign_id ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetDomainDeliverabilityCampaignInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetDomainDeliverabilityCampaignInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetDomainDeliverabilityCampaign::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetDomainDeliverabilityCampaign", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetDomainDeliverabilityCampaignInput`](crate::input::GetDomainDeliverabilityCampaignInput) pub fn builder() -> crate::input::get_domain_deliverability_campaign_input::Builder { crate::input::get_domain_deliverability_campaign_input::Builder::default() } } /// See [`GetDomainStatisticsReportInput`](crate::input::GetDomainStatisticsReportInput) pub mod get_domain_statistics_report_input { /// A builder for [`GetDomainStatisticsReportInput`](crate::input::GetDomainStatisticsReportInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain: std::option::Option<std::string::String>, pub(crate) start_date: std::option::Option<aws_smithy_types::DateTime>, pub(crate) end_date: std::option::Option<aws_smithy_types::DateTime>, } impl Builder { /// <p>The domain that you want to obtain deliverability metrics for.</p> pub fn domain(mut self, input: impl Into<std::string::String>) -> Self { self.domain = Some(input.into()); self } /// <p>The domain that you want to obtain deliverability metrics for.</p> pub fn set_domain(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain = input; self } /// <p>The first day (in Unix time) that you want to obtain domain deliverability metrics /// for.</p> pub fn start_date(mut self, input: aws_smithy_types::DateTime) -> Self { self.start_date = Some(input); self } /// <p>The first day (in Unix time) that you want to obtain domain deliverability metrics /// for.</p> pub fn set_start_date( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.start_date = input; self } /// <p>The last day (in Unix time) that you want to obtain domain deliverability metrics for. /// The <code>EndDate</code> that you specify has to be less than or equal to 30 days after /// the <code>StartDate</code>.</p> pub fn end_date(mut self, input: aws_smithy_types::DateTime) -> Self { self.end_date = Some(input); self } /// <p>The last day (in Unix time) that you want to obtain domain deliverability metrics for. /// The <code>EndDate</code> that you specify has to be less than or equal to 30 days after /// the <code>StartDate</code>.</p> pub fn set_end_date( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.end_date = input; self } /// Consumes the builder and constructs a [`GetDomainStatisticsReportInput`](crate::input::GetDomainStatisticsReportInput) pub fn build( self, ) -> std::result::Result< crate::input::GetDomainStatisticsReportInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetDomainStatisticsReportInput { domain: self.domain, start_date: self.start_date, end_date: self.end_date, }) } } } #[doc(hidden)] pub type GetDomainStatisticsReportInputOperationOutputAlias = crate::operation::GetDomainStatisticsReport; #[doc(hidden)] pub type GetDomainStatisticsReportInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetDomainStatisticsReportInput { /// Consumes the builder and constructs an Operation<[`GetDomainStatisticsReport`](crate::operation::GetDomainStatisticsReport)> #[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::GetDomainStatisticsReport, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetDomainStatisticsReportInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_32 = &_input.domain; let input_32 = input_32 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "domain", details: "cannot be empty or unset", })?; let domain = aws_smithy_http::label::fmt_string(input_32, false); if domain.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "domain", details: "cannot be empty or unset", }); } write!( output, "/v2/email/deliverability-dashboard/statistics-report/{Domain}", Domain = domain ) .expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::GetDomainStatisticsReportInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_33) = &_input.start_date { query.push_kv( "StartDate", &aws_smithy_http::query::fmt_timestamp( inner_33, aws_smithy_types::date_time::Format::DateTime, )?, ); } if let Some(inner_34) = &_input.end_date { query.push_kv( "EndDate", &aws_smithy_http::query::fmt_timestamp( inner_34, aws_smithy_types::date_time::Format::DateTime, )?, ); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetDomainStatisticsReportInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetDomainStatisticsReportInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetDomainStatisticsReport::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetDomainStatisticsReport", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetDomainStatisticsReportInput`](crate::input::GetDomainStatisticsReportInput) pub fn builder() -> crate::input::get_domain_statistics_report_input::Builder { crate::input::get_domain_statistics_report_input::Builder::default() } } /// See [`GetEmailIdentityInput`](crate::input::GetEmailIdentityInput) pub mod get_email_identity_input { /// A builder for [`GetEmailIdentityInput`](crate::input::GetEmailIdentityInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, } impl Builder { /// <p>The email identity.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The email identity.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// Consumes the builder and constructs a [`GetEmailIdentityInput`](crate::input::GetEmailIdentityInput) pub fn build( self, ) -> std::result::Result< crate::input::GetEmailIdentityInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetEmailIdentityInput { email_identity: self.email_identity, }) } } } #[doc(hidden)] pub type GetEmailIdentityInputOperationOutputAlias = crate::operation::GetEmailIdentity; #[doc(hidden)] pub type GetEmailIdentityInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetEmailIdentityInput { /// Consumes the builder and constructs an Operation<[`GetEmailIdentity`](crate::operation::GetEmailIdentity)> #[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::GetEmailIdentity, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetEmailIdentityInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_35 = &_input.email_identity; let input_35 = input_35 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", })?; let email_identity = aws_smithy_http::label::fmt_string(input_35, false); if email_identity.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", }); } write!( output, "/v2/email/identities/{EmailIdentity}", EmailIdentity = email_identity ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetEmailIdentityInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetEmailIdentityInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetEmailIdentity::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetEmailIdentity", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetEmailIdentityInput`](crate::input::GetEmailIdentityInput) pub fn builder() -> crate::input::get_email_identity_input::Builder { crate::input::get_email_identity_input::Builder::default() } } /// See [`GetEmailIdentityPoliciesInput`](crate::input::GetEmailIdentityPoliciesInput) pub mod get_email_identity_policies_input { /// A builder for [`GetEmailIdentityPoliciesInput`](crate::input::GetEmailIdentityPoliciesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, } impl Builder { /// <p>The email identity.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The email identity.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// Consumes the builder and constructs a [`GetEmailIdentityPoliciesInput`](crate::input::GetEmailIdentityPoliciesInput) pub fn build( self, ) -> std::result::Result< crate::input::GetEmailIdentityPoliciesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetEmailIdentityPoliciesInput { email_identity: self.email_identity, }) } } } #[doc(hidden)] pub type GetEmailIdentityPoliciesInputOperationOutputAlias = crate::operation::GetEmailIdentityPolicies; #[doc(hidden)] pub type GetEmailIdentityPoliciesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetEmailIdentityPoliciesInput { /// Consumes the builder and constructs an Operation<[`GetEmailIdentityPolicies`](crate::operation::GetEmailIdentityPolicies)> #[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::GetEmailIdentityPolicies, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetEmailIdentityPoliciesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_36 = &_input.email_identity; let input_36 = input_36 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", })?; let email_identity = aws_smithy_http::label::fmt_string(input_36, false); if email_identity.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", }); } write!( output, "/v2/email/identities/{EmailIdentity}/policies", EmailIdentity = email_identity ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetEmailIdentityPoliciesInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetEmailIdentityPoliciesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetEmailIdentityPolicies::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetEmailIdentityPolicies", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetEmailIdentityPoliciesInput`](crate::input::GetEmailIdentityPoliciesInput) pub fn builder() -> crate::input::get_email_identity_policies_input::Builder { crate::input::get_email_identity_policies_input::Builder::default() } } /// See [`GetEmailTemplateInput`](crate::input::GetEmailTemplateInput) pub mod get_email_template_input { /// A builder for [`GetEmailTemplateInput`](crate::input::GetEmailTemplateInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) template_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the template.</p> pub fn template_name(mut self, input: impl Into<std::string::String>) -> Self { self.template_name = Some(input.into()); self } /// <p>The name of the template.</p> pub fn set_template_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_name = input; self } /// Consumes the builder and constructs a [`GetEmailTemplateInput`](crate::input::GetEmailTemplateInput) pub fn build( self, ) -> std::result::Result< crate::input::GetEmailTemplateInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetEmailTemplateInput { template_name: self.template_name, }) } } } #[doc(hidden)] pub type GetEmailTemplateInputOperationOutputAlias = crate::operation::GetEmailTemplate; #[doc(hidden)] pub type GetEmailTemplateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetEmailTemplateInput { /// Consumes the builder and constructs an Operation<[`GetEmailTemplate`](crate::operation::GetEmailTemplate)> #[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::GetEmailTemplate, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetEmailTemplateInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_37 = &_input.template_name; let input_37 = input_37 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", })?; let template_name = aws_smithy_http::label::fmt_string(input_37, false); if template_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/templates/{TemplateName}", TemplateName = template_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetEmailTemplateInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetEmailTemplateInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetEmailTemplate::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetEmailTemplate", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetEmailTemplateInput`](crate::input::GetEmailTemplateInput) pub fn builder() -> crate::input::get_email_template_input::Builder { crate::input::get_email_template_input::Builder::default() } } /// See [`GetImportJobInput`](crate::input::GetImportJobInput) pub mod get_import_job_input { /// A builder for [`GetImportJobInput`](crate::input::GetImportJobInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) job_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The ID of the import job.</p> pub fn job_id(mut self, input: impl Into<std::string::String>) -> Self { self.job_id = Some(input.into()); self } /// <p>The ID of the import job.</p> pub fn set_job_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.job_id = input; self } /// Consumes the builder and constructs a [`GetImportJobInput`](crate::input::GetImportJobInput) pub fn build( self, ) -> std::result::Result< crate::input::GetImportJobInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetImportJobInput { job_id: self.job_id, }) } } } #[doc(hidden)] pub type GetImportJobInputOperationOutputAlias = crate::operation::GetImportJob; #[doc(hidden)] pub type GetImportJobInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetImportJobInput { /// Consumes the builder and constructs an Operation<[`GetImportJob`](crate::operation::GetImportJob)> #[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::GetImportJob, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetImportJobInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_38 = &_input.job_id; let input_38 = input_38 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "job_id", details: "cannot be empty or unset", })?; let job_id = aws_smithy_http::label::fmt_string(input_38, false); if job_id.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "job_id", details: "cannot be empty or unset", }); } write!(output, "/v2/email/import-jobs/{JobId}", JobId = job_id) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetImportJobInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetImportJobInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetImportJob::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetImportJob", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetImportJobInput`](crate::input::GetImportJobInput) pub fn builder() -> crate::input::get_import_job_input::Builder { crate::input::get_import_job_input::Builder::default() } } /// See [`GetSuppressedDestinationInput`](crate::input::GetSuppressedDestinationInput) pub mod get_suppressed_destination_input { /// A builder for [`GetSuppressedDestinationInput`](crate::input::GetSuppressedDestinationInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_address: std::option::Option<std::string::String>, } impl Builder { /// <p>The email address that's on the account suppression list.</p> pub fn email_address(mut self, input: impl Into<std::string::String>) -> Self { self.email_address = Some(input.into()); self } /// <p>The email address that's on the account suppression list.</p> pub fn set_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_address = input; self } /// Consumes the builder and constructs a [`GetSuppressedDestinationInput`](crate::input::GetSuppressedDestinationInput) pub fn build( self, ) -> std::result::Result< crate::input::GetSuppressedDestinationInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::GetSuppressedDestinationInput { email_address: self.email_address, }) } } } #[doc(hidden)] pub type GetSuppressedDestinationInputOperationOutputAlias = crate::operation::GetSuppressedDestination; #[doc(hidden)] pub type GetSuppressedDestinationInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl GetSuppressedDestinationInput { /// Consumes the builder and constructs an Operation<[`GetSuppressedDestination`](crate::operation::GetSuppressedDestination)> #[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::GetSuppressedDestination, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::GetSuppressedDestinationInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_39 = &_input.email_address; let input_39 = input_39 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_address", details: "cannot be empty or unset", })?; let email_address = aws_smithy_http::label::fmt_string(input_39, false); if email_address.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_address", details: "cannot be empty or unset", }); } write!( output, "/v2/email/suppression/addresses/{EmailAddress}", EmailAddress = email_address ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::GetSuppressedDestinationInput, 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("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::GetSuppressedDestinationInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::GetSuppressedDestination::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "GetSuppressedDestination", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`GetSuppressedDestinationInput`](crate::input::GetSuppressedDestinationInput) pub fn builder() -> crate::input::get_suppressed_destination_input::Builder { crate::input::get_suppressed_destination_input::Builder::default() } } /// See [`ListConfigurationSetsInput`](crate::input::ListConfigurationSetsInput) pub mod list_configuration_sets_input { /// A builder for [`ListConfigurationSetsInput`](crate::input::ListConfigurationSetsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) page_size: std::option::Option<i32>, } impl Builder { /// <p>A token returned from a previous call to <code>ListConfigurationSets</code> to /// indicate the position in the list of configuration sets.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A token returned from a previous call to <code>ListConfigurationSets</code> to /// indicate the position in the list of configuration sets.</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 results to show in a single call to <code>ListConfigurationSets</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>The number of results to show in a single call to <code>ListConfigurationSets</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// Consumes the builder and constructs a [`ListConfigurationSetsInput`](crate::input::ListConfigurationSetsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListConfigurationSetsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListConfigurationSetsInput { next_token: self.next_token, page_size: self.page_size, }) } } } #[doc(hidden)] pub type ListConfigurationSetsInputOperationOutputAlias = crate::operation::ListConfigurationSets; #[doc(hidden)] pub type ListConfigurationSetsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListConfigurationSetsInput { /// Consumes the builder and constructs an Operation<[`ListConfigurationSets`](crate::operation::ListConfigurationSets)> #[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::ListConfigurationSets, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListConfigurationSetsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/configuration-sets").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListConfigurationSetsInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_40) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_40)); } if let Some(inner_41) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_41).encode(), ); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListConfigurationSetsInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListConfigurationSetsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::ListConfigurationSets::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListConfigurationSets", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListConfigurationSetsInput`](crate::input::ListConfigurationSetsInput) pub fn builder() -> crate::input::list_configuration_sets_input::Builder { crate::input::list_configuration_sets_input::Builder::default() } } /// See [`ListContactListsInput`](crate::input::ListContactListsInput) pub mod list_contact_lists_input { /// A builder for [`ListContactListsInput`](crate::input::ListContactListsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) page_size: std::option::Option<i32>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p>Maximum number of contact lists to return at once. Use this parameter to paginate /// results. If additional contact lists exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// lists.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>Maximum number of contact lists to return at once. Use this parameter to paginate /// results. If additional contact lists exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// lists.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// <p>A string token indicating that there might be additional contact lists available to be /// listed. Use the token provided in the Response to use in the subsequent call to /// ListContactLists with the same parameters to retrieve the next page of contact /// lists.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A string token indicating that there might be additional contact lists available to be /// listed. Use the token provided in the Response to use in the subsequent call to /// ListContactLists with the same parameters to retrieve the next page of contact /// lists.</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 [`ListContactListsInput`](crate::input::ListContactListsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListContactListsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListContactListsInput { page_size: self.page_size, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListContactListsInputOperationOutputAlias = crate::operation::ListContactLists; #[doc(hidden)] pub type ListContactListsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListContactListsInput { /// Consumes the builder and constructs an Operation<[`ListContactLists`](crate::operation::ListContactLists)> #[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::ListContactLists, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListContactListsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/contact-lists").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListContactListsInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_42) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_42).encode(), ); } if let Some(inner_43) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_43)); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListContactListsInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListContactListsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::ListContactLists::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListContactLists", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListContactListsInput`](crate::input::ListContactListsInput) pub fn builder() -> crate::input::list_contact_lists_input::Builder { crate::input::list_contact_lists_input::Builder::default() } } /// See [`ListContactsInput`](crate::input::ListContactsInput) pub mod list_contacts_input { /// A builder for [`ListContactsInput`](crate::input::ListContactsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) contact_list_name: std::option::Option<std::string::String>, pub(crate) filter: std::option::Option<crate::model::ListContactsFilter>, pub(crate) page_size: std::option::Option<i32>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the contact list.</p> pub fn contact_list_name(mut self, input: impl Into<std::string::String>) -> Self { self.contact_list_name = Some(input.into()); self } /// <p>The name of the contact list.</p> pub fn set_contact_list_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.contact_list_name = input; self } /// <p>A filter that can be applied to a list of contacts.</p> pub fn filter(mut self, input: crate::model::ListContactsFilter) -> Self { self.filter = Some(input); self } /// <p>A filter that can be applied to a list of contacts.</p> pub fn set_filter( mut self, input: std::option::Option<crate::model::ListContactsFilter>, ) -> Self { self.filter = input; self } /// <p>The number of contacts that may be returned at once, which is dependent on if there /// are more or less contacts than the value of the PageSize. Use this parameter to /// paginate results. If additional contacts exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// contacts.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>The number of contacts that may be returned at once, which is dependent on if there /// are more or less contacts than the value of the PageSize. Use this parameter to /// paginate results. If additional contacts exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// contacts.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// <p>A string token indicating that there might be additional contacts available to be /// listed. Use the token provided in the Response to use in the subsequent call to /// ListContacts with the same parameters to retrieve the next page of contacts.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A string token indicating that there might be additional contacts available to be /// listed. Use the token provided in the Response to use in the subsequent call to /// ListContacts with the same parameters to retrieve the next page of contacts.</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 [`ListContactsInput`](crate::input::ListContactsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListContactsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListContactsInput { contact_list_name: self.contact_list_name, filter: self.filter, page_size: self.page_size, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListContactsInputOperationOutputAlias = crate::operation::ListContacts; #[doc(hidden)] pub type ListContactsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListContactsInput { /// Consumes the builder and constructs an Operation<[`ListContacts`](crate::operation::ListContacts)> #[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::ListContacts, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListContactsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_44 = &_input.contact_list_name; let input_44 = input_44 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", })?; let contact_list_name = aws_smithy_http::label::fmt_string(input_44, false); if contact_list_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/contact-lists/{ContactListName}/contacts", ContactListName = contact_list_name ) .expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListContactsInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_45) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_45).encode(), ); } if let Some(inner_46) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_46)); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListContactsInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListContactsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_list_contacts(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::ListContacts::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListContacts", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListContactsInput`](crate::input::ListContactsInput) pub fn builder() -> crate::input::list_contacts_input::Builder { crate::input::list_contacts_input::Builder::default() } } /// See [`ListCustomVerificationEmailTemplatesInput`](crate::input::ListCustomVerificationEmailTemplatesInput) pub mod list_custom_verification_email_templates_input { /// A builder for [`ListCustomVerificationEmailTemplatesInput`](crate::input::ListCustomVerificationEmailTemplatesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) page_size: std::option::Option<i32>, } impl Builder { /// <p>A token returned from a previous call to /// <code>ListCustomVerificationEmailTemplates</code> to indicate the position in the /// list of custom verification email templates.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A token returned from a previous call to /// <code>ListCustomVerificationEmailTemplates</code> to indicate the position in the /// list of custom verification email templates.</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 results to show in a single call to /// <code>ListCustomVerificationEmailTemplates</code>. If the number of results is /// larger than the number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> /// <p>The value you specify has to be at least 1, and can be no more than 50.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>The number of results to show in a single call to /// <code>ListCustomVerificationEmailTemplates</code>. If the number of results is /// larger than the number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> /// <p>The value you specify has to be at least 1, and can be no more than 50.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// Consumes the builder and constructs a [`ListCustomVerificationEmailTemplatesInput`](crate::input::ListCustomVerificationEmailTemplatesInput) pub fn build( self, ) -> std::result::Result< crate::input::ListCustomVerificationEmailTemplatesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListCustomVerificationEmailTemplatesInput { next_token: self.next_token, page_size: self.page_size, }) } } } #[doc(hidden)] pub type ListCustomVerificationEmailTemplatesInputOperationOutputAlias = crate::operation::ListCustomVerificationEmailTemplates; #[doc(hidden)] pub type ListCustomVerificationEmailTemplatesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListCustomVerificationEmailTemplatesInput { /// Consumes the builder and constructs an Operation<[`ListCustomVerificationEmailTemplates`](crate::operation::ListCustomVerificationEmailTemplates)> #[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::ListCustomVerificationEmailTemplates, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListCustomVerificationEmailTemplatesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/custom-verification-email-templates") .expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListCustomVerificationEmailTemplatesInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_47) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_47)); } if let Some(inner_48) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_48).encode(), ); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListCustomVerificationEmailTemplatesInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListCustomVerificationEmailTemplatesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::ListCustomVerificationEmailTemplates::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListCustomVerificationEmailTemplates", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListCustomVerificationEmailTemplatesInput`](crate::input::ListCustomVerificationEmailTemplatesInput) pub fn builder() -> crate::input::list_custom_verification_email_templates_input::Builder { crate::input::list_custom_verification_email_templates_input::Builder::default() } } /// See [`ListDedicatedIpPoolsInput`](crate::input::ListDedicatedIpPoolsInput) pub mod list_dedicated_ip_pools_input { /// A builder for [`ListDedicatedIpPoolsInput`](crate::input::ListDedicatedIpPoolsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) page_size: std::option::Option<i32>, } impl Builder { /// <p>A token returned from a previous call to <code>ListDedicatedIpPools</code> to indicate /// the position in the list of dedicated IP pools.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A token returned from a previous call to <code>ListDedicatedIpPools</code> to indicate /// the position in the list of dedicated IP pools.</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 results to show in a single call to <code>ListDedicatedIpPools</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>The number of results to show in a single call to <code>ListDedicatedIpPools</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// Consumes the builder and constructs a [`ListDedicatedIpPoolsInput`](crate::input::ListDedicatedIpPoolsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListDedicatedIpPoolsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListDedicatedIpPoolsInput { next_token: self.next_token, page_size: self.page_size, }) } } } #[doc(hidden)] pub type ListDedicatedIpPoolsInputOperationOutputAlias = crate::operation::ListDedicatedIpPools; #[doc(hidden)] pub type ListDedicatedIpPoolsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListDedicatedIpPoolsInput { /// Consumes the builder and constructs an Operation<[`ListDedicatedIpPools`](crate::operation::ListDedicatedIpPools)> #[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::ListDedicatedIpPools, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListDedicatedIpPoolsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/dedicated-ip-pools").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListDedicatedIpPoolsInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_49) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_49)); } if let Some(inner_50) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_50).encode(), ); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListDedicatedIpPoolsInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListDedicatedIpPoolsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::ListDedicatedIpPools::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListDedicatedIpPools", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListDedicatedIpPoolsInput`](crate::input::ListDedicatedIpPoolsInput) pub fn builder() -> crate::input::list_dedicated_ip_pools_input::Builder { crate::input::list_dedicated_ip_pools_input::Builder::default() } } /// See [`ListDeliverabilityTestReportsInput`](crate::input::ListDeliverabilityTestReportsInput) pub mod list_deliverability_test_reports_input { /// A builder for [`ListDeliverabilityTestReportsInput`](crate::input::ListDeliverabilityTestReportsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) page_size: std::option::Option<i32>, } impl Builder { /// <p>A token returned from a previous call to <code>ListDeliverabilityTestReports</code> to /// indicate the position in the list of predictive inbox placement tests.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A token returned from a previous call to <code>ListDeliverabilityTestReports</code> to /// indicate the position in the list of predictive inbox placement tests.</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 results to show in a single call to /// <code>ListDeliverabilityTestReports</code>. If the number of results is larger than /// the number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> /// <p>The value you specify has to be at least 0, and can be no more than 1000.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>The number of results to show in a single call to /// <code>ListDeliverabilityTestReports</code>. If the number of results is larger than /// the number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> /// <p>The value you specify has to be at least 0, and can be no more than 1000.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// Consumes the builder and constructs a [`ListDeliverabilityTestReportsInput`](crate::input::ListDeliverabilityTestReportsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListDeliverabilityTestReportsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListDeliverabilityTestReportsInput { next_token: self.next_token, page_size: self.page_size, }) } } } #[doc(hidden)] pub type ListDeliverabilityTestReportsInputOperationOutputAlias = crate::operation::ListDeliverabilityTestReports; #[doc(hidden)] pub type ListDeliverabilityTestReportsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListDeliverabilityTestReportsInput { /// Consumes the builder and constructs an Operation<[`ListDeliverabilityTestReports`](crate::operation::ListDeliverabilityTestReports)> #[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::ListDeliverabilityTestReports, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListDeliverabilityTestReportsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/deliverability-dashboard/test-reports") .expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListDeliverabilityTestReportsInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_51) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_51)); } if let Some(inner_52) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_52).encode(), ); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListDeliverabilityTestReportsInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListDeliverabilityTestReportsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::ListDeliverabilityTestReports::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListDeliverabilityTestReports", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListDeliverabilityTestReportsInput`](crate::input::ListDeliverabilityTestReportsInput) pub fn builder() -> crate::input::list_deliverability_test_reports_input::Builder { crate::input::list_deliverability_test_reports_input::Builder::default() } } /// See [`ListDomainDeliverabilityCampaignsInput`](crate::input::ListDomainDeliverabilityCampaignsInput) pub mod list_domain_deliverability_campaigns_input { /// A builder for [`ListDomainDeliverabilityCampaignsInput`](crate::input::ListDomainDeliverabilityCampaignsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) start_date: std::option::Option<aws_smithy_types::DateTime>, pub(crate) end_date: std::option::Option<aws_smithy_types::DateTime>, pub(crate) subscribed_domain: std::option::Option<std::string::String>, pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) page_size: std::option::Option<i32>, } impl Builder { /// <p>The first day, in Unix time format, that you want to obtain deliverability data /// for.</p> pub fn start_date(mut self, input: aws_smithy_types::DateTime) -> Self { self.start_date = Some(input); self } /// <p>The first day, in Unix time format, that you want to obtain deliverability data /// for.</p> pub fn set_start_date( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.start_date = input; self } /// <p>The last day, in Unix time format, that you want to obtain deliverability data for. /// This value has to be less than or equal to 30 days after the value of the /// <code>StartDate</code> parameter.</p> pub fn end_date(mut self, input: aws_smithy_types::DateTime) -> Self { self.end_date = Some(input); self } /// <p>The last day, in Unix time format, that you want to obtain deliverability data for. /// This value has to be less than or equal to 30 days after the value of the /// <code>StartDate</code> parameter.</p> pub fn set_end_date( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.end_date = input; self } /// <p>The domain to obtain deliverability data for.</p> pub fn subscribed_domain(mut self, input: impl Into<std::string::String>) -> Self { self.subscribed_domain = Some(input.into()); self } /// <p>The domain to obtain deliverability data for.</p> pub fn set_subscribed_domain( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.subscribed_domain = input; self } /// <p>A token that’s returned from a previous call to the /// <code>ListDomainDeliverabilityCampaigns</code> operation. This token indicates the /// position of a campaign in the list of campaigns.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A token that’s returned from a previous call to the /// <code>ListDomainDeliverabilityCampaigns</code> operation. This token indicates the /// position of a campaign in the list of campaigns.</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 results to include in response to a single call to the /// <code>ListDomainDeliverabilityCampaigns</code> operation. If the number of results /// is larger than the number that you specify in this parameter, the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>The maximum number of results to include in response to a single call to the /// <code>ListDomainDeliverabilityCampaigns</code> operation. If the number of results /// is larger than the number that you specify in this parameter, the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// Consumes the builder and constructs a [`ListDomainDeliverabilityCampaignsInput`](crate::input::ListDomainDeliverabilityCampaignsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListDomainDeliverabilityCampaignsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListDomainDeliverabilityCampaignsInput { start_date: self.start_date, end_date: self.end_date, subscribed_domain: self.subscribed_domain, next_token: self.next_token, page_size: self.page_size, }) } } } #[doc(hidden)] pub type ListDomainDeliverabilityCampaignsInputOperationOutputAlias = crate::operation::ListDomainDeliverabilityCampaigns; #[doc(hidden)] pub type ListDomainDeliverabilityCampaignsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListDomainDeliverabilityCampaignsInput { /// Consumes the builder and constructs an Operation<[`ListDomainDeliverabilityCampaigns`](crate::operation::ListDomainDeliverabilityCampaigns)> #[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::ListDomainDeliverabilityCampaigns, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListDomainDeliverabilityCampaignsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_53 = &_input.subscribed_domain; let input_53 = input_53 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "subscribed_domain", details: "cannot be empty or unset", })?; let subscribed_domain = aws_smithy_http::label::fmt_string(input_53, false); if subscribed_domain.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "subscribed_domain", details: "cannot be empty or unset", }); } write!( output, "/v2/email/deliverability-dashboard/domains/{SubscribedDomain}/campaigns", SubscribedDomain = subscribed_domain ) .expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListDomainDeliverabilityCampaignsInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_54) = &_input.start_date { query.push_kv( "StartDate", &aws_smithy_http::query::fmt_timestamp( inner_54, aws_smithy_types::date_time::Format::DateTime, )?, ); } if let Some(inner_55) = &_input.end_date { query.push_kv( "EndDate", &aws_smithy_http::query::fmt_timestamp( inner_55, aws_smithy_types::date_time::Format::DateTime, )?, ); } if let Some(inner_56) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_56)); } if let Some(inner_57) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_57).encode(), ); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListDomainDeliverabilityCampaignsInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListDomainDeliverabilityCampaignsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::ListDomainDeliverabilityCampaigns::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListDomainDeliverabilityCampaigns", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListDomainDeliverabilityCampaignsInput`](crate::input::ListDomainDeliverabilityCampaignsInput) pub fn builder() -> crate::input::list_domain_deliverability_campaigns_input::Builder { crate::input::list_domain_deliverability_campaigns_input::Builder::default() } } /// See [`ListEmailIdentitiesInput`](crate::input::ListEmailIdentitiesInput) pub mod list_email_identities_input { /// A builder for [`ListEmailIdentitiesInput`](crate::input::ListEmailIdentitiesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) page_size: std::option::Option<i32>, } impl Builder { /// <p>A token returned from a previous call to <code>ListEmailIdentities</code> to indicate /// the position in the list of identities.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A token returned from a previous call to <code>ListEmailIdentities</code> to indicate /// the position in the list of identities.</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 results to show in a single call to <code>ListEmailIdentities</code>. If /// the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> /// <p>The value you specify has to be at least 0, and can be no more than 1000.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>The number of results to show in a single call to <code>ListEmailIdentities</code>. If /// the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> /// <p>The value you specify has to be at least 0, and can be no more than 1000.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// Consumes the builder and constructs a [`ListEmailIdentitiesInput`](crate::input::ListEmailIdentitiesInput) pub fn build( self, ) -> std::result::Result< crate::input::ListEmailIdentitiesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListEmailIdentitiesInput { next_token: self.next_token, page_size: self.page_size, }) } } } #[doc(hidden)] pub type ListEmailIdentitiesInputOperationOutputAlias = crate::operation::ListEmailIdentities; #[doc(hidden)] pub type ListEmailIdentitiesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListEmailIdentitiesInput { /// Consumes the builder and constructs an Operation<[`ListEmailIdentities`](crate::operation::ListEmailIdentities)> #[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::ListEmailIdentities, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListEmailIdentitiesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/identities").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListEmailIdentitiesInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_58) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_58)); } if let Some(inner_59) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_59).encode(), ); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListEmailIdentitiesInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListEmailIdentitiesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::ListEmailIdentities::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListEmailIdentities", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListEmailIdentitiesInput`](crate::input::ListEmailIdentitiesInput) pub fn builder() -> crate::input::list_email_identities_input::Builder { crate::input::list_email_identities_input::Builder::default() } } /// See [`ListEmailTemplatesInput`](crate::input::ListEmailTemplatesInput) pub mod list_email_templates_input { /// A builder for [`ListEmailTemplatesInput`](crate::input::ListEmailTemplatesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) page_size: std::option::Option<i32>, } impl Builder { /// <p>A token returned from a previous call to <code>ListEmailTemplates</code> to indicate /// the position in the list of email templates.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A token returned from a previous call to <code>ListEmailTemplates</code> to indicate /// the position in the list of email templates.</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 results to show in a single call to <code>ListEmailTemplates</code>. If the number of /// results is larger than the number you specified in this parameter, then the response /// includes a <code>NextToken</code> element, which you can use to obtain additional results.</p> /// <p>The value you specify has to be at least 1, and can be no more than 10.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>The number of results to show in a single call to <code>ListEmailTemplates</code>. If the number of /// results is larger than the number you specified in this parameter, then the response /// includes a <code>NextToken</code> element, which you can use to obtain additional results.</p> /// <p>The value you specify has to be at least 1, and can be no more than 10.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// Consumes the builder and constructs a [`ListEmailTemplatesInput`](crate::input::ListEmailTemplatesInput) pub fn build( self, ) -> std::result::Result< crate::input::ListEmailTemplatesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListEmailTemplatesInput { next_token: self.next_token, page_size: self.page_size, }) } } } #[doc(hidden)] pub type ListEmailTemplatesInputOperationOutputAlias = crate::operation::ListEmailTemplates; #[doc(hidden)] pub type ListEmailTemplatesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListEmailTemplatesInput { /// Consumes the builder and constructs an Operation<[`ListEmailTemplates`](crate::operation::ListEmailTemplates)> #[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::ListEmailTemplates, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListEmailTemplatesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/templates").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListEmailTemplatesInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_60) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_60)); } if let Some(inner_61) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_61).encode(), ); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListEmailTemplatesInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListEmailTemplatesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::ListEmailTemplates::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListEmailTemplates", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListEmailTemplatesInput`](crate::input::ListEmailTemplatesInput) pub fn builder() -> crate::input::list_email_templates_input::Builder { crate::input::list_email_templates_input::Builder::default() } } /// See [`ListImportJobsInput`](crate::input::ListImportJobsInput) pub mod list_import_jobs_input { /// A builder for [`ListImportJobsInput`](crate::input::ListImportJobsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) import_destination_type: std::option::Option<crate::model::ImportDestinationType>, pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) page_size: std::option::Option<i32>, } impl Builder { /// <p>The destination of the import job, which can be used to list import jobs that have a /// certain <code>ImportDestinationType</code>.</p> pub fn import_destination_type( mut self, input: crate::model::ImportDestinationType, ) -> Self { self.import_destination_type = Some(input); self } /// <p>The destination of the import job, which can be used to list import jobs that have a /// certain <code>ImportDestinationType</code>.</p> pub fn set_import_destination_type( mut self, input: std::option::Option<crate::model::ImportDestinationType>, ) -> Self { self.import_destination_type = input; self } /// <p>A string token indicating that there might be additional import jobs available to be /// listed. Copy this token to a subsequent call to <code>ListImportJobs</code> with the /// same parameters to retrieve the next page of import jobs.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A string token indicating that there might be additional import jobs available to be /// listed. Copy this token to a subsequent call to <code>ListImportJobs</code> with the /// same parameters to retrieve the next page of import jobs.</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 import jobs to return at once. Use this parameter to paginate /// results. If additional import jobs exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// addresses.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>Maximum number of import jobs to return at once. Use this parameter to paginate /// results. If additional import jobs exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// addresses.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// Consumes the builder and constructs a [`ListImportJobsInput`](crate::input::ListImportJobsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListImportJobsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListImportJobsInput { import_destination_type: self.import_destination_type, next_token: self.next_token, page_size: self.page_size, }) } } } #[doc(hidden)] pub type ListImportJobsInputOperationOutputAlias = crate::operation::ListImportJobs; #[doc(hidden)] pub type ListImportJobsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListImportJobsInput { /// Consumes the builder and constructs an Operation<[`ListImportJobs`](crate::operation::ListImportJobs)> #[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::ListImportJobs, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListImportJobsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/import-jobs").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListImportJobsInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_62) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_62)); } if let Some(inner_63) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_63).encode(), ); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListImportJobsInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListImportJobsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_list_import_jobs(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::ListImportJobs::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListImportJobs", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListImportJobsInput`](crate::input::ListImportJobsInput) pub fn builder() -> crate::input::list_import_jobs_input::Builder { crate::input::list_import_jobs_input::Builder::default() } } /// See [`ListSuppressedDestinationsInput`](crate::input::ListSuppressedDestinationsInput) pub mod list_suppressed_destinations_input { /// A builder for [`ListSuppressedDestinationsInput`](crate::input::ListSuppressedDestinationsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) reasons: std::option::Option<std::vec::Vec<crate::model::SuppressionListReason>>, pub(crate) start_date: std::option::Option<aws_smithy_types::DateTime>, pub(crate) end_date: std::option::Option<aws_smithy_types::DateTime>, pub(crate) next_token: std::option::Option<std::string::String>, pub(crate) page_size: std::option::Option<i32>, } impl Builder { /// Appends an item to `reasons`. /// /// To override the contents of this collection use [`set_reasons`](Self::set_reasons). /// /// <p>The factors that caused the email address to be added to .</p> pub fn reasons(mut self, input: impl Into<crate::model::SuppressionListReason>) -> Self { let mut v = self.reasons.unwrap_or_default(); v.push(input.into()); self.reasons = Some(v); self } /// <p>The factors that caused the email address to be added to .</p> pub fn set_reasons( mut self, input: std::option::Option<std::vec::Vec<crate::model::SuppressionListReason>>, ) -> Self { self.reasons = input; self } /// <p>Used to filter the list of suppressed email destinations so that it only includes /// addresses that were added to the list after a specific date. The date that you specify /// should be in Unix time format.</p> pub fn start_date(mut self, input: aws_smithy_types::DateTime) -> Self { self.start_date = Some(input); self } /// <p>Used to filter the list of suppressed email destinations so that it only includes /// addresses that were added to the list after a specific date. The date that you specify /// should be in Unix time format.</p> pub fn set_start_date( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.start_date = input; self } /// <p>Used to filter the list of suppressed email destinations so that it only includes /// addresses that were added to the list before a specific date. The date that you specify /// should be in Unix time format.</p> pub fn end_date(mut self, input: aws_smithy_types::DateTime) -> Self { self.end_date = Some(input); self } /// <p>Used to filter the list of suppressed email destinations so that it only includes /// addresses that were added to the list before a specific date. The date that you specify /// should be in Unix time format.</p> pub fn set_end_date( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.end_date = input; self } /// <p>A token returned from a previous call to <code>ListSuppressedDestinations</code> to /// indicate the position in the list of suppressed email addresses.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>A token returned from a previous call to <code>ListSuppressedDestinations</code> to /// indicate the position in the list of suppressed email addresses.</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 results to show in a single call to /// <code>ListSuppressedDestinations</code>. If the number of results is larger than the /// number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> pub fn page_size(mut self, input: i32) -> Self { self.page_size = Some(input); self } /// <p>The number of results to show in a single call to /// <code>ListSuppressedDestinations</code>. If the number of results is larger than the /// number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> pub fn set_page_size(mut self, input: std::option::Option<i32>) -> Self { self.page_size = input; self } /// Consumes the builder and constructs a [`ListSuppressedDestinationsInput`](crate::input::ListSuppressedDestinationsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListSuppressedDestinationsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::ListSuppressedDestinationsInput { reasons: self.reasons, start_date: self.start_date, end_date: self.end_date, next_token: self.next_token, page_size: self.page_size, }) } } } #[doc(hidden)] pub type ListSuppressedDestinationsInputOperationOutputAlias = crate::operation::ListSuppressedDestinations; #[doc(hidden)] pub type ListSuppressedDestinationsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListSuppressedDestinationsInput { /// Consumes the builder and constructs an Operation<[`ListSuppressedDestinations`](crate::operation::ListSuppressedDestinations)> #[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::ListSuppressedDestinations, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListSuppressedDestinationsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/suppression/addresses").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListSuppressedDestinationsInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_64) = &_input.reasons { for inner_65 in inner_64 { query.push_kv("Reason", &aws_smithy_http::query::fmt_string(&inner_65)); } } if let Some(inner_66) = &_input.start_date { query.push_kv( "StartDate", &aws_smithy_http::query::fmt_timestamp( inner_66, aws_smithy_types::date_time::Format::DateTime, )?, ); } if let Some(inner_67) = &_input.end_date { query.push_kv( "EndDate", &aws_smithy_http::query::fmt_timestamp( inner_67, aws_smithy_types::date_time::Format::DateTime, )?, ); } if let Some(inner_68) = &_input.next_token { query.push_kv("NextToken", &aws_smithy_http::query::fmt_string(&inner_68)); } if let Some(inner_69) = &_input.page_size { query.push_kv( "PageSize", aws_smithy_types::primitive::Encoder::from(*inner_69).encode(), ); } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::ListSuppressedDestinationsInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListSuppressedDestinationsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::ListSuppressedDestinations::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "ListSuppressedDestinations", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListSuppressedDestinationsInput`](crate::input::ListSuppressedDestinationsInput) pub fn builder() -> crate::input::list_suppressed_destinations_input::Builder { crate::input::list_suppressed_destinations_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_arn: std::option::Option<std::string::String>, } impl Builder { /// <p>The Amazon Resource Name (ARN) of the resource that you want to retrieve tag /// information for.</p> pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self { self.resource_arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the resource that you want to retrieve tag /// information for.</p> pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.resource_arn = 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_arn: self.resource_arn, }) } } } #[doc(hidden)] pub type ListTagsForResourceInputOperationOutputAlias = crate::operation::ListTagsForResource; #[doc(hidden)] pub type ListTagsForResourceInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListTagsForResourceInput { /// Consumes the builder and constructs an Operation<[`ListTagsForResource`](crate::operation::ListTagsForResource)> #[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::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::ListTagsForResourceInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/tags").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::ListTagsForResourceInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_70) = &_input.resource_arn { query.push_kv( "ResourceArn", &aws_smithy_http::query::fmt_string(&inner_70), ); } 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)?; uri_query(input, &mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::ListTagsForResourceInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// 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 [`PutAccountDedicatedIpWarmupAttributesInput`](crate::input::PutAccountDedicatedIpWarmupAttributesInput) pub mod put_account_dedicated_ip_warmup_attributes_input { /// A builder for [`PutAccountDedicatedIpWarmupAttributesInput`](crate::input::PutAccountDedicatedIpWarmupAttributesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) auto_warmup_enabled: std::option::Option<bool>, } impl Builder { /// <p>Enables or disables the automatic warm-up feature for dedicated IP addresses that are /// associated with your Amazon SES account in the current Amazon Web Services Region. Set to <code>true</code> /// to enable the automatic warm-up feature, or set to <code>false</code> to disable /// it.</p> pub fn auto_warmup_enabled(mut self, input: bool) -> Self { self.auto_warmup_enabled = Some(input); self } /// <p>Enables or disables the automatic warm-up feature for dedicated IP addresses that are /// associated with your Amazon SES account in the current Amazon Web Services Region. Set to <code>true</code> /// to enable the automatic warm-up feature, or set to <code>false</code> to disable /// it.</p> pub fn set_auto_warmup_enabled(mut self, input: std::option::Option<bool>) -> Self { self.auto_warmup_enabled = input; self } /// Consumes the builder and constructs a [`PutAccountDedicatedIpWarmupAttributesInput`](crate::input::PutAccountDedicatedIpWarmupAttributesInput) pub fn build( self, ) -> std::result::Result< crate::input::PutAccountDedicatedIpWarmupAttributesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutAccountDedicatedIpWarmupAttributesInput { auto_warmup_enabled: self.auto_warmup_enabled.unwrap_or_default(), }) } } } #[doc(hidden)] pub type PutAccountDedicatedIpWarmupAttributesInputOperationOutputAlias = crate::operation::PutAccountDedicatedIpWarmupAttributes; #[doc(hidden)] pub type PutAccountDedicatedIpWarmupAttributesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutAccountDedicatedIpWarmupAttributesInput { /// Consumes the builder and constructs an Operation<[`PutAccountDedicatedIpWarmupAttributes`](crate::operation::PutAccountDedicatedIpWarmupAttributes)> #[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::PutAccountDedicatedIpWarmupAttributes, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutAccountDedicatedIpWarmupAttributesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/account/dedicated-ips/warmup") .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutAccountDedicatedIpWarmupAttributesInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutAccountDedicatedIpWarmupAttributesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_account_dedicated_ip_warmup_attributes(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutAccountDedicatedIpWarmupAttributes::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutAccountDedicatedIpWarmupAttributes", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutAccountDedicatedIpWarmupAttributesInput`](crate::input::PutAccountDedicatedIpWarmupAttributesInput) pub fn builder() -> crate::input::put_account_dedicated_ip_warmup_attributes_input::Builder { crate::input::put_account_dedicated_ip_warmup_attributes_input::Builder::default() } } /// See [`PutAccountDetailsInput`](crate::input::PutAccountDetailsInput) pub mod put_account_details_input { /// A builder for [`PutAccountDetailsInput`](crate::input::PutAccountDetailsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) mail_type: std::option::Option<crate::model::MailType>, pub(crate) website_url: std::option::Option<std::string::String>, pub(crate) contact_language: std::option::Option<crate::model::ContactLanguage>, pub(crate) use_case_description: std::option::Option<std::string::String>, pub(crate) additional_contact_email_addresses: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) production_access_enabled: std::option::Option<bool>, } impl Builder { /// <p>The type of email your account will send.</p> pub fn mail_type(mut self, input: crate::model::MailType) -> Self { self.mail_type = Some(input); self } /// <p>The type of email your account will send.</p> pub fn set_mail_type(mut self, input: std::option::Option<crate::model::MailType>) -> Self { self.mail_type = input; self } /// <p>The URL of your website. This information helps us better understand the type of /// content that you plan to send.</p> pub fn website_url(mut self, input: impl Into<std::string::String>) -> Self { self.website_url = Some(input.into()); self } /// <p>The URL of your website. This information helps us better understand the type of /// content that you plan to send.</p> pub fn set_website_url(mut self, input: std::option::Option<std::string::String>) -> Self { self.website_url = input; self } /// <p>The language you would prefer to be contacted with.</p> pub fn contact_language(mut self, input: crate::model::ContactLanguage) -> Self { self.contact_language = Some(input); self } /// <p>The language you would prefer to be contacted with.</p> pub fn set_contact_language( mut self, input: std::option::Option<crate::model::ContactLanguage>, ) -> Self { self.contact_language = input; self } /// <p>A description of the types of email that you plan to send.</p> pub fn use_case_description(mut self, input: impl Into<std::string::String>) -> Self { self.use_case_description = Some(input.into()); self } /// <p>A description of the types of email that you plan to send.</p> pub fn set_use_case_description( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.use_case_description = input; self } /// Appends an item to `additional_contact_email_addresses`. /// /// To override the contents of this collection use [`set_additional_contact_email_addresses`](Self::set_additional_contact_email_addresses). /// /// <p>Additional email addresses that you would like to be notified regarding Amazon SES /// matters.</p> pub fn additional_contact_email_addresses( mut self, input: impl Into<std::string::String>, ) -> Self { let mut v = self.additional_contact_email_addresses.unwrap_or_default(); v.push(input.into()); self.additional_contact_email_addresses = Some(v); self } /// <p>Additional email addresses that you would like to be notified regarding Amazon SES /// matters.</p> pub fn set_additional_contact_email_addresses( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.additional_contact_email_addresses = input; self } /// <p>Indicates whether or not your account should have production access in the current /// Amazon Web Services Region.</p> /// <p>If the value is <code>false</code>, then your account is in the /// <i>sandbox</i>. When your account is in the sandbox, you can only send /// email to verified identities. Additionally, the maximum number of emails you can send in /// a 24-hour period (your sending quota) is 200, and the maximum number of emails you can /// send per second (your maximum sending rate) is 1.</p> /// <p>If the value is <code>true</code>, then your account has production access. When your /// account has production access, you can send email to any address. The sending quota and /// maximum sending rate for your account vary based on your specific use case.</p> pub fn production_access_enabled(mut self, input: bool) -> Self { self.production_access_enabled = Some(input); self } /// <p>Indicates whether or not your account should have production access in the current /// Amazon Web Services Region.</p> /// <p>If the value is <code>false</code>, then your account is in the /// <i>sandbox</i>. When your account is in the sandbox, you can only send /// email to verified identities. Additionally, the maximum number of emails you can send in /// a 24-hour period (your sending quota) is 200, and the maximum number of emails you can /// send per second (your maximum sending rate) is 1.</p> /// <p>If the value is <code>true</code>, then your account has production access. When your /// account has production access, you can send email to any address. The sending quota and /// maximum sending rate for your account vary based on your specific use case.</p> pub fn set_production_access_enabled(mut self, input: std::option::Option<bool>) -> Self { self.production_access_enabled = input; self } /// Consumes the builder and constructs a [`PutAccountDetailsInput`](crate::input::PutAccountDetailsInput) pub fn build( self, ) -> std::result::Result< crate::input::PutAccountDetailsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutAccountDetailsInput { mail_type: self.mail_type, website_url: self.website_url, contact_language: self.contact_language, use_case_description: self.use_case_description, additional_contact_email_addresses: self.additional_contact_email_addresses, production_access_enabled: self.production_access_enabled, }) } } } #[doc(hidden)] pub type PutAccountDetailsInputOperationOutputAlias = crate::operation::PutAccountDetails; #[doc(hidden)] pub type PutAccountDetailsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutAccountDetailsInput { /// Consumes the builder and constructs an Operation<[`PutAccountDetails`](crate::operation::PutAccountDetails)> #[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::PutAccountDetails, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutAccountDetailsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/account/details").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutAccountDetailsInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutAccountDetailsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_account_details(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutAccountDetails::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutAccountDetails", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutAccountDetailsInput`](crate::input::PutAccountDetailsInput) pub fn builder() -> crate::input::put_account_details_input::Builder { crate::input::put_account_details_input::Builder::default() } } /// See [`PutAccountSendingAttributesInput`](crate::input::PutAccountSendingAttributesInput) pub mod put_account_sending_attributes_input { /// A builder for [`PutAccountSendingAttributesInput`](crate::input::PutAccountSendingAttributesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) sending_enabled: std::option::Option<bool>, } impl Builder { /// <p>Enables or disables your account's ability to send email. Set to <code>true</code> to /// enable email sending, or set to <code>false</code> to disable email sending.</p> /// <note> /// <p>If Amazon Web Services paused your account's ability to send email, you can't use this operation /// to resume your account's ability to send email.</p> /// </note> pub fn sending_enabled(mut self, input: bool) -> Self { self.sending_enabled = Some(input); self } /// <p>Enables or disables your account's ability to send email. Set to <code>true</code> to /// enable email sending, or set to <code>false</code> to disable email sending.</p> /// <note> /// <p>If Amazon Web Services paused your account's ability to send email, you can't use this operation /// to resume your account's ability to send email.</p> /// </note> pub fn set_sending_enabled(mut self, input: std::option::Option<bool>) -> Self { self.sending_enabled = input; self } /// Consumes the builder and constructs a [`PutAccountSendingAttributesInput`](crate::input::PutAccountSendingAttributesInput) pub fn build( self, ) -> std::result::Result< crate::input::PutAccountSendingAttributesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutAccountSendingAttributesInput { sending_enabled: self.sending_enabled.unwrap_or_default(), }) } } } #[doc(hidden)] pub type PutAccountSendingAttributesInputOperationOutputAlias = crate::operation::PutAccountSendingAttributes; #[doc(hidden)] pub type PutAccountSendingAttributesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutAccountSendingAttributesInput { /// Consumes the builder and constructs an Operation<[`PutAccountSendingAttributes`](crate::operation::PutAccountSendingAttributes)> #[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::PutAccountSendingAttributes, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutAccountSendingAttributesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/account/sending").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutAccountSendingAttributesInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutAccountSendingAttributesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_account_sending_attributes(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutAccountSendingAttributes::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutAccountSendingAttributes", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutAccountSendingAttributesInput`](crate::input::PutAccountSendingAttributesInput) pub fn builder() -> crate::input::put_account_sending_attributes_input::Builder { crate::input::put_account_sending_attributes_input::Builder::default() } } /// See [`PutAccountSuppressionAttributesInput`](crate::input::PutAccountSuppressionAttributesInput) pub mod put_account_suppression_attributes_input { /// A builder for [`PutAccountSuppressionAttributesInput`](crate::input::PutAccountSuppressionAttributesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) suppressed_reasons: std::option::Option<std::vec::Vec<crate::model::SuppressionListReason>>, } impl Builder { /// Appends an item to `suppressed_reasons`. /// /// To override the contents of this collection use [`set_suppressed_reasons`](Self::set_suppressed_reasons). /// /// <p>A list that contains the reasons that email addresses will be automatically added to /// the suppression list for your account. This list can contain any or all of the /// following:</p> /// <ul> /// <li> /// <p> /// <code>COMPLAINT</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a /// complaint.</p> /// </li> /// <li> /// <p> /// <code>BOUNCE</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a hard /// bounce.</p> /// </li> /// </ul> pub fn suppressed_reasons( mut self, input: impl Into<crate::model::SuppressionListReason>, ) -> Self { let mut v = self.suppressed_reasons.unwrap_or_default(); v.push(input.into()); self.suppressed_reasons = Some(v); self } /// <p>A list that contains the reasons that email addresses will be automatically added to /// the suppression list for your account. This list can contain any or all of the /// following:</p> /// <ul> /// <li> /// <p> /// <code>COMPLAINT</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a /// complaint.</p> /// </li> /// <li> /// <p> /// <code>BOUNCE</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a hard /// bounce.</p> /// </li> /// </ul> pub fn set_suppressed_reasons( mut self, input: std::option::Option<std::vec::Vec<crate::model::SuppressionListReason>>, ) -> Self { self.suppressed_reasons = input; self } /// Consumes the builder and constructs a [`PutAccountSuppressionAttributesInput`](crate::input::PutAccountSuppressionAttributesInput) pub fn build( self, ) -> std::result::Result< crate::input::PutAccountSuppressionAttributesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutAccountSuppressionAttributesInput { suppressed_reasons: self.suppressed_reasons, }) } } } #[doc(hidden)] pub type PutAccountSuppressionAttributesInputOperationOutputAlias = crate::operation::PutAccountSuppressionAttributes; #[doc(hidden)] pub type PutAccountSuppressionAttributesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutAccountSuppressionAttributesInput { /// Consumes the builder and constructs an Operation<[`PutAccountSuppressionAttributes`](crate::operation::PutAccountSuppressionAttributes)> #[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::PutAccountSuppressionAttributes, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutAccountSuppressionAttributesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/account/suppression").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutAccountSuppressionAttributesInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutAccountSuppressionAttributesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_account_suppression_attributes(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutAccountSuppressionAttributes::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutAccountSuppressionAttributes", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutAccountSuppressionAttributesInput`](crate::input::PutAccountSuppressionAttributesInput) pub fn builder() -> crate::input::put_account_suppression_attributes_input::Builder { crate::input::put_account_suppression_attributes_input::Builder::default() } } /// See [`PutConfigurationSetDeliveryOptionsInput`](crate::input::PutConfigurationSetDeliveryOptionsInput) pub mod put_configuration_set_delivery_options_input { /// A builder for [`PutConfigurationSetDeliveryOptionsInput`](crate::input::PutConfigurationSetDeliveryOptionsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, pub(crate) tls_policy: std::option::Option<crate::model::TlsPolicy>, pub(crate) sending_pool_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the configuration set to associate with a dedicated IP pool.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set to associate with a dedicated IP pool.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// <p>Specifies whether messages that use the configuration set are required to use /// Transport Layer Security (TLS). If the value is <code>Require</code>, messages are only /// delivered if a TLS connection can be established. If the value is <code>Optional</code>, /// messages can be delivered in plain text if a TLS connection can't be established.</p> pub fn tls_policy(mut self, input: crate::model::TlsPolicy) -> Self { self.tls_policy = Some(input); self } /// <p>Specifies whether messages that use the configuration set are required to use /// Transport Layer Security (TLS). If the value is <code>Require</code>, messages are only /// delivered if a TLS connection can be established. If the value is <code>Optional</code>, /// messages can be delivered in plain text if a TLS connection can't be established.</p> pub fn set_tls_policy( mut self, input: std::option::Option<crate::model::TlsPolicy>, ) -> Self { self.tls_policy = input; self } /// <p>The name of the dedicated IP pool to associate with the configuration set.</p> pub fn sending_pool_name(mut self, input: impl Into<std::string::String>) -> Self { self.sending_pool_name = Some(input.into()); self } /// <p>The name of the dedicated IP pool to associate with the configuration set.</p> pub fn set_sending_pool_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.sending_pool_name = input; self } /// Consumes the builder and constructs a [`PutConfigurationSetDeliveryOptionsInput`](crate::input::PutConfigurationSetDeliveryOptionsInput) pub fn build( self, ) -> std::result::Result< crate::input::PutConfigurationSetDeliveryOptionsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutConfigurationSetDeliveryOptionsInput { configuration_set_name: self.configuration_set_name, tls_policy: self.tls_policy, sending_pool_name: self.sending_pool_name, }) } } } #[doc(hidden)] pub type PutConfigurationSetDeliveryOptionsInputOperationOutputAlias = crate::operation::PutConfigurationSetDeliveryOptions; #[doc(hidden)] pub type PutConfigurationSetDeliveryOptionsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutConfigurationSetDeliveryOptionsInput { /// Consumes the builder and constructs an Operation<[`PutConfigurationSetDeliveryOptions`](crate::operation::PutConfigurationSetDeliveryOptions)> #[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::PutConfigurationSetDeliveryOptions, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutConfigurationSetDeliveryOptionsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_71 = &_input.configuration_set_name; let input_71 = input_71 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", })?; let configuration_set_name = aws_smithy_http::label::fmt_string(input_71, false); if configuration_set_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/configuration-sets/{ConfigurationSetName}/delivery-options", ConfigurationSetName = configuration_set_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutConfigurationSetDeliveryOptionsInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutConfigurationSetDeliveryOptionsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_configuration_set_delivery_options(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutConfigurationSetDeliveryOptions::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutConfigurationSetDeliveryOptions", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutConfigurationSetDeliveryOptionsInput`](crate::input::PutConfigurationSetDeliveryOptionsInput) pub fn builder() -> crate::input::put_configuration_set_delivery_options_input::Builder { crate::input::put_configuration_set_delivery_options_input::Builder::default() } } /// See [`PutConfigurationSetReputationOptionsInput`](crate::input::PutConfigurationSetReputationOptionsInput) pub mod put_configuration_set_reputation_options_input { /// A builder for [`PutConfigurationSetReputationOptionsInput`](crate::input::PutConfigurationSetReputationOptionsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, pub(crate) reputation_metrics_enabled: std::option::Option<bool>, } impl Builder { /// <p>The name of the configuration set.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// <p>If <code>true</code>, tracking of reputation metrics is enabled for the configuration /// set. If <code>false</code>, tracking of reputation metrics is disabled for the /// configuration set.</p> pub fn reputation_metrics_enabled(mut self, input: bool) -> Self { self.reputation_metrics_enabled = Some(input); self } /// <p>If <code>true</code>, tracking of reputation metrics is enabled for the configuration /// set. If <code>false</code>, tracking of reputation metrics is disabled for the /// configuration set.</p> pub fn set_reputation_metrics_enabled(mut self, input: std::option::Option<bool>) -> Self { self.reputation_metrics_enabled = input; self } /// Consumes the builder and constructs a [`PutConfigurationSetReputationOptionsInput`](crate::input::PutConfigurationSetReputationOptionsInput) pub fn build( self, ) -> std::result::Result< crate::input::PutConfigurationSetReputationOptionsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutConfigurationSetReputationOptionsInput { configuration_set_name: self.configuration_set_name, reputation_metrics_enabled: self.reputation_metrics_enabled.unwrap_or_default(), }) } } } #[doc(hidden)] pub type PutConfigurationSetReputationOptionsInputOperationOutputAlias = crate::operation::PutConfigurationSetReputationOptions; #[doc(hidden)] pub type PutConfigurationSetReputationOptionsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutConfigurationSetReputationOptionsInput { /// Consumes the builder and constructs an Operation<[`PutConfigurationSetReputationOptions`](crate::operation::PutConfigurationSetReputationOptions)> #[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::PutConfigurationSetReputationOptions, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutConfigurationSetReputationOptionsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_72 = &_input.configuration_set_name; let input_72 = input_72 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", })?; let configuration_set_name = aws_smithy_http::label::fmt_string(input_72, false); if configuration_set_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/configuration-sets/{ConfigurationSetName}/reputation-options", ConfigurationSetName = configuration_set_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutConfigurationSetReputationOptionsInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutConfigurationSetReputationOptionsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_configuration_set_reputation_options(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutConfigurationSetReputationOptions::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutConfigurationSetReputationOptions", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutConfigurationSetReputationOptionsInput`](crate::input::PutConfigurationSetReputationOptionsInput) pub fn builder() -> crate::input::put_configuration_set_reputation_options_input::Builder { crate::input::put_configuration_set_reputation_options_input::Builder::default() } } /// See [`PutConfigurationSetSendingOptionsInput`](crate::input::PutConfigurationSetSendingOptionsInput) pub mod put_configuration_set_sending_options_input { /// A builder for [`PutConfigurationSetSendingOptionsInput`](crate::input::PutConfigurationSetSendingOptionsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, pub(crate) sending_enabled: std::option::Option<bool>, } impl Builder { /// <p>The name of the configuration set to enable or disable email sending for.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set to enable or disable email sending for.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// <p>If <code>true</code>, email sending is enabled for the configuration set. If /// <code>false</code>, email sending is disabled for the configuration set.</p> pub fn sending_enabled(mut self, input: bool) -> Self { self.sending_enabled = Some(input); self } /// <p>If <code>true</code>, email sending is enabled for the configuration set. If /// <code>false</code>, email sending is disabled for the configuration set.</p> pub fn set_sending_enabled(mut self, input: std::option::Option<bool>) -> Self { self.sending_enabled = input; self } /// Consumes the builder and constructs a [`PutConfigurationSetSendingOptionsInput`](crate::input::PutConfigurationSetSendingOptionsInput) pub fn build( self, ) -> std::result::Result< crate::input::PutConfigurationSetSendingOptionsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutConfigurationSetSendingOptionsInput { configuration_set_name: self.configuration_set_name, sending_enabled: self.sending_enabled.unwrap_or_default(), }) } } } #[doc(hidden)] pub type PutConfigurationSetSendingOptionsInputOperationOutputAlias = crate::operation::PutConfigurationSetSendingOptions; #[doc(hidden)] pub type PutConfigurationSetSendingOptionsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutConfigurationSetSendingOptionsInput { /// Consumes the builder and constructs an Operation<[`PutConfigurationSetSendingOptions`](crate::operation::PutConfigurationSetSendingOptions)> #[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::PutConfigurationSetSendingOptions, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutConfigurationSetSendingOptionsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_73 = &_input.configuration_set_name; let input_73 = input_73 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", })?; let configuration_set_name = aws_smithy_http::label::fmt_string(input_73, false); if configuration_set_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/configuration-sets/{ConfigurationSetName}/sending", ConfigurationSetName = configuration_set_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutConfigurationSetSendingOptionsInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutConfigurationSetSendingOptionsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_configuration_set_sending_options(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutConfigurationSetSendingOptions::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutConfigurationSetSendingOptions", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutConfigurationSetSendingOptionsInput`](crate::input::PutConfigurationSetSendingOptionsInput) pub fn builder() -> crate::input::put_configuration_set_sending_options_input::Builder { crate::input::put_configuration_set_sending_options_input::Builder::default() } } /// See [`PutConfigurationSetSuppressionOptionsInput`](crate::input::PutConfigurationSetSuppressionOptionsInput) pub mod put_configuration_set_suppression_options_input { /// A builder for [`PutConfigurationSetSuppressionOptionsInput`](crate::input::PutConfigurationSetSuppressionOptionsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, pub(crate) suppressed_reasons: std::option::Option<std::vec::Vec<crate::model::SuppressionListReason>>, } impl Builder { /// <p>The name of the configuration set to change the suppression list preferences /// for.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set to change the suppression list preferences /// for.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// Appends an item to `suppressed_reasons`. /// /// To override the contents of this collection use [`set_suppressed_reasons`](Self::set_suppressed_reasons). /// /// <p>A list that contains the reasons that email addresses are automatically added to the /// suppression list for your account. This list can contain any or all of the /// following:</p> /// <ul> /// <li> /// <p> /// <code>COMPLAINT</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a /// complaint.</p> /// </li> /// <li> /// <p> /// <code>BOUNCE</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a hard /// bounce.</p> /// </li> /// </ul> pub fn suppressed_reasons( mut self, input: impl Into<crate::model::SuppressionListReason>, ) -> Self { let mut v = self.suppressed_reasons.unwrap_or_default(); v.push(input.into()); self.suppressed_reasons = Some(v); self } /// <p>A list that contains the reasons that email addresses are automatically added to the /// suppression list for your account. This list can contain any or all of the /// following:</p> /// <ul> /// <li> /// <p> /// <code>COMPLAINT</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a /// complaint.</p> /// </li> /// <li> /// <p> /// <code>BOUNCE</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a hard /// bounce.</p> /// </li> /// </ul> pub fn set_suppressed_reasons( mut self, input: std::option::Option<std::vec::Vec<crate::model::SuppressionListReason>>, ) -> Self { self.suppressed_reasons = input; self } /// Consumes the builder and constructs a [`PutConfigurationSetSuppressionOptionsInput`](crate::input::PutConfigurationSetSuppressionOptionsInput) pub fn build( self, ) -> std::result::Result< crate::input::PutConfigurationSetSuppressionOptionsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutConfigurationSetSuppressionOptionsInput { configuration_set_name: self.configuration_set_name, suppressed_reasons: self.suppressed_reasons, }) } } } #[doc(hidden)] pub type PutConfigurationSetSuppressionOptionsInputOperationOutputAlias = crate::operation::PutConfigurationSetSuppressionOptions; #[doc(hidden)] pub type PutConfigurationSetSuppressionOptionsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutConfigurationSetSuppressionOptionsInput { /// Consumes the builder and constructs an Operation<[`PutConfigurationSetSuppressionOptions`](crate::operation::PutConfigurationSetSuppressionOptions)> #[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::PutConfigurationSetSuppressionOptions, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutConfigurationSetSuppressionOptionsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_74 = &_input.configuration_set_name; let input_74 = input_74 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", })?; let configuration_set_name = aws_smithy_http::label::fmt_string(input_74, false); if configuration_set_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/configuration-sets/{ConfigurationSetName}/suppression-options", ConfigurationSetName = configuration_set_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutConfigurationSetSuppressionOptionsInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutConfigurationSetSuppressionOptionsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_configuration_set_suppression_options(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutConfigurationSetSuppressionOptions::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutConfigurationSetSuppressionOptions", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutConfigurationSetSuppressionOptionsInput`](crate::input::PutConfigurationSetSuppressionOptionsInput) pub fn builder() -> crate::input::put_configuration_set_suppression_options_input::Builder { crate::input::put_configuration_set_suppression_options_input::Builder::default() } } /// See [`PutConfigurationSetTrackingOptionsInput`](crate::input::PutConfigurationSetTrackingOptionsInput) pub mod put_configuration_set_tracking_options_input { /// A builder for [`PutConfigurationSetTrackingOptionsInput`](crate::input::PutConfigurationSetTrackingOptionsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, pub(crate) custom_redirect_domain: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the configuration set.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// <p>The domain to use to track open and click events.</p> pub fn custom_redirect_domain(mut self, input: impl Into<std::string::String>) -> Self { self.custom_redirect_domain = Some(input.into()); self } /// <p>The domain to use to track open and click events.</p> pub fn set_custom_redirect_domain( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.custom_redirect_domain = input; self } /// Consumes the builder and constructs a [`PutConfigurationSetTrackingOptionsInput`](crate::input::PutConfigurationSetTrackingOptionsInput) pub fn build( self, ) -> std::result::Result< crate::input::PutConfigurationSetTrackingOptionsInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutConfigurationSetTrackingOptionsInput { configuration_set_name: self.configuration_set_name, custom_redirect_domain: self.custom_redirect_domain, }) } } } #[doc(hidden)] pub type PutConfigurationSetTrackingOptionsInputOperationOutputAlias = crate::operation::PutConfigurationSetTrackingOptions; #[doc(hidden)] pub type PutConfigurationSetTrackingOptionsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutConfigurationSetTrackingOptionsInput { /// Consumes the builder and constructs an Operation<[`PutConfigurationSetTrackingOptions`](crate::operation::PutConfigurationSetTrackingOptions)> #[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::PutConfigurationSetTrackingOptions, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutConfigurationSetTrackingOptionsInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_75 = &_input.configuration_set_name; let input_75 = input_75 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", })?; let configuration_set_name = aws_smithy_http::label::fmt_string(input_75, false); if configuration_set_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/configuration-sets/{ConfigurationSetName}/tracking-options", ConfigurationSetName = configuration_set_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutConfigurationSetTrackingOptionsInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutConfigurationSetTrackingOptionsInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_configuration_set_tracking_options(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutConfigurationSetTrackingOptions::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutConfigurationSetTrackingOptions", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutConfigurationSetTrackingOptionsInput`](crate::input::PutConfigurationSetTrackingOptionsInput) pub fn builder() -> crate::input::put_configuration_set_tracking_options_input::Builder { crate::input::put_configuration_set_tracking_options_input::Builder::default() } } /// See [`PutDedicatedIpInPoolInput`](crate::input::PutDedicatedIpInPoolInput) pub mod put_dedicated_ip_in_pool_input { /// A builder for [`PutDedicatedIpInPoolInput`](crate::input::PutDedicatedIpInPoolInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) ip: std::option::Option<std::string::String>, pub(crate) destination_pool_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The IP address that you want to move to the dedicated IP pool. The value you specify /// has to be a dedicated IP address that's associated with your Amazon Web Services account.</p> pub fn ip(mut self, input: impl Into<std::string::String>) -> Self { self.ip = Some(input.into()); self } /// <p>The IP address that you want to move to the dedicated IP pool. The value you specify /// has to be a dedicated IP address that's associated with your Amazon Web Services account.</p> pub fn set_ip(mut self, input: std::option::Option<std::string::String>) -> Self { self.ip = input; self } /// <p>The name of the IP pool that you want to add the dedicated IP address to. You have to /// specify an IP pool that already exists.</p> pub fn destination_pool_name(mut self, input: impl Into<std::string::String>) -> Self { self.destination_pool_name = Some(input.into()); self } /// <p>The name of the IP pool that you want to add the dedicated IP address to. You have to /// specify an IP pool that already exists.</p> pub fn set_destination_pool_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.destination_pool_name = input; self } /// Consumes the builder and constructs a [`PutDedicatedIpInPoolInput`](crate::input::PutDedicatedIpInPoolInput) pub fn build( self, ) -> std::result::Result< crate::input::PutDedicatedIpInPoolInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutDedicatedIpInPoolInput { ip: self.ip, destination_pool_name: self.destination_pool_name, }) } } } #[doc(hidden)] pub type PutDedicatedIpInPoolInputOperationOutputAlias = crate::operation::PutDedicatedIpInPool; #[doc(hidden)] pub type PutDedicatedIpInPoolInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutDedicatedIpInPoolInput { /// Consumes the builder and constructs an Operation<[`PutDedicatedIpInPool`](crate::operation::PutDedicatedIpInPool)> #[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::PutDedicatedIpInPool, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutDedicatedIpInPoolInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_76 = &_input.ip; let input_76 = input_76 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "ip", details: "cannot be empty or unset", })?; let ip = aws_smithy_http::label::fmt_string(input_76, false); if ip.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "ip", details: "cannot be empty or unset", }); } write!(output, "/v2/email/dedicated-ips/{Ip}/pool", Ip = ip) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutDedicatedIpInPoolInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutDedicatedIpInPoolInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_dedicated_ip_in_pool( &self, )?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutDedicatedIpInPool::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutDedicatedIpInPool", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutDedicatedIpInPoolInput`](crate::input::PutDedicatedIpInPoolInput) pub fn builder() -> crate::input::put_dedicated_ip_in_pool_input::Builder { crate::input::put_dedicated_ip_in_pool_input::Builder::default() } } /// See [`PutDedicatedIpWarmupAttributesInput`](crate::input::PutDedicatedIpWarmupAttributesInput) pub mod put_dedicated_ip_warmup_attributes_input { /// A builder for [`PutDedicatedIpWarmupAttributesInput`](crate::input::PutDedicatedIpWarmupAttributesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) ip: std::option::Option<std::string::String>, pub(crate) warmup_percentage: std::option::Option<i32>, } impl Builder { /// <p>The dedicated IP address that you want to update the warm-up attributes for.</p> pub fn ip(mut self, input: impl Into<std::string::String>) -> Self { self.ip = Some(input.into()); self } /// <p>The dedicated IP address that you want to update the warm-up attributes for.</p> pub fn set_ip(mut self, input: std::option::Option<std::string::String>) -> Self { self.ip = input; self } /// <p>The warm-up percentage that you want to associate with the dedicated IP /// address.</p> pub fn warmup_percentage(mut self, input: i32) -> Self { self.warmup_percentage = Some(input); self } /// <p>The warm-up percentage that you want to associate with the dedicated IP /// address.</p> pub fn set_warmup_percentage(mut self, input: std::option::Option<i32>) -> Self { self.warmup_percentage = input; self } /// Consumes the builder and constructs a [`PutDedicatedIpWarmupAttributesInput`](crate::input::PutDedicatedIpWarmupAttributesInput) pub fn build( self, ) -> std::result::Result< crate::input::PutDedicatedIpWarmupAttributesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutDedicatedIpWarmupAttributesInput { ip: self.ip, warmup_percentage: self.warmup_percentage, }) } } } #[doc(hidden)] pub type PutDedicatedIpWarmupAttributesInputOperationOutputAlias = crate::operation::PutDedicatedIpWarmupAttributes; #[doc(hidden)] pub type PutDedicatedIpWarmupAttributesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutDedicatedIpWarmupAttributesInput { /// Consumes the builder and constructs an Operation<[`PutDedicatedIpWarmupAttributes`](crate::operation::PutDedicatedIpWarmupAttributes)> #[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::PutDedicatedIpWarmupAttributes, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutDedicatedIpWarmupAttributesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_77 = &_input.ip; let input_77 = input_77 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "ip", details: "cannot be empty or unset", })?; let ip = aws_smithy_http::label::fmt_string(input_77, false); if ip.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "ip", details: "cannot be empty or unset", }); } write!(output, "/v2/email/dedicated-ips/{Ip}/warmup", Ip = ip) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutDedicatedIpWarmupAttributesInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutDedicatedIpWarmupAttributesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_dedicated_ip_warmup_attributes(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutDedicatedIpWarmupAttributes::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutDedicatedIpWarmupAttributes", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutDedicatedIpWarmupAttributesInput`](crate::input::PutDedicatedIpWarmupAttributesInput) pub fn builder() -> crate::input::put_dedicated_ip_warmup_attributes_input::Builder { crate::input::put_dedicated_ip_warmup_attributes_input::Builder::default() } } /// See [`PutDeliverabilityDashboardOptionInput`](crate::input::PutDeliverabilityDashboardOptionInput) pub mod put_deliverability_dashboard_option_input { /// A builder for [`PutDeliverabilityDashboardOptionInput`](crate::input::PutDeliverabilityDashboardOptionInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) dashboard_enabled: std::option::Option<bool>, pub(crate) subscribed_domains: std::option::Option<std::vec::Vec<crate::model::DomainDeliverabilityTrackingOption>>, } impl Builder { /// <p>Specifies whether to enable the Deliverability dashboard. To enable the dashboard, set this /// value to <code>true</code>.</p> pub fn dashboard_enabled(mut self, input: bool) -> Self { self.dashboard_enabled = Some(input); self } /// <p>Specifies whether to enable the Deliverability dashboard. To enable the dashboard, set this /// value to <code>true</code>.</p> pub fn set_dashboard_enabled(mut self, input: std::option::Option<bool>) -> Self { self.dashboard_enabled = input; self } /// Appends an item to `subscribed_domains`. /// /// To override the contents of this collection use [`set_subscribed_domains`](Self::set_subscribed_domains). /// /// <p>An array of objects, one for each verified domain that you use to send email and /// enabled the Deliverability dashboard for.</p> pub fn subscribed_domains( mut self, input: impl Into<crate::model::DomainDeliverabilityTrackingOption>, ) -> Self { let mut v = self.subscribed_domains.unwrap_or_default(); v.push(input.into()); self.subscribed_domains = Some(v); self } /// <p>An array of objects, one for each verified domain that you use to send email and /// enabled the Deliverability dashboard for.</p> pub fn set_subscribed_domains( mut self, input: std::option::Option< std::vec::Vec<crate::model::DomainDeliverabilityTrackingOption>, >, ) -> Self { self.subscribed_domains = input; self } /// Consumes the builder and constructs a [`PutDeliverabilityDashboardOptionInput`](crate::input::PutDeliverabilityDashboardOptionInput) pub fn build( self, ) -> std::result::Result< crate::input::PutDeliverabilityDashboardOptionInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutDeliverabilityDashboardOptionInput { dashboard_enabled: self.dashboard_enabled.unwrap_or_default(), subscribed_domains: self.subscribed_domains, }) } } } #[doc(hidden)] pub type PutDeliverabilityDashboardOptionInputOperationOutputAlias = crate::operation::PutDeliverabilityDashboardOption; #[doc(hidden)] pub type PutDeliverabilityDashboardOptionInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutDeliverabilityDashboardOptionInput { /// Consumes the builder and constructs an Operation<[`PutDeliverabilityDashboardOption`](crate::operation::PutDeliverabilityDashboardOption)> #[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::PutDeliverabilityDashboardOption, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutDeliverabilityDashboardOptionInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/deliverability-dashboard") .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutDeliverabilityDashboardOptionInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutDeliverabilityDashboardOptionInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_deliverability_dashboard_option(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutDeliverabilityDashboardOption::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutDeliverabilityDashboardOption", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutDeliverabilityDashboardOptionInput`](crate::input::PutDeliverabilityDashboardOptionInput) pub fn builder() -> crate::input::put_deliverability_dashboard_option_input::Builder { crate::input::put_deliverability_dashboard_option_input::Builder::default() } } /// See [`PutEmailIdentityConfigurationSetAttributesInput`](crate::input::PutEmailIdentityConfigurationSetAttributesInput) pub mod put_email_identity_configuration_set_attributes_input { /// A builder for [`PutEmailIdentityConfigurationSetAttributesInput`](crate::input::PutEmailIdentityConfigurationSetAttributesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, pub(crate) configuration_set_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The email address or domain to associate with a configuration set.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The email address or domain to associate with a configuration set.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// <p>The configuration set to associate with an email identity.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The configuration set to associate with an email identity.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// Consumes the builder and constructs a [`PutEmailIdentityConfigurationSetAttributesInput`](crate::input::PutEmailIdentityConfigurationSetAttributesInput) pub fn build( self, ) -> std::result::Result< crate::input::PutEmailIdentityConfigurationSetAttributesInput, aws_smithy_http::operation::BuildError, > { Ok( crate::input::PutEmailIdentityConfigurationSetAttributesInput { email_identity: self.email_identity, configuration_set_name: self.configuration_set_name, }, ) } } } #[doc(hidden)] pub type PutEmailIdentityConfigurationSetAttributesInputOperationOutputAlias = crate::operation::PutEmailIdentityConfigurationSetAttributes; #[doc(hidden)] pub type PutEmailIdentityConfigurationSetAttributesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutEmailIdentityConfigurationSetAttributesInput { /// Consumes the builder and constructs an Operation<[`PutEmailIdentityConfigurationSetAttributes`](crate::operation::PutEmailIdentityConfigurationSetAttributes)> #[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::PutEmailIdentityConfigurationSetAttributes, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutEmailIdentityConfigurationSetAttributesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_78 = &_input.email_identity; let input_78 = input_78 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", })?; let email_identity = aws_smithy_http::label::fmt_string(input_78, false); if email_identity.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", }); } write!( output, "/v2/email/identities/{EmailIdentity}/configuration-set", EmailIdentity = email_identity ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutEmailIdentityConfigurationSetAttributesInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutEmailIdentityConfigurationSetAttributesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_email_identity_configuration_set_attributes(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutEmailIdentityConfigurationSetAttributes::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutEmailIdentityConfigurationSetAttributes", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutEmailIdentityConfigurationSetAttributesInput`](crate::input::PutEmailIdentityConfigurationSetAttributesInput) pub fn builder() -> crate::input::put_email_identity_configuration_set_attributes_input::Builder { crate::input::put_email_identity_configuration_set_attributes_input::Builder::default() } } /// See [`PutEmailIdentityDkimAttributesInput`](crate::input::PutEmailIdentityDkimAttributesInput) pub mod put_email_identity_dkim_attributes_input { /// A builder for [`PutEmailIdentityDkimAttributesInput`](crate::input::PutEmailIdentityDkimAttributesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, pub(crate) signing_enabled: std::option::Option<bool>, } impl Builder { /// <p>The email identity.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The email identity.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// <p>Sets the DKIM signing configuration for the identity.</p> /// <p>When you set this value <code>true</code>, then the messages that are sent from the /// identity are signed using DKIM. If you set this value to <code>false</code>, your /// messages are sent without DKIM signing.</p> pub fn signing_enabled(mut self, input: bool) -> Self { self.signing_enabled = Some(input); self } /// <p>Sets the DKIM signing configuration for the identity.</p> /// <p>When you set this value <code>true</code>, then the messages that are sent from the /// identity are signed using DKIM. If you set this value to <code>false</code>, your /// messages are sent without DKIM signing.</p> pub fn set_signing_enabled(mut self, input: std::option::Option<bool>) -> Self { self.signing_enabled = input; self } /// Consumes the builder and constructs a [`PutEmailIdentityDkimAttributesInput`](crate::input::PutEmailIdentityDkimAttributesInput) pub fn build( self, ) -> std::result::Result< crate::input::PutEmailIdentityDkimAttributesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutEmailIdentityDkimAttributesInput { email_identity: self.email_identity, signing_enabled: self.signing_enabled.unwrap_or_default(), }) } } } #[doc(hidden)] pub type PutEmailIdentityDkimAttributesInputOperationOutputAlias = crate::operation::PutEmailIdentityDkimAttributes; #[doc(hidden)] pub type PutEmailIdentityDkimAttributesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutEmailIdentityDkimAttributesInput { /// Consumes the builder and constructs an Operation<[`PutEmailIdentityDkimAttributes`](crate::operation::PutEmailIdentityDkimAttributes)> #[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::PutEmailIdentityDkimAttributes, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutEmailIdentityDkimAttributesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_79 = &_input.email_identity; let input_79 = input_79 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", })?; let email_identity = aws_smithy_http::label::fmt_string(input_79, false); if email_identity.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", }); } write!( output, "/v2/email/identities/{EmailIdentity}/dkim", EmailIdentity = email_identity ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutEmailIdentityDkimAttributesInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutEmailIdentityDkimAttributesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_email_identity_dkim_attributes(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutEmailIdentityDkimAttributes::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutEmailIdentityDkimAttributes", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutEmailIdentityDkimAttributesInput`](crate::input::PutEmailIdentityDkimAttributesInput) pub fn builder() -> crate::input::put_email_identity_dkim_attributes_input::Builder { crate::input::put_email_identity_dkim_attributes_input::Builder::default() } } /// See [`PutEmailIdentityDkimSigningAttributesInput`](crate::input::PutEmailIdentityDkimSigningAttributesInput) pub mod put_email_identity_dkim_signing_attributes_input { /// A builder for [`PutEmailIdentityDkimSigningAttributesInput`](crate::input::PutEmailIdentityDkimSigningAttributesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, pub(crate) signing_attributes_origin: std::option::Option<crate::model::DkimSigningAttributesOrigin>, pub(crate) signing_attributes: std::option::Option<crate::model::DkimSigningAttributes>, } impl Builder { /// <p>The email identity.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The email identity.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// <p>The method to use to configure DKIM for the identity. There are the following possible /// values:</p> /// <ul> /// <li> /// <p> /// <code>AWS_SES</code> – Configure DKIM for the identity by using <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy /// DKIM</a>.</p> /// </li> /// <li> /// <p> /// <code>EXTERNAL</code> – Configure DKIM for the identity by using Bring /// Your Own DKIM (BYODKIM).</p> /// </li> /// </ul> pub fn signing_attributes_origin( mut self, input: crate::model::DkimSigningAttributesOrigin, ) -> Self { self.signing_attributes_origin = Some(input); self } /// <p>The method to use to configure DKIM for the identity. There are the following possible /// values:</p> /// <ul> /// <li> /// <p> /// <code>AWS_SES</code> – Configure DKIM for the identity by using <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy /// DKIM</a>.</p> /// </li> /// <li> /// <p> /// <code>EXTERNAL</code> – Configure DKIM for the identity by using Bring /// Your Own DKIM (BYODKIM).</p> /// </li> /// </ul> pub fn set_signing_attributes_origin( mut self, input: std::option::Option<crate::model::DkimSigningAttributesOrigin>, ) -> Self { self.signing_attributes_origin = input; self } /// <p>An object that contains information about the private key and selector that you want /// to use to configure DKIM for the identity for Bring Your Own DKIM (BYODKIM) for the identity, or, /// configures the key length to be used for /// <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy DKIM</a>.</p> pub fn signing_attributes(mut self, input: crate::model::DkimSigningAttributes) -> Self { self.signing_attributes = Some(input); self } /// <p>An object that contains information about the private key and selector that you want /// to use to configure DKIM for the identity for Bring Your Own DKIM (BYODKIM) for the identity, or, /// configures the key length to be used for /// <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy DKIM</a>.</p> pub fn set_signing_attributes( mut self, input: std::option::Option<crate::model::DkimSigningAttributes>, ) -> Self { self.signing_attributes = input; self } /// Consumes the builder and constructs a [`PutEmailIdentityDkimSigningAttributesInput`](crate::input::PutEmailIdentityDkimSigningAttributesInput) pub fn build( self, ) -> std::result::Result< crate::input::PutEmailIdentityDkimSigningAttributesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutEmailIdentityDkimSigningAttributesInput { email_identity: self.email_identity, signing_attributes_origin: self.signing_attributes_origin, signing_attributes: self.signing_attributes, }) } } } #[doc(hidden)] pub type PutEmailIdentityDkimSigningAttributesInputOperationOutputAlias = crate::operation::PutEmailIdentityDkimSigningAttributes; #[doc(hidden)] pub type PutEmailIdentityDkimSigningAttributesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutEmailIdentityDkimSigningAttributesInput { /// Consumes the builder and constructs an Operation<[`PutEmailIdentityDkimSigningAttributes`](crate::operation::PutEmailIdentityDkimSigningAttributes)> #[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::PutEmailIdentityDkimSigningAttributes, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutEmailIdentityDkimSigningAttributesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_80 = &_input.email_identity; let input_80 = input_80 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", })?; let email_identity = aws_smithy_http::label::fmt_string(input_80, false); if email_identity.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", }); } write!( output, "/v1/email/identities/{EmailIdentity}/dkim/signing", EmailIdentity = email_identity ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutEmailIdentityDkimSigningAttributesInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutEmailIdentityDkimSigningAttributesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_email_identity_dkim_signing_attributes(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutEmailIdentityDkimSigningAttributes::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutEmailIdentityDkimSigningAttributes", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutEmailIdentityDkimSigningAttributesInput`](crate::input::PutEmailIdentityDkimSigningAttributesInput) pub fn builder() -> crate::input::put_email_identity_dkim_signing_attributes_input::Builder { crate::input::put_email_identity_dkim_signing_attributes_input::Builder::default() } } /// See [`PutEmailIdentityFeedbackAttributesInput`](crate::input::PutEmailIdentityFeedbackAttributesInput) pub mod put_email_identity_feedback_attributes_input { /// A builder for [`PutEmailIdentityFeedbackAttributesInput`](crate::input::PutEmailIdentityFeedbackAttributesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, pub(crate) email_forwarding_enabled: std::option::Option<bool>, } impl Builder { /// <p>The email identity.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The email identity.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// <p>Sets the feedback forwarding configuration for the identity.</p> /// <p>If the value is <code>true</code>, you receive email notifications when bounce or /// complaint events occur. These notifications are sent to the address that you specified /// in the <code>Return-Path</code> header of the original email.</p> /// <p>You're required to have a method of tracking bounces and complaints. If you haven't /// set up another mechanism for receiving bounce or complaint notifications (for example, /// by setting up an event destination), you receive an email notification when these events /// occur (even if this setting is disabled).</p> pub fn email_forwarding_enabled(mut self, input: bool) -> Self { self.email_forwarding_enabled = Some(input); self } /// <p>Sets the feedback forwarding configuration for the identity.</p> /// <p>If the value is <code>true</code>, you receive email notifications when bounce or /// complaint events occur. These notifications are sent to the address that you specified /// in the <code>Return-Path</code> header of the original email.</p> /// <p>You're required to have a method of tracking bounces and complaints. If you haven't /// set up another mechanism for receiving bounce or complaint notifications (for example, /// by setting up an event destination), you receive an email notification when these events /// occur (even if this setting is disabled).</p> pub fn set_email_forwarding_enabled(mut self, input: std::option::Option<bool>) -> Self { self.email_forwarding_enabled = input; self } /// Consumes the builder and constructs a [`PutEmailIdentityFeedbackAttributesInput`](crate::input::PutEmailIdentityFeedbackAttributesInput) pub fn build( self, ) -> std::result::Result< crate::input::PutEmailIdentityFeedbackAttributesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutEmailIdentityFeedbackAttributesInput { email_identity: self.email_identity, email_forwarding_enabled: self.email_forwarding_enabled.unwrap_or_default(), }) } } } #[doc(hidden)] pub type PutEmailIdentityFeedbackAttributesInputOperationOutputAlias = crate::operation::PutEmailIdentityFeedbackAttributes; #[doc(hidden)] pub type PutEmailIdentityFeedbackAttributesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutEmailIdentityFeedbackAttributesInput { /// Consumes the builder and constructs an Operation<[`PutEmailIdentityFeedbackAttributes`](crate::operation::PutEmailIdentityFeedbackAttributes)> #[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::PutEmailIdentityFeedbackAttributes, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutEmailIdentityFeedbackAttributesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_81 = &_input.email_identity; let input_81 = input_81 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", })?; let email_identity = aws_smithy_http::label::fmt_string(input_81, false); if email_identity.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", }); } write!( output, "/v2/email/identities/{EmailIdentity}/feedback", EmailIdentity = email_identity ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutEmailIdentityFeedbackAttributesInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutEmailIdentityFeedbackAttributesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_email_identity_feedback_attributes(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutEmailIdentityFeedbackAttributes::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutEmailIdentityFeedbackAttributes", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutEmailIdentityFeedbackAttributesInput`](crate::input::PutEmailIdentityFeedbackAttributesInput) pub fn builder() -> crate::input::put_email_identity_feedback_attributes_input::Builder { crate::input::put_email_identity_feedback_attributes_input::Builder::default() } } /// See [`PutEmailIdentityMailFromAttributesInput`](crate::input::PutEmailIdentityMailFromAttributesInput) pub mod put_email_identity_mail_from_attributes_input { /// A builder for [`PutEmailIdentityMailFromAttributesInput`](crate::input::PutEmailIdentityMailFromAttributesInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, pub(crate) mail_from_domain: std::option::Option<std::string::String>, pub(crate) behavior_on_mx_failure: std::option::Option<crate::model::BehaviorOnMxFailure>, } impl Builder { /// <p>The verified email identity.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The verified email identity.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// <p> The custom MAIL FROM domain that you want the verified identity to use. The MAIL FROM /// domain must meet the following criteria:</p> /// <ul> /// <li> /// <p>It has to be a subdomain of the verified identity.</p> /// </li> /// <li> /// <p>It can't be used to receive email.</p> /// </li> /// <li> /// <p>It can't be used in a "From" address if the MAIL FROM domain is a destination /// for feedback forwarding emails.</p> /// </li> /// </ul> pub fn mail_from_domain(mut self, input: impl Into<std::string::String>) -> Self { self.mail_from_domain = Some(input.into()); self } /// <p> The custom MAIL FROM domain that you want the verified identity to use. The MAIL FROM /// domain must meet the following criteria:</p> /// <ul> /// <li> /// <p>It has to be a subdomain of the verified identity.</p> /// </li> /// <li> /// <p>It can't be used to receive email.</p> /// </li> /// <li> /// <p>It can't be used in a "From" address if the MAIL FROM domain is a destination /// for feedback forwarding emails.</p> /// </li> /// </ul> pub fn set_mail_from_domain( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.mail_from_domain = input; self } /// <p>The action to take if the required MX record isn't found when you send an email. When /// you set this value to <code>UseDefaultValue</code>, the mail is sent using /// <i>amazonses.com</i> as the MAIL FROM domain. When you set this value /// to <code>RejectMessage</code>, the Amazon SES API v2 returns a /// <code>MailFromDomainNotVerified</code> error, and doesn't attempt to deliver the /// email.</p> /// <p>These behaviors are taken when the custom MAIL FROM domain configuration is in the /// <code>Pending</code>, <code>Failed</code>, and <code>TemporaryFailure</code> /// states.</p> pub fn behavior_on_mx_failure(mut self, input: crate::model::BehaviorOnMxFailure) -> Self { self.behavior_on_mx_failure = Some(input); self } /// <p>The action to take if the required MX record isn't found when you send an email. When /// you set this value to <code>UseDefaultValue</code>, the mail is sent using /// <i>amazonses.com</i> as the MAIL FROM domain. When you set this value /// to <code>RejectMessage</code>, the Amazon SES API v2 returns a /// <code>MailFromDomainNotVerified</code> error, and doesn't attempt to deliver the /// email.</p> /// <p>These behaviors are taken when the custom MAIL FROM domain configuration is in the /// <code>Pending</code>, <code>Failed</code>, and <code>TemporaryFailure</code> /// states.</p> pub fn set_behavior_on_mx_failure( mut self, input: std::option::Option<crate::model::BehaviorOnMxFailure>, ) -> Self { self.behavior_on_mx_failure = input; self } /// Consumes the builder and constructs a [`PutEmailIdentityMailFromAttributesInput`](crate::input::PutEmailIdentityMailFromAttributesInput) pub fn build( self, ) -> std::result::Result< crate::input::PutEmailIdentityMailFromAttributesInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutEmailIdentityMailFromAttributesInput { email_identity: self.email_identity, mail_from_domain: self.mail_from_domain, behavior_on_mx_failure: self.behavior_on_mx_failure, }) } } } #[doc(hidden)] pub type PutEmailIdentityMailFromAttributesInputOperationOutputAlias = crate::operation::PutEmailIdentityMailFromAttributes; #[doc(hidden)] pub type PutEmailIdentityMailFromAttributesInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutEmailIdentityMailFromAttributesInput { /// Consumes the builder and constructs an Operation<[`PutEmailIdentityMailFromAttributes`](crate::operation::PutEmailIdentityMailFromAttributes)> #[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::PutEmailIdentityMailFromAttributes, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutEmailIdentityMailFromAttributesInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_82 = &_input.email_identity; let input_82 = input_82 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", })?; let email_identity = aws_smithy_http::label::fmt_string(input_82, false); if email_identity.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", }); } write!( output, "/v2/email/identities/{EmailIdentity}/mail-from", EmailIdentity = email_identity ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutEmailIdentityMailFromAttributesInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutEmailIdentityMailFromAttributesInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_email_identity_mail_from_attributes(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutEmailIdentityMailFromAttributes::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutEmailIdentityMailFromAttributes", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutEmailIdentityMailFromAttributesInput`](crate::input::PutEmailIdentityMailFromAttributesInput) pub fn builder() -> crate::input::put_email_identity_mail_from_attributes_input::Builder { crate::input::put_email_identity_mail_from_attributes_input::Builder::default() } } /// See [`PutSuppressedDestinationInput`](crate::input::PutSuppressedDestinationInput) pub mod put_suppressed_destination_input { /// A builder for [`PutSuppressedDestinationInput`](crate::input::PutSuppressedDestinationInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_address: std::option::Option<std::string::String>, pub(crate) reason: std::option::Option<crate::model::SuppressionListReason>, } impl Builder { /// <p>The email address that should be added to the suppression list for your /// account.</p> pub fn email_address(mut self, input: impl Into<std::string::String>) -> Self { self.email_address = Some(input.into()); self } /// <p>The email address that should be added to the suppression list for your /// account.</p> pub fn set_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_address = input; self } /// <p>The factors that should cause the email address to be added to the suppression list /// for your account.</p> pub fn reason(mut self, input: crate::model::SuppressionListReason) -> Self { self.reason = Some(input); self } /// <p>The factors that should cause the email address to be added to the suppression list /// for your account.</p> pub fn set_reason( mut self, input: std::option::Option<crate::model::SuppressionListReason>, ) -> Self { self.reason = input; self } /// Consumes the builder and constructs a [`PutSuppressedDestinationInput`](crate::input::PutSuppressedDestinationInput) pub fn build( self, ) -> std::result::Result< crate::input::PutSuppressedDestinationInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::PutSuppressedDestinationInput { email_address: self.email_address, reason: self.reason, }) } } } #[doc(hidden)] pub type PutSuppressedDestinationInputOperationOutputAlias = crate::operation::PutSuppressedDestination; #[doc(hidden)] pub type PutSuppressedDestinationInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl PutSuppressedDestinationInput { /// Consumes the builder and constructs an Operation<[`PutSuppressedDestination`](crate::operation::PutSuppressedDestination)> #[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::PutSuppressedDestination, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::PutSuppressedDestinationInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/suppression/addresses").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::PutSuppressedDestinationInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::PutSuppressedDestinationInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_put_suppressed_destination( &self, )?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::PutSuppressedDestination::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "PutSuppressedDestination", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`PutSuppressedDestinationInput`](crate::input::PutSuppressedDestinationInput) pub fn builder() -> crate::input::put_suppressed_destination_input::Builder { crate::input::put_suppressed_destination_input::Builder::default() } } /// See [`SendBulkEmailInput`](crate::input::SendBulkEmailInput) pub mod send_bulk_email_input { /// A builder for [`SendBulkEmailInput`](crate::input::SendBulkEmailInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) from_email_address: std::option::Option<std::string::String>, pub(crate) from_email_address_identity_arn: std::option::Option<std::string::String>, pub(crate) reply_to_addresses: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) feedback_forwarding_email_address: std::option::Option<std::string::String>, pub(crate) feedback_forwarding_email_address_identity_arn: std::option::Option<std::string::String>, pub(crate) default_email_tags: std::option::Option<std::vec::Vec<crate::model::MessageTag>>, pub(crate) default_content: std::option::Option<crate::model::BulkEmailContent>, pub(crate) bulk_email_entries: std::option::Option<std::vec::Vec<crate::model::BulkEmailEntry>>, pub(crate) configuration_set_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The email address to use as the "From" address for the email. The /// address that you specify has to be verified.</p> pub fn from_email_address(mut self, input: impl Into<std::string::String>) -> Self { self.from_email_address = Some(input.into()); self } /// <p>The email address to use as the "From" address for the email. The /// address that you specify has to be verified.</p> pub fn set_from_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.from_email_address = input; self } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FromEmailAddress</code> parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FromEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FromEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub fn from_email_address_identity_arn( mut self, input: impl Into<std::string::String>, ) -> Self { self.from_email_address_identity_arn = Some(input.into()); self } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FromEmailAddress</code> parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FromEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FromEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub fn set_from_email_address_identity_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.from_email_address_identity_arn = input; self } /// Appends an item to `reply_to_addresses`. /// /// To override the contents of this collection use [`set_reply_to_addresses`](Self::set_reply_to_addresses). /// /// <p>The "Reply-to" email addresses for the message. When the recipient replies to the /// message, each Reply-to address receives the reply.</p> pub fn reply_to_addresses(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.reply_to_addresses.unwrap_or_default(); v.push(input.into()); self.reply_to_addresses = Some(v); self } /// <p>The "Reply-to" email addresses for the message. When the recipient replies to the /// message, each Reply-to address receives the reply.</p> pub fn set_reply_to_addresses( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.reply_to_addresses = input; self } /// <p>The address that you want bounce and complaint notifications to be sent to.</p> pub fn feedback_forwarding_email_address( mut self, input: impl Into<std::string::String>, ) -> Self { self.feedback_forwarding_email_address = Some(input.into()); self } /// <p>The address that you want bounce and complaint notifications to be sent to.</p> pub fn set_feedback_forwarding_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.feedback_forwarding_email_address = input; self } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FeedbackForwardingEmailAddress</code> /// parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FeedbackForwardingEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FeedbackForwardingEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub fn feedback_forwarding_email_address_identity_arn( mut self, input: impl Into<std::string::String>, ) -> Self { self.feedback_forwarding_email_address_identity_arn = Some(input.into()); self } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FeedbackForwardingEmailAddress</code> /// parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FeedbackForwardingEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FeedbackForwardingEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub fn set_feedback_forwarding_email_address_identity_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.feedback_forwarding_email_address_identity_arn = input; self } /// Appends an item to `default_email_tags`. /// /// To override the contents of this collection use [`set_default_email_tags`](Self::set_default_email_tags). /// /// <p>A list of tags, in the form of name/value pairs, to apply to an email that you send /// using the <code>SendEmail</code> operation. Tags correspond to characteristics of the /// email that you define, so that you can publish email sending events.</p> pub fn default_email_tags(mut self, input: impl Into<crate::model::MessageTag>) -> Self { let mut v = self.default_email_tags.unwrap_or_default(); v.push(input.into()); self.default_email_tags = Some(v); self } /// <p>A list of tags, in the form of name/value pairs, to apply to an email that you send /// using the <code>SendEmail</code> operation. Tags correspond to characteristics of the /// email that you define, so that you can publish email sending events.</p> pub fn set_default_email_tags( mut self, input: std::option::Option<std::vec::Vec<crate::model::MessageTag>>, ) -> Self { self.default_email_tags = input; self } /// <p>An object that contains the body of the message. You can specify a template /// message.</p> pub fn default_content(mut self, input: crate::model::BulkEmailContent) -> Self { self.default_content = Some(input); self } /// <p>An object that contains the body of the message. You can specify a template /// message.</p> pub fn set_default_content( mut self, input: std::option::Option<crate::model::BulkEmailContent>, ) -> Self { self.default_content = input; self } /// Appends an item to `bulk_email_entries`. /// /// To override the contents of this collection use [`set_bulk_email_entries`](Self::set_bulk_email_entries). /// /// <p>The list of bulk email entry objects.</p> pub fn bulk_email_entries( mut self, input: impl Into<crate::model::BulkEmailEntry>, ) -> Self { let mut v = self.bulk_email_entries.unwrap_or_default(); v.push(input.into()); self.bulk_email_entries = Some(v); self } /// <p>The list of bulk email entry objects.</p> pub fn set_bulk_email_entries( mut self, input: std::option::Option<std::vec::Vec<crate::model::BulkEmailEntry>>, ) -> Self { self.bulk_email_entries = input; self } /// <p>The name of the configuration set to use when sending the email.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set to use when sending the email.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// Consumes the builder and constructs a [`SendBulkEmailInput`](crate::input::SendBulkEmailInput) pub fn build( self, ) -> std::result::Result< crate::input::SendBulkEmailInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::SendBulkEmailInput { from_email_address: self.from_email_address, from_email_address_identity_arn: self.from_email_address_identity_arn, reply_to_addresses: self.reply_to_addresses, feedback_forwarding_email_address: self.feedback_forwarding_email_address, feedback_forwarding_email_address_identity_arn: self .feedback_forwarding_email_address_identity_arn, default_email_tags: self.default_email_tags, default_content: self.default_content, bulk_email_entries: self.bulk_email_entries, configuration_set_name: self.configuration_set_name, }) } } } #[doc(hidden)] pub type SendBulkEmailInputOperationOutputAlias = crate::operation::SendBulkEmail; #[doc(hidden)] pub type SendBulkEmailInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl SendBulkEmailInput { /// Consumes the builder and constructs an Operation<[`SendBulkEmail`](crate::operation::SendBulkEmail)> #[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::SendBulkEmail, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::SendBulkEmailInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/outbound-bulk-emails").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::SendBulkEmailInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::SendBulkEmailInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_send_bulk_email(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::SendBulkEmail::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "SendBulkEmail", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`SendBulkEmailInput`](crate::input::SendBulkEmailInput) pub fn builder() -> crate::input::send_bulk_email_input::Builder { crate::input::send_bulk_email_input::Builder::default() } } /// See [`SendCustomVerificationEmailInput`](crate::input::SendCustomVerificationEmailInput) pub mod send_custom_verification_email_input { /// A builder for [`SendCustomVerificationEmailInput`](crate::input::SendCustomVerificationEmailInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_address: std::option::Option<std::string::String>, pub(crate) template_name: std::option::Option<std::string::String>, pub(crate) configuration_set_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The email address to verify.</p> pub fn email_address(mut self, input: impl Into<std::string::String>) -> Self { self.email_address = Some(input.into()); self } /// <p>The email address to verify.</p> pub fn set_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_address = input; self } /// <p>The name of the custom verification email template to use when sending the /// verification email.</p> pub fn template_name(mut self, input: impl Into<std::string::String>) -> Self { self.template_name = Some(input.into()); self } /// <p>The name of the custom verification email template to use when sending the /// verification email.</p> pub fn set_template_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_name = input; self } /// <p>Name of a configuration set to use when sending the verification email.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>Name of a configuration set to use when sending the verification email.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// Consumes the builder and constructs a [`SendCustomVerificationEmailInput`](crate::input::SendCustomVerificationEmailInput) pub fn build( self, ) -> std::result::Result< crate::input::SendCustomVerificationEmailInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::SendCustomVerificationEmailInput { email_address: self.email_address, template_name: self.template_name, configuration_set_name: self.configuration_set_name, }) } } } #[doc(hidden)] pub type SendCustomVerificationEmailInputOperationOutputAlias = crate::operation::SendCustomVerificationEmail; #[doc(hidden)] pub type SendCustomVerificationEmailInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl SendCustomVerificationEmailInput { /// Consumes the builder and constructs an Operation<[`SendCustomVerificationEmail`](crate::operation::SendCustomVerificationEmail)> #[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::SendCustomVerificationEmail, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::SendCustomVerificationEmailInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/outbound-custom-verification-emails") .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::SendCustomVerificationEmailInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::SendCustomVerificationEmailInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_send_custom_verification_email(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::SendCustomVerificationEmail::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "SendCustomVerificationEmail", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`SendCustomVerificationEmailInput`](crate::input::SendCustomVerificationEmailInput) pub fn builder() -> crate::input::send_custom_verification_email_input::Builder { crate::input::send_custom_verification_email_input::Builder::default() } } /// See [`SendEmailInput`](crate::input::SendEmailInput) pub mod send_email_input { /// A builder for [`SendEmailInput`](crate::input::SendEmailInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) from_email_address: std::option::Option<std::string::String>, pub(crate) from_email_address_identity_arn: std::option::Option<std::string::String>, pub(crate) destination: std::option::Option<crate::model::Destination>, pub(crate) reply_to_addresses: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) feedback_forwarding_email_address: std::option::Option<std::string::String>, pub(crate) feedback_forwarding_email_address_identity_arn: std::option::Option<std::string::String>, pub(crate) content: std::option::Option<crate::model::EmailContent>, pub(crate) email_tags: std::option::Option<std::vec::Vec<crate::model::MessageTag>>, pub(crate) configuration_set_name: std::option::Option<std::string::String>, pub(crate) list_management_options: std::option::Option<crate::model::ListManagementOptions>, } impl Builder { /// <p>The email address to use as the "From" address for the email. The /// address that you specify has to be verified. /// </p> pub fn from_email_address(mut self, input: impl Into<std::string::String>) -> Self { self.from_email_address = Some(input.into()); self } /// <p>The email address to use as the "From" address for the email. The /// address that you specify has to be verified. /// </p> pub fn set_from_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.from_email_address = input; self } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FromEmailAddress</code> parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FromEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FromEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> /// <p>For Raw emails, the <code>FromEmailAddressIdentityArn</code> value overrides the /// X-SES-SOURCE-ARN and X-SES-FROM-ARN headers specified in raw email message /// content.</p> pub fn from_email_address_identity_arn( mut self, input: impl Into<std::string::String>, ) -> Self { self.from_email_address_identity_arn = Some(input.into()); self } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FromEmailAddress</code> parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FromEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FromEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> /// <p>For Raw emails, the <code>FromEmailAddressIdentityArn</code> value overrides the /// X-SES-SOURCE-ARN and X-SES-FROM-ARN headers specified in raw email message /// content.</p> pub fn set_from_email_address_identity_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.from_email_address_identity_arn = input; self } /// <p>An object that contains the recipients of the email message.</p> pub fn destination(mut self, input: crate::model::Destination) -> Self { self.destination = Some(input); self } /// <p>An object that contains the recipients of the email message.</p> pub fn set_destination( mut self, input: std::option::Option<crate::model::Destination>, ) -> Self { self.destination = input; self } /// Appends an item to `reply_to_addresses`. /// /// To override the contents of this collection use [`set_reply_to_addresses`](Self::set_reply_to_addresses). /// /// <p>The "Reply-to" email addresses for the message. When the recipient replies to the /// message, each Reply-to address receives the reply.</p> pub fn reply_to_addresses(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.reply_to_addresses.unwrap_or_default(); v.push(input.into()); self.reply_to_addresses = Some(v); self } /// <p>The "Reply-to" email addresses for the message. When the recipient replies to the /// message, each Reply-to address receives the reply.</p> pub fn set_reply_to_addresses( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.reply_to_addresses = input; self } /// <p>The address that you want bounce and complaint notifications to be sent to.</p> pub fn feedback_forwarding_email_address( mut self, input: impl Into<std::string::String>, ) -> Self { self.feedback_forwarding_email_address = Some(input.into()); self } /// <p>The address that you want bounce and complaint notifications to be sent to.</p> pub fn set_feedback_forwarding_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.feedback_forwarding_email_address = input; self } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FeedbackForwardingEmailAddress</code> /// parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FeedbackForwardingEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FeedbackForwardingEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub fn feedback_forwarding_email_address_identity_arn( mut self, input: impl Into<std::string::String>, ) -> Self { self.feedback_forwarding_email_address_identity_arn = Some(input.into()); self } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FeedbackForwardingEmailAddress</code> /// parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FeedbackForwardingEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FeedbackForwardingEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub fn set_feedback_forwarding_email_address_identity_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.feedback_forwarding_email_address_identity_arn = input; self } /// <p>An object that contains the body of the message. You can send either a Simple message /// Raw message or a template Message.</p> pub fn content(mut self, input: crate::model::EmailContent) -> Self { self.content = Some(input); self } /// <p>An object that contains the body of the message. You can send either a Simple message /// Raw message or a template Message.</p> pub fn set_content( mut self, input: std::option::Option<crate::model::EmailContent>, ) -> Self { self.content = input; self } /// Appends an item to `email_tags`. /// /// To override the contents of this collection use [`set_email_tags`](Self::set_email_tags). /// /// <p>A list of tags, in the form of name/value pairs, to apply to an email that you send /// using the <code>SendEmail</code> operation. Tags correspond to characteristics of the /// email that you define, so that you can publish email sending events. </p> pub fn email_tags(mut self, input: impl Into<crate::model::MessageTag>) -> Self { let mut v = self.email_tags.unwrap_or_default(); v.push(input.into()); self.email_tags = Some(v); self } /// <p>A list of tags, in the form of name/value pairs, to apply to an email that you send /// using the <code>SendEmail</code> operation. Tags correspond to characteristics of the /// email that you define, so that you can publish email sending events. </p> pub fn set_email_tags( mut self, input: std::option::Option<std::vec::Vec<crate::model::MessageTag>>, ) -> Self { self.email_tags = input; self } /// <p>The name of the configuration set to use when sending the email.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set to use when sending the email.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// <p>An object used to specify a list or topic to which an email belongs, which will be /// used when a contact chooses to unsubscribe.</p> pub fn list_management_options( mut self, input: crate::model::ListManagementOptions, ) -> Self { self.list_management_options = Some(input); self } /// <p>An object used to specify a list or topic to which an email belongs, which will be /// used when a contact chooses to unsubscribe.</p> pub fn set_list_management_options( mut self, input: std::option::Option<crate::model::ListManagementOptions>, ) -> Self { self.list_management_options = input; self } /// Consumes the builder and constructs a [`SendEmailInput`](crate::input::SendEmailInput) pub fn build( self, ) -> std::result::Result<crate::input::SendEmailInput, aws_smithy_http::operation::BuildError> { Ok(crate::input::SendEmailInput { from_email_address: self.from_email_address, from_email_address_identity_arn: self.from_email_address_identity_arn, destination: self.destination, reply_to_addresses: self.reply_to_addresses, feedback_forwarding_email_address: self.feedback_forwarding_email_address, feedback_forwarding_email_address_identity_arn: self .feedback_forwarding_email_address_identity_arn, content: self.content, email_tags: self.email_tags, configuration_set_name: self.configuration_set_name, list_management_options: self.list_management_options, }) } } } #[doc(hidden)] pub type SendEmailInputOperationOutputAlias = crate::operation::SendEmail; #[doc(hidden)] pub type SendEmailInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl SendEmailInput { /// Consumes the builder and constructs an Operation<[`SendEmail`](crate::operation::SendEmail)> #[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::SendEmail, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::SendEmailInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/outbound-emails").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::SendEmailInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::SendEmailInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_send_email(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::SendEmail::new()) .with_metadata(aws_smithy_http::operation::Metadata::new( "SendEmail", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`SendEmailInput`](crate::input::SendEmailInput) pub fn builder() -> crate::input::send_email_input::Builder { crate::input::send_email_input::Builder::default() } } /// See [`TagResourceInput`](crate::input::TagResourceInput) pub mod tag_resource_input { /// A builder for [`TagResourceInput`](crate::input::TagResourceInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) resource_arn: std::option::Option<std::string::String>, pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl Builder { /// <p>The Amazon Resource Name (ARN) of the resource that you want to add one or more tags /// to.</p> pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self { self.resource_arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the resource that you want to add one or more tags /// to.</p> pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.resource_arn = input; self } /// Appends an item to `tags`. /// /// To override the contents of this collection use [`set_tags`](Self::set_tags). /// /// <p>A list of the tags that you want to add to the resource. A tag consists of a required /// tag key (<code>Key</code>) and an associated tag value (<code>Value</code>). The maximum /// length of a tag key is 128 characters. The maximum length of a tag value is 256 /// characters.</p> pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self { let mut v = self.tags.unwrap_or_default(); v.push(input.into()); self.tags = Some(v); self } /// <p>A list of the tags that you want to add to the resource. A tag consists of a required /// tag key (<code>Key</code>) and an associated tag value (<code>Value</code>). The maximum /// length of a tag key is 128 characters. The maximum length of a tag value is 256 /// characters.</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 [`TagResourceInput`](crate::input::TagResourceInput) pub fn build( self, ) -> std::result::Result< crate::input::TagResourceInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::TagResourceInput { resource_arn: self.resource_arn, tags: self.tags, }) } } } #[doc(hidden)] pub type TagResourceInputOperationOutputAlias = crate::operation::TagResource; #[doc(hidden)] pub type TagResourceInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl TagResourceInput { /// Consumes the builder and constructs an Operation<[`TagResource`](crate::operation::TagResource)> #[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::TagResource, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::TagResourceInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/tags").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::TagResourceInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::TagResourceInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_tag_resource(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::TagResource::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "TagResource", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`TagResourceInput`](crate::input::TagResourceInput) pub fn builder() -> crate::input::tag_resource_input::Builder { crate::input::tag_resource_input::Builder::default() } } /// See [`TestRenderEmailTemplateInput`](crate::input::TestRenderEmailTemplateInput) pub mod test_render_email_template_input { /// A builder for [`TestRenderEmailTemplateInput`](crate::input::TestRenderEmailTemplateInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) template_name: std::option::Option<std::string::String>, pub(crate) template_data: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the template.</p> pub fn template_name(mut self, input: impl Into<std::string::String>) -> Self { self.template_name = Some(input.into()); self } /// <p>The name of the template.</p> pub fn set_template_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_name = input; self } /// <p>A list of replacement values to apply to the template. This parameter is a JSON /// object, typically consisting of key-value pairs in which the keys correspond to /// replacement tags in the email template.</p> pub fn template_data(mut self, input: impl Into<std::string::String>) -> Self { self.template_data = Some(input.into()); self } /// <p>A list of replacement values to apply to the template. This parameter is a JSON /// object, typically consisting of key-value pairs in which the keys correspond to /// replacement tags in the email template.</p> pub fn set_template_data( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_data = input; self } /// Consumes the builder and constructs a [`TestRenderEmailTemplateInput`](crate::input::TestRenderEmailTemplateInput) pub fn build( self, ) -> std::result::Result< crate::input::TestRenderEmailTemplateInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::TestRenderEmailTemplateInput { template_name: self.template_name, template_data: self.template_data, }) } } } #[doc(hidden)] pub type TestRenderEmailTemplateInputOperationOutputAlias = crate::operation::TestRenderEmailTemplate; #[doc(hidden)] pub type TestRenderEmailTemplateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl TestRenderEmailTemplateInput { /// Consumes the builder and constructs an Operation<[`TestRenderEmailTemplate`](crate::operation::TestRenderEmailTemplate)> #[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::TestRenderEmailTemplate, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::TestRenderEmailTemplateInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_83 = &_input.template_name; let input_83 = input_83 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", })?; let template_name = aws_smithy_http::label::fmt_string(input_83, false); if template_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/templates/{TemplateName}/render", TemplateName = template_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::TestRenderEmailTemplateInput, 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)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::TestRenderEmailTemplateInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_test_render_email_template( &self, )?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::TestRenderEmailTemplate::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "TestRenderEmailTemplate", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`TestRenderEmailTemplateInput`](crate::input::TestRenderEmailTemplateInput) pub fn builder() -> crate::input::test_render_email_template_input::Builder { crate::input::test_render_email_template_input::Builder::default() } } /// See [`UntagResourceInput`](crate::input::UntagResourceInput) pub mod untag_resource_input { /// A builder for [`UntagResourceInput`](crate::input::UntagResourceInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) resource_arn: std::option::Option<std::string::String>, pub(crate) tag_keys: std::option::Option<std::vec::Vec<std::string::String>>, } impl Builder { /// <p>The Amazon Resource Name (ARN) of the resource that you want to remove one or more /// tags from.</p> pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self { self.resource_arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the resource that you want to remove one or more /// tags from.</p> pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.resource_arn = 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 tags (tag keys) that you want to remove from the resource. When you specify a tag /// key, the action removes both that key and its associated tag value.</p> /// <p>To remove more than one tag from the resource, append the <code>TagKeys</code> /// parameter and argument for each additional tag to remove, separated by an ampersand. For /// example: /// <code>/v2/email/tags?ResourceArn=ResourceArn&TagKeys=Key1&TagKeys=Key2</code> /// </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 tags (tag keys) that you want to remove from the resource. When you specify a tag /// key, the action removes both that key and its associated tag value.</p> /// <p>To remove more than one tag from the resource, append the <code>TagKeys</code> /// parameter and argument for each additional tag to remove, separated by an ampersand. For /// example: /// <code>/v2/email/tags?ResourceArn=ResourceArn&TagKeys=Key1&TagKeys=Key2</code> /// </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 [`UntagResourceInput`](crate::input::UntagResourceInput) pub fn build( self, ) -> std::result::Result< crate::input::UntagResourceInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::UntagResourceInput { resource_arn: self.resource_arn, tag_keys: self.tag_keys, }) } } } #[doc(hidden)] pub type UntagResourceInputOperationOutputAlias = crate::operation::UntagResource; #[doc(hidden)] pub type UntagResourceInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UntagResourceInput { /// Consumes the builder and constructs an Operation<[`UntagResource`](crate::operation::UntagResource)> #[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::UntagResource, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::UntagResourceInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { write!(output, "/v2/email/tags").expect("formatting should succeed"); Ok(()) } fn uri_query( _input: &crate::input::UntagResourceInput, mut output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let mut query = aws_smithy_http::query::Writer::new(&mut output); if let Some(inner_84) = &_input.resource_arn { query.push_kv( "ResourceArn", &aws_smithy_http::query::fmt_string(&inner_84), ); } if let Some(inner_85) = &_input.tag_keys { for inner_86 in inner_85 { query.push_kv("TagKeys", &aws_smithy_http::query::fmt_string(&inner_86)); } } Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::UntagResourceInput, 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)?; uri_query(input, &mut uri)?; Ok(builder.method("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::UntagResourceInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = aws_smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::UntagResource::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "UntagResource", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UntagResourceInput`](crate::input::UntagResourceInput) pub fn builder() -> crate::input::untag_resource_input::Builder { crate::input::untag_resource_input::Builder::default() } } /// See [`UpdateConfigurationSetEventDestinationInput`](crate::input::UpdateConfigurationSetEventDestinationInput) pub mod update_configuration_set_event_destination_input { /// A builder for [`UpdateConfigurationSetEventDestinationInput`](crate::input::UpdateConfigurationSetEventDestinationInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) configuration_set_name: std::option::Option<std::string::String>, pub(crate) event_destination_name: std::option::Option<std::string::String>, pub(crate) event_destination: std::option::Option<crate::model::EventDestinationDefinition>, } impl Builder { /// <p>The name of the configuration set that contains the event destination to /// modify.</p> pub fn configuration_set_name(mut self, input: impl Into<std::string::String>) -> Self { self.configuration_set_name = Some(input.into()); self } /// <p>The name of the configuration set that contains the event destination to /// modify.</p> pub fn set_configuration_set_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.configuration_set_name = input; self } /// <p>The name of the event destination.</p> pub fn event_destination_name(mut self, input: impl Into<std::string::String>) -> Self { self.event_destination_name = Some(input.into()); self } /// <p>The name of the event destination.</p> pub fn set_event_destination_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.event_destination_name = input; self } /// <p>An object that defines the event destination.</p> pub fn event_destination( mut self, input: crate::model::EventDestinationDefinition, ) -> Self { self.event_destination = Some(input); self } /// <p>An object that defines the event destination.</p> pub fn set_event_destination( mut self, input: std::option::Option<crate::model::EventDestinationDefinition>, ) -> Self { self.event_destination = input; self } /// Consumes the builder and constructs a [`UpdateConfigurationSetEventDestinationInput`](crate::input::UpdateConfigurationSetEventDestinationInput) pub fn build( self, ) -> std::result::Result< crate::input::UpdateConfigurationSetEventDestinationInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::UpdateConfigurationSetEventDestinationInput { configuration_set_name: self.configuration_set_name, event_destination_name: self.event_destination_name, event_destination: self.event_destination, }) } } } #[doc(hidden)] pub type UpdateConfigurationSetEventDestinationInputOperationOutputAlias = crate::operation::UpdateConfigurationSetEventDestination; #[doc(hidden)] pub type UpdateConfigurationSetEventDestinationInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UpdateConfigurationSetEventDestinationInput { /// Consumes the builder and constructs an Operation<[`UpdateConfigurationSetEventDestination`](crate::operation::UpdateConfigurationSetEventDestination)> #[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::UpdateConfigurationSetEventDestination, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::UpdateConfigurationSetEventDestinationInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_87 = &_input.configuration_set_name; let input_87 = input_87 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", })?; let configuration_set_name = aws_smithy_http::label::fmt_string(input_87, false); if configuration_set_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "configuration_set_name", details: "cannot be empty or unset", }); } let input_88 = &_input.event_destination_name; let input_88 = input_88 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "event_destination_name", details: "cannot be empty or unset", })?; let event_destination_name = aws_smithy_http::label::fmt_string(input_88, false); if event_destination_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "event_destination_name", details: "cannot be empty or unset", }); } write!(output, "/v2/email/configuration-sets/{ConfigurationSetName}/event-destinations/{EventDestinationName}", ConfigurationSetName = configuration_set_name, EventDestinationName = event_destination_name).expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::UpdateConfigurationSetEventDestinationInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::UpdateConfigurationSetEventDestinationInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_update_configuration_set_event_destination(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::UpdateConfigurationSetEventDestination::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "UpdateConfigurationSetEventDestination", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UpdateConfigurationSetEventDestinationInput`](crate::input::UpdateConfigurationSetEventDestinationInput) pub fn builder() -> crate::input::update_configuration_set_event_destination_input::Builder { crate::input::update_configuration_set_event_destination_input::Builder::default() } } /// See [`UpdateContactInput`](crate::input::UpdateContactInput) pub mod update_contact_input { /// A builder for [`UpdateContactInput`](crate::input::UpdateContactInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) contact_list_name: std::option::Option<std::string::String>, pub(crate) email_address: std::option::Option<std::string::String>, pub(crate) topic_preferences: std::option::Option<std::vec::Vec<crate::model::TopicPreference>>, pub(crate) unsubscribe_all: std::option::Option<bool>, pub(crate) attributes_data: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the contact list.</p> pub fn contact_list_name(mut self, input: impl Into<std::string::String>) -> Self { self.contact_list_name = Some(input.into()); self } /// <p>The name of the contact list.</p> pub fn set_contact_list_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.contact_list_name = input; self } /// <p>The contact's email addres.</p> pub fn email_address(mut self, input: impl Into<std::string::String>) -> Self { self.email_address = Some(input.into()); self } /// <p>The contact's email addres.</p> pub fn set_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_address = input; self } /// Appends an item to `topic_preferences`. /// /// To override the contents of this collection use [`set_topic_preferences`](Self::set_topic_preferences). /// /// <p>The contact's preference for being opted-in to or opted-out of a topic.</p> pub fn topic_preferences( mut self, input: impl Into<crate::model::TopicPreference>, ) -> Self { let mut v = self.topic_preferences.unwrap_or_default(); v.push(input.into()); self.topic_preferences = Some(v); self } /// <p>The contact's preference for being opted-in to or opted-out of a topic.</p> pub fn set_topic_preferences( mut self, input: std::option::Option<std::vec::Vec<crate::model::TopicPreference>>, ) -> Self { self.topic_preferences = input; self } /// <p>A boolean value status noting if the contact is unsubscribed from all contact list /// topics.</p> pub fn unsubscribe_all(mut self, input: bool) -> Self { self.unsubscribe_all = Some(input); self } /// <p>A boolean value status noting if the contact is unsubscribed from all contact list /// topics.</p> pub fn set_unsubscribe_all(mut self, input: std::option::Option<bool>) -> Self { self.unsubscribe_all = input; self } /// <p>The attribute data attached to a contact.</p> pub fn attributes_data(mut self, input: impl Into<std::string::String>) -> Self { self.attributes_data = Some(input.into()); self } /// <p>The attribute data attached to a contact.</p> pub fn set_attributes_data( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.attributes_data = input; self } /// Consumes the builder and constructs a [`UpdateContactInput`](crate::input::UpdateContactInput) pub fn build( self, ) -> std::result::Result< crate::input::UpdateContactInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::UpdateContactInput { contact_list_name: self.contact_list_name, email_address: self.email_address, topic_preferences: self.topic_preferences, unsubscribe_all: self.unsubscribe_all.unwrap_or_default(), attributes_data: self.attributes_data, }) } } } #[doc(hidden)] pub type UpdateContactInputOperationOutputAlias = crate::operation::UpdateContact; #[doc(hidden)] pub type UpdateContactInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UpdateContactInput { /// Consumes the builder and constructs an Operation<[`UpdateContact`](crate::operation::UpdateContact)> #[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::UpdateContact, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::UpdateContactInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_89 = &_input.contact_list_name; let input_89 = input_89 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", })?; let contact_list_name = aws_smithy_http::label::fmt_string(input_89, false); if contact_list_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", }); } let input_90 = &_input.email_address; let input_90 = input_90 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_address", details: "cannot be empty or unset", })?; let email_address = aws_smithy_http::label::fmt_string(input_90, false); if email_address.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_address", details: "cannot be empty or unset", }); } write!( output, "/v2/email/contact-lists/{ContactListName}/contacts/{EmailAddress}", ContactListName = contact_list_name, EmailAddress = email_address ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::UpdateContactInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::UpdateContactInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_update_contact(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::UpdateContact::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "UpdateContact", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UpdateContactInput`](crate::input::UpdateContactInput) pub fn builder() -> crate::input::update_contact_input::Builder { crate::input::update_contact_input::Builder::default() } } /// See [`UpdateContactListInput`](crate::input::UpdateContactListInput) pub mod update_contact_list_input { /// A builder for [`UpdateContactListInput`](crate::input::UpdateContactListInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) contact_list_name: std::option::Option<std::string::String>, pub(crate) topics: std::option::Option<std::vec::Vec<crate::model::Topic>>, pub(crate) description: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the contact list.</p> pub fn contact_list_name(mut self, input: impl Into<std::string::String>) -> Self { self.contact_list_name = Some(input.into()); self } /// <p>The name of the contact list.</p> pub fn set_contact_list_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.contact_list_name = input; self } /// Appends an item to `topics`. /// /// To override the contents of this collection use [`set_topics`](Self::set_topics). /// /// <p>An interest group, theme, or label within a list. A contact list can have multiple /// topics.</p> pub fn topics(mut self, input: impl Into<crate::model::Topic>) -> Self { let mut v = self.topics.unwrap_or_default(); v.push(input.into()); self.topics = Some(v); self } /// <p>An interest group, theme, or label within a list. A contact list can have multiple /// topics.</p> pub fn set_topics( mut self, input: std::option::Option<std::vec::Vec<crate::model::Topic>>, ) -> Self { self.topics = input; self } /// <p>A description of what the contact list is about.</p> pub fn description(mut self, input: impl Into<std::string::String>) -> Self { self.description = Some(input.into()); self } /// <p>A description of what the contact list is about.</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 [`UpdateContactListInput`](crate::input::UpdateContactListInput) pub fn build( self, ) -> std::result::Result< crate::input::UpdateContactListInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::UpdateContactListInput { contact_list_name: self.contact_list_name, topics: self.topics, description: self.description, }) } } } #[doc(hidden)] pub type UpdateContactListInputOperationOutputAlias = crate::operation::UpdateContactList; #[doc(hidden)] pub type UpdateContactListInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UpdateContactListInput { /// Consumes the builder and constructs an Operation<[`UpdateContactList`](crate::operation::UpdateContactList)> #[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::UpdateContactList, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::UpdateContactListInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_91 = &_input.contact_list_name; let input_91 = input_91 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", })?; let contact_list_name = aws_smithy_http::label::fmt_string(input_91, false); if contact_list_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "contact_list_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/contact-lists/{ContactListName}", ContactListName = contact_list_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::UpdateContactListInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::UpdateContactListInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_update_contact_list(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::UpdateContactList::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "UpdateContactList", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UpdateContactListInput`](crate::input::UpdateContactListInput) pub fn builder() -> crate::input::update_contact_list_input::Builder { crate::input::update_contact_list_input::Builder::default() } } /// See [`UpdateCustomVerificationEmailTemplateInput`](crate::input::UpdateCustomVerificationEmailTemplateInput) pub mod update_custom_verification_email_template_input { /// A builder for [`UpdateCustomVerificationEmailTemplateInput`](crate::input::UpdateCustomVerificationEmailTemplateInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) template_name: std::option::Option<std::string::String>, pub(crate) from_email_address: std::option::Option<std::string::String>, pub(crate) template_subject: std::option::Option<std::string::String>, pub(crate) template_content: std::option::Option<std::string::String>, pub(crate) success_redirection_url: std::option::Option<std::string::String>, pub(crate) failure_redirection_url: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the custom verification email template that you want to update.</p> pub fn template_name(mut self, input: impl Into<std::string::String>) -> Self { self.template_name = Some(input.into()); self } /// <p>The name of the custom verification email template that you want to update.</p> pub fn set_template_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_name = input; self } /// <p>The email address that the custom verification email is sent from.</p> pub fn from_email_address(mut self, input: impl Into<std::string::String>) -> Self { self.from_email_address = Some(input.into()); self } /// <p>The email address that the custom verification email is sent from.</p> pub fn set_from_email_address( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.from_email_address = input; self } /// <p>The subject line of the custom verification email.</p> pub fn template_subject(mut self, input: impl Into<std::string::String>) -> Self { self.template_subject = Some(input.into()); self } /// <p>The subject line of the custom verification email.</p> pub fn set_template_subject( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_subject = input; self } /// <p>The content of the custom verification email. The total size of the email must be less /// than 10 MB. The message body may contain HTML, with some limitations. For more /// information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-verify-address-custom.html#custom-verification-emails-faq">Custom Verification Email Frequently Asked Questions</a> in the <i>Amazon SES /// Developer Guide</i>.</p> pub fn template_content(mut self, input: impl Into<std::string::String>) -> Self { self.template_content = Some(input.into()); self } /// <p>The content of the custom verification email. The total size of the email must be less /// than 10 MB. The message body may contain HTML, with some limitations. For more /// information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-verify-address-custom.html#custom-verification-emails-faq">Custom Verification Email Frequently Asked Questions</a> in the <i>Amazon SES /// Developer Guide</i>.</p> pub fn set_template_content( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_content = input; self } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is successfully verified.</p> pub fn success_redirection_url(mut self, input: impl Into<std::string::String>) -> Self { self.success_redirection_url = Some(input.into()); self } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is successfully verified.</p> pub fn set_success_redirection_url( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.success_redirection_url = input; self } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is not successfully verified.</p> pub fn failure_redirection_url(mut self, input: impl Into<std::string::String>) -> Self { self.failure_redirection_url = Some(input.into()); self } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is not successfully verified.</p> pub fn set_failure_redirection_url( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.failure_redirection_url = input; self } /// Consumes the builder and constructs a [`UpdateCustomVerificationEmailTemplateInput`](crate::input::UpdateCustomVerificationEmailTemplateInput) pub fn build( self, ) -> std::result::Result< crate::input::UpdateCustomVerificationEmailTemplateInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::UpdateCustomVerificationEmailTemplateInput { template_name: self.template_name, from_email_address: self.from_email_address, template_subject: self.template_subject, template_content: self.template_content, success_redirection_url: self.success_redirection_url, failure_redirection_url: self.failure_redirection_url, }) } } } #[doc(hidden)] pub type UpdateCustomVerificationEmailTemplateInputOperationOutputAlias = crate::operation::UpdateCustomVerificationEmailTemplate; #[doc(hidden)] pub type UpdateCustomVerificationEmailTemplateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UpdateCustomVerificationEmailTemplateInput { /// Consumes the builder and constructs an Operation<[`UpdateCustomVerificationEmailTemplate`](crate::operation::UpdateCustomVerificationEmailTemplate)> #[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::UpdateCustomVerificationEmailTemplate, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::UpdateCustomVerificationEmailTemplateInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_92 = &_input.template_name; let input_92 = input_92 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", })?; let template_name = aws_smithy_http::label::fmt_string(input_92, false); if template_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/custom-verification-email-templates/{TemplateName}", TemplateName = template_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::UpdateCustomVerificationEmailTemplateInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::UpdateCustomVerificationEmailTemplateInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_update_custom_verification_email_template(&self)? ; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::UpdateCustomVerificationEmailTemplate::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "UpdateCustomVerificationEmailTemplate", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UpdateCustomVerificationEmailTemplateInput`](crate::input::UpdateCustomVerificationEmailTemplateInput) pub fn builder() -> crate::input::update_custom_verification_email_template_input::Builder { crate::input::update_custom_verification_email_template_input::Builder::default() } } /// See [`UpdateEmailIdentityPolicyInput`](crate::input::UpdateEmailIdentityPolicyInput) pub mod update_email_identity_policy_input { /// A builder for [`UpdateEmailIdentityPolicyInput`](crate::input::UpdateEmailIdentityPolicyInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) email_identity: std::option::Option<std::string::String>, pub(crate) policy_name: std::option::Option<std::string::String>, pub(crate) policy: std::option::Option<std::string::String>, } impl Builder { /// <p>The email identity.</p> pub fn email_identity(mut self, input: impl Into<std::string::String>) -> Self { self.email_identity = Some(input.into()); self } /// <p>The email identity.</p> pub fn set_email_identity( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.email_identity = input; self } /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub fn policy_name(mut self, input: impl Into<std::string::String>) -> Self { self.policy_name = Some(input.into()); self } /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub fn set_policy_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.policy_name = input; self } /// <p>The text of the policy in JSON format. The policy cannot exceed 4 KB.</p> /// <p> For information about the syntax of sending authorization policies, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES Developer /// Guide</a>.</p> pub fn policy(mut self, input: impl Into<std::string::String>) -> Self { self.policy = Some(input.into()); self } /// <p>The text of the policy in JSON format. The policy cannot exceed 4 KB.</p> /// <p> For information about the syntax of sending authorization policies, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES Developer /// Guide</a>.</p> pub fn set_policy(mut self, input: std::option::Option<std::string::String>) -> Self { self.policy = input; self } /// Consumes the builder and constructs a [`UpdateEmailIdentityPolicyInput`](crate::input::UpdateEmailIdentityPolicyInput) pub fn build( self, ) -> std::result::Result< crate::input::UpdateEmailIdentityPolicyInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::UpdateEmailIdentityPolicyInput { email_identity: self.email_identity, policy_name: self.policy_name, policy: self.policy, }) } } } #[doc(hidden)] pub type UpdateEmailIdentityPolicyInputOperationOutputAlias = crate::operation::UpdateEmailIdentityPolicy; #[doc(hidden)] pub type UpdateEmailIdentityPolicyInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UpdateEmailIdentityPolicyInput { /// Consumes the builder and constructs an Operation<[`UpdateEmailIdentityPolicy`](crate::operation::UpdateEmailIdentityPolicy)> #[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::UpdateEmailIdentityPolicy, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::UpdateEmailIdentityPolicyInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_93 = &_input.email_identity; let input_93 = input_93 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", })?; let email_identity = aws_smithy_http::label::fmt_string(input_93, false); if email_identity.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "email_identity", details: "cannot be empty or unset", }); } let input_94 = &_input.policy_name; let input_94 = input_94 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "policy_name", details: "cannot be empty or unset", })?; let policy_name = aws_smithy_http::label::fmt_string(input_94, false); if policy_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "policy_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/identities/{EmailIdentity}/policies/{PolicyName}", EmailIdentity = email_identity, PolicyName = policy_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::UpdateEmailIdentityPolicyInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::UpdateEmailIdentityPolicyInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_update_email_identity_policy( &self, )?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::UpdateEmailIdentityPolicy::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "UpdateEmailIdentityPolicy", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UpdateEmailIdentityPolicyInput`](crate::input::UpdateEmailIdentityPolicyInput) pub fn builder() -> crate::input::update_email_identity_policy_input::Builder { crate::input::update_email_identity_policy_input::Builder::default() } } /// See [`UpdateEmailTemplateInput`](crate::input::UpdateEmailTemplateInput) pub mod update_email_template_input { /// A builder for [`UpdateEmailTemplateInput`](crate::input::UpdateEmailTemplateInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) template_name: std::option::Option<std::string::String>, pub(crate) template_content: std::option::Option<crate::model::EmailTemplateContent>, } impl Builder { /// <p>The name of the template.</p> pub fn template_name(mut self, input: impl Into<std::string::String>) -> Self { self.template_name = Some(input.into()); self } /// <p>The name of the template.</p> pub fn set_template_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.template_name = input; self } /// <p>The content of the email template, composed of a subject line, an HTML part, and a /// text-only part.</p> pub fn template_content(mut self, input: crate::model::EmailTemplateContent) -> Self { self.template_content = Some(input); self } /// <p>The content of the email template, composed of a subject line, an HTML part, and a /// text-only part.</p> pub fn set_template_content( mut self, input: std::option::Option<crate::model::EmailTemplateContent>, ) -> Self { self.template_content = input; self } /// Consumes the builder and constructs a [`UpdateEmailTemplateInput`](crate::input::UpdateEmailTemplateInput) pub fn build( self, ) -> std::result::Result< crate::input::UpdateEmailTemplateInput, aws_smithy_http::operation::BuildError, > { Ok(crate::input::UpdateEmailTemplateInput { template_name: self.template_name, template_content: self.template_content, }) } } } #[doc(hidden)] pub type UpdateEmailTemplateInputOperationOutputAlias = crate::operation::UpdateEmailTemplate; #[doc(hidden)] pub type UpdateEmailTemplateInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UpdateEmailTemplateInput { /// Consumes the builder and constructs an Operation<[`UpdateEmailTemplate`](crate::operation::UpdateEmailTemplate)> #[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::UpdateEmailTemplate, aws_http::AwsErrorRetryPolicy, >, aws_smithy_http::operation::BuildError, > { fn uri_base( _input: &crate::input::UpdateEmailTemplateInput, output: &mut String, ) -> Result<(), aws_smithy_http::operation::BuildError> { let input_95 = &_input.template_name; let input_95 = input_95 .as_ref() .ok_or(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", })?; let template_name = aws_smithy_http::label::fmt_string(input_95, false); if template_name.is_empty() { return Err(aws_smithy_http::operation::BuildError::MissingField { field: "template_name", details: "cannot be empty or unset", }); } write!( output, "/v2/email/templates/{TemplateName}", TemplateName = template_name ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( input: &crate::input::UpdateEmailTemplateInput, 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("PUT").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( input: &crate::input::UpdateEmailTemplateInput, ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError> { #[allow(unused_mut)] let mut builder = update_http_builder(input, http::request::Builder::new())?; builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::HeaderName::from_static("content-type"), "application/json", ); Ok(builder) } let properties = aws_smithy_http::property_bag::SharedPropertyBag::new(); let request = request_builder_base(&self)?; let body = crate::operation_ser::serialize_operation_crate_operation_update_email_template(&self)?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = aws_smithy_http::operation::Request::from_parts( request.map(aws_smithy_http::body::SdkBody::from), 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); #[allow(unused_mut)] 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::UpdateEmailTemplate::new(), ) .with_metadata(aws_smithy_http::operation::Metadata::new( "UpdateEmailTemplate", "sesv2", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); Ok(op) } fn assemble( builder: http::request::Builder, body: aws_smithy_http::body::SdkBody, ) -> http::request::Request<aws_smithy_http::body::SdkBody> { let mut builder = builder; if let Some(content_length) = body.content_length() { builder = aws_smithy_http::header::set_header_if_absent( builder, http::header::CONTENT_LENGTH, content_length, ); } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UpdateEmailTemplateInput`](crate::input::UpdateEmailTemplateInput) pub fn builder() -> crate::input::update_email_template_input::Builder { crate::input::update_email_template_input::Builder::default() } } /// <p>Represents a request to update an email template. For more information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html">Amazon SES /// Developer Guide</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateEmailTemplateInput { /// <p>The name of the template.</p> pub template_name: std::option::Option<std::string::String>, /// <p>The content of the email template, composed of a subject line, an HTML part, and a /// text-only part.</p> pub template_content: std::option::Option<crate::model::EmailTemplateContent>, } impl UpdateEmailTemplateInput { /// <p>The name of the template.</p> pub fn template_name(&self) -> std::option::Option<&str> { self.template_name.as_deref() } /// <p>The content of the email template, composed of a subject line, an HTML part, and a /// text-only part.</p> pub fn template_content(&self) -> std::option::Option<&crate::model::EmailTemplateContent> { self.template_content.as_ref() } } impl std::fmt::Debug for UpdateEmailTemplateInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateEmailTemplateInput"); formatter.field("template_name", &self.template_name); formatter.field("template_content", &self.template_content); formatter.finish() } } /// <p>Represents a request to update a sending authorization policy for an identity. Sending /// authorization is an Amazon SES feature that enables you to authorize other senders to use /// your identities. For information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-identity-owner-tasks-management.html">Amazon SES Developer Guide</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateEmailIdentityPolicyInput { /// <p>The email identity.</p> pub email_identity: std::option::Option<std::string::String>, /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub policy_name: std::option::Option<std::string::String>, /// <p>The text of the policy in JSON format. The policy cannot exceed 4 KB.</p> /// <p> For information about the syntax of sending authorization policies, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES Developer /// Guide</a>.</p> pub policy: std::option::Option<std::string::String>, } impl UpdateEmailIdentityPolicyInput { /// <p>The email identity.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub fn policy_name(&self) -> std::option::Option<&str> { self.policy_name.as_deref() } /// <p>The text of the policy in JSON format. The policy cannot exceed 4 KB.</p> /// <p> For information about the syntax of sending authorization policies, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES Developer /// Guide</a>.</p> pub fn policy(&self) -> std::option::Option<&str> { self.policy.as_deref() } } impl std::fmt::Debug for UpdateEmailIdentityPolicyInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateEmailIdentityPolicyInput"); formatter.field("email_identity", &self.email_identity); formatter.field("policy_name", &self.policy_name); formatter.field("policy", &self.policy); formatter.finish() } } /// <p>Represents a request to update an existing custom verification email template.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateCustomVerificationEmailTemplateInput { /// <p>The name of the custom verification email template that you want to update.</p> pub template_name: std::option::Option<std::string::String>, /// <p>The email address that the custom verification email is sent from.</p> pub from_email_address: std::option::Option<std::string::String>, /// <p>The subject line of the custom verification email.</p> pub template_subject: std::option::Option<std::string::String>, /// <p>The content of the custom verification email. The total size of the email must be less /// than 10 MB. The message body may contain HTML, with some limitations. For more /// information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-verify-address-custom.html#custom-verification-emails-faq">Custom Verification Email Frequently Asked Questions</a> in the <i>Amazon SES /// Developer Guide</i>.</p> pub template_content: std::option::Option<std::string::String>, /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is successfully verified.</p> pub success_redirection_url: std::option::Option<std::string::String>, /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is not successfully verified.</p> pub failure_redirection_url: std::option::Option<std::string::String>, } impl UpdateCustomVerificationEmailTemplateInput { /// <p>The name of the custom verification email template that you want to update.</p> pub fn template_name(&self) -> std::option::Option<&str> { self.template_name.as_deref() } /// <p>The email address that the custom verification email is sent from.</p> pub fn from_email_address(&self) -> std::option::Option<&str> { self.from_email_address.as_deref() } /// <p>The subject line of the custom verification email.</p> pub fn template_subject(&self) -> std::option::Option<&str> { self.template_subject.as_deref() } /// <p>The content of the custom verification email. The total size of the email must be less /// than 10 MB. The message body may contain HTML, with some limitations. For more /// information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-verify-address-custom.html#custom-verification-emails-faq">Custom Verification Email Frequently Asked Questions</a> in the <i>Amazon SES /// Developer Guide</i>.</p> pub fn template_content(&self) -> std::option::Option<&str> { self.template_content.as_deref() } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is successfully verified.</p> pub fn success_redirection_url(&self) -> std::option::Option<&str> { self.success_redirection_url.as_deref() } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is not successfully verified.</p> pub fn failure_redirection_url(&self) -> std::option::Option<&str> { self.failure_redirection_url.as_deref() } } impl std::fmt::Debug for UpdateCustomVerificationEmailTemplateInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateCustomVerificationEmailTemplateInput"); formatter.field("template_name", &self.template_name); formatter.field("from_email_address", &self.from_email_address); formatter.field("template_subject", &self.template_subject); formatter.field("template_content", &self.template_content); formatter.field("success_redirection_url", &self.success_redirection_url); formatter.field("failure_redirection_url", &self.failure_redirection_url); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateContactListInput { /// <p>The name of the contact list.</p> pub contact_list_name: std::option::Option<std::string::String>, /// <p>An interest group, theme, or label within a list. A contact list can have multiple /// topics.</p> pub topics: std::option::Option<std::vec::Vec<crate::model::Topic>>, /// <p>A description of what the contact list is about.</p> pub description: std::option::Option<std::string::String>, } impl UpdateContactListInput { /// <p>The name of the contact list.</p> pub fn contact_list_name(&self) -> std::option::Option<&str> { self.contact_list_name.as_deref() } /// <p>An interest group, theme, or label within a list. A contact list can have multiple /// topics.</p> pub fn topics(&self) -> std::option::Option<&[crate::model::Topic]> { self.topics.as_deref() } /// <p>A description of what the contact list is about.</p> pub fn description(&self) -> std::option::Option<&str> { self.description.as_deref() } } impl std::fmt::Debug for UpdateContactListInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateContactListInput"); formatter.field("contact_list_name", &self.contact_list_name); formatter.field("topics", &self.topics); 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 UpdateContactInput { /// <p>The name of the contact list.</p> pub contact_list_name: std::option::Option<std::string::String>, /// <p>The contact's email addres.</p> pub email_address: std::option::Option<std::string::String>, /// <p>The contact's preference for being opted-in to or opted-out of a topic.</p> pub topic_preferences: std::option::Option<std::vec::Vec<crate::model::TopicPreference>>, /// <p>A boolean value status noting if the contact is unsubscribed from all contact list /// topics.</p> pub unsubscribe_all: bool, /// <p>The attribute data attached to a contact.</p> pub attributes_data: std::option::Option<std::string::String>, } impl UpdateContactInput { /// <p>The name of the contact list.</p> pub fn contact_list_name(&self) -> std::option::Option<&str> { self.contact_list_name.as_deref() } /// <p>The contact's email addres.</p> pub fn email_address(&self) -> std::option::Option<&str> { self.email_address.as_deref() } /// <p>The contact's preference for being opted-in to or opted-out of a topic.</p> pub fn topic_preferences(&self) -> std::option::Option<&[crate::model::TopicPreference]> { self.topic_preferences.as_deref() } /// <p>A boolean value status noting if the contact is unsubscribed from all contact list /// topics.</p> pub fn unsubscribe_all(&self) -> bool { self.unsubscribe_all } /// <p>The attribute data attached to a contact.</p> pub fn attributes_data(&self) -> std::option::Option<&str> { self.attributes_data.as_deref() } } impl std::fmt::Debug for UpdateContactInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateContactInput"); formatter.field("contact_list_name", &self.contact_list_name); formatter.field("email_address", &self.email_address); formatter.field("topic_preferences", &self.topic_preferences); formatter.field("unsubscribe_all", &self.unsubscribe_all); formatter.field("attributes_data", &self.attributes_data); formatter.finish() } } /// <p>A request to change the settings for an event destination for a configuration /// set.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateConfigurationSetEventDestinationInput { /// <p>The name of the configuration set that contains the event destination to /// modify.</p> pub configuration_set_name: std::option::Option<std::string::String>, /// <p>The name of the event destination.</p> pub event_destination_name: std::option::Option<std::string::String>, /// <p>An object that defines the event destination.</p> pub event_destination: std::option::Option<crate::model::EventDestinationDefinition>, } impl UpdateConfigurationSetEventDestinationInput { /// <p>The name of the configuration set that contains the event destination to /// modify.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } /// <p>The name of the event destination.</p> pub fn event_destination_name(&self) -> std::option::Option<&str> { self.event_destination_name.as_deref() } /// <p>An object that defines the event destination.</p> pub fn event_destination( &self, ) -> std::option::Option<&crate::model::EventDestinationDefinition> { self.event_destination.as_ref() } } impl std::fmt::Debug for UpdateConfigurationSetEventDestinationInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateConfigurationSetEventDestinationInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.field("event_destination_name", &self.event_destination_name); formatter.field("event_destination", &self.event_destination); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UntagResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource that you want to remove one or more /// tags from.</p> pub resource_arn: std::option::Option<std::string::String>, /// <p>The tags (tag keys) that you want to remove from the resource. When you specify a tag /// key, the action removes both that key and its associated tag value.</p> /// <p>To remove more than one tag from the resource, append the <code>TagKeys</code> /// parameter and argument for each additional tag to remove, separated by an ampersand. For /// example: /// <code>/v2/email/tags?ResourceArn=ResourceArn&TagKeys=Key1&TagKeys=Key2</code> /// </p> pub tag_keys: std::option::Option<std::vec::Vec<std::string::String>>, } impl UntagResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource that you want to remove one or more /// tags from.</p> pub fn resource_arn(&self) -> std::option::Option<&str> { self.resource_arn.as_deref() } /// <p>The tags (tag keys) that you want to remove from the resource. When you specify a tag /// key, the action removes both that key and its associated tag value.</p> /// <p>To remove more than one tag from the resource, append the <code>TagKeys</code> /// parameter and argument for each additional tag to remove, separated by an ampersand. For /// example: /// <code>/v2/email/tags?ResourceArn=ResourceArn&TagKeys=Key1&TagKeys=Key2</code> /// </p> pub fn tag_keys(&self) -> std::option::Option<&[std::string::String]> { self.tag_keys.as_deref() } } impl std::fmt::Debug for UntagResourceInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UntagResourceInput"); formatter.field("resource_arn", &self.resource_arn); formatter.field("tag_keys", &self.tag_keys); formatter.finish() } } /// <p>>Represents a request to create a preview of the MIME content of an email when /// provided with a template and a set of replacement data.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct TestRenderEmailTemplateInput { /// <p>The name of the template.</p> pub template_name: std::option::Option<std::string::String>, /// <p>A list of replacement values to apply to the template. This parameter is a JSON /// object, typically consisting of key-value pairs in which the keys correspond to /// replacement tags in the email template.</p> pub template_data: std::option::Option<std::string::String>, } impl TestRenderEmailTemplateInput { /// <p>The name of the template.</p> pub fn template_name(&self) -> std::option::Option<&str> { self.template_name.as_deref() } /// <p>A list of replacement values to apply to the template. This parameter is a JSON /// object, typically consisting of key-value pairs in which the keys correspond to /// replacement tags in the email template.</p> pub fn template_data(&self) -> std::option::Option<&str> { self.template_data.as_deref() } } impl std::fmt::Debug for TestRenderEmailTemplateInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("TestRenderEmailTemplateInput"); formatter.field("template_name", &self.template_name); formatter.field("template_data", &self.template_data); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct TagResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource that you want to add one or more tags /// to.</p> pub resource_arn: std::option::Option<std::string::String>, /// <p>A list of the tags that you want to add to the resource. A tag consists of a required /// tag key (<code>Key</code>) and an associated tag value (<code>Value</code>). The maximum /// length of a tag key is 128 characters. The maximum length of a tag value is 256 /// characters.</p> pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl TagResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource that you want to add one or more tags /// to.</p> pub fn resource_arn(&self) -> std::option::Option<&str> { self.resource_arn.as_deref() } /// <p>A list of the tags that you want to add to the resource. A tag consists of a required /// tag key (<code>Key</code>) and an associated tag value (<code>Value</code>). The maximum /// length of a tag key is 128 characters. The maximum length of a tag value is 256 /// characters.</p> pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> { self.tags.as_deref() } } impl std::fmt::Debug for TagResourceInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("TagResourceInput"); formatter.field("resource_arn", &self.resource_arn); formatter.field("tags", &self.tags); formatter.finish() } } /// <p>Represents a request to send a single formatted email using Amazon SES. For more /// information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-formatted.html">Amazon SES Developer /// Guide</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct SendEmailInput { /// <p>The email address to use as the "From" address for the email. The /// address that you specify has to be verified. /// </p> pub from_email_address: std::option::Option<std::string::String>, /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FromEmailAddress</code> parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FromEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FromEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> /// <p>For Raw emails, the <code>FromEmailAddressIdentityArn</code> value overrides the /// X-SES-SOURCE-ARN and X-SES-FROM-ARN headers specified in raw email message /// content.</p> pub from_email_address_identity_arn: std::option::Option<std::string::String>, /// <p>An object that contains the recipients of the email message.</p> pub destination: std::option::Option<crate::model::Destination>, /// <p>The "Reply-to" email addresses for the message. When the recipient replies to the /// message, each Reply-to address receives the reply.</p> pub reply_to_addresses: std::option::Option<std::vec::Vec<std::string::String>>, /// <p>The address that you want bounce and complaint notifications to be sent to.</p> pub feedback_forwarding_email_address: std::option::Option<std::string::String>, /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FeedbackForwardingEmailAddress</code> /// parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FeedbackForwardingEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FeedbackForwardingEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub feedback_forwarding_email_address_identity_arn: std::option::Option<std::string::String>, /// <p>An object that contains the body of the message. You can send either a Simple message /// Raw message or a template Message.</p> pub content: std::option::Option<crate::model::EmailContent>, /// <p>A list of tags, in the form of name/value pairs, to apply to an email that you send /// using the <code>SendEmail</code> operation. Tags correspond to characteristics of the /// email that you define, so that you can publish email sending events. </p> pub email_tags: std::option::Option<std::vec::Vec<crate::model::MessageTag>>, /// <p>The name of the configuration set to use when sending the email.</p> pub configuration_set_name: std::option::Option<std::string::String>, /// <p>An object used to specify a list or topic to which an email belongs, which will be /// used when a contact chooses to unsubscribe.</p> pub list_management_options: std::option::Option<crate::model::ListManagementOptions>, } impl SendEmailInput { /// <p>The email address to use as the "From" address for the email. The /// address that you specify has to be verified. /// </p> pub fn from_email_address(&self) -> std::option::Option<&str> { self.from_email_address.as_deref() } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FromEmailAddress</code> parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FromEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FromEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> /// <p>For Raw emails, the <code>FromEmailAddressIdentityArn</code> value overrides the /// X-SES-SOURCE-ARN and X-SES-FROM-ARN headers specified in raw email message /// content.</p> pub fn from_email_address_identity_arn(&self) -> std::option::Option<&str> { self.from_email_address_identity_arn.as_deref() } /// <p>An object that contains the recipients of the email message.</p> pub fn destination(&self) -> std::option::Option<&crate::model::Destination> { self.destination.as_ref() } /// <p>The "Reply-to" email addresses for the message. When the recipient replies to the /// message, each Reply-to address receives the reply.</p> pub fn reply_to_addresses(&self) -> std::option::Option<&[std::string::String]> { self.reply_to_addresses.as_deref() } /// <p>The address that you want bounce and complaint notifications to be sent to.</p> pub fn feedback_forwarding_email_address(&self) -> std::option::Option<&str> { self.feedback_forwarding_email_address.as_deref() } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FeedbackForwardingEmailAddress</code> /// parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FeedbackForwardingEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FeedbackForwardingEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub fn feedback_forwarding_email_address_identity_arn(&self) -> std::option::Option<&str> { self.feedback_forwarding_email_address_identity_arn .as_deref() } /// <p>An object that contains the body of the message. You can send either a Simple message /// Raw message or a template Message.</p> pub fn content(&self) -> std::option::Option<&crate::model::EmailContent> { self.content.as_ref() } /// <p>A list of tags, in the form of name/value pairs, to apply to an email that you send /// using the <code>SendEmail</code> operation. Tags correspond to characteristics of the /// email that you define, so that you can publish email sending events. </p> pub fn email_tags(&self) -> std::option::Option<&[crate::model::MessageTag]> { self.email_tags.as_deref() } /// <p>The name of the configuration set to use when sending the email.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } /// <p>An object used to specify a list or topic to which an email belongs, which will be /// used when a contact chooses to unsubscribe.</p> pub fn list_management_options( &self, ) -> std::option::Option<&crate::model::ListManagementOptions> { self.list_management_options.as_ref() } } impl std::fmt::Debug for SendEmailInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("SendEmailInput"); formatter.field("from_email_address", &self.from_email_address); formatter.field( "from_email_address_identity_arn", &self.from_email_address_identity_arn, ); formatter.field("destination", &self.destination); formatter.field("reply_to_addresses", &self.reply_to_addresses); formatter.field( "feedback_forwarding_email_address", &self.feedback_forwarding_email_address, ); formatter.field( "feedback_forwarding_email_address_identity_arn", &self.feedback_forwarding_email_address_identity_arn, ); formatter.field("content", &self.content); formatter.field("email_tags", &self.email_tags); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.field("list_management_options", &self.list_management_options); formatter.finish() } } /// <p>Represents a request to send a custom verification email to a specified /// recipient.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct SendCustomVerificationEmailInput { /// <p>The email address to verify.</p> pub email_address: std::option::Option<std::string::String>, /// <p>The name of the custom verification email template to use when sending the /// verification email.</p> pub template_name: std::option::Option<std::string::String>, /// <p>Name of a configuration set to use when sending the verification email.</p> pub configuration_set_name: std::option::Option<std::string::String>, } impl SendCustomVerificationEmailInput { /// <p>The email address to verify.</p> pub fn email_address(&self) -> std::option::Option<&str> { self.email_address.as_deref() } /// <p>The name of the custom verification email template to use when sending the /// verification email.</p> pub fn template_name(&self) -> std::option::Option<&str> { self.template_name.as_deref() } /// <p>Name of a configuration set to use when sending the verification email.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } } impl std::fmt::Debug for SendCustomVerificationEmailInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("SendCustomVerificationEmailInput"); formatter.field("email_address", &self.email_address); formatter.field("template_name", &self.template_name); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.finish() } } /// <p>Represents a request to send email messages to multiple destinations using Amazon SES. For /// more information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html">Amazon SES Developer /// Guide</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct SendBulkEmailInput { /// <p>The email address to use as the "From" address for the email. The /// address that you specify has to be verified.</p> pub from_email_address: std::option::Option<std::string::String>, /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FromEmailAddress</code> parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FromEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FromEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub from_email_address_identity_arn: std::option::Option<std::string::String>, /// <p>The "Reply-to" email addresses for the message. When the recipient replies to the /// message, each Reply-to address receives the reply.</p> pub reply_to_addresses: std::option::Option<std::vec::Vec<std::string::String>>, /// <p>The address that you want bounce and complaint notifications to be sent to.</p> pub feedback_forwarding_email_address: std::option::Option<std::string::String>, /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FeedbackForwardingEmailAddress</code> /// parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FeedbackForwardingEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FeedbackForwardingEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub feedback_forwarding_email_address_identity_arn: std::option::Option<std::string::String>, /// <p>A list of tags, in the form of name/value pairs, to apply to an email that you send /// using the <code>SendEmail</code> operation. Tags correspond to characteristics of the /// email that you define, so that you can publish email sending events.</p> pub default_email_tags: std::option::Option<std::vec::Vec<crate::model::MessageTag>>, /// <p>An object that contains the body of the message. You can specify a template /// message.</p> pub default_content: std::option::Option<crate::model::BulkEmailContent>, /// <p>The list of bulk email entry objects.</p> pub bulk_email_entries: std::option::Option<std::vec::Vec<crate::model::BulkEmailEntry>>, /// <p>The name of the configuration set to use when sending the email.</p> pub configuration_set_name: std::option::Option<std::string::String>, } impl SendBulkEmailInput { /// <p>The email address to use as the "From" address for the email. The /// address that you specify has to be verified.</p> pub fn from_email_address(&self) -> std::option::Option<&str> { self.from_email_address.as_deref() } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FromEmailAddress</code> parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FromEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FromEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub fn from_email_address_identity_arn(&self) -> std::option::Option<&str> { self.from_email_address_identity_arn.as_deref() } /// <p>The "Reply-to" email addresses for the message. When the recipient replies to the /// message, each Reply-to address receives the reply.</p> pub fn reply_to_addresses(&self) -> std::option::Option<&[std::string::String]> { self.reply_to_addresses.as_deref() } /// <p>The address that you want bounce and complaint notifications to be sent to.</p> pub fn feedback_forwarding_email_address(&self) -> std::option::Option<&str> { self.feedback_forwarding_email_address.as_deref() } /// <p>This parameter is used only for sending authorization. It is the ARN of the identity /// that is associated with the sending authorization policy that permits you to use the /// email address specified in the <code>FeedbackForwardingEmailAddress</code> /// parameter.</p> /// <p>For example, if the owner of example.com (which has ARN /// arn:aws:ses:us-east-1:123456789012:identity/example.com) attaches a policy to it that /// authorizes you to use [email protected], then you would specify the /// <code>FeedbackForwardingEmailAddressIdentityArn</code> to be /// arn:aws:ses:us-east-1:123456789012:identity/example.com, and the /// <code>FeedbackForwardingEmailAddress</code> to be [email protected].</p> /// <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer /// Guide</a>.</p> pub fn feedback_forwarding_email_address_identity_arn(&self) -> std::option::Option<&str> { self.feedback_forwarding_email_address_identity_arn .as_deref() } /// <p>A list of tags, in the form of name/value pairs, to apply to an email that you send /// using the <code>SendEmail</code> operation. Tags correspond to characteristics of the /// email that you define, so that you can publish email sending events.</p> pub fn default_email_tags(&self) -> std::option::Option<&[crate::model::MessageTag]> { self.default_email_tags.as_deref() } /// <p>An object that contains the body of the message. You can specify a template /// message.</p> pub fn default_content(&self) -> std::option::Option<&crate::model::BulkEmailContent> { self.default_content.as_ref() } /// <p>The list of bulk email entry objects.</p> pub fn bulk_email_entries(&self) -> std::option::Option<&[crate::model::BulkEmailEntry]> { self.bulk_email_entries.as_deref() } /// <p>The name of the configuration set to use when sending the email.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } } impl std::fmt::Debug for SendBulkEmailInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("SendBulkEmailInput"); formatter.field("from_email_address", &self.from_email_address); formatter.field( "from_email_address_identity_arn", &self.from_email_address_identity_arn, ); formatter.field("reply_to_addresses", &self.reply_to_addresses); formatter.field( "feedback_forwarding_email_address", &self.feedback_forwarding_email_address, ); formatter.field( "feedback_forwarding_email_address_identity_arn", &self.feedback_forwarding_email_address_identity_arn, ); formatter.field("default_email_tags", &self.default_email_tags); formatter.field("default_content", &self.default_content); formatter.field("bulk_email_entries", &self.bulk_email_entries); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.finish() } } /// <p>A request to add an email destination to the suppression list for your account.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutSuppressedDestinationInput { /// <p>The email address that should be added to the suppression list for your /// account.</p> pub email_address: std::option::Option<std::string::String>, /// <p>The factors that should cause the email address to be added to the suppression list /// for your account.</p> pub reason: std::option::Option<crate::model::SuppressionListReason>, } impl PutSuppressedDestinationInput { /// <p>The email address that should be added to the suppression list for your /// account.</p> pub fn email_address(&self) -> std::option::Option<&str> { self.email_address.as_deref() } /// <p>The factors that should cause the email address to be added to the suppression list /// for your account.</p> pub fn reason(&self) -> std::option::Option<&crate::model::SuppressionListReason> { self.reason.as_ref() } } impl std::fmt::Debug for PutSuppressedDestinationInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutSuppressedDestinationInput"); formatter.field("email_address", &self.email_address); formatter.field("reason", &self.reason); formatter.finish() } } /// <p>A request to configure the custom MAIL FROM domain for a verified identity.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutEmailIdentityMailFromAttributesInput { /// <p>The verified email identity.</p> pub email_identity: std::option::Option<std::string::String>, /// <p> The custom MAIL FROM domain that you want the verified identity to use. The MAIL FROM /// domain must meet the following criteria:</p> /// <ul> /// <li> /// <p>It has to be a subdomain of the verified identity.</p> /// </li> /// <li> /// <p>It can't be used to receive email.</p> /// </li> /// <li> /// <p>It can't be used in a "From" address if the MAIL FROM domain is a destination /// for feedback forwarding emails.</p> /// </li> /// </ul> pub mail_from_domain: std::option::Option<std::string::String>, /// <p>The action to take if the required MX record isn't found when you send an email. When /// you set this value to <code>UseDefaultValue</code>, the mail is sent using /// <i>amazonses.com</i> as the MAIL FROM domain. When you set this value /// to <code>RejectMessage</code>, the Amazon SES API v2 returns a /// <code>MailFromDomainNotVerified</code> error, and doesn't attempt to deliver the /// email.</p> /// <p>These behaviors are taken when the custom MAIL FROM domain configuration is in the /// <code>Pending</code>, <code>Failed</code>, and <code>TemporaryFailure</code> /// states.</p> pub behavior_on_mx_failure: std::option::Option<crate::model::BehaviorOnMxFailure>, } impl PutEmailIdentityMailFromAttributesInput { /// <p>The verified email identity.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } /// <p> The custom MAIL FROM domain that you want the verified identity to use. The MAIL FROM /// domain must meet the following criteria:</p> /// <ul> /// <li> /// <p>It has to be a subdomain of the verified identity.</p> /// </li> /// <li> /// <p>It can't be used to receive email.</p> /// </li> /// <li> /// <p>It can't be used in a "From" address if the MAIL FROM domain is a destination /// for feedback forwarding emails.</p> /// </li> /// </ul> pub fn mail_from_domain(&self) -> std::option::Option<&str> { self.mail_from_domain.as_deref() } /// <p>The action to take if the required MX record isn't found when you send an email. When /// you set this value to <code>UseDefaultValue</code>, the mail is sent using /// <i>amazonses.com</i> as the MAIL FROM domain. When you set this value /// to <code>RejectMessage</code>, the Amazon SES API v2 returns a /// <code>MailFromDomainNotVerified</code> error, and doesn't attempt to deliver the /// email.</p> /// <p>These behaviors are taken when the custom MAIL FROM domain configuration is in the /// <code>Pending</code>, <code>Failed</code>, and <code>TemporaryFailure</code> /// states.</p> pub fn behavior_on_mx_failure( &self, ) -> std::option::Option<&crate::model::BehaviorOnMxFailure> { self.behavior_on_mx_failure.as_ref() } } impl std::fmt::Debug for PutEmailIdentityMailFromAttributesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutEmailIdentityMailFromAttributesInput"); formatter.field("email_identity", &self.email_identity); formatter.field("mail_from_domain", &self.mail_from_domain); formatter.field("behavior_on_mx_failure", &self.behavior_on_mx_failure); formatter.finish() } } /// <p>A request to set the attributes that control how bounce and complaint events are /// processed.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutEmailIdentityFeedbackAttributesInput { /// <p>The email identity.</p> pub email_identity: std::option::Option<std::string::String>, /// <p>Sets the feedback forwarding configuration for the identity.</p> /// <p>If the value is <code>true</code>, you receive email notifications when bounce or /// complaint events occur. These notifications are sent to the address that you specified /// in the <code>Return-Path</code> header of the original email.</p> /// <p>You're required to have a method of tracking bounces and complaints. If you haven't /// set up another mechanism for receiving bounce or complaint notifications (for example, /// by setting up an event destination), you receive an email notification when these events /// occur (even if this setting is disabled).</p> pub email_forwarding_enabled: bool, } impl PutEmailIdentityFeedbackAttributesInput { /// <p>The email identity.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } /// <p>Sets the feedback forwarding configuration for the identity.</p> /// <p>If the value is <code>true</code>, you receive email notifications when bounce or /// complaint events occur. These notifications are sent to the address that you specified /// in the <code>Return-Path</code> header of the original email.</p> /// <p>You're required to have a method of tracking bounces and complaints. If you haven't /// set up another mechanism for receiving bounce or complaint notifications (for example, /// by setting up an event destination), you receive an email notification when these events /// occur (even if this setting is disabled).</p> pub fn email_forwarding_enabled(&self) -> bool { self.email_forwarding_enabled } } impl std::fmt::Debug for PutEmailIdentityFeedbackAttributesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutEmailIdentityFeedbackAttributesInput"); formatter.field("email_identity", &self.email_identity); formatter.field("email_forwarding_enabled", &self.email_forwarding_enabled); formatter.finish() } } /// <p>A request to change the DKIM attributes for an email identity.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutEmailIdentityDkimSigningAttributesInput { /// <p>The email identity.</p> pub email_identity: std::option::Option<std::string::String>, /// <p>The method to use to configure DKIM for the identity. There are the following possible /// values:</p> /// <ul> /// <li> /// <p> /// <code>AWS_SES</code> – Configure DKIM for the identity by using <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy /// DKIM</a>.</p> /// </li> /// <li> /// <p> /// <code>EXTERNAL</code> – Configure DKIM for the identity by using Bring /// Your Own DKIM (BYODKIM).</p> /// </li> /// </ul> pub signing_attributes_origin: std::option::Option<crate::model::DkimSigningAttributesOrigin>, /// <p>An object that contains information about the private key and selector that you want /// to use to configure DKIM for the identity for Bring Your Own DKIM (BYODKIM) for the identity, or, /// configures the key length to be used for /// <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy DKIM</a>.</p> pub signing_attributes: std::option::Option<crate::model::DkimSigningAttributes>, } impl PutEmailIdentityDkimSigningAttributesInput { /// <p>The email identity.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } /// <p>The method to use to configure DKIM for the identity. There are the following possible /// values:</p> /// <ul> /// <li> /// <p> /// <code>AWS_SES</code> – Configure DKIM for the identity by using <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy /// DKIM</a>.</p> /// </li> /// <li> /// <p> /// <code>EXTERNAL</code> – Configure DKIM for the identity by using Bring /// Your Own DKIM (BYODKIM).</p> /// </li> /// </ul> pub fn signing_attributes_origin( &self, ) -> std::option::Option<&crate::model::DkimSigningAttributesOrigin> { self.signing_attributes_origin.as_ref() } /// <p>An object that contains information about the private key and selector that you want /// to use to configure DKIM for the identity for Bring Your Own DKIM (BYODKIM) for the identity, or, /// configures the key length to be used for /// <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy DKIM</a>.</p> pub fn signing_attributes(&self) -> std::option::Option<&crate::model::DkimSigningAttributes> { self.signing_attributes.as_ref() } } impl std::fmt::Debug for PutEmailIdentityDkimSigningAttributesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutEmailIdentityDkimSigningAttributesInput"); formatter.field("email_identity", &self.email_identity); formatter.field("signing_attributes_origin", &self.signing_attributes_origin); formatter.field("signing_attributes", &self.signing_attributes); formatter.finish() } } /// <p>A request to enable or disable DKIM signing of email that you send from an email /// identity.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutEmailIdentityDkimAttributesInput { /// <p>The email identity.</p> pub email_identity: std::option::Option<std::string::String>, /// <p>Sets the DKIM signing configuration for the identity.</p> /// <p>When you set this value <code>true</code>, then the messages that are sent from the /// identity are signed using DKIM. If you set this value to <code>false</code>, your /// messages are sent without DKIM signing.</p> pub signing_enabled: bool, } impl PutEmailIdentityDkimAttributesInput { /// <p>The email identity.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } /// <p>Sets the DKIM signing configuration for the identity.</p> /// <p>When you set this value <code>true</code>, then the messages that are sent from the /// identity are signed using DKIM. If you set this value to <code>false</code>, your /// messages are sent without DKIM signing.</p> pub fn signing_enabled(&self) -> bool { self.signing_enabled } } impl std::fmt::Debug for PutEmailIdentityDkimAttributesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutEmailIdentityDkimAttributesInput"); formatter.field("email_identity", &self.email_identity); formatter.field("signing_enabled", &self.signing_enabled); formatter.finish() } } /// <p>A request to associate a configuration set with an email identity.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutEmailIdentityConfigurationSetAttributesInput { /// <p>The email address or domain to associate with a configuration set.</p> pub email_identity: std::option::Option<std::string::String>, /// <p>The configuration set to associate with an email identity.</p> pub configuration_set_name: std::option::Option<std::string::String>, } impl PutEmailIdentityConfigurationSetAttributesInput { /// <p>The email address or domain to associate with a configuration set.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } /// <p>The configuration set to associate with an email identity.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } } impl std::fmt::Debug for PutEmailIdentityConfigurationSetAttributesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutEmailIdentityConfigurationSetAttributesInput"); formatter.field("email_identity", &self.email_identity); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.finish() } } /// <p>Enable or disable the Deliverability dashboard. When you enable the Deliverability dashboard, you gain /// access to reputation, deliverability, and other metrics for the domains that you use to /// send email using Amazon SES API v2. You also gain the ability to perform predictive inbox placement tests.</p> /// <p>When you use the Deliverability dashboard, you pay a monthly subscription charge, in addition /// to any other fees that you accrue by using Amazon SES and other Amazon Web Services services. For more /// information about the features and cost of a Deliverability dashboard subscription, see <a href="http://aws.amazon.com/pinpoint/pricing/">Amazon Pinpoint Pricing</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutDeliverabilityDashboardOptionInput { /// <p>Specifies whether to enable the Deliverability dashboard. To enable the dashboard, set this /// value to <code>true</code>.</p> pub dashboard_enabled: bool, /// <p>An array of objects, one for each verified domain that you use to send email and /// enabled the Deliverability dashboard for.</p> pub subscribed_domains: std::option::Option<std::vec::Vec<crate::model::DomainDeliverabilityTrackingOption>>, } impl PutDeliverabilityDashboardOptionInput { /// <p>Specifies whether to enable the Deliverability dashboard. To enable the dashboard, set this /// value to <code>true</code>.</p> pub fn dashboard_enabled(&self) -> bool { self.dashboard_enabled } /// <p>An array of objects, one for each verified domain that you use to send email and /// enabled the Deliverability dashboard for.</p> pub fn subscribed_domains( &self, ) -> std::option::Option<&[crate::model::DomainDeliverabilityTrackingOption]> { self.subscribed_domains.as_deref() } } impl std::fmt::Debug for PutDeliverabilityDashboardOptionInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutDeliverabilityDashboardOptionInput"); formatter.field("dashboard_enabled", &self.dashboard_enabled); formatter.field("subscribed_domains", &self.subscribed_domains); formatter.finish() } } /// <p>A request to change the warm-up attributes for a dedicated IP address. This operation /// is useful when you want to resume the warm-up process for an existing IP address.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutDedicatedIpWarmupAttributesInput { /// <p>The dedicated IP address that you want to update the warm-up attributes for.</p> pub ip: std::option::Option<std::string::String>, /// <p>The warm-up percentage that you want to associate with the dedicated IP /// address.</p> pub warmup_percentage: std::option::Option<i32>, } impl PutDedicatedIpWarmupAttributesInput { /// <p>The dedicated IP address that you want to update the warm-up attributes for.</p> pub fn ip(&self) -> std::option::Option<&str> { self.ip.as_deref() } /// <p>The warm-up percentage that you want to associate with the dedicated IP /// address.</p> pub fn warmup_percentage(&self) -> std::option::Option<i32> { self.warmup_percentage } } impl std::fmt::Debug for PutDedicatedIpWarmupAttributesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutDedicatedIpWarmupAttributesInput"); formatter.field("ip", &self.ip); formatter.field("warmup_percentage", &self.warmup_percentage); formatter.finish() } } /// <p>A request to move a dedicated IP address to a dedicated IP pool.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutDedicatedIpInPoolInput { /// <p>The IP address that you want to move to the dedicated IP pool. The value you specify /// has to be a dedicated IP address that's associated with your Amazon Web Services account.</p> pub ip: std::option::Option<std::string::String>, /// <p>The name of the IP pool that you want to add the dedicated IP address to. You have to /// specify an IP pool that already exists.</p> pub destination_pool_name: std::option::Option<std::string::String>, } impl PutDedicatedIpInPoolInput { /// <p>The IP address that you want to move to the dedicated IP pool. The value you specify /// has to be a dedicated IP address that's associated with your Amazon Web Services account.</p> pub fn ip(&self) -> std::option::Option<&str> { self.ip.as_deref() } /// <p>The name of the IP pool that you want to add the dedicated IP address to. You have to /// specify an IP pool that already exists.</p> pub fn destination_pool_name(&self) -> std::option::Option<&str> { self.destination_pool_name.as_deref() } } impl std::fmt::Debug for PutDedicatedIpInPoolInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutDedicatedIpInPoolInput"); formatter.field("ip", &self.ip); formatter.field("destination_pool_name", &self.destination_pool_name); formatter.finish() } } /// <p>A request to add a custom domain for tracking open and click events to a configuration /// set.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutConfigurationSetTrackingOptionsInput { /// <p>The name of the configuration set.</p> pub configuration_set_name: std::option::Option<std::string::String>, /// <p>The domain to use to track open and click events.</p> pub custom_redirect_domain: std::option::Option<std::string::String>, } impl PutConfigurationSetTrackingOptionsInput { /// <p>The name of the configuration set.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } /// <p>The domain to use to track open and click events.</p> pub fn custom_redirect_domain(&self) -> std::option::Option<&str> { self.custom_redirect_domain.as_deref() } } impl std::fmt::Debug for PutConfigurationSetTrackingOptionsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutConfigurationSetTrackingOptionsInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.field("custom_redirect_domain", &self.custom_redirect_domain); formatter.finish() } } /// <p>A request to change the account suppression list preferences for a specific /// configuration set.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutConfigurationSetSuppressionOptionsInput { /// <p>The name of the configuration set to change the suppression list preferences /// for.</p> pub configuration_set_name: std::option::Option<std::string::String>, /// <p>A list that contains the reasons that email addresses are automatically added to the /// suppression list for your account. This list can contain any or all of the /// following:</p> /// <ul> /// <li> /// <p> /// <code>COMPLAINT</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a /// complaint.</p> /// </li> /// <li> /// <p> /// <code>BOUNCE</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a hard /// bounce.</p> /// </li> /// </ul> pub suppressed_reasons: std::option::Option<std::vec::Vec<crate::model::SuppressionListReason>>, } impl PutConfigurationSetSuppressionOptionsInput { /// <p>The name of the configuration set to change the suppression list preferences /// for.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } /// <p>A list that contains the reasons that email addresses are automatically added to the /// suppression list for your account. This list can contain any or all of the /// following:</p> /// <ul> /// <li> /// <p> /// <code>COMPLAINT</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a /// complaint.</p> /// </li> /// <li> /// <p> /// <code>BOUNCE</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a hard /// bounce.</p> /// </li> /// </ul> pub fn suppressed_reasons( &self, ) -> std::option::Option<&[crate::model::SuppressionListReason]> { self.suppressed_reasons.as_deref() } } impl std::fmt::Debug for PutConfigurationSetSuppressionOptionsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutConfigurationSetSuppressionOptionsInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.field("suppressed_reasons", &self.suppressed_reasons); formatter.finish() } } /// <p>A request to enable or disable the ability of Amazon SES to send emails that use a specific /// configuration set.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutConfigurationSetSendingOptionsInput { /// <p>The name of the configuration set to enable or disable email sending for.</p> pub configuration_set_name: std::option::Option<std::string::String>, /// <p>If <code>true</code>, email sending is enabled for the configuration set. If /// <code>false</code>, email sending is disabled for the configuration set.</p> pub sending_enabled: bool, } impl PutConfigurationSetSendingOptionsInput { /// <p>The name of the configuration set to enable or disable email sending for.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } /// <p>If <code>true</code>, email sending is enabled for the configuration set. If /// <code>false</code>, email sending is disabled for the configuration set.</p> pub fn sending_enabled(&self) -> bool { self.sending_enabled } } impl std::fmt::Debug for PutConfigurationSetSendingOptionsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutConfigurationSetSendingOptionsInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.field("sending_enabled", &self.sending_enabled); formatter.finish() } } /// <p>A request to enable or disable tracking of reputation metrics for a configuration /// set.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutConfigurationSetReputationOptionsInput { /// <p>The name of the configuration set.</p> pub configuration_set_name: std::option::Option<std::string::String>, /// <p>If <code>true</code>, tracking of reputation metrics is enabled for the configuration /// set. If <code>false</code>, tracking of reputation metrics is disabled for the /// configuration set.</p> pub reputation_metrics_enabled: bool, } impl PutConfigurationSetReputationOptionsInput { /// <p>The name of the configuration set.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } /// <p>If <code>true</code>, tracking of reputation metrics is enabled for the configuration /// set. If <code>false</code>, tracking of reputation metrics is disabled for the /// configuration set.</p> pub fn reputation_metrics_enabled(&self) -> bool { self.reputation_metrics_enabled } } impl std::fmt::Debug for PutConfigurationSetReputationOptionsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutConfigurationSetReputationOptionsInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.field( "reputation_metrics_enabled", &self.reputation_metrics_enabled, ); formatter.finish() } } /// <p>A request to associate a configuration set with a dedicated IP pool.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutConfigurationSetDeliveryOptionsInput { /// <p>The name of the configuration set to associate with a dedicated IP pool.</p> pub configuration_set_name: std::option::Option<std::string::String>, /// <p>Specifies whether messages that use the configuration set are required to use /// Transport Layer Security (TLS). If the value is <code>Require</code>, messages are only /// delivered if a TLS connection can be established. If the value is <code>Optional</code>, /// messages can be delivered in plain text if a TLS connection can't be established.</p> pub tls_policy: std::option::Option<crate::model::TlsPolicy>, /// <p>The name of the dedicated IP pool to associate with the configuration set.</p> pub sending_pool_name: std::option::Option<std::string::String>, } impl PutConfigurationSetDeliveryOptionsInput { /// <p>The name of the configuration set to associate with a dedicated IP pool.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } /// <p>Specifies whether messages that use the configuration set are required to use /// Transport Layer Security (TLS). If the value is <code>Require</code>, messages are only /// delivered if a TLS connection can be established. If the value is <code>Optional</code>, /// messages can be delivered in plain text if a TLS connection can't be established.</p> pub fn tls_policy(&self) -> std::option::Option<&crate::model::TlsPolicy> { self.tls_policy.as_ref() } /// <p>The name of the dedicated IP pool to associate with the configuration set.</p> pub fn sending_pool_name(&self) -> std::option::Option<&str> { self.sending_pool_name.as_deref() } } impl std::fmt::Debug for PutConfigurationSetDeliveryOptionsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutConfigurationSetDeliveryOptionsInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.field("tls_policy", &self.tls_policy); formatter.field("sending_pool_name", &self.sending_pool_name); formatter.finish() } } /// <p>A request to change your account's suppression preferences.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutAccountSuppressionAttributesInput { /// <p>A list that contains the reasons that email addresses will be automatically added to /// the suppression list for your account. This list can contain any or all of the /// following:</p> /// <ul> /// <li> /// <p> /// <code>COMPLAINT</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a /// complaint.</p> /// </li> /// <li> /// <p> /// <code>BOUNCE</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a hard /// bounce.</p> /// </li> /// </ul> pub suppressed_reasons: std::option::Option<std::vec::Vec<crate::model::SuppressionListReason>>, } impl PutAccountSuppressionAttributesInput { /// <p>A list that contains the reasons that email addresses will be automatically added to /// the suppression list for your account. This list can contain any or all of the /// following:</p> /// <ul> /// <li> /// <p> /// <code>COMPLAINT</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a /// complaint.</p> /// </li> /// <li> /// <p> /// <code>BOUNCE</code> – Amazon SES adds an email address to the suppression /// list for your account when a message sent to that address results in a hard /// bounce.</p> /// </li> /// </ul> pub fn suppressed_reasons( &self, ) -> std::option::Option<&[crate::model::SuppressionListReason]> { self.suppressed_reasons.as_deref() } } impl std::fmt::Debug for PutAccountSuppressionAttributesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutAccountSuppressionAttributesInput"); formatter.field("suppressed_reasons", &self.suppressed_reasons); formatter.finish() } } /// <p>A request to change the ability of your account to send email.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutAccountSendingAttributesInput { /// <p>Enables or disables your account's ability to send email. Set to <code>true</code> to /// enable email sending, or set to <code>false</code> to disable email sending.</p> /// <note> /// <p>If Amazon Web Services paused your account's ability to send email, you can't use this operation /// to resume your account's ability to send email.</p> /// </note> pub sending_enabled: bool, } impl PutAccountSendingAttributesInput { /// <p>Enables or disables your account's ability to send email. Set to <code>true</code> to /// enable email sending, or set to <code>false</code> to disable email sending.</p> /// <note> /// <p>If Amazon Web Services paused your account's ability to send email, you can't use this operation /// to resume your account's ability to send email.</p> /// </note> pub fn sending_enabled(&self) -> bool { self.sending_enabled } } impl std::fmt::Debug for PutAccountSendingAttributesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutAccountSendingAttributesInput"); formatter.field("sending_enabled", &self.sending_enabled); formatter.finish() } } /// <p>A request to submit new account details.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutAccountDetailsInput { /// <p>The type of email your account will send.</p> pub mail_type: std::option::Option<crate::model::MailType>, /// <p>The URL of your website. This information helps us better understand the type of /// content that you plan to send.</p> pub website_url: std::option::Option<std::string::String>, /// <p>The language you would prefer to be contacted with.</p> pub contact_language: std::option::Option<crate::model::ContactLanguage>, /// <p>A description of the types of email that you plan to send.</p> pub use_case_description: std::option::Option<std::string::String>, /// <p>Additional email addresses that you would like to be notified regarding Amazon SES /// matters.</p> pub additional_contact_email_addresses: std::option::Option<std::vec::Vec<std::string::String>>, /// <p>Indicates whether or not your account should have production access in the current /// Amazon Web Services Region.</p> /// <p>If the value is <code>false</code>, then your account is in the /// <i>sandbox</i>. When your account is in the sandbox, you can only send /// email to verified identities. Additionally, the maximum number of emails you can send in /// a 24-hour period (your sending quota) is 200, and the maximum number of emails you can /// send per second (your maximum sending rate) is 1.</p> /// <p>If the value is <code>true</code>, then your account has production access. When your /// account has production access, you can send email to any address. The sending quota and /// maximum sending rate for your account vary based on your specific use case.</p> pub production_access_enabled: std::option::Option<bool>, } impl PutAccountDetailsInput { /// <p>The type of email your account will send.</p> pub fn mail_type(&self) -> std::option::Option<&crate::model::MailType> { self.mail_type.as_ref() } /// <p>The URL of your website. This information helps us better understand the type of /// content that you plan to send.</p> pub fn website_url(&self) -> std::option::Option<&str> { self.website_url.as_deref() } /// <p>The language you would prefer to be contacted with.</p> pub fn contact_language(&self) -> std::option::Option<&crate::model::ContactLanguage> { self.contact_language.as_ref() } /// <p>A description of the types of email that you plan to send.</p> pub fn use_case_description(&self) -> std::option::Option<&str> { self.use_case_description.as_deref() } /// <p>Additional email addresses that you would like to be notified regarding Amazon SES /// matters.</p> pub fn additional_contact_email_addresses( &self, ) -> std::option::Option<&[std::string::String]> { self.additional_contact_email_addresses.as_deref() } /// <p>Indicates whether or not your account should have production access in the current /// Amazon Web Services Region.</p> /// <p>If the value is <code>false</code>, then your account is in the /// <i>sandbox</i>. When your account is in the sandbox, you can only send /// email to verified identities. Additionally, the maximum number of emails you can send in /// a 24-hour period (your sending quota) is 200, and the maximum number of emails you can /// send per second (your maximum sending rate) is 1.</p> /// <p>If the value is <code>true</code>, then your account has production access. When your /// account has production access, you can send email to any address. The sending quota and /// maximum sending rate for your account vary based on your specific use case.</p> pub fn production_access_enabled(&self) -> std::option::Option<bool> { self.production_access_enabled } } impl std::fmt::Debug for PutAccountDetailsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutAccountDetailsInput"); formatter.field("mail_type", &self.mail_type); formatter.field("website_url", &"*** Sensitive Data Redacted ***"); formatter.field("contact_language", &self.contact_language); formatter.field("use_case_description", &"*** Sensitive Data Redacted ***"); formatter.field( "additional_contact_email_addresses", &"*** Sensitive Data Redacted ***", ); formatter.field("production_access_enabled", &self.production_access_enabled); formatter.finish() } } /// <p>A request to enable or disable the automatic IP address warm-up feature.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct PutAccountDedicatedIpWarmupAttributesInput { /// <p>Enables or disables the automatic warm-up feature for dedicated IP addresses that are /// associated with your Amazon SES account in the current Amazon Web Services Region. Set to <code>true</code> /// to enable the automatic warm-up feature, or set to <code>false</code> to disable /// it.</p> pub auto_warmup_enabled: bool, } impl PutAccountDedicatedIpWarmupAttributesInput { /// <p>Enables or disables the automatic warm-up feature for dedicated IP addresses that are /// associated with your Amazon SES account in the current Amazon Web Services Region. Set to <code>true</code> /// to enable the automatic warm-up feature, or set to <code>false</code> to disable /// it.</p> pub fn auto_warmup_enabled(&self) -> bool { self.auto_warmup_enabled } } impl std::fmt::Debug for PutAccountDedicatedIpWarmupAttributesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("PutAccountDedicatedIpWarmupAttributesInput"); formatter.field("auto_warmup_enabled", &self.auto_warmup_enabled); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListTagsForResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource that you want to retrieve tag /// information for.</p> pub resource_arn: std::option::Option<std::string::String>, } impl ListTagsForResourceInput { /// <p>The Amazon Resource Name (ARN) of the resource that you want to retrieve tag /// information for.</p> pub fn resource_arn(&self) -> std::option::Option<&str> { self.resource_arn.as_deref() } } 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_arn", &self.resource_arn); formatter.finish() } } /// <p>A request to obtain a list of email destinations that are on the suppression list for /// your account.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListSuppressedDestinationsInput { /// <p>The factors that caused the email address to be added to .</p> pub reasons: std::option::Option<std::vec::Vec<crate::model::SuppressionListReason>>, /// <p>Used to filter the list of suppressed email destinations so that it only includes /// addresses that were added to the list after a specific date. The date that you specify /// should be in Unix time format.</p> pub start_date: std::option::Option<aws_smithy_types::DateTime>, /// <p>Used to filter the list of suppressed email destinations so that it only includes /// addresses that were added to the list before a specific date. The date that you specify /// should be in Unix time format.</p> pub end_date: std::option::Option<aws_smithy_types::DateTime>, /// <p>A token returned from a previous call to <code>ListSuppressedDestinations</code> to /// indicate the position in the list of suppressed email addresses.</p> pub next_token: std::option::Option<std::string::String>, /// <p>The number of results to show in a single call to /// <code>ListSuppressedDestinations</code>. If the number of results is larger than the /// number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> pub page_size: std::option::Option<i32>, } impl ListSuppressedDestinationsInput { /// <p>The factors that caused the email address to be added to .</p> pub fn reasons(&self) -> std::option::Option<&[crate::model::SuppressionListReason]> { self.reasons.as_deref() } /// <p>Used to filter the list of suppressed email destinations so that it only includes /// addresses that were added to the list after a specific date. The date that you specify /// should be in Unix time format.</p> pub fn start_date(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.start_date.as_ref() } /// <p>Used to filter the list of suppressed email destinations so that it only includes /// addresses that were added to the list before a specific date. The date that you specify /// should be in Unix time format.</p> pub fn end_date(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.end_date.as_ref() } /// <p>A token returned from a previous call to <code>ListSuppressedDestinations</code> to /// indicate the position in the list of suppressed email addresses.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } /// <p>The number of results to show in a single call to /// <code>ListSuppressedDestinations</code>. If the number of results is larger than the /// number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } } impl std::fmt::Debug for ListSuppressedDestinationsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListSuppressedDestinationsInput"); formatter.field("reasons", &self.reasons); formatter.field("start_date", &self.start_date); formatter.field("end_date", &self.end_date); formatter.field("next_token", &self.next_token); formatter.field("page_size", &self.page_size); formatter.finish() } } /// <p>Represents a request to list all of the import jobs for a data destination within the /// specified maximum number of import jobs.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListImportJobsInput { /// <p>The destination of the import job, which can be used to list import jobs that have a /// certain <code>ImportDestinationType</code>.</p> pub import_destination_type: std::option::Option<crate::model::ImportDestinationType>, /// <p>A string token indicating that there might be additional import jobs available to be /// listed. Copy this token to a subsequent call to <code>ListImportJobs</code> with the /// same parameters to retrieve the next page of import jobs.</p> pub next_token: std::option::Option<std::string::String>, /// <p>Maximum number of import jobs to return at once. Use this parameter to paginate /// results. If additional import jobs exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// addresses.</p> pub page_size: std::option::Option<i32>, } impl ListImportJobsInput { /// <p>The destination of the import job, which can be used to list import jobs that have a /// certain <code>ImportDestinationType</code>.</p> pub fn import_destination_type( &self, ) -> std::option::Option<&crate::model::ImportDestinationType> { self.import_destination_type.as_ref() } /// <p>A string token indicating that there might be additional import jobs available to be /// listed. Copy this token to a subsequent call to <code>ListImportJobs</code> with the /// same parameters to retrieve the next page of import jobs.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } /// <p>Maximum number of import jobs to return at once. Use this parameter to paginate /// results. If additional import jobs exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// addresses.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } } impl std::fmt::Debug for ListImportJobsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListImportJobsInput"); formatter.field("import_destination_type", &self.import_destination_type); formatter.field("next_token", &self.next_token); formatter.field("page_size", &self.page_size); formatter.finish() } } /// <p>Represents a request to list the email templates present in your Amazon SES account in the /// current Amazon Web Services Region. For more information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html">Amazon SES Developer /// Guide</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListEmailTemplatesInput { /// <p>A token returned from a previous call to <code>ListEmailTemplates</code> to indicate /// the position in the list of email templates.</p> pub next_token: std::option::Option<std::string::String>, /// <p>The number of results to show in a single call to <code>ListEmailTemplates</code>. If the number of /// results is larger than the number you specified in this parameter, then the response /// includes a <code>NextToken</code> element, which you can use to obtain additional results.</p> /// <p>The value you specify has to be at least 1, and can be no more than 10.</p> pub page_size: std::option::Option<i32>, } impl ListEmailTemplatesInput { /// <p>A token returned from a previous call to <code>ListEmailTemplates</code> to indicate /// the position in the list of email templates.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } /// <p>The number of results to show in a single call to <code>ListEmailTemplates</code>. If the number of /// results is larger than the number you specified in this parameter, then the response /// includes a <code>NextToken</code> element, which you can use to obtain additional results.</p> /// <p>The value you specify has to be at least 1, and can be no more than 10.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } } impl std::fmt::Debug for ListEmailTemplatesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListEmailTemplatesInput"); formatter.field("next_token", &self.next_token); formatter.field("page_size", &self.page_size); formatter.finish() } } /// <p>A request to list all of the email identities associated with your Amazon Web Services account. This /// list includes identities that you've already verified, identities that are unverified, /// and identities that were verified in the past, but are no longer verified.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListEmailIdentitiesInput { /// <p>A token returned from a previous call to <code>ListEmailIdentities</code> to indicate /// the position in the list of identities.</p> pub next_token: std::option::Option<std::string::String>, /// <p>The number of results to show in a single call to <code>ListEmailIdentities</code>. If /// the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> /// <p>The value you specify has to be at least 0, and can be no more than 1000.</p> pub page_size: std::option::Option<i32>, } impl ListEmailIdentitiesInput { /// <p>A token returned from a previous call to <code>ListEmailIdentities</code> to indicate /// the position in the list of identities.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } /// <p>The number of results to show in a single call to <code>ListEmailIdentities</code>. If /// the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> /// <p>The value you specify has to be at least 0, and can be no more than 1000.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } } impl std::fmt::Debug for ListEmailIdentitiesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListEmailIdentitiesInput"); formatter.field("next_token", &self.next_token); formatter.field("page_size", &self.page_size); formatter.finish() } } /// <p>Retrieve deliverability data for all the campaigns that used a specific domain to send /// email during a specified time range. This data is available for a domain only if you /// enabled the Deliverability dashboard.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListDomainDeliverabilityCampaignsInput { /// <p>The first day, in Unix time format, that you want to obtain deliverability data /// for.</p> pub start_date: std::option::Option<aws_smithy_types::DateTime>, /// <p>The last day, in Unix time format, that you want to obtain deliverability data for. /// This value has to be less than or equal to 30 days after the value of the /// <code>StartDate</code> parameter.</p> pub end_date: std::option::Option<aws_smithy_types::DateTime>, /// <p>The domain to obtain deliverability data for.</p> pub subscribed_domain: std::option::Option<std::string::String>, /// <p>A token that’s returned from a previous call to the /// <code>ListDomainDeliverabilityCampaigns</code> operation. This token indicates the /// position of a campaign in the list of campaigns.</p> pub next_token: std::option::Option<std::string::String>, /// <p>The maximum number of results to include in response to a single call to the /// <code>ListDomainDeliverabilityCampaigns</code> operation. If the number of results /// is larger than the number that you specify in this parameter, the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> pub page_size: std::option::Option<i32>, } impl ListDomainDeliverabilityCampaignsInput { /// <p>The first day, in Unix time format, that you want to obtain deliverability data /// for.</p> pub fn start_date(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.start_date.as_ref() } /// <p>The last day, in Unix time format, that you want to obtain deliverability data for. /// This value has to be less than or equal to 30 days after the value of the /// <code>StartDate</code> parameter.</p> pub fn end_date(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.end_date.as_ref() } /// <p>The domain to obtain deliverability data for.</p> pub fn subscribed_domain(&self) -> std::option::Option<&str> { self.subscribed_domain.as_deref() } /// <p>A token that’s returned from a previous call to the /// <code>ListDomainDeliverabilityCampaigns</code> operation. This token indicates the /// position of a campaign in the list of campaigns.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } /// <p>The maximum number of results to include in response to a single call to the /// <code>ListDomainDeliverabilityCampaigns</code> operation. If the number of results /// is larger than the number that you specify in this parameter, the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } } impl std::fmt::Debug for ListDomainDeliverabilityCampaignsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListDomainDeliverabilityCampaignsInput"); formatter.field("start_date", &self.start_date); formatter.field("end_date", &self.end_date); formatter.field("subscribed_domain", &self.subscribed_domain); formatter.field("next_token", &self.next_token); formatter.field("page_size", &self.page_size); formatter.finish() } } /// <p>A request to list all of the predictive inbox placement tests that you've performed.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListDeliverabilityTestReportsInput { /// <p>A token returned from a previous call to <code>ListDeliverabilityTestReports</code> to /// indicate the position in the list of predictive inbox placement tests.</p> pub next_token: std::option::Option<std::string::String>, /// <p>The number of results to show in a single call to /// <code>ListDeliverabilityTestReports</code>. If the number of results is larger than /// the number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> /// <p>The value you specify has to be at least 0, and can be no more than 1000.</p> pub page_size: std::option::Option<i32>, } impl ListDeliverabilityTestReportsInput { /// <p>A token returned from a previous call to <code>ListDeliverabilityTestReports</code> to /// indicate the position in the list of predictive inbox placement tests.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } /// <p>The number of results to show in a single call to /// <code>ListDeliverabilityTestReports</code>. If the number of results is larger than /// the number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> /// <p>The value you specify has to be at least 0, and can be no more than 1000.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } } impl std::fmt::Debug for ListDeliverabilityTestReportsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListDeliverabilityTestReportsInput"); formatter.field("next_token", &self.next_token); formatter.field("page_size", &self.page_size); formatter.finish() } } /// <p>A request to obtain a list of dedicated IP pools.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListDedicatedIpPoolsInput { /// <p>A token returned from a previous call to <code>ListDedicatedIpPools</code> to indicate /// the position in the list of dedicated IP pools.</p> pub next_token: std::option::Option<std::string::String>, /// <p>The number of results to show in a single call to <code>ListDedicatedIpPools</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub page_size: std::option::Option<i32>, } impl ListDedicatedIpPoolsInput { /// <p>A token returned from a previous call to <code>ListDedicatedIpPools</code> to indicate /// the position in the list of dedicated IP pools.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } /// <p>The number of results to show in a single call to <code>ListDedicatedIpPools</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } } impl std::fmt::Debug for ListDedicatedIpPoolsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListDedicatedIpPoolsInput"); formatter.field("next_token", &self.next_token); formatter.field("page_size", &self.page_size); formatter.finish() } } /// <p>Represents a request to list the existing custom verification email templates for your /// account.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListCustomVerificationEmailTemplatesInput { /// <p>A token returned from a previous call to /// <code>ListCustomVerificationEmailTemplates</code> to indicate the position in the /// list of custom verification email templates.</p> pub next_token: std::option::Option<std::string::String>, /// <p>The number of results to show in a single call to /// <code>ListCustomVerificationEmailTemplates</code>. If the number of results is /// larger than the number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> /// <p>The value you specify has to be at least 1, and can be no more than 50.</p> pub page_size: std::option::Option<i32>, } impl ListCustomVerificationEmailTemplatesInput { /// <p>A token returned from a previous call to /// <code>ListCustomVerificationEmailTemplates</code> to indicate the position in the /// list of custom verification email templates.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } /// <p>The number of results to show in a single call to /// <code>ListCustomVerificationEmailTemplates</code>. If the number of results is /// larger than the number you specified in this parameter, then the response includes a /// <code>NextToken</code> element, which you can use to obtain additional /// results.</p> /// <p>The value you specify has to be at least 1, and can be no more than 50.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } } impl std::fmt::Debug for ListCustomVerificationEmailTemplatesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListCustomVerificationEmailTemplatesInput"); formatter.field("next_token", &self.next_token); formatter.field("page_size", &self.page_size); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListContactsInput { /// <p>The name of the contact list.</p> pub contact_list_name: std::option::Option<std::string::String>, /// <p>A filter that can be applied to a list of contacts.</p> pub filter: std::option::Option<crate::model::ListContactsFilter>, /// <p>The number of contacts that may be returned at once, which is dependent on if there /// are more or less contacts than the value of the PageSize. Use this parameter to /// paginate results. If additional contacts exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// contacts.</p> pub page_size: std::option::Option<i32>, /// <p>A string token indicating that there might be additional contacts available to be /// listed. Use the token provided in the Response to use in the subsequent call to /// ListContacts with the same parameters to retrieve the next page of contacts.</p> pub next_token: std::option::Option<std::string::String>, } impl ListContactsInput { /// <p>The name of the contact list.</p> pub fn contact_list_name(&self) -> std::option::Option<&str> { self.contact_list_name.as_deref() } /// <p>A filter that can be applied to a list of contacts.</p> pub fn filter(&self) -> std::option::Option<&crate::model::ListContactsFilter> { self.filter.as_ref() } /// <p>The number of contacts that may be returned at once, which is dependent on if there /// are more or less contacts than the value of the PageSize. Use this parameter to /// paginate results. If additional contacts exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// contacts.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } /// <p>A string token indicating that there might be additional contacts available to be /// listed. Use the token provided in the Response to use in the subsequent call to /// ListContacts with the same parameters to retrieve the next page of contacts.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListContactsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListContactsInput"); formatter.field("contact_list_name", &self.contact_list_name); formatter.field("filter", &self.filter); formatter.field("page_size", &self.page_size); 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 ListContactListsInput { /// <p>Maximum number of contact lists to return at once. Use this parameter to paginate /// results. If additional contact lists exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// lists.</p> pub page_size: std::option::Option<i32>, /// <p>A string token indicating that there might be additional contact lists available to be /// listed. Use the token provided in the Response to use in the subsequent call to /// ListContactLists with the same parameters to retrieve the next page of contact /// lists.</p> pub next_token: std::option::Option<std::string::String>, } impl ListContactListsInput { /// <p>Maximum number of contact lists to return at once. Use this parameter to paginate /// results. If additional contact lists exist beyond the specified limit, the /// <code>NextToken</code> element is sent in the response. Use the /// <code>NextToken</code> value in subsequent requests to retrieve additional /// lists.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } /// <p>A string token indicating that there might be additional contact lists available to be /// listed. Use the token provided in the Response to use in the subsequent call to /// ListContactLists with the same parameters to retrieve the next page of contact /// lists.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListContactListsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListContactListsInput"); formatter.field("page_size", &self.page_size); formatter.field("next_token", &self.next_token); formatter.finish() } } /// <p>A request to obtain a list of configuration sets for your Amazon SES account in the current /// Amazon Web Services Region.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListConfigurationSetsInput { /// <p>A token returned from a previous call to <code>ListConfigurationSets</code> to /// indicate the position in the list of configuration sets.</p> pub next_token: std::option::Option<std::string::String>, /// <p>The number of results to show in a single call to <code>ListConfigurationSets</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub page_size: std::option::Option<i32>, } impl ListConfigurationSetsInput { /// <p>A token returned from a previous call to <code>ListConfigurationSets</code> to /// indicate the position in the list of configuration sets.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } /// <p>The number of results to show in a single call to <code>ListConfigurationSets</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } } impl std::fmt::Debug for ListConfigurationSetsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListConfigurationSetsInput"); formatter.field("next_token", &self.next_token); formatter.field("page_size", &self.page_size); formatter.finish() } } /// <p>A request to retrieve information about an email address that's on the suppression /// list for your account.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetSuppressedDestinationInput { /// <p>The email address that's on the account suppression list.</p> pub email_address: std::option::Option<std::string::String>, } impl GetSuppressedDestinationInput { /// <p>The email address that's on the account suppression list.</p> pub fn email_address(&self) -> std::option::Option<&str> { self.email_address.as_deref() } } impl std::fmt::Debug for GetSuppressedDestinationInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetSuppressedDestinationInput"); formatter.field("email_address", &self.email_address); formatter.finish() } } /// <p>Represents a request for information about an import job using the import job /// ID.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetImportJobInput { /// <p>The ID of the import job.</p> pub job_id: std::option::Option<std::string::String>, } impl GetImportJobInput { /// <p>The ID of the import job.</p> pub fn job_id(&self) -> std::option::Option<&str> { self.job_id.as_deref() } } impl std::fmt::Debug for GetImportJobInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetImportJobInput"); formatter.field("job_id", &self.job_id); formatter.finish() } } /// <p>Represents a request to display the template object (which includes the subject line, /// HTML part and text part) for the template you specify.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetEmailTemplateInput { /// <p>The name of the template.</p> pub template_name: std::option::Option<std::string::String>, } impl GetEmailTemplateInput { /// <p>The name of the template.</p> pub fn template_name(&self) -> std::option::Option<&str> { self.template_name.as_deref() } } impl std::fmt::Debug for GetEmailTemplateInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetEmailTemplateInput"); formatter.field("template_name", &self.template_name); formatter.finish() } } /// <p>A request to return the policies of an email identity.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetEmailIdentityPoliciesInput { /// <p>The email identity.</p> pub email_identity: std::option::Option<std::string::String>, } impl GetEmailIdentityPoliciesInput { /// <p>The email identity.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } } impl std::fmt::Debug for GetEmailIdentityPoliciesInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetEmailIdentityPoliciesInput"); formatter.field("email_identity", &self.email_identity); formatter.finish() } } /// <p>A request to return details about an email identity.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetEmailIdentityInput { /// <p>The email identity.</p> pub email_identity: std::option::Option<std::string::String>, } impl GetEmailIdentityInput { /// <p>The email identity.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } } impl std::fmt::Debug for GetEmailIdentityInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetEmailIdentityInput"); formatter.field("email_identity", &self.email_identity); formatter.finish() } } /// <p>A request to obtain deliverability metrics for a domain.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetDomainStatisticsReportInput { /// <p>The domain that you want to obtain deliverability metrics for.</p> pub domain: std::option::Option<std::string::String>, /// <p>The first day (in Unix time) that you want to obtain domain deliverability metrics /// for.</p> pub start_date: std::option::Option<aws_smithy_types::DateTime>, /// <p>The last day (in Unix time) that you want to obtain domain deliverability metrics for. /// The <code>EndDate</code> that you specify has to be less than or equal to 30 days after /// the <code>StartDate</code>.</p> pub end_date: std::option::Option<aws_smithy_types::DateTime>, } impl GetDomainStatisticsReportInput { /// <p>The domain that you want to obtain deliverability metrics for.</p> pub fn domain(&self) -> std::option::Option<&str> { self.domain.as_deref() } /// <p>The first day (in Unix time) that you want to obtain domain deliverability metrics /// for.</p> pub fn start_date(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.start_date.as_ref() } /// <p>The last day (in Unix time) that you want to obtain domain deliverability metrics for. /// The <code>EndDate</code> that you specify has to be less than or equal to 30 days after /// the <code>StartDate</code>.</p> pub fn end_date(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.end_date.as_ref() } } impl std::fmt::Debug for GetDomainStatisticsReportInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetDomainStatisticsReportInput"); formatter.field("domain", &self.domain); formatter.field("start_date", &self.start_date); formatter.field("end_date", &self.end_date); formatter.finish() } } /// <p>Retrieve all the deliverability data for a specific campaign. This data is available /// for a campaign only if the campaign sent email by using a domain that the /// Deliverability dashboard is enabled for (<code>PutDeliverabilityDashboardOption</code> /// operation).</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetDomainDeliverabilityCampaignInput { /// <p>The unique identifier for the campaign. The Deliverability dashboard automatically generates /// and assigns this identifier to a campaign.</p> pub campaign_id: std::option::Option<std::string::String>, } impl GetDomainDeliverabilityCampaignInput { /// <p>The unique identifier for the campaign. The Deliverability dashboard automatically generates /// and assigns this identifier to a campaign.</p> pub fn campaign_id(&self) -> std::option::Option<&str> { self.campaign_id.as_deref() } } impl std::fmt::Debug for GetDomainDeliverabilityCampaignInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetDomainDeliverabilityCampaignInput"); formatter.field("campaign_id", &self.campaign_id); formatter.finish() } } /// <p>A request to retrieve the results of a predictive inbox placement test.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetDeliverabilityTestReportInput { /// <p>A unique string that identifies the predictive inbox placement test.</p> pub report_id: std::option::Option<std::string::String>, } impl GetDeliverabilityTestReportInput { /// <p>A unique string that identifies the predictive inbox placement test.</p> pub fn report_id(&self) -> std::option::Option<&str> { self.report_id.as_deref() } } impl std::fmt::Debug for GetDeliverabilityTestReportInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetDeliverabilityTestReportInput"); formatter.field("report_id", &self.report_id); formatter.finish() } } /// <p>Retrieve information about the status of the Deliverability dashboard for your Amazon Web Services account. /// When the Deliverability dashboard is enabled, you gain access to reputation, deliverability, and /// other metrics for your domains. You also gain the ability to perform predictive inbox placement tests.</p> /// /// <p>When you use the Deliverability dashboard, you pay a monthly subscription charge, in addition /// to any other fees that you accrue by using Amazon SES and other Amazon Web Services services. For more /// information about the features and cost of a Deliverability dashboard subscription, see <a href="http://aws.amazon.com/pinpoint/pricing/">Amazon Pinpoint Pricing</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetDeliverabilityDashboardOptionsInput {} impl std::fmt::Debug for GetDeliverabilityDashboardOptionsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetDeliverabilityDashboardOptionsInput"); formatter.finish() } } /// <p>A request to obtain more information about dedicated IP pools.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetDedicatedIpsInput { /// <p>The name of the IP pool that the dedicated IP address is associated with.</p> pub pool_name: std::option::Option<std::string::String>, /// <p>A token returned from a previous call to <code>GetDedicatedIps</code> to indicate the /// position of the dedicated IP pool in the list of IP pools.</p> pub next_token: std::option::Option<std::string::String>, /// <p>The number of results to show in a single call to <code>GetDedicatedIpsRequest</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub page_size: std::option::Option<i32>, } impl GetDedicatedIpsInput { /// <p>The name of the IP pool that the dedicated IP address is associated with.</p> pub fn pool_name(&self) -> std::option::Option<&str> { self.pool_name.as_deref() } /// <p>A token returned from a previous call to <code>GetDedicatedIps</code> to indicate the /// position of the dedicated IP pool in the list of IP pools.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } /// <p>The number of results to show in a single call to <code>GetDedicatedIpsRequest</code>. /// If the number of results is larger than the number you specified in this parameter, then /// the response includes a <code>NextToken</code> element, which you can use to obtain /// additional results.</p> pub fn page_size(&self) -> std::option::Option<i32> { self.page_size } } impl std::fmt::Debug for GetDedicatedIpsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetDedicatedIpsInput"); formatter.field("pool_name", &self.pool_name); formatter.field("next_token", &self.next_token); formatter.field("page_size", &self.page_size); formatter.finish() } } /// <p>A request to obtain more information about a dedicated IP address.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetDedicatedIpInput { /// <p>The IP address that you want to obtain more information about. The value you specify /// has to be a dedicated IP address that's assocaited with your Amazon Web Services account.</p> pub ip: std::option::Option<std::string::String>, } impl GetDedicatedIpInput { /// <p>The IP address that you want to obtain more information about. The value you specify /// has to be a dedicated IP address that's assocaited with your Amazon Web Services account.</p> pub fn ip(&self) -> std::option::Option<&str> { self.ip.as_deref() } } impl std::fmt::Debug for GetDedicatedIpInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetDedicatedIpInput"); formatter.field("ip", &self.ip); formatter.finish() } } /// <p>Represents a request to retrieve an existing custom verification email /// template.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetCustomVerificationEmailTemplateInput { /// <p>The name of the custom verification email template that you want to retrieve.</p> pub template_name: std::option::Option<std::string::String>, } impl GetCustomVerificationEmailTemplateInput { /// <p>The name of the custom verification email template that you want to retrieve.</p> pub fn template_name(&self) -> std::option::Option<&str> { self.template_name.as_deref() } } impl std::fmt::Debug for GetCustomVerificationEmailTemplateInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetCustomVerificationEmailTemplateInput"); formatter.field("template_name", &self.template_name); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetContactListInput { /// <p>The name of the contact list.</p> pub contact_list_name: std::option::Option<std::string::String>, } impl GetContactListInput { /// <p>The name of the contact list.</p> pub fn contact_list_name(&self) -> std::option::Option<&str> { self.contact_list_name.as_deref() } } impl std::fmt::Debug for GetContactListInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetContactListInput"); formatter.field("contact_list_name", &self.contact_list_name); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetContactInput { /// <p>The name of the contact list to which the contact belongs.</p> pub contact_list_name: std::option::Option<std::string::String>, /// <p>The contact's email addres.</p> pub email_address: std::option::Option<std::string::String>, } impl GetContactInput { /// <p>The name of the contact list to which the contact belongs.</p> pub fn contact_list_name(&self) -> std::option::Option<&str> { self.contact_list_name.as_deref() } /// <p>The contact's email addres.</p> pub fn email_address(&self) -> std::option::Option<&str> { self.email_address.as_deref() } } impl std::fmt::Debug for GetContactInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetContactInput"); formatter.field("contact_list_name", &self.contact_list_name); formatter.field("email_address", &self.email_address); formatter.finish() } } /// <p>A request to obtain information about the event destinations for a configuration /// set.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetConfigurationSetEventDestinationsInput { /// <p>The name of the configuration set that contains the event destination.</p> pub configuration_set_name: std::option::Option<std::string::String>, } impl GetConfigurationSetEventDestinationsInput { /// <p>The name of the configuration set that contains the event destination.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } } impl std::fmt::Debug for GetConfigurationSetEventDestinationsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetConfigurationSetEventDestinationsInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.finish() } } /// <p>A request to obtain information about a configuration set.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetConfigurationSetInput { /// <p>The name of the configuration set.</p> pub configuration_set_name: std::option::Option<std::string::String>, } impl GetConfigurationSetInput { /// <p>The name of the configuration set.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } } impl std::fmt::Debug for GetConfigurationSetInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetConfigurationSetInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.finish() } } /// <p>A request to retrieve a list of the blacklists that your dedicated IP addresses appear /// on.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetBlacklistReportsInput { /// <p>A list of IP addresses that you want to retrieve blacklist information about. You can /// only specify the dedicated IP addresses that you use to send email using Amazon SES or /// Amazon Pinpoint.</p> pub blacklist_item_names: std::option::Option<std::vec::Vec<std::string::String>>, } impl GetBlacklistReportsInput { /// <p>A list of IP addresses that you want to retrieve blacklist information about. You can /// only specify the dedicated IP addresses that you use to send email using Amazon SES or /// Amazon Pinpoint.</p> pub fn blacklist_item_names(&self) -> std::option::Option<&[std::string::String]> { self.blacklist_item_names.as_deref() } } impl std::fmt::Debug for GetBlacklistReportsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetBlacklistReportsInput"); formatter.field("blacklist_item_names", &self.blacklist_item_names); formatter.finish() } } /// <p>A request to obtain information about the email-sending capabilities of your Amazon SES /// account.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GetAccountInput {} impl std::fmt::Debug for GetAccountInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GetAccountInput"); formatter.finish() } } /// <p>A request to remove an email address from the suppression list for your /// account.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteSuppressedDestinationInput { /// <p>The suppressed email destination to remove from the account suppression list.</p> pub email_address: std::option::Option<std::string::String>, } impl DeleteSuppressedDestinationInput { /// <p>The suppressed email destination to remove from the account suppression list.</p> pub fn email_address(&self) -> std::option::Option<&str> { self.email_address.as_deref() } } impl std::fmt::Debug for DeleteSuppressedDestinationInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteSuppressedDestinationInput"); formatter.field("email_address", &self.email_address); formatter.finish() } } /// <p>Represents a request to delete an email template. For more information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html">Amazon SES Developer /// Guide</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteEmailTemplateInput { /// <p>The name of the template to be deleted.</p> pub template_name: std::option::Option<std::string::String>, } impl DeleteEmailTemplateInput { /// <p>The name of the template to be deleted.</p> pub fn template_name(&self) -> std::option::Option<&str> { self.template_name.as_deref() } } impl std::fmt::Debug for DeleteEmailTemplateInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteEmailTemplateInput"); formatter.field("template_name", &self.template_name); formatter.finish() } } /// <p>Represents a request to delete a sending authorization policy for an identity. Sending /// authorization is an Amazon SES feature that enables you to authorize other senders to /// use your identities. For information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-identity-owner-tasks-management.html">Amazon SES Developer Guide</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteEmailIdentityPolicyInput { /// <p>The email identity.</p> pub email_identity: std::option::Option<std::string::String>, /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub policy_name: std::option::Option<std::string::String>, } impl DeleteEmailIdentityPolicyInput { /// <p>The email identity.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub fn policy_name(&self) -> std::option::Option<&str> { self.policy_name.as_deref() } } impl std::fmt::Debug for DeleteEmailIdentityPolicyInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteEmailIdentityPolicyInput"); formatter.field("email_identity", &self.email_identity); formatter.field("policy_name", &self.policy_name); formatter.finish() } } /// <p>A request to delete an existing email identity. When you delete an identity, you lose /// the ability to send email from that identity. You can restore your ability to send email /// by completing the verification process for the identity again.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteEmailIdentityInput { /// <p>The identity (that is, the email address or domain) to delete.</p> pub email_identity: std::option::Option<std::string::String>, } impl DeleteEmailIdentityInput { /// <p>The identity (that is, the email address or domain) to delete.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } } impl std::fmt::Debug for DeleteEmailIdentityInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteEmailIdentityInput"); formatter.field("email_identity", &self.email_identity); formatter.finish() } } /// <p>A request to delete a dedicated IP pool.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteDedicatedIpPoolInput { /// <p>The name of the dedicated IP pool that you want to delete.</p> pub pool_name: std::option::Option<std::string::String>, } impl DeleteDedicatedIpPoolInput { /// <p>The name of the dedicated IP pool that you want to delete.</p> pub fn pool_name(&self) -> std::option::Option<&str> { self.pool_name.as_deref() } } impl std::fmt::Debug for DeleteDedicatedIpPoolInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteDedicatedIpPoolInput"); formatter.field("pool_name", &self.pool_name); formatter.finish() } } /// <p>Represents a request to delete an existing custom verification email template.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteCustomVerificationEmailTemplateInput { /// <p>The name of the custom verification email template that you want to delete.</p> pub template_name: std::option::Option<std::string::String>, } impl DeleteCustomVerificationEmailTemplateInput { /// <p>The name of the custom verification email template that you want to delete.</p> pub fn template_name(&self) -> std::option::Option<&str> { self.template_name.as_deref() } } impl std::fmt::Debug for DeleteCustomVerificationEmailTemplateInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteCustomVerificationEmailTemplateInput"); formatter.field("template_name", &self.template_name); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteContactListInput { /// <p>The name of the contact list.</p> pub contact_list_name: std::option::Option<std::string::String>, } impl DeleteContactListInput { /// <p>The name of the contact list.</p> pub fn contact_list_name(&self) -> std::option::Option<&str> { self.contact_list_name.as_deref() } } impl std::fmt::Debug for DeleteContactListInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteContactListInput"); formatter.field("contact_list_name", &self.contact_list_name); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteContactInput { /// <p>The name of the contact list from which the contact should be removed.</p> pub contact_list_name: std::option::Option<std::string::String>, /// <p>The contact's email address.</p> pub email_address: std::option::Option<std::string::String>, } impl DeleteContactInput { /// <p>The name of the contact list from which the contact should be removed.</p> pub fn contact_list_name(&self) -> std::option::Option<&str> { self.contact_list_name.as_deref() } /// <p>The contact's email address.</p> pub fn email_address(&self) -> std::option::Option<&str> { self.email_address.as_deref() } } impl std::fmt::Debug for DeleteContactInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteContactInput"); formatter.field("contact_list_name", &self.contact_list_name); formatter.field("email_address", &self.email_address); formatter.finish() } } /// <p>A request to delete an event destination from a configuration set.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteConfigurationSetEventDestinationInput { /// <p>The name of the configuration set that contains the event destination to /// delete.</p> pub configuration_set_name: std::option::Option<std::string::String>, /// <p>The name of the event destination to delete.</p> pub event_destination_name: std::option::Option<std::string::String>, } impl DeleteConfigurationSetEventDestinationInput { /// <p>The name of the configuration set that contains the event destination to /// delete.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } /// <p>The name of the event destination to delete.</p> pub fn event_destination_name(&self) -> std::option::Option<&str> { self.event_destination_name.as_deref() } } impl std::fmt::Debug for DeleteConfigurationSetEventDestinationInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteConfigurationSetEventDestinationInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.field("event_destination_name", &self.event_destination_name); formatter.finish() } } /// <p>A request to delete a configuration set.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteConfigurationSetInput { /// <p>The name of the configuration set.</p> pub configuration_set_name: std::option::Option<std::string::String>, } impl DeleteConfigurationSetInput { /// <p>The name of the configuration set.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } } impl std::fmt::Debug for DeleteConfigurationSetInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteConfigurationSetInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.finish() } } /// <p>Represents a request to create an import job from a data source for a data /// destination.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateImportJobInput { /// <p>The destination for the import job.</p> pub import_destination: std::option::Option<crate::model::ImportDestination>, /// <p>The data source for the import job.</p> pub import_data_source: std::option::Option<crate::model::ImportDataSource>, } impl CreateImportJobInput { /// <p>The destination for the import job.</p> pub fn import_destination(&self) -> std::option::Option<&crate::model::ImportDestination> { self.import_destination.as_ref() } /// <p>The data source for the import job.</p> pub fn import_data_source(&self) -> std::option::Option<&crate::model::ImportDataSource> { self.import_data_source.as_ref() } } impl std::fmt::Debug for CreateImportJobInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateImportJobInput"); formatter.field("import_destination", &self.import_destination); formatter.field("import_data_source", &self.import_data_source); formatter.finish() } } /// <p>Represents a request to create an email template. For more information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html">Amazon SES /// Developer Guide</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateEmailTemplateInput { /// <p>The name of the template.</p> pub template_name: std::option::Option<std::string::String>, /// <p>The content of the email template, composed of a subject line, an HTML part, and a /// text-only part.</p> pub template_content: std::option::Option<crate::model::EmailTemplateContent>, } impl CreateEmailTemplateInput { /// <p>The name of the template.</p> pub fn template_name(&self) -> std::option::Option<&str> { self.template_name.as_deref() } /// <p>The content of the email template, composed of a subject line, an HTML part, and a /// text-only part.</p> pub fn template_content(&self) -> std::option::Option<&crate::model::EmailTemplateContent> { self.template_content.as_ref() } } impl std::fmt::Debug for CreateEmailTemplateInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateEmailTemplateInput"); formatter.field("template_name", &self.template_name); formatter.field("template_content", &self.template_content); formatter.finish() } } /// <p>Represents a request to create a sending authorization policy for an identity. Sending /// authorization is an Amazon SES feature that enables you to authorize other senders to use /// your identities. For information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-identity-owner-tasks-management.html">Amazon SES Developer Guide</a>.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateEmailIdentityPolicyInput { /// <p>The email identity.</p> pub email_identity: std::option::Option<std::string::String>, /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub policy_name: std::option::Option<std::string::String>, /// <p>The text of the policy in JSON format. The policy cannot exceed 4 KB.</p> /// <p>For information about the syntax of sending authorization policies, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES Developer /// Guide</a>.</p> pub policy: std::option::Option<std::string::String>, } impl CreateEmailIdentityPolicyInput { /// <p>The email identity.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } /// <p>The name of the policy.</p> /// /// <p>The policy name cannot exceed 64 characters and can only include alphanumeric /// characters, dashes, and underscores.</p> pub fn policy_name(&self) -> std::option::Option<&str> { self.policy_name.as_deref() } /// <p>The text of the policy in JSON format. The policy cannot exceed 4 KB.</p> /// <p>For information about the syntax of sending authorization policies, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization-policies.html">Amazon SES Developer /// Guide</a>.</p> pub fn policy(&self) -> std::option::Option<&str> { self.policy.as_deref() } } impl std::fmt::Debug for CreateEmailIdentityPolicyInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateEmailIdentityPolicyInput"); formatter.field("email_identity", &self.email_identity); formatter.field("policy_name", &self.policy_name); formatter.field("policy", &self.policy); formatter.finish() } } /// <p>A request to begin the verification process for an email identity (an email address or /// domain).</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateEmailIdentityInput { /// <p>The email address or domain to verify.</p> pub email_identity: std::option::Option<std::string::String>, /// <p>An array of objects that define the tags (keys and values) to associate with the email /// identity.</p> pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, /// <p>If your request includes this object, Amazon SES configures the identity to use Bring Your /// Own DKIM (BYODKIM) for DKIM authentication purposes, or, configures the key length to be used for /// <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy DKIM</a>.</p> /// <p>You can only specify this object if the email identity is a domain, as opposed to an /// address.</p> pub dkim_signing_attributes: std::option::Option<crate::model::DkimSigningAttributes>, /// <p>The configuration set to use by default when sending from this identity. Note that any /// configuration set defined in the email sending request takes precedence. </p> pub configuration_set_name: std::option::Option<std::string::String>, } impl CreateEmailIdentityInput { /// <p>The email address or domain to verify.</p> pub fn email_identity(&self) -> std::option::Option<&str> { self.email_identity.as_deref() } /// <p>An array of objects that define the tags (keys and values) to associate with the email /// identity.</p> pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> { self.tags.as_deref() } /// <p>If your request includes this object, Amazon SES configures the identity to use Bring Your /// Own DKIM (BYODKIM) for DKIM authentication purposes, or, configures the key length to be used for /// <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Easy DKIM</a>.</p> /// <p>You can only specify this object if the email identity is a domain, as opposed to an /// address.</p> pub fn dkim_signing_attributes( &self, ) -> std::option::Option<&crate::model::DkimSigningAttributes> { self.dkim_signing_attributes.as_ref() } /// <p>The configuration set to use by default when sending from this identity. Note that any /// configuration set defined in the email sending request takes precedence. </p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } } impl std::fmt::Debug for CreateEmailIdentityInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateEmailIdentityInput"); formatter.field("email_identity", &self.email_identity); formatter.field("tags", &self.tags); formatter.field("dkim_signing_attributes", &self.dkim_signing_attributes); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.finish() } } /// <p>A request to perform a predictive inbox placement test. Predictive inbox placement tests can help you predict how your messages will /// be handled by various email providers around the world. When you perform a predictive inbox placement test, you /// provide a sample message that contains the content that you plan to send to your /// customers. We send that message to special email addresses spread across several major /// email providers around the world. The test takes about 24 hours to complete. When the /// test is complete, you can use the <code>GetDeliverabilityTestReport</code> operation to /// view the results of the test.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateDeliverabilityTestReportInput { /// <p>A unique name that helps you to identify the predictive inbox placement test when you retrieve the /// results.</p> pub report_name: std::option::Option<std::string::String>, /// <p>The email address that the predictive inbox placement test email was sent from.</p> pub from_email_address: std::option::Option<std::string::String>, /// <p>The HTML body of the message that you sent when you performed the predictive inbox placement test.</p> pub content: std::option::Option<crate::model::EmailContent>, /// <p>An array of objects that define the tags (keys and values) that you want to associate /// with the predictive inbox placement test.</p> pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl CreateDeliverabilityTestReportInput { /// <p>A unique name that helps you to identify the predictive inbox placement test when you retrieve the /// results.</p> pub fn report_name(&self) -> std::option::Option<&str> { self.report_name.as_deref() } /// <p>The email address that the predictive inbox placement test email was sent from.</p> pub fn from_email_address(&self) -> std::option::Option<&str> { self.from_email_address.as_deref() } /// <p>The HTML body of the message that you sent when you performed the predictive inbox placement test.</p> pub fn content(&self) -> std::option::Option<&crate::model::EmailContent> { self.content.as_ref() } /// <p>An array of objects that define the tags (keys and values) that you want to associate /// with the predictive inbox placement test.</p> pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> { self.tags.as_deref() } } impl std::fmt::Debug for CreateDeliverabilityTestReportInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateDeliverabilityTestReportInput"); formatter.field("report_name", &self.report_name); formatter.field("from_email_address", &self.from_email_address); formatter.field("content", &self.content); formatter.field("tags", &self.tags); formatter.finish() } } /// <p>A request to create a new dedicated IP pool.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateDedicatedIpPoolInput { /// <p>The name of the dedicated IP pool.</p> pub pool_name: std::option::Option<std::string::String>, /// <p>An object that defines the tags (keys and values) that you want to associate with the /// pool.</p> pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl CreateDedicatedIpPoolInput { /// <p>The name of the dedicated IP pool.</p> pub fn pool_name(&self) -> std::option::Option<&str> { self.pool_name.as_deref() } /// <p>An object that defines the tags (keys and values) that you want to associate with the /// pool.</p> pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> { self.tags.as_deref() } } impl std::fmt::Debug for CreateDedicatedIpPoolInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateDedicatedIpPoolInput"); formatter.field("pool_name", &self.pool_name); formatter.field("tags", &self.tags); formatter.finish() } } /// <p>Represents a request to create a custom verification email template.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateCustomVerificationEmailTemplateInput { /// <p>The name of the custom verification email template.</p> pub template_name: std::option::Option<std::string::String>, /// <p>The email address that the custom verification email is sent from.</p> pub from_email_address: std::option::Option<std::string::String>, /// <p>The subject line of the custom verification email.</p> pub template_subject: std::option::Option<std::string::String>, /// <p>The content of the custom verification email. The total size of the email must be less /// than 10 MB. The message body may contain HTML, with some limitations. For more /// information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-verify-address-custom.html#custom-verification-emails-faq">Custom Verification Email Frequently Asked Questions</a> in the <i>Amazon SES /// Developer Guide</i>.</p> pub template_content: std::option::Option<std::string::String>, /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is successfully verified.</p> pub success_redirection_url: std::option::Option<std::string::String>, /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is not successfully verified.</p> pub failure_redirection_url: std::option::Option<std::string::String>, } impl CreateCustomVerificationEmailTemplateInput { /// <p>The name of the custom verification email template.</p> pub fn template_name(&self) -> std::option::Option<&str> { self.template_name.as_deref() } /// <p>The email address that the custom verification email is sent from.</p> pub fn from_email_address(&self) -> std::option::Option<&str> { self.from_email_address.as_deref() } /// <p>The subject line of the custom verification email.</p> pub fn template_subject(&self) -> std::option::Option<&str> { self.template_subject.as_deref() } /// <p>The content of the custom verification email. The total size of the email must be less /// than 10 MB. The message body may contain HTML, with some limitations. For more /// information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-verify-address-custom.html#custom-verification-emails-faq">Custom Verification Email Frequently Asked Questions</a> in the <i>Amazon SES /// Developer Guide</i>.</p> pub fn template_content(&self) -> std::option::Option<&str> { self.template_content.as_deref() } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is successfully verified.</p> pub fn success_redirection_url(&self) -> std::option::Option<&str> { self.success_redirection_url.as_deref() } /// <p>The URL that the recipient of the verification email is sent to if his or her address /// is not successfully verified.</p> pub fn failure_redirection_url(&self) -> std::option::Option<&str> { self.failure_redirection_url.as_deref() } } impl std::fmt::Debug for CreateCustomVerificationEmailTemplateInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateCustomVerificationEmailTemplateInput"); formatter.field("template_name", &self.template_name); formatter.field("from_email_address", &self.from_email_address); formatter.field("template_subject", &self.template_subject); formatter.field("template_content", &self.template_content); formatter.field("success_redirection_url", &self.success_redirection_url); formatter.field("failure_redirection_url", &self.failure_redirection_url); formatter.finish() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateContactListInput { /// <p>The name of the contact list.</p> pub contact_list_name: std::option::Option<std::string::String>, /// <p>An interest group, theme, or label within a list. A contact list can have multiple /// topics.</p> pub topics: std::option::Option<std::vec::Vec<crate::model::Topic>>, /// <p>A description of what the contact list is about.</p> pub description: std::option::Option<std::string::String>, /// <p>The tags associated with a contact list.</p> pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, } impl CreateContactListInput { /// <p>The name of the contact list.</p> pub fn contact_list_name(&self) -> std::option::Option<&str> { self.contact_list_name.as_deref() } /// <p>An interest group, theme, or label within a list. A contact list can have multiple /// topics.</p> pub fn topics(&self) -> std::option::Option<&[crate::model::Topic]> { self.topics.as_deref() } /// <p>A description of what the contact list is about.</p> pub fn description(&self) -> std::option::Option<&str> { self.description.as_deref() } /// <p>The tags associated with a contact list.</p> pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> { self.tags.as_deref() } } impl std::fmt::Debug for CreateContactListInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateContactListInput"); formatter.field("contact_list_name", &self.contact_list_name); formatter.field("topics", &self.topics); formatter.field("description", &self.description); 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 CreateContactInput { /// <p>The name of the contact list to which the contact should be added.</p> pub contact_list_name: std::option::Option<std::string::String>, /// <p>The contact's email address.</p> pub email_address: std::option::Option<std::string::String>, /// <p>The contact's preferences for being opted-in to or opted-out of topics.</p> pub topic_preferences: std::option::Option<std::vec::Vec<crate::model::TopicPreference>>, /// <p>A boolean value status noting if the contact is unsubscribed from all contact list /// topics.</p> pub unsubscribe_all: bool, /// <p>The attribute data attached to a contact.</p> pub attributes_data: std::option::Option<std::string::String>, } impl CreateContactInput { /// <p>The name of the contact list to which the contact should be added.</p> pub fn contact_list_name(&self) -> std::option::Option<&str> { self.contact_list_name.as_deref() } /// <p>The contact's email address.</p> pub fn email_address(&self) -> std::option::Option<&str> { self.email_address.as_deref() } /// <p>The contact's preferences for being opted-in to or opted-out of topics.</p> pub fn topic_preferences(&self) -> std::option::Option<&[crate::model::TopicPreference]> { self.topic_preferences.as_deref() } /// <p>A boolean value status noting if the contact is unsubscribed from all contact list /// topics.</p> pub fn unsubscribe_all(&self) -> bool { self.unsubscribe_all } /// <p>The attribute data attached to a contact.</p> pub fn attributes_data(&self) -> std::option::Option<&str> { self.attributes_data.as_deref() } } impl std::fmt::Debug for CreateContactInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateContactInput"); formatter.field("contact_list_name", &self.contact_list_name); formatter.field("email_address", &self.email_address); formatter.field("topic_preferences", &self.topic_preferences); formatter.field("unsubscribe_all", &self.unsubscribe_all); formatter.field("attributes_data", &self.attributes_data); formatter.finish() } } /// <p>A request to add an event destination to a configuration set.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateConfigurationSetEventDestinationInput { /// <p>The name of the configuration set .</p> pub configuration_set_name: std::option::Option<std::string::String>, /// <p>A name that identifies the event destination within the configuration set.</p> pub event_destination_name: std::option::Option<std::string::String>, /// <p>An object that defines the event destination.</p> pub event_destination: std::option::Option<crate::model::EventDestinationDefinition>, } impl CreateConfigurationSetEventDestinationInput { /// <p>The name of the configuration set .</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } /// <p>A name that identifies the event destination within the configuration set.</p> pub fn event_destination_name(&self) -> std::option::Option<&str> { self.event_destination_name.as_deref() } /// <p>An object that defines the event destination.</p> pub fn event_destination( &self, ) -> std::option::Option<&crate::model::EventDestinationDefinition> { self.event_destination.as_ref() } } impl std::fmt::Debug for CreateConfigurationSetEventDestinationInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateConfigurationSetEventDestinationInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.field("event_destination_name", &self.event_destination_name); formatter.field("event_destination", &self.event_destination); formatter.finish() } } /// <p>A request to create a configuration set.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateConfigurationSetInput { /// <p>The name of the configuration set. The name can contain up to 64 alphanumeric /// characters, including letters, numbers, hyphens (-) and underscores (_) only.</p> pub configuration_set_name: std::option::Option<std::string::String>, /// <p>An object that defines the open and click tracking options for emails that you send /// using the configuration set.</p> pub tracking_options: std::option::Option<crate::model::TrackingOptions>, /// <p>An object that defines the dedicated IP pool that is used to send emails that you send /// using the configuration set.</p> pub delivery_options: std::option::Option<crate::model::DeliveryOptions>, /// <p>An object that defines whether or not Amazon SES collects reputation metrics for the emails /// that you send that use the configuration set.</p> pub reputation_options: std::option::Option<crate::model::ReputationOptions>, /// <p>An object that defines whether or not Amazon SES can send email that you send using the /// configuration set.</p> pub sending_options: std::option::Option<crate::model::SendingOptions>, /// <p>An array of objects that define the tags (keys and values) to associate with the /// configuration set.</p> pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>, /// <p>An object that contains information about the suppression list preferences for your /// account.</p> pub suppression_options: std::option::Option<crate::model::SuppressionOptions>, } impl CreateConfigurationSetInput { /// <p>The name of the configuration set. The name can contain up to 64 alphanumeric /// characters, including letters, numbers, hyphens (-) and underscores (_) only.</p> pub fn configuration_set_name(&self) -> std::option::Option<&str> { self.configuration_set_name.as_deref() } /// <p>An object that defines the open and click tracking options for emails that you send /// using the configuration set.</p> pub fn tracking_options(&self) -> std::option::Option<&crate::model::TrackingOptions> { self.tracking_options.as_ref() } /// <p>An object that defines the dedicated IP pool that is used to send emails that you send /// using the configuration set.</p> pub fn delivery_options(&self) -> std::option::Option<&crate::model::DeliveryOptions> { self.delivery_options.as_ref() } /// <p>An object that defines whether or not Amazon SES collects reputation metrics for the emails /// that you send that use the configuration set.</p> pub fn reputation_options(&self) -> std::option::Option<&crate::model::ReputationOptions> { self.reputation_options.as_ref() } /// <p>An object that defines whether or not Amazon SES can send email that you send using the /// configuration set.</p> pub fn sending_options(&self) -> std::option::Option<&crate::model::SendingOptions> { self.sending_options.as_ref() } /// <p>An array of objects that define the tags (keys and values) to associate with the /// configuration set.</p> pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> { self.tags.as_deref() } /// <p>An object that contains information about the suppression list preferences for your /// account.</p> pub fn suppression_options(&self) -> std::option::Option<&crate::model::SuppressionOptions> { self.suppression_options.as_ref() } } impl std::fmt::Debug for CreateConfigurationSetInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateConfigurationSetInput"); formatter.field("configuration_set_name", &self.configuration_set_name); formatter.field("tracking_options", &self.tracking_options); formatter.field("delivery_options", &self.delivery_options); formatter.field("reputation_options", &self.reputation_options); formatter.field("sending_options", &self.sending_options); formatter.field("tags", &self.tags); formatter.field("suppression_options", &self.suppression_options); formatter.finish() } }
45.286629
254
0.622308
fbd7f840da6e15748e2972899771deaa7b5307d5
28,884
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Overloadable operators //! //! Implementing these traits allows you to get an effect similar to //! overloading operators. //! //! Some of these traits are imported by the prelude, so they are available in //! every Rust program. //! //! Many of the operators take their operands by value. In non-generic //! contexts involving built-in types, this is usually not a problem. //! However, using these operators in generic code, requires some //! attention if values have to be reused as opposed to letting the operators //! consume them. One option is to occasionally use `clone()`. //! Another option is to rely on the types involved providing additional //! operator implementations for references. For example, for a user-defined //! type `T` which is supposed to support addition, it is probably a good //! idea to have both `T` and `&T` implement the traits `Add<T>` and `Add<&T>` //! so that generic code can be written without unnecessary cloning. //! //! # Example //! //! This example creates a `Point` struct that implements `Add` and `Sub`, and then //! demonstrates adding and subtracting two `Point`s. //! //! ```rust //! use std::ops::{Add, Sub}; //! //! #[derive(Debug)] //! struct Point { //! x: i32, //! y: i32 //! } //! //! impl Add for Point { //! type Output = Point; //! //! fn add(self, other: Point) -> Point { //! Point {x: self.x + other.x, y: self.y + other.y} //! } //! } //! //! impl Sub for Point { //! type Output = Point; //! //! fn sub(self, other: Point) -> Point { //! Point {x: self.x - other.x, y: self.y - other.y} //! } //! } //! fn main() { //! println!("{:?}", Point {x: 1, y: 0} + Point {x: 2, y: 3}); //! println!("{:?}", Point {x: 1, y: 0} - Point {x: 2, y: 3}); //! } //! ``` //! //! See the documentation for each trait for a minimum implementation that prints //! something to the screen. #![stable(feature = "rust1", since = "1.0.0")] use marker::Sized; use fmt; /// The `Drop` trait is used to run some code when a value goes out of scope. This /// is sometimes called a 'destructor'. /// /// # Example /// /// A trivial implementation of `Drop`. The `drop` method is called when `_x` goes /// out of scope, and therefore `main` prints `Dropping!`. /// /// ```rust /// struct HasDrop; /// /// impl Drop for HasDrop { /// fn drop(&mut self) { /// println!("Dropping!"); /// } /// } /// /// fn main() { /// let _x = HasDrop; /// } /// ``` #[lang="drop"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Drop { /// The `drop` method, called when the value goes out of scope. #[stable(feature = "rust1", since = "1.0.0")] fn drop(&mut self); } // implements the unary operator "op &T" // based on "op T" where T is expected to be `Copy`able macro_rules! forward_ref_unop { (impl $imp:ident, $method:ident for $t:ty) => { #[unstable(feature = "core", reason = "recently added, waiting for dust to settle")] impl<'a> $imp for &'a $t { type Output = <$t as $imp>::Output; #[inline] fn $method(self) -> <$t as $imp>::Output { $imp::$method(*self) } } } } // implements binary operators "&T op U", "T op &U", "&T op &U" // based on "T op U" where T and U are expected to be `Copy`able macro_rules! forward_ref_binop { (impl $imp:ident, $method:ident for $t:ty, $u:ty) => { #[unstable(feature = "core", reason = "recently added, waiting for dust to settle")] impl<'a> $imp<$u> for &'a $t { type Output = <$t as $imp<$u>>::Output; #[inline] fn $method(self, other: $u) -> <$t as $imp<$u>>::Output { $imp::$method(*self, other) } } #[unstable(feature = "core", reason = "recently added, waiting for dust to settle")] impl<'a> $imp<&'a $u> for $t { type Output = <$t as $imp<$u>>::Output; #[inline] fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output { $imp::$method(self, *other) } } #[unstable(feature = "core", reason = "recently added, waiting for dust to settle")] impl<'a, 'b> $imp<&'a $u> for &'b $t { type Output = <$t as $imp<$u>>::Output; #[inline] fn $method(self, other: &'a $u) -> <$t as $imp<$u>>::Output { $imp::$method(*self, *other) } } } } /// The `Add` trait is used to specify the functionality of `+`. /// /// # Example /// /// A trivial implementation of `Add`. When `Foo + Foo` happens, it ends up /// calling `add`, and therefore, `main` prints `Adding!`. /// /// ```rust /// use std::ops::Add; /// /// #[derive(Copy)] /// struct Foo; /// /// impl Add for Foo { /// type Output = Foo; /// /// fn add(self, _rhs: Foo) -> Foo { /// println!("Adding!"); /// self /// } /// } /// /// fn main() { /// Foo + Foo; /// } /// ``` #[lang="add"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Add<RHS=Self> { #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `+` operator #[stable(feature = "rust1", since = "1.0.0")] fn add(self, rhs: RHS) -> Self::Output; } macro_rules! add_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Add for $t { type Output = $t; #[inline] fn add(self, other: $t) -> $t { self + other } } forward_ref_binop! { impl Add, add for $t, $t } )*) } add_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 } /// The `Sub` trait is used to specify the functionality of `-`. /// /// # Example /// /// A trivial implementation of `Sub`. When `Foo - Foo` happens, it ends up /// calling `sub`, and therefore, `main` prints `Subtracting!`. /// /// ```rust /// use std::ops::Sub; /// /// #[derive(Copy)] /// struct Foo; /// /// impl Sub for Foo { /// type Output = Foo; /// /// fn sub(self, _rhs: Foo) -> Foo { /// println!("Subtracting!"); /// self /// } /// } /// /// fn main() { /// Foo - Foo; /// } /// ``` #[lang="sub"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Sub<RHS=Self> { #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `-` operator #[stable(feature = "rust1", since = "1.0.0")] fn sub(self, rhs: RHS) -> Self::Output; } macro_rules! sub_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Sub for $t { type Output = $t; #[inline] fn sub(self, other: $t) -> $t { self - other } } forward_ref_binop! { impl Sub, sub for $t, $t } )*) } sub_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 } /// The `Mul` trait is used to specify the functionality of `*`. /// /// # Example /// /// A trivial implementation of `Mul`. When `Foo * Foo` happens, it ends up /// calling `mul`, and therefore, `main` prints `Multiplying!`. /// /// ```rust /// use std::ops::Mul; /// /// #[derive(Copy)] /// struct Foo; /// /// impl Mul for Foo { /// type Output = Foo; /// /// fn mul(self, _rhs: Foo) -> Foo { /// println!("Multiplying!"); /// self /// } /// } /// /// fn main() { /// Foo * Foo; /// } /// ``` #[lang="mul"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Mul<RHS=Self> { #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `*` operator #[stable(feature = "rust1", since = "1.0.0")] fn mul(self, rhs: RHS) -> Self::Output; } macro_rules! mul_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Mul for $t { type Output = $t; #[inline] fn mul(self, other: $t) -> $t { self * other } } forward_ref_binop! { impl Mul, mul for $t, $t } )*) } mul_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 } /// The `Div` trait is used to specify the functionality of `/`. /// /// # Example /// /// A trivial implementation of `Div`. When `Foo / Foo` happens, it ends up /// calling `div`, and therefore, `main` prints `Dividing!`. /// /// ``` /// use std::ops::Div; /// /// #[derive(Copy)] /// struct Foo; /// /// impl Div for Foo { /// type Output = Foo; /// /// fn div(self, _rhs: Foo) -> Foo { /// println!("Dividing!"); /// self /// } /// } /// /// fn main() { /// Foo / Foo; /// } /// ``` #[lang="div"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Div<RHS=Self> { #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `/` operator #[stable(feature = "rust1", since = "1.0.0")] fn div(self, rhs: RHS) -> Self::Output; } macro_rules! div_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Div for $t { type Output = $t; #[inline] fn div(self, other: $t) -> $t { self / other } } forward_ref_binop! { impl Div, div for $t, $t } )*) } div_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 } /// The `Rem` trait is used to specify the functionality of `%`. /// /// # Example /// /// A trivial implementation of `Rem`. When `Foo % Foo` happens, it ends up /// calling `rem`, and therefore, `main` prints `Remainder-ing!`. /// /// ``` /// use std::ops::Rem; /// /// #[derive(Copy)] /// struct Foo; /// /// impl Rem for Foo { /// type Output = Foo; /// /// fn rem(self, _rhs: Foo) -> Foo { /// println!("Remainder-ing!"); /// self /// } /// } /// /// fn main() { /// Foo % Foo; /// } /// ``` #[lang="rem"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Rem<RHS=Self> { #[stable(feature = "rust1", since = "1.0.0")] type Output = Self; /// The method for the `%` operator #[stable(feature = "rust1", since = "1.0.0")] fn rem(self, rhs: RHS) -> Self::Output; } macro_rules! rem_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Rem for $t { type Output = $t; #[inline] fn rem(self, other: $t) -> $t { self % other } } forward_ref_binop! { impl Rem, rem for $t, $t } )*) } macro_rules! rem_float_impl { ($t:ty, $fmod:ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl Rem for $t { type Output = $t; #[inline] fn rem(self, other: $t) -> $t { extern { fn $fmod(a: $t, b: $t) -> $t; } unsafe { $fmod(self, other) } } } forward_ref_binop! { impl Rem, rem for $t, $t } } } rem_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 } rem_float_impl! { f32, fmodf } rem_float_impl! { f64, fmod } /// The `Neg` trait is used to specify the functionality of unary `-`. /// /// # Example /// /// A trivial implementation of `Neg`. When `-Foo` happens, it ends up calling /// `neg`, and therefore, `main` prints `Negating!`. /// /// ``` /// use std::ops::Neg; /// /// #[derive(Copy)] /// struct Foo; /// /// impl Neg for Foo { /// type Output = Foo; /// /// fn neg(self) -> Foo { /// println!("Negating!"); /// self /// } /// } /// /// fn main() { /// -Foo; /// } /// ``` #[lang="neg"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Neg { #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the unary `-` operator #[stable(feature = "rust1", since = "1.0.0")] fn neg(self) -> Self::Output; } macro_rules! neg_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Neg for $t { #[stable(feature = "rust1", since = "1.0.0")] type Output = $t; #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn neg(self) -> $t { -self } } forward_ref_unop! { impl Neg, neg for $t } )*) } macro_rules! neg_uint_impl { ($t:ty, $t_signed:ty) => { #[stable(feature = "rust1", since = "1.0.0")] impl Neg for $t { type Output = $t; #[inline] fn neg(self) -> $t { -(self as $t_signed) as $t } } forward_ref_unop! { impl Neg, neg for $t } } } neg_impl! { isize i8 i16 i32 i64 f32 f64 } neg_uint_impl! { usize, isize } neg_uint_impl! { u8, i8 } neg_uint_impl! { u16, i16 } neg_uint_impl! { u32, i32 } neg_uint_impl! { u64, i64 } /// The `Not` trait is used to specify the functionality of unary `!`. /// /// # Example /// /// A trivial implementation of `Not`. When `!Foo` happens, it ends up calling /// `not`, and therefore, `main` prints `Not-ing!`. /// /// ``` /// use std::ops::Not; /// /// #[derive(Copy)] /// struct Foo; /// /// impl Not for Foo { /// type Output = Foo; /// /// fn not(self) -> Foo { /// println!("Not-ing!"); /// self /// } /// } /// /// fn main() { /// !Foo; /// } /// ``` #[lang="not"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Not { #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the unary `!` operator #[stable(feature = "rust1", since = "1.0.0")] fn not(self) -> Self::Output; } macro_rules! not_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl Not for $t { type Output = $t; #[inline] fn not(self) -> $t { !self } } forward_ref_unop! { impl Not, not for $t } )*) } not_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 } /// The `BitAnd` trait is used to specify the functionality of `&`. /// /// # Example /// /// A trivial implementation of `BitAnd`. When `Foo & Foo` happens, it ends up /// calling `bitand`, and therefore, `main` prints `Bitwise And-ing!`. /// /// ``` /// use std::ops::BitAnd; /// /// #[derive(Copy)] /// struct Foo; /// /// impl BitAnd for Foo { /// type Output = Foo; /// /// fn bitand(self, _rhs: Foo) -> Foo { /// println!("Bitwise And-ing!"); /// self /// } /// } /// /// fn main() { /// Foo & Foo; /// } /// ``` #[lang="bitand"] #[stable(feature = "rust1", since = "1.0.0")] pub trait BitAnd<RHS=Self> { #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `&` operator #[stable(feature = "rust1", since = "1.0.0")] fn bitand(self, rhs: RHS) -> Self::Output; } macro_rules! bitand_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl BitAnd for $t { type Output = $t; #[inline] fn bitand(self, rhs: $t) -> $t { self & rhs } } forward_ref_binop! { impl BitAnd, bitand for $t, $t } )*) } bitand_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 } /// The `BitOr` trait is used to specify the functionality of `|`. /// /// # Example /// /// A trivial implementation of `BitOr`. When `Foo | Foo` happens, it ends up /// calling `bitor`, and therefore, `main` prints `Bitwise Or-ing!`. /// /// ``` /// use std::ops::BitOr; /// /// #[derive(Copy)] /// struct Foo; /// /// impl BitOr for Foo { /// type Output = Foo; /// /// fn bitor(self, _rhs: Foo) -> Foo { /// println!("Bitwise Or-ing!"); /// self /// } /// } /// /// fn main() { /// Foo | Foo; /// } /// ``` #[lang="bitor"] #[stable(feature = "rust1", since = "1.0.0")] pub trait BitOr<RHS=Self> { #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `|` operator #[stable(feature = "rust1", since = "1.0.0")] fn bitor(self, rhs: RHS) -> Self::Output; } macro_rules! bitor_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl BitOr for $t { type Output = $t; #[inline] fn bitor(self, rhs: $t) -> $t { self | rhs } } forward_ref_binop! { impl BitOr, bitor for $t, $t } )*) } bitor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 } /// The `BitXor` trait is used to specify the functionality of `^`. /// /// # Example /// /// A trivial implementation of `BitXor`. When `Foo ^ Foo` happens, it ends up /// calling `bitxor`, and therefore, `main` prints `Bitwise Xor-ing!`. /// /// ``` /// use std::ops::BitXor; /// /// #[derive(Copy)] /// struct Foo; /// /// impl BitXor for Foo { /// type Output = Foo; /// /// fn bitxor(self, _rhs: Foo) -> Foo { /// println!("Bitwise Xor-ing!"); /// self /// } /// } /// /// fn main() { /// Foo ^ Foo; /// } /// ``` #[lang="bitxor"] #[stable(feature = "rust1", since = "1.0.0")] pub trait BitXor<RHS=Self> { #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `^` operator #[stable(feature = "rust1", since = "1.0.0")] fn bitxor(self, rhs: RHS) -> Self::Output; } macro_rules! bitxor_impl { ($($t:ty)*) => ($( #[stable(feature = "rust1", since = "1.0.0")] impl BitXor for $t { type Output = $t; #[inline] fn bitxor(self, other: $t) -> $t { self ^ other } } forward_ref_binop! { impl BitXor, bitxor for $t, $t } )*) } bitxor_impl! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 } /// The `Shl` trait is used to specify the functionality of `<<`. /// /// # Example /// /// A trivial implementation of `Shl`. When `Foo << Foo` happens, it ends up /// calling `shl`, and therefore, `main` prints `Shifting left!`. /// /// ``` /// use std::ops::Shl; /// /// #[derive(Copy)] /// struct Foo; /// /// impl Shl<Foo> for Foo { /// type Output = Foo; /// /// fn shl(self, _rhs: Foo) -> Foo { /// println!("Shifting left!"); /// self /// } /// } /// /// fn main() { /// Foo << Foo; /// } /// ``` #[lang="shl"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Shl<RHS> { #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `<<` operator #[stable(feature = "rust1", since = "1.0.0")] fn shl(self, rhs: RHS) -> Self::Output; } macro_rules! shl_impl { ($t:ty, $f:ty) => ( #[stable(feature = "rust1", since = "1.0.0")] impl Shl<$f> for $t { type Output = $t; #[inline] fn shl(self, other: $f) -> $t { self << other } } forward_ref_binop! { impl Shl, shl for $t, $f } ) } macro_rules! shl_impl_all { ($($t:ty)*) => ($( shl_impl! { $t, u8 } shl_impl! { $t, u16 } shl_impl! { $t, u32 } shl_impl! { $t, u64 } shl_impl! { $t, usize } shl_impl! { $t, i8 } shl_impl! { $t, i16 } shl_impl! { $t, i32 } shl_impl! { $t, i64 } shl_impl! { $t, isize } )*) } shl_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize } /// The `Shr` trait is used to specify the functionality of `>>`. /// /// # Example /// /// A trivial implementation of `Shr`. When `Foo >> Foo` happens, it ends up /// calling `shr`, and therefore, `main` prints `Shifting right!`. /// /// ``` /// use std::ops::Shr; /// /// #[derive(Copy)] /// struct Foo; /// /// impl Shr<Foo> for Foo { /// type Output = Foo; /// /// fn shr(self, _rhs: Foo) -> Foo { /// println!("Shifting right!"); /// self /// } /// } /// /// fn main() { /// Foo >> Foo; /// } /// ``` #[lang="shr"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Shr<RHS> { #[stable(feature = "rust1", since = "1.0.0")] type Output; /// The method for the `>>` operator #[stable(feature = "rust1", since = "1.0.0")] fn shr(self, rhs: RHS) -> Self::Output; } macro_rules! shr_impl { ($t:ty, $f:ty) => ( impl Shr<$f> for $t { type Output = $t; #[inline] fn shr(self, other: $f) -> $t { self >> other } } forward_ref_binop! { impl Shr, shr for $t, $f } ) } macro_rules! shr_impl_all { ($($t:ty)*) => ($( shr_impl! { $t, u8 } shr_impl! { $t, u16 } shr_impl! { $t, u32 } shr_impl! { $t, u64 } shr_impl! { $t, usize } shr_impl! { $t, i8 } shr_impl! { $t, i16 } shr_impl! { $t, i32 } shr_impl! { $t, i64 } shr_impl! { $t, isize } )*) } shr_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize } /// The `Index` trait is used to specify the functionality of indexing operations /// like `arr[idx]` when used in an immutable context. /// /// # Example /// /// A trivial implementation of `Index`. When `Foo[Bar]` happens, it ends up /// calling `index`, and therefore, `main` prints `Indexing!`. /// /// ``` /// use std::ops::Index; /// /// #[derive(Copy)] /// struct Foo; /// struct Bar; /// /// impl Index<Bar> for Foo { /// type Output = Foo; /// /// fn index<'a>(&'a self, _index: &Bar) -> &'a Foo { /// println!("Indexing!"); /// self /// } /// } /// /// fn main() { /// Foo[Bar]; /// } /// ``` #[lang="index"] #[rustc_on_unimplemented = "the type `{Self}` cannot be indexed by `{Idx}`"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Index<Idx: ?Sized> { type Output: ?Sized; /// The method for the indexing (`Foo[Bar]`) operation #[stable(feature = "rust1", since = "1.0.0")] fn index<'a>(&'a self, index: &Idx) -> &'a Self::Output; } /// The `IndexMut` trait is used to specify the functionality of indexing /// operations like `arr[idx]`, when used in a mutable context. /// /// # Example /// /// A trivial implementation of `IndexMut`. When `Foo[Bar]` happens, it ends up /// calling `index_mut`, and therefore, `main` prints `Indexing!`. /// /// ``` /// use std::ops::{Index, IndexMut}; /// /// #[derive(Copy)] /// struct Foo; /// struct Bar; /// /// impl Index<Bar> for Foo { /// type Output = Foo; /// /// fn index<'a>(&'a self, _index: &Bar) -> &'a Foo { /// self /// } /// } /// /// impl IndexMut<Bar> for Foo { /// fn index_mut<'a>(&'a mut self, _index: &Bar) -> &'a mut Foo { /// println!("Indexing!"); /// self /// } /// } /// /// fn main() { /// &mut Foo[Bar]; /// } /// ``` #[lang="index_mut"] #[rustc_on_unimplemented = "the type `{Self}` cannot be mutably indexed by `{Idx}`"] #[stable(feature = "rust1", since = "1.0.0")] pub trait IndexMut<Idx: ?Sized>: Index<Idx> { /// The method for the indexing (`Foo[Bar]`) operation #[stable(feature = "rust1", since = "1.0.0")] fn index_mut<'a>(&'a mut self, index: &Idx) -> &'a mut Self::Output; } /// An unbounded range. #[derive(Copy, Clone, PartialEq, Eq)] #[lang="range_full"] #[stable(feature = "rust1", since = "1.0.0")] pub struct RangeFull; #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for RangeFull { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt("..", fmt) } } /// A (half-open) range which is bounded at both ends. #[derive(Clone, PartialEq, Eq)] #[lang="range"] #[stable(feature = "rust1", since = "1.0.0")] pub struct Range<Idx> { /// The lower bound of the range (inclusive). pub start: Idx, /// The upper bound of the range (exclusive). pub end: Idx, } #[stable(feature = "rust1", since = "1.0.0")] impl<Idx: fmt::Debug> fmt::Debug for Range<Idx> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}..{:?}", self.start, self.end) } } /// A range which is only bounded below. #[derive(Clone, PartialEq, Eq)] #[lang="range_from"] #[stable(feature = "rust1", since = "1.0.0")] pub struct RangeFrom<Idx> { /// The lower bound of the range (inclusive). pub start: Idx, } #[stable(feature = "rust1", since = "1.0.0")] impl<Idx: fmt::Debug> fmt::Debug for RangeFrom<Idx> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}..", self.start) } } /// A range which is only bounded above. #[derive(Copy, Clone, PartialEq, Eq)] #[lang="range_to"] #[stable(feature = "rust1", since = "1.0.0")] pub struct RangeTo<Idx> { /// The upper bound of the range (exclusive). pub end: Idx, } #[stable(feature = "rust1", since = "1.0.0")] impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "..{:?}", self.end) } } /// The `Deref` trait is used to specify the functionality of dereferencing /// operations like `*v`. /// /// # Example /// /// A struct with a single field which is accessible via dereferencing the /// struct. /// /// ``` /// use std::ops::Deref; /// /// struct DerefExample<T> { /// value: T /// } /// /// impl<T> Deref for DerefExample<T> { /// type Target = T; /// /// fn deref<'a>(&'a self) -> &'a T { /// &self.value /// } /// } /// /// fn main() { /// let x = DerefExample { value: 'a' }; /// assert_eq!('a', *x); /// } /// ``` #[lang="deref"] #[stable(feature = "rust1", since = "1.0.0")] pub trait Deref { #[stable(feature = "rust1", since = "1.0.0")] type Target: ?Sized; /// The method called to dereference a value #[stable(feature = "rust1", since = "1.0.0")] fn deref<'a>(&'a self) -> &'a Self::Target; } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized> Deref for &'a T { type Target = T; fn deref(&self) -> &T { *self } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized> Deref for &'a mut T { type Target = T; fn deref(&self) -> &T { *self } } /// The `DerefMut` trait is used to specify the functionality of dereferencing /// mutably like `*v = 1;` /// /// # Example /// /// A struct with a single field which is modifiable via dereferencing the /// struct. /// /// ``` /// use std::ops::{Deref, DerefMut}; /// /// struct DerefMutExample<T> { /// value: T /// } /// /// impl<T> Deref for DerefMutExample<T> { /// type Target = T; /// /// fn deref<'a>(&'a self) -> &'a T { /// &self.value /// } /// } /// /// impl<T> DerefMut for DerefMutExample<T> { /// fn deref_mut<'a>(&'a mut self) -> &'a mut T { /// &mut self.value /// } /// } /// /// fn main() { /// let mut x = DerefMutExample { value: 'a' }; /// *x = 'b'; /// assert_eq!('b', *x); /// } /// ``` #[lang="deref_mut"] #[stable(feature = "rust1", since = "1.0.0")] pub trait DerefMut: Deref { /// The method called to mutably dereference a value #[stable(feature = "rust1", since = "1.0.0")] fn deref_mut<'a>(&'a mut self) -> &'a mut Self::Target; } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: ?Sized> DerefMut for &'a mut T { fn deref_mut(&mut self) -> &mut T { *self } } /// A version of the call operator that takes an immutable receiver. #[lang="fn"] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_paren_sugar] pub trait Fn<Args> { type Output; /// This is called when the call operator is used. extern "rust-call" fn call(&self, args: Args) -> Self::Output; } /// A version of the call operator that takes a mutable receiver. #[lang="fn_mut"] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_paren_sugar] pub trait FnMut<Args> { type Output; /// This is called when the call operator is used. extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output; } /// A version of the call operator that takes a by-value receiver. #[lang="fn_once"] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_paren_sugar] pub trait FnOnce<Args> { type Output; /// This is called when the call operator is used. extern "rust-call" fn call_once(self, args: Args) -> Self::Output; } impl<F: ?Sized, A> FnMut<A> for F where F : Fn<A> { type Output = <F as Fn<A>>::Output; extern "rust-call" fn call_mut(&mut self, args: A) -> <F as Fn<A>>::Output { self.call(args) } } impl<F,A> FnOnce<A> for F where F : FnMut<A> { type Output = <F as FnMut<A>>::Output; extern "rust-call" fn call_once(mut self, args: A) -> <F as FnMut<A>>::Output { self.call_mut(args) } }
24.645051
84
0.52472
1cf5a1bbf5f9cf5a091dff501c4f3141a903950c
1,607
use std::path::Path; use std::fs::File; mod ioctl; mod wmi; pub fn file_offset(fd: &File) -> Option<u64> { ioctl::starting_vcn(fd) } pub fn in_ssd(path: &Path) -> Option<bool> { let drive = match get_drive_letter(path) { Some(letter) => letter, None => return None, }; wmi::co_init().ok()?; // doesn't handle multiple drives mounted to the same volume (e.g. C:\) let is_ssd = if let Some(index) = wmi::get_device_index(drive.as_ref()).ok()? { wmi::get_media_type(index).ok()?? } else { wmi::DriveKind::Unknown }; wmi::co_exit(); match is_ssd { wmi::DriveKind::SSD => Some(true), wmi::DriveKind::HDD => Some(false), wmi::DriveKind::Unknown => None, } } fn get_drive_letter(path: &Path) -> Option<String> { let mut path_iter = path.to_str()?.chars(); let letter = path_iter.next()?.to_uppercase(); let colon = path_iter.next()?; if colon == ':' { // C: Some(format!("{}{}", letter, colon)) } else { // \\?\C: let letter = path_iter.nth(2)?; let colon = path_iter.next()?; if colon == ':' { Some(format!("{}{}", letter, colon)) } else { None } } } #[cfg(test)] mod tests { use super::*; #[test] fn drive_letter() { assert_eq!(get_drive_letter(Path::new(r"C:\test\directory")), Some("C:".into())); assert_eq!(get_drive_letter(Path::new(r"\\?\C:\test\directory")), Some("C:".into())); assert_eq!(get_drive_letter(Path::new(r"\\?\test\directory")), None); } }
24.348485
93
0.545737
3a1a5414d81c374a5eb7483b1e4526c7c27003d8
963
use crate::dataflow::operators::MapInPlace; use differential_dataflow::{difference::Abelian, AsCollection, Collection, Data}; use std::panic::Location; use timely::dataflow::Scope; pub trait NegateExt { type Output; fn negate_named(&self, name: &str) -> Self::Output; #[track_caller] fn negate_located(&self) -> Self::Output; } impl<S, D, R> NegateExt for Collection<S, D, R> where S: Scope, D: Data, R: Abelian, { type Output = Self; fn negate_named(&self, name: &str) -> Self::Output { self.inner .map_in_place_named(name, |x| x.2 = -x.2.clone()) .as_collection() } #[track_caller] fn negate_located(&self) -> Self::Output { let caller = Location::caller(); let name = format!( "MapInPlace: Negate @ {}:{}:{}", caller.file(), caller.line(), caller.column(), ); self.negate_named(&name) } }
22.928571
81
0.573209
50451f34d5bd8d5ab4c00f88f08046c273109063
14,850
//! Main Router instructions. use { crate::{ farm::Farm, instruction::refdb::RefDbInstruction, pack::{check_data_len, pack_array_string64, unpack_array_string64}, pool::Pool, string::ArrayString64, token::Token, vault::Vault, }, arrayref::{array_mut_ref, array_ref, mut_array_refs}, num_enum::TryFromPrimitive, paychains_program::program_error::ProgramError, }; #[derive(Clone, Copy, Debug, PartialEq)] pub enum MainInstruction { /// Record Vault's metadata on-chain /// /// # Account references /// 0. [SIGNER] Funding account, must be main router admin /// 1. [WRITE] Vault's RefDB index PDA /// 2. [WRITE] Vault's RefDB data PDA /// 3. [] Sytem program AddVault { vault: Vault }, /// Delete Vault's metadata /// /// # Account references /// 0. [SIGNER] Funding account, must be main router admin /// 1. [WRITE] Vault's RefDB index PDA /// 2. [WRITE] Vault's RefDB data PDA /// 3. [] Sytem program RemoveVault { name: ArrayString64 }, /// Record Pool's metadata on-chain /// /// # Account references /// 0. [SIGNER] Funding account, must be main router admin /// 1. [WRITE] Pool's RefDB index PDA /// 2. [WRITE] Pool's RefDB data PDA /// 3. [] Sytem program AddPool { pool: Pool }, /// Delete Pool's metadata /// /// # Account references /// 0. [SIGNER] Funding account, must be main router admin /// 1. [WRITE] Pool's RefDB index PDA /// 2. [WRITE] Pool's RefDB data PDA /// 3. [] Sytem program RemovePool { name: ArrayString64 }, /// Record Farm's metadata on-chain /// /// # Account references /// 0. [SIGNER] Funding account, must be main router admin /// 1. [WRITE] Farm's RefDB index PDA /// 2. [WRITE] Farm's RefDB data PDA /// 3. [] Sytem program AddFarm { farm: Farm }, /// Delete Farm's metadata /// /// # Account references /// 0. [SIGNER] Funding account, must be main router admin /// 1. [WRITE] Farm's RefDB index PDA /// 2. [WRITE] Farm's RefDB data PDA /// 3. [] Sytem program RemoveFarm { name: ArrayString64 }, /// Record Token's metadata on-chain /// /// # Account references /// 0. [SIGNER] Funding account, must be main router admin /// 1. [WRITE] Token's RefDB index PDA /// 2. [WRITE] Token's RefDB data PDA /// 3. [] Sytem program AddToken { token: Token }, /// Delete Token's metadata /// /// # Account references /// 0. [SIGNER] Funding account, must be main router admin /// 1. [WRITE] Token's RefDB index PDA /// 2. [WRITE] Token's RefDB data PDA /// 3. [] Sytem program RemoveToken { name: ArrayString64 }, /// Perform generic RefDB instruction /// /// # Account references are instruction specific, /// see RefDbInstruction definition for more info RefDbInstruction { instruction: RefDbInstruction }, } #[repr(u8)] #[derive(Clone, Copy, Debug, Eq, PartialEq, TryFromPrimitive)] pub enum MainInstructionType { AddVault, RemoveVault, AddPool, RemovePool, AddFarm, RemoveFarm, AddToken, RemoveToken, RefDbInstruction, } impl MainInstruction { pub const MAX_LEN: usize = MainInstruction::max(Vault::MAX_LEN + 1, Pool::MAX_LEN + 1); pub const REMOVE_VAULT_LEN: usize = 65; pub const REMOVE_POOL_LEN: usize = 65; pub const REMOVE_FARM_LEN: usize = 65; pub const REMOVE_TOKEN_LEN: usize = 65; const fn max(a: usize, b: usize) -> usize { [a, b][(a < b) as usize] } pub fn pack(&self, output: &mut [u8]) -> Result<usize, ProgramError> { check_data_len(output, 1)?; match self { Self::AddVault { vault } => self.pack_add_vault(output, vault), Self::RemoveVault { name } => self.pack_remove_vault(output, name), Self::AddPool { pool } => self.pack_add_pool(output, pool), Self::RemovePool { name } => self.pack_remove_pool(output, name), Self::AddFarm { farm } => self.pack_add_farm(output, farm), Self::RemoveFarm { name } => self.pack_remove_farm(output, name), Self::AddToken { token } => self.pack_add_token(output, token), Self::RemoveToken { name } => self.pack_remove_token(output, name), Self::RefDbInstruction { instruction } => { self.pack_refdb_instruction(output, instruction) } } } pub fn to_vec(&self) -> Result<Vec<u8>, ProgramError> { let mut output: [u8; MainInstruction::MAX_LEN] = [0; MainInstruction::MAX_LEN]; if let Ok(len) = self.pack(&mut output[..]) { Ok(output[..len].to_vec()) } else { Err(ProgramError::InvalidInstructionData) } } pub fn unpack(input: &[u8]) -> Result<MainInstruction, ProgramError> { check_data_len(input, 1)?; let instruction_type = MainInstructionType::try_from_primitive(input[0]) .or(Err(ProgramError::InvalidInstructionData))?; match instruction_type { MainInstructionType::AddVault => MainInstruction::unpack_add_vault(input), MainInstructionType::RemoveVault => MainInstruction::unpack_remove_vault(input), MainInstructionType::AddPool => MainInstruction::unpack_add_pool(input), MainInstructionType::RemovePool => MainInstruction::unpack_remove_pool(input), MainInstructionType::AddFarm => MainInstruction::unpack_add_farm(input), MainInstructionType::RemoveFarm => MainInstruction::unpack_remove_farm(input), MainInstructionType::AddToken => MainInstruction::unpack_add_token(input), MainInstructionType::RemoveToken => MainInstruction::unpack_remove_token(input), MainInstructionType::RefDbInstruction => { MainInstruction::unpack_refdb_instruction(input) } } } fn pack_add_vault(&self, output: &mut [u8], vault: &Vault) -> Result<usize, ProgramError> { let packed = vault.pack(&mut output[1..])?; let instruction_type_out = array_mut_ref![output, 0, 1]; instruction_type_out[0] = MainInstructionType::AddVault as u8; Ok(packed + 1) } fn pack_remove_vault( &self, output: &mut [u8], name: &ArrayString64, ) -> Result<usize, ProgramError> { check_data_len(output, MainInstruction::REMOVE_VAULT_LEN)?; let output = array_mut_ref![output, 0, MainInstruction::REMOVE_VAULT_LEN]; let (instruction_type_out, name_out) = mut_array_refs![output, 1, 64]; instruction_type_out[0] = MainInstructionType::RemoveVault as u8; pack_array_string64(name, name_out); Ok(MainInstruction::REMOVE_VAULT_LEN) } fn pack_add_pool(&self, output: &mut [u8], pool: &Pool) -> Result<usize, ProgramError> { let packed = pool.pack(&mut output[1..])?; let instruction_type_out = array_mut_ref![output, 0, 1]; instruction_type_out[0] = MainInstructionType::AddPool as u8; Ok(packed + 1) } fn pack_remove_pool( &self, output: &mut [u8], name: &ArrayString64, ) -> Result<usize, ProgramError> { check_data_len(output, MainInstruction::REMOVE_POOL_LEN)?; let output = array_mut_ref![output, 0, MainInstruction::REMOVE_POOL_LEN]; let (instruction_type_out, name_out) = mut_array_refs![output, 1, 64]; instruction_type_out[0] = MainInstructionType::RemovePool as u8; pack_array_string64(name, name_out); Ok(MainInstruction::REMOVE_POOL_LEN) } fn pack_add_farm(&self, output: &mut [u8], farm: &Farm) -> Result<usize, ProgramError> { let packed = farm.pack(&mut output[1..])?; let instruction_type_out = array_mut_ref![output, 0, 1]; instruction_type_out[0] = MainInstructionType::AddFarm as u8; Ok(packed + 1) } fn pack_remove_farm( &self, output: &mut [u8], name: &ArrayString64, ) -> Result<usize, ProgramError> { check_data_len(output, MainInstruction::REMOVE_FARM_LEN)?; let output = array_mut_ref![output, 0, MainInstruction::REMOVE_FARM_LEN]; let (instruction_type_out, name_out) = mut_array_refs![output, 1, 64]; instruction_type_out[0] = MainInstructionType::RemoveFarm as u8; pack_array_string64(name, name_out); Ok(MainInstruction::REMOVE_FARM_LEN) } fn pack_add_token(&self, output: &mut [u8], token: &Token) -> Result<usize, ProgramError> { let packed = token.pack(&mut output[1..])?; let instruction_type_out = array_mut_ref![output, 0, 1]; instruction_type_out[0] = MainInstructionType::AddToken as u8; Ok(packed + 1) } fn pack_remove_token( &self, output: &mut [u8], name: &ArrayString64, ) -> Result<usize, ProgramError> { check_data_len(output, MainInstruction::REMOVE_TOKEN_LEN)?; let output = array_mut_ref![output, 0, MainInstruction::REMOVE_TOKEN_LEN]; let (instruction_type_out, name_out) = mut_array_refs![output, 1, 64]; instruction_type_out[0] = MainInstructionType::RemoveToken as u8; pack_array_string64(name, name_out); Ok(MainInstruction::REMOVE_TOKEN_LEN) } fn pack_refdb_instruction( &self, output: &mut [u8], instruction: &RefDbInstruction, ) -> Result<usize, ProgramError> { let packed = instruction.pack(&mut output[1..])?; let instruction_type_out = array_mut_ref![output, 0, 1]; instruction_type_out[0] = MainInstructionType::RefDbInstruction as u8; Ok(packed + 1) } fn unpack_add_vault(input: &[u8]) -> Result<MainInstruction, ProgramError> { let vault = Vault::unpack(&input[1..])?; Ok(Self::AddVault { vault }) } fn unpack_remove_vault(input: &[u8]) -> Result<MainInstruction, ProgramError> { check_data_len(input, MainInstruction::REMOVE_VAULT_LEN)?; let input = array_ref![input, 1, MainInstruction::REMOVE_VAULT_LEN - 1]; Ok(Self::RemoveVault { name: unpack_array_string64(input)?, }) } fn unpack_add_pool(input: &[u8]) -> Result<MainInstruction, ProgramError> { let pool = Pool::unpack(&input[1..])?; Ok(Self::AddPool { pool }) } fn unpack_remove_pool(input: &[u8]) -> Result<MainInstruction, ProgramError> { check_data_len(input, MainInstruction::REMOVE_POOL_LEN)?; let input = array_ref![input, 1, MainInstruction::REMOVE_POOL_LEN - 1]; Ok(Self::RemovePool { name: unpack_array_string64(input)?, }) } fn unpack_add_farm(input: &[u8]) -> Result<MainInstruction, ProgramError> { let farm = Farm::unpack(&input[1..])?; Ok(Self::AddFarm { farm }) } fn unpack_remove_farm(input: &[u8]) -> Result<MainInstruction, ProgramError> { check_data_len(input, MainInstruction::REMOVE_FARM_LEN)?; let input = array_ref![input, 1, MainInstruction::REMOVE_FARM_LEN - 1]; Ok(Self::RemoveFarm { name: unpack_array_string64(input)?, }) } fn unpack_add_token(input: &[u8]) -> Result<MainInstruction, ProgramError> { let token = Token::unpack(&input[1..])?; Ok(Self::AddToken { token }) } fn unpack_remove_token(input: &[u8]) -> Result<MainInstruction, ProgramError> { check_data_len(input, MainInstruction::REMOVE_TOKEN_LEN)?; let input = array_ref![input, 1, MainInstruction::REMOVE_TOKEN_LEN - 1]; Ok(Self::RemoveToken { name: unpack_array_string64(input)?, }) } fn unpack_refdb_instruction(input: &[u8]) -> Result<MainInstruction, ProgramError> { let instruction = RefDbInstruction::unpack(&input[1..])?; Ok(Self::RefDbInstruction { instruction }) } } impl std::fmt::Display for MainInstructionType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { MainInstructionType::AddVault => write!(f, "AddVault"), MainInstructionType::RemoveVault => write!(f, "RemoveVault"), MainInstructionType::AddPool => write!(f, "AddPool"), MainInstructionType::RemovePool => write!(f, "RemovePool"), MainInstructionType::AddFarm => write!(f, "AddFarm"), MainInstructionType::RemoveFarm => write!(f, "RemoveFarm"), MainInstructionType::AddToken => write!(f, "AddToken"), MainInstructionType::RemoveToken => write!(f, "RemoveToken"), MainInstructionType::RefDbInstruction => write!(f, "RefDbInstruction"), } } } #[cfg(test)] mod tests { use super::*; use crate::pool::{PoolRoute, PoolType}; use crate::string::ArrayString64; use paychains_program::pubkey::Pubkey; #[test] fn test_vec_serialization() { let ri1 = MainInstruction::AddPool { pool: Pool { name: ArrayString64::from_utf8("test").unwrap(), version: 2, pool_type: PoolType::Amm, official: true, refdb_index: Some(1), refdb_counter: 2, token_a_ref: Some(Pubkey::new_unique()), token_b_ref: Some(Pubkey::new_unique()), lp_token_ref: Some(Pubkey::new_unique()), token_a_account: None, token_b_account: None, router_program_id: Pubkey::new_unique(), pool_program_id: Pubkey::new_unique(), route: PoolRoute::Raydium { amm_id: Pubkey::new_unique(), amm_authority: Pubkey::new_unique(), amm_open_orders: Pubkey::new_unique(), amm_target: Pubkey::new_unique(), pool_withdraw_queue: Pubkey::new_unique(), pool_temp_lp_token_account: Pubkey::new_unique(), serum_program_id: Pubkey::new_unique(), serum_market: Pubkey::new_unique(), serum_coin_vault_account: Pubkey::new_unique(), serum_pc_vault_account: Pubkey::new_unique(), serum_vault_signer: Pubkey::new_unique(), serum_bids: Some(Pubkey::new_unique()), serum_asks: Some(Pubkey::new_unique()), serum_event_queue: Some(Pubkey::new_unique()), }, }, }; let vec = ri1.to_vec().unwrap(); let ri2 = MainInstruction::unpack(&vec[..]).unwrap(); assert_eq!(ri1, ri2); } }
37.032419
95
0.609226
6a240c3c6ebd365146c2e72ef2e8a86d724fa113
3,568
use crate::error::{LoftyError, Result}; use crate::id3::v2::frame::{FrameFlags, FrameRef, FrameValue}; use crate::id3::v2::synch_u32; use std::io::Write; use byteorder::{BigEndian, WriteBytesExt}; pub(in crate::id3::v2) fn create_items<'a, W>( writer: &mut W, frames: &mut dyn Iterator<Item = FrameRef<'a>>, ) -> Result<()> where W: Write, { for frame in frames { verify_frame(&frame)?; let value = frame.value.as_bytes()?; write_frame(writer, frame.id, frame.flags, &value)?; } Ok(()) } fn verify_frame(frame: &FrameRef) -> Result<()> { match (frame.id, frame.value.as_ref()) { ("APIC", FrameValue::Picture { .. }) | ("USLT", FrameValue::UnSyncText(_)) | ("COMM", FrameValue::Comment(_)) | ("TXXX", FrameValue::UserText(_)) | ("WXXX", FrameValue::UserURL(_)) | (_, FrameValue::Binary(_)) | ("WFED" | "GRP1", FrameValue::Text { .. }) => Ok(()), (id, FrameValue::Text { .. }) if id.starts_with('T') => Ok(()), (id, FrameValue::URL(_)) if id.starts_with('W') => Ok(()), (id, frame_value) => Err(LoftyError::BadFrame( id.to_string(), match frame_value { FrameValue::Comment(_) => "Comment", FrameValue::UnSyncText(_) => "UnSyncText", FrameValue::Text { .. } => "Text", FrameValue::UserText(_) => "UserText", FrameValue::URL(_) => "URL", FrameValue::UserURL(_) => "UserURL", FrameValue::Picture { .. } => "Picture", FrameValue::Binary(_) => "Binary", }, )), } } fn write_frame<W>(writer: &mut W, name: &str, flags: FrameFlags, value: &[u8]) -> Result<()> where W: Write, { if flags.encryption.0 { write_encrypted(writer, name, value, flags)?; return Ok(()); } let len = value.len() as u32; let is_grouping_identity = flags.grouping_identity.0; write_frame_header( writer, name, if is_grouping_identity { len + 1 } else { len }, flags, )?; if is_grouping_identity { writer.write_u8(flags.grouping_identity.1)?; } writer.write_all(value)?; Ok(()) } fn write_encrypted<W>(writer: &mut W, name: &str, value: &[u8], flags: FrameFlags) -> Result<()> where W: Write, { let method_symbol = flags.encryption.1; let data_length_indicator = flags.data_length_indicator; if method_symbol > 0x80 { return Err(LoftyError::Id3v2( "Attempted to write an encrypted frame with an invalid method symbol (> 0x80)", )); } if data_length_indicator.0 && data_length_indicator.1 > 0 { write_frame_header(writer, name, (value.len() + 1) as u32, flags)?; writer.write_u32::<BigEndian>(synch_u32(data_length_indicator.1)?)?; writer.write_u8(method_symbol)?; writer.write_all(value)?; return Ok(()); } Err(LoftyError::Id3v2( "Attempted to write an encrypted frame without a data length indicator", )) } fn write_frame_header<W>(writer: &mut W, name: &str, len: u32, flags: FrameFlags) -> Result<()> where W: Write, { writer.write_all(name.as_bytes())?; writer.write_u32::<BigEndian>(synch_u32(len)?)?; writer.write_u16::<BigEndian>(get_flags(flags))?; Ok(()) } fn get_flags(tag_flags: FrameFlags) -> u16 { let mut flags = 0; if tag_flags == FrameFlags::default() { return flags; } if tag_flags.tag_alter_preservation { flags |= 0x4000 } if tag_flags.file_alter_preservation { flags |= 0x2000 } if tag_flags.read_only { flags |= 0x1000 } if tag_flags.grouping_identity.0 { flags |= 0x0040 } if tag_flags.compression { flags |= 0x0008 } if tag_flags.encryption.0 { flags |= 0x0004 } if tag_flags.unsynchronisation { flags |= 0x0002 } if tag_flags.data_length_indicator.0 { flags |= 0x0001 } flags }
22.3
96
0.653307
9b10ebed3f4dcab49781b964615c421d08db9b01
1,848
use crate::prelude::*; use nu_errors::ShellError; use nu_protocol::{CommandAction, ReturnSuccess, Signature, SyntaxShape}; pub struct Exit; impl WholeStreamCommand for Exit { fn name(&self) -> &str { "exit" } fn signature(&self) -> Signature { Signature::build("exit") .optional( "code", SyntaxShape::Number, "Status code to return if this was the last shell or --now was specified", ) .switch("now", "Exit out of the shell immediately", Some('n')) } fn usage(&self) -> &str { "Exit the current shell (or all shells)." } fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> { exit(args) } fn examples(&self) -> Vec<Example> { vec![ Example { description: "Exit the current shell", example: "exit", result: None, }, Example { description: "Exit all shells (exiting Nu)", example: "exit --now", result: None, }, ] } } pub fn exit(args: CommandArgs) -> Result<OutputStream, ShellError> { let args = args.evaluate_once()?; let code = if let Some(value) = args.call_info.args.nth(0) { value.as_i32()? } else { 0 }; let command_action = if args.call_info.args.has("now") { CommandAction::Exit(code) } else { CommandAction::LeaveShell(code) }; Ok(OutputStream::one(ReturnSuccess::action(command_action))) } #[cfg(test)] mod tests { use super::Exit; use super::ShellError; #[test] fn examples_work_as_expected() -> Result<(), ShellError> { use crate::examples::test as test_examples; test_examples(Exit {}) } }
24.315789
90
0.541126
bb5937a1acb334b3d03844b9d79ec5f251c10683
52
mod utils; mod test_alphabeta; mod test_montecarlo;
13
20
0.826923
d9eb23a7ac7700bb3839a7223694100afa604824
7,041
use lazy_static::lazy_static; use std::path::PathBuf; use structopt::StructOpt; lazy_static! { static ref DEFAULT_CONFIG_FILE: PathBuf = PathBuf::from(std::env::var("HOME").unwrap() + "/.config/aur-thumbsup.toml"); } #[derive(StructOpt, PartialEq, Debug)] #[structopt(author, about)] pub struct Arguments { /// Configuration file /// #[structopt( short = "c", long = "config", parse(from_os_str), default_value = DEFAULT_CONFIG_FILE.to_str().unwrap() )] pub config: PathBuf, /// Suppress stdout #[structopt(short = "q", long = "quiet")] pub quiet: bool, /// Increment verbosity level once per call /// [error, -v: warn, -vv: info, -vvv: debug, -vvvv: trace] #[structopt(short = "v", long = "verbose", parse(from_occurrences))] pub verbose: u8, #[structopt(subcommand)] pub cmd: Option<Commands>, } #[derive(StructOpt, PartialEq, Debug)] pub enum Commands { #[structopt(about = "Vote for packages")] Vote { #[structopt(required = true)] packages: Vec<String>, }, #[structopt(about = "Unvote packages")] Unvote { #[structopt(required = true)] packages: Vec<String>, }, #[structopt(about = "Unvote for all installed packages")] UnvoteAll {}, #[structopt(about = "Check for voted packages")] Check { #[structopt(required = true)] packages: Vec<String>, }, #[structopt(about = "List all voted packages")] List {}, #[structopt(about = "Vote/Unvote for installed packages")] Autovote {}, #[structopt(about = "Create configuration file")] CreateConfig { #[structopt(required = true, parse(from_os_str))] path: PathBuf, }, #[structopt(about = "Check configuration file")] CheckConfig { #[structopt(required = true, parse(from_os_str))] path: PathBuf, }, } #[cfg(test)] mod tests { use super::*; #[test] fn test_main_flags() { assert_eq!( Arguments { config: DEFAULT_CONFIG_FILE.to_path_buf(), quiet: false, verbose: 0, cmd: None }, Arguments::from_clap(&Arguments::clap().get_matches_from(&["test"])) ); assert_eq!( Arguments { config: PathBuf::from(r"/etc/aur-thumbsup.toml"), quiet: false, verbose: 0, cmd: None }, Arguments::from_clap(&Arguments::clap().get_matches_from(&[ "test", "-c", "/etc/aur-thumbsup.toml" ])) ); assert_eq!( Arguments { config: PathBuf::from(r"/etc/aur-thumbsup.toml"), quiet: false, verbose: 0, cmd: None }, Arguments::from_clap(&Arguments::clap().get_matches_from(&[ "test", "--config", "/etc/aur-thumbsup.toml" ])) ); assert_eq!( Arguments { config: DEFAULT_CONFIG_FILE.to_path_buf(), quiet: true, verbose: 0, cmd: None }, Arguments::from_clap(&Arguments::clap().get_matches_from(&["test", "-q"])) ); assert_eq!( Arguments { config: DEFAULT_CONFIG_FILE.to_path_buf(), quiet: true, verbose: 0, cmd: None }, Arguments::from_clap(&Arguments::clap().get_matches_from(&["test", "--quiet"])) ); assert_eq!( Arguments { config: DEFAULT_CONFIG_FILE.to_path_buf(), quiet: false, verbose: 4, cmd: None }, Arguments::from_clap(&Arguments::clap().get_matches_from(&["test", "-vvvv"])) ); assert_eq!( Arguments { config: DEFAULT_CONFIG_FILE.to_path_buf(), quiet: false, verbose: 4, cmd: None }, Arguments::from_clap( &Arguments::clap().get_matches_from(&["test", "-v", "-v", "-v", "-v"]) ) ); assert_eq!( Arguments { config: DEFAULT_CONFIG_FILE.to_path_buf(), quiet: false, verbose: 4, cmd: None }, Arguments::from_clap(&Arguments::clap().get_matches_from(&[ "test", "--verbose", "--verbose", "--verbose", "--verbose" ])) ); } #[test] fn test_vote() { assert_eq!( Arguments { config: DEFAULT_CONFIG_FILE.to_path_buf(), quiet: false, verbose: 0, cmd: Some(Commands::Vote { packages: vec!["pkg1".to_owned(), "pkg2".to_owned()] }) }, Arguments::from_clap( &Arguments::clap().get_matches_from(&["test", "vote", "pkg1", "pkg2"]) ) ); } #[test] fn test_unvote() { assert_eq!( Arguments { config: DEFAULT_CONFIG_FILE.to_path_buf(), quiet: false, verbose: 0, cmd: Some(Commands::Unvote { packages: vec!["pkg1".to_owned(), "pkg2".to_owned()] }) }, Arguments::from_clap( &Arguments::clap().get_matches_from(&["test", "unvote", "pkg1", "pkg2"]) ) ); } #[test] fn test_check() { assert_eq!( Arguments { config: DEFAULT_CONFIG_FILE.to_path_buf(), quiet: false, verbose: 0, cmd: Some(Commands::Check { packages: vec!["pkg1".to_owned(), "pkg2".to_owned()] }) }, Arguments::from_clap( &Arguments::clap().get_matches_from(&["test", "check", "pkg1", "pkg2"]) ) ); } #[test] fn test_list() { assert_eq!( Arguments { config: DEFAULT_CONFIG_FILE.to_path_buf(), quiet: false, verbose: 0, cmd: Some(Commands::List {}) }, Arguments::from_clap(&Arguments::clap().get_matches_from(&["test", "list"])) ); } #[test] fn test_autovote() { assert_eq!( Arguments { config: DEFAULT_CONFIG_FILE.to_path_buf(), quiet: false, verbose: 0, cmd: Some(Commands::Autovote {}) }, Arguments::from_clap(&Arguments::clap().get_matches_from(&["test", "autovote"])) ); } }
27.290698
92
0.465985
623d597fbe978bff3979f2b5bc526beaf4ad808b
570
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use glib::translate::*; use TextAttributes; use TextIter; impl TextIter { pub fn get_attributes(&self, values: &TextAttributes) -> bool { unsafe { from_glib( ffi::gtk_text_iter_get_attributes(self.to_glib_none().0, mut_override(values.to_glib_none().0))) } } }
30
95
0.661404
22ce3413490b86fca1816dda0cfb10393ba27a77
2,858
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // use common_datablocks::DataBlock; use common_datavalues::prelude::SeriesFrom; use common_datavalues::series::Series; use common_datavalues::DataField; use common_datavalues::DataSchemaRefExt; use common_datavalues::DataType; use common_datavalues::DataValue; use common_exception::ErrorCode; use crate::storages::fuse::statistics::accumulator; use crate::storages::fuse::statistics::block_meta_acc; use crate::storages::fuse::statistics::util; use crate::storages::fuse::table_test_fixture::TestFixture; #[test] fn test_ft_stats_block_stats() -> common_exception::Result<()> { let schema = DataSchemaRefExt::create(vec![DataField::new("a", DataType::Int32, false)]); let block = DataBlock::create_by_array(schema, vec![Series::new(vec![1, 2, 3])]); let r = util::block_stats(&block)?; assert_eq!(1, r.len()); let col_stats = r.get(&0).unwrap(); assert_eq!(col_stats.min, DataValue::Int32(Some(1))); assert_eq!(col_stats.max, DataValue::Int32(Some(3))); Ok(()) } #[test] fn test_ft_stats_col_stats_reduce() -> common_exception::Result<()> { let blocks = TestFixture::gen_block_stream(10, 1); let schema = DataSchemaRefExt::create(vec![DataField::new("a", DataType::Int32, false)]); let col_stats = blocks .iter() .map(|b| util::block_stats(&b.clone().unwrap())) .collect::<common_exception::Result<Vec<_>>>()?; let r = util::reduce_block_stats(&col_stats, &schema); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(1, r.len()); let col_stats = r.get(&0).unwrap(); assert_eq!(col_stats.min, DataValue::Int32(Some(1))); assert_eq!(col_stats.max, DataValue::Int32(Some(3))); Ok(()) } #[test] fn test_ft_stats_accumulator() -> common_exception::Result<()> { let blocks = TestFixture::gen_block_stream(10, 1); let mut stats_acc = accumulator::StatisticsAccumulator::new(); let mut meta_acc = block_meta_acc::BlockMetaAccumulator::new(); blocks.iter().try_for_each(|item| { let item = item.clone().unwrap(); stats_acc.acc(&item)?; meta_acc.acc(1, "".to_owned(), &mut stats_acc); Ok::<_, ErrorCode>(()) })?; assert_eq!(10, stats_acc.blocks_stats.len()); // TODO more cases here pls Ok(()) }
38.106667
93
0.686844
5b3d897e556238c986524217d4b39c23a6908bba
1,671
#![allow(clippy::module_inception)] #![allow(clippy::upper_case_acronyms)] #![allow(clippy::large_enum_variant)] #![allow(clippy::wrong_self_convention)] #![allow(clippy::should_implement_trait)] #![allow(clippy::blacklisted_name)] #![allow(clippy::vec_init_then_push)] #![allow(rustdoc::bare_urls)] #![warn(missing_docs)] //! <fullname>Resource Groups Tagging API</fullname> // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use error_meta::Error; pub use config::Config; mod aws_endpoint; /// Client and fluent builders for calling the service. #[cfg(feature = "client")] pub mod client; /// Configuration for the service. pub mod config; /// Errors that can occur when calling the service. pub mod error; mod error_meta; /// Input structures for operations. pub mod input; mod json_deser; mod json_errors; mod json_ser; /// Data structures used by operation inputs/outputs. pub mod model; mod no_credentials; /// All operations that this crate can perform. pub mod operation; mod operation_deser; mod operation_ser; /// Output structures for operations. pub mod output; /// Crate version number. pub static PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); pub use aws_smithy_http::byte_stream::ByteStream; pub use aws_smithy_http::result::SdkError; pub use aws_smithy_types::Blob; static API_METADATA: aws_http::user_agent::ApiMetadata = aws_http::user_agent::ApiMetadata::new("resourcegroupstaggingapi", PKG_VERSION); pub use aws_smithy_http::endpoint::Endpoint; pub use aws_smithy_types::retry::RetryConfig; pub use aws_types::region::Region; pub use aws_types::Credentials; #[cfg(feature = "client")] pub use client::Client;
31.528302
84
0.769599
0ea543fdcb74415cea55c9b2f1a1e5f44bdc4dbf
447
// quad.rs use footile::{Path2D, Plotter}; use pix::matte::Matte8; use pix::Raster; mod png; fn main() -> Result<(), std::io::Error> { let path = Path2D::default() .relative() .pen_width(2.0) .move_to(0.0, 16.0) .quad_to(100.0, 16.0, 0.0, 32.0) .finish(); let r = Raster::with_clear(64, 64); let mut p = Plotter::new(r); png::write_matte(p.stroke(&path, Matte8::new(255)), "./quad.png") }
23.526316
69
0.55481
091786f7c752e10308ddac9d393557294231bf63
1,982
use alloc::collections::btree_map::BTreeMap as HashMap; use abscissa_core::{Command, Options, Runnable}; use ibc::core::ics24_host::identifier::ChainId; use ibc_relayer::{ config::{ChainConfig, Config}, keyring::{KeyEntry, KeyRing, Store}, }; use crate::conclude::Output; use crate::{application::app_config, conclude::json}; #[derive(Clone, Command, Debug, Options)] pub struct KeysListCmd { #[options(free, required, help = "identifier of the chain")] chain_id: ChainId, } impl KeysListCmd { fn options(&self, config: &Config) -> Result<KeysListOptions, String> { let chain_config = config .find_chain(&self.chain_id) .ok_or_else(|| format!("chain '{}' not found in configuration file", self.chain_id))?; Ok(KeysListOptions { chain_config: chain_config.clone(), }) } } impl Runnable for KeysListCmd { fn run(&self) { let config = app_config(); let opts = match self.options(&config) { Err(err) => return Output::error(err).exit(), Ok(result) => result, }; match list_keys(opts.chain_config) { Ok(keys) if json() => { let keys = keys.into_iter().collect::<HashMap<_, _>>(); Output::success(keys).exit() } Ok(keys) => { let mut msg = String::new(); for (name, key) in keys { msg.push_str(&format!("\n- {} ({})", name, key.account)); } Output::success_msg(msg).exit() } Err(e) => Output::error(e).exit(), } } } #[derive(Clone, Debug)] pub struct KeysListOptions { pub chain_config: ChainConfig, } pub fn list_keys( config: ChainConfig, ) -> Result<Vec<(String, KeyEntry)>, Box<dyn std::error::Error>> { let keyring = KeyRing::new(Store::Test, &config.account_prefix, &config.id)?; let keys = keyring.keys()?; Ok(keys) }
28.314286
98
0.571645
2884439e66ced5862aeb73a9c49c5880e260bcc5
772
pub mod unit; use crate::Scalar; /// `Direction`s are `Point`s with zero weight #[derive(Debug, Copy, Clone)] pub struct Direction { pub e01: Scalar, pub e20: Scalar, } impl std::ops::Mul<Scalar> for Direction { type Output = Direction; fn mul(self, s: Scalar) -> Direction { Direction { e01: self.e01 * s, e20: self.e20 * s, } } } impl std::ops::Mul<Direction> for Scalar { type Output = Direction; fn mul(self, d: Direction) -> Direction { d * self } } impl std::ops::Add<Direction> for Direction { type Output = Direction; fn add(self, d: Direction) -> Direction { Direction { e01: self.e01 + d.e01, e20: self.e20 + d.e20, } } }
18.829268
46
0.551813
c15973c773b7caddcd314931a8ffdb9e3e30bcea
9,202
// Copyright 2018 Kyle Mayes // // 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::env; use std::fs::File; use std::io::{self, Error, ErrorKind, Read, Seek, SeekFrom}; use std::path::{Path, PathBuf}; use super::common; /// Returns the ELF class from the ELF header in the supplied file. fn parse_elf_header(path: &Path) -> io::Result<u8> { let mut file = File::open(path)?; let mut buffer = [0; 5]; file.read_exact(&mut buffer)?; if buffer[..4] == [127, 69, 76, 70] { Ok(buffer[4]) } else { Err(Error::new(ErrorKind::InvalidData, "invalid ELF header")) } } /// Returns the magic number from the PE header in the supplied file. fn parse_pe_header(path: &Path) -> io::Result<u16> { let mut file = File::open(path)?; // Determine the header offset. let mut buffer = [0; 4]; let start = SeekFrom::Start(0x3C); file.seek(start)?; file.read_exact(&mut buffer)?; let offset = i32::from_le_bytes(buffer); // Determine the validity of the header. file.seek(SeekFrom::Start(offset as u64))?; file.read_exact(&mut buffer)?; if buffer != [80, 69, 0, 0] { return Err(Error::new(ErrorKind::InvalidData, "invalid PE header")); } // Find the magic number. let mut buffer = [0; 2]; file.seek(SeekFrom::Current(20))?; file.read_exact(&mut buffer)?; Ok(u16::from_le_bytes(buffer)) } /// Validates the header for the supplied `libclang` shared library. fn validate_header(path: &Path) -> Result<(), String> { if cfg!(any(target_os = "freebsd", target_os = "linux")) { let class = parse_elf_header(path).map_err(|e| e.to_string())?; if cfg!(target_pointer_width = "32") && class != 1 { return Err("invalid ELF class (64-bit)".into()); } if cfg!(target_pointer_width = "64") && class != 2 { return Err("invalid ELF class (32-bit)".into()); } Ok(()) } else if cfg!(target_os = "windows") { let magic = parse_pe_header(path).map_err(|e| e.to_string())?; if cfg!(target_pointer_width = "32") && magic != 267 { return Err("invalid DLL (64-bit)".into()); } if cfg!(target_pointer_width = "64") && magic != 523 { return Err("invalid DLL (32-bit)".into()); } Ok(()) } else { Ok(()) } } /// Returns the components of the version in the supplied `libclang` shared // library filename. fn parse_version(filename: &str) -> Vec<u32> { let version = if filename.starts_with("libclang.so.") { &filename[12..] } else if filename.starts_with("libclang-") { &filename[9..filename.len() - 3] } else { return vec![]; }; version.split('.').map(|s| s.parse().unwrap_or(0)).collect() } /// Returns the paths to, the filenames, and the versions of the `libclang` // shared libraries. fn search_libclang_directories(runtime: bool) -> Result<Vec<(PathBuf, String, Vec<u32>)>, String> { let mut files = vec![format!( "{}clang{}", env::consts::DLL_PREFIX, env::consts::DLL_SUFFIX )]; if cfg!(target_os = "linux") { // Some Linux distributions don't create a `libclang.so` symlink, so we // need to look for versioned files (e.g., `libclang-3.9.so`). files.push("libclang-*.so".into()); // Some Linux distributions don't create a `libclang.so` symlink and // don't have versioned files as described above, so we need to look for // suffix versioned files (e.g., `libclang.so.1`). However, `ld` cannot // link to these files, so this will only be included when linking at // runtime. if runtime { files.push("libclang.so.*".into()); files.push("libclang-*.so.*".into()); } } if cfg!(any( target_os = "openbsd", target_os = "freebsd", target_os = "netbsd" )) { // Some BSD distributions don't create a `libclang.so` symlink either, // but use a different naming scheme for versioned files (e.g., // `libclang.so.7.0`). files.push("libclang.so.*".into()); } if cfg!(target_os = "windows") { // The official LLVM build uses `libclang.dll` on Windows instead of // `clang.dll`. However, unofficial builds such as MinGW use `clang.dll`. files.push("libclang.dll".into()); } // Validate the `libclang` shared libraries and collect the versions. let mut valid = vec![]; let mut invalid = vec![]; for (directory, filename) in common::search_libclang_directories(&files, "LIBCLANG_PATH") { let path = directory.join(&filename); match validate_header(&path) { Ok(()) => { let version = parse_version(&filename); valid.push((directory, filename, version)) } Err(message) => invalid.push(format!("({}: {})", path.display(), message)), } } if !valid.is_empty() { return Ok(valid); } let message = format!( "couldn't find any valid shared libraries matching: [{}], set the \ `LIBCLANG_PATH` environment variable to a path where one of these files \ can be found (invalid: [{}])", files .iter() .map(|f| format!("'{}'", f)) .collect::<Vec<_>>() .join(", "), invalid.join(", "), ); Err(message) } /// Returns the directory and filename of the "best" available `libclang` shared /// library. pub fn find(runtime: bool) -> Result<(PathBuf, String), String> { search_libclang_directories(runtime)? .iter() // We want to find the `libclang` shared library with the highest // version number, hence `max_by_key` below. // // However, in the case where there are multiple such `libclang` shared // libraries, we want to use the order in which they appeared in the // list returned by `search_libclang_directories` as a tiebreaker since // that function returns `libclang` shared libraries in descending order // of preference by how they were found. // // `max_by_key`, perhaps surprisingly, returns the *last* item with the // maximum key rather than the first which results in the opposite of // the tiebreaking behavior we want. This is easily fixed by reversing // the list first. .rev() .max_by_key(|f| &f.2) .cloned() .map(|(path, filename, _)| (path, filename)) .ok_or_else(|| "unreachable".into()) } /// Find and link to `libclang` dynamically. #[cfg(not(feature = "runtime"))] pub fn link() { let cep = common::CommandErrorPrinter::default(); use std::fs; let (directory, filename) = find(false).unwrap(); println!("cargo:rustc-link-search={}", directory.display()); if cfg!(all(target_os = "windows", target_env = "msvc")) { // Find the `libclang` stub static library required for the MSVC // toolchain. let lib = if !directory.ends_with("bin") { directory } else { directory.parent().unwrap().join("lib") }; if lib.join("libclang.lib").exists() { println!("cargo:rustc-link-search={}", lib.display()); } else if lib.join("libclang.dll.a").exists() { // MSYS and MinGW use `libclang.dll.a` instead of `libclang.lib`. // It is linkable with the MSVC linker, but Rust doesn't recognize // the `.a` suffix, so we need to copy it with a different name. // // FIXME: Maybe we can just hardlink or symlink it? let out = env::var("OUT_DIR").unwrap(); fs::copy( lib.join("libclang.dll.a"), Path::new(&out).join("libclang.lib"), ) .unwrap(); println!("cargo:rustc-link-search=native={}", out); } else { panic!( "using '{}', so 'libclang.lib' or 'libclang.dll.a' must be \ available in {}", filename, lib.display(), ); } println!("cargo:rustc-link-lib=dylib=libclang"); } else { let name = filename.trim_start_matches("lib"); // Strip extensions and trailing version numbers (e.g., the `.so.7.0` in // `libclang.so.7.0`). let name = match name.find(".dylib").or_else(|| name.find(".so")) { Some(index) => &name[0..index], None => &name, }; println!("cargo:rustc-link-lib=dylib={}", name); } cep.discard(); }
34.988593
99
0.581178
1886f5695ab1665a87b44719dc70b13b04431c30
7,066
#[doc = "Reader of register CCACTRL"] pub type R = crate::R<u32, super::CCACTRL>; #[doc = "Writer for register CCACTRL"] pub type W = crate::W<u32, super::CCACTRL>; #[doc = "Register CCACTRL `reset()`'s with value 0"] impl crate::ResetValue for super::CCACTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "CCA mode of operation\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum CCAMODE_A { #[doc = "0: Energy above threshold"] EDMODE = 0, #[doc = "1: Carrier seen"] CARRIERMODE = 1, #[doc = "2: Energy above threshold AND carrier seen"] CARRIERANDEDMODE = 2, #[doc = "3: Energy above threshold OR carrier seen"] CARRIEROREDMODE = 3, #[doc = "4: Energy above threshold test mode that will abort when first ED measurement over threshold is seen. No averaging."] EDMODETEST1 = 4, } impl From<CCAMODE_A> for u8 { #[inline(always)] fn from(variant: CCAMODE_A) -> Self { variant as _ } } #[doc = "Reader of field `CCAMODE`"] pub type CCAMODE_R = crate::R<u8, CCAMODE_A>; impl CCAMODE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, CCAMODE_A> { use crate::Variant::*; match self.bits { 0 => Val(CCAMODE_A::EDMODE), 1 => Val(CCAMODE_A::CARRIERMODE), 2 => Val(CCAMODE_A::CARRIERANDEDMODE), 3 => Val(CCAMODE_A::CARRIEROREDMODE), 4 => Val(CCAMODE_A::EDMODETEST1), i => Res(i), } } #[doc = "Checks if the value of the field is `EDMODE`"] #[inline(always)] pub fn is_ed_mode(&self) -> bool { *self == CCAMODE_A::EDMODE } #[doc = "Checks if the value of the field is `CARRIERMODE`"] #[inline(always)] pub fn is_carrier_mode(&self) -> bool { *self == CCAMODE_A::CARRIERMODE } #[doc = "Checks if the value of the field is `CARRIERANDEDMODE`"] #[inline(always)] pub fn is_carrier_and_ed_mode(&self) -> bool { *self == CCAMODE_A::CARRIERANDEDMODE } #[doc = "Checks if the value of the field is `CARRIEROREDMODE`"] #[inline(always)] pub fn is_carrier_or_ed_mode(&self) -> bool { *self == CCAMODE_A::CARRIEROREDMODE } #[doc = "Checks if the value of the field is `EDMODETEST1`"] #[inline(always)] pub fn is_ed_mode_test1(&self) -> bool { *self == CCAMODE_A::EDMODETEST1 } } #[doc = "Write proxy for field `CCAMODE`"] pub struct CCAMODE_W<'a> { w: &'a mut W, } impl<'a> CCAMODE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CCAMODE_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Energy above threshold"] #[inline(always)] pub fn ed_mode(self) -> &'a mut W { self.variant(CCAMODE_A::EDMODE) } #[doc = "Carrier seen"] #[inline(always)] pub fn carrier_mode(self) -> &'a mut W { self.variant(CCAMODE_A::CARRIERMODE) } #[doc = "Energy above threshold AND carrier seen"] #[inline(always)] pub fn carrier_and_ed_mode(self) -> &'a mut W { self.variant(CCAMODE_A::CARRIERANDEDMODE) } #[doc = "Energy above threshold OR carrier seen"] #[inline(always)] pub fn carrier_or_ed_mode(self) -> &'a mut W { self.variant(CCAMODE_A::CARRIEROREDMODE) } #[doc = "Energy above threshold test mode that will abort when first ED measurement over threshold is seen. No averaging."] #[inline(always)] pub fn ed_mode_test1(self) -> &'a mut W { self.variant(CCAMODE_A::EDMODETEST1) } #[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 & !0x07) | ((value as u32) & 0x07); self.w } } #[doc = "Reader of field `CCAEDTHRES`"] pub type CCAEDTHRES_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CCAEDTHRES`"] pub struct CCAEDTHRES_W<'a> { w: &'a mut W, } impl<'a> CCAEDTHRES_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 & !(0xff << 8)) | (((value as u32) & 0xff) << 8); self.w } } #[doc = "Reader of field `CCACORRTHRES`"] pub type CCACORRTHRES_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CCACORRTHRES`"] pub struct CCACORRTHRES_W<'a> { w: &'a mut W, } impl<'a> CCACORRTHRES_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 & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } #[doc = "Reader of field `CCACORRCNT`"] pub type CCACORRCNT_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CCACORRCNT`"] pub struct CCACORRCNT_W<'a> { w: &'a mut W, } impl<'a> CCACORRCNT_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 & !(0xff << 24)) | (((value as u32) & 0xff) << 24); self.w } } impl R { #[doc = "Bits 0:2 - CCA mode of operation"] #[inline(always)] pub fn ccamode(&self) -> CCAMODE_R { CCAMODE_R::new((self.bits & 0x07) as u8) } #[doc = "Bits 8:15 - CCA energy busy threshold. Used in all the CCA modes except CarrierMode."] #[inline(always)] pub fn ccaedthres(&self) -> CCAEDTHRES_R { CCAEDTHRES_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 16:23 - CCA correlator busy threshold. Only relevant to CarrierMode, CarrierAndEdMode and CarrierOrEdMode."] #[inline(always)] pub fn ccacorrthres(&self) -> CCACORRTHRES_R { CCACORRTHRES_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bits 24:31 - Limit for occurances above CCACORRTHRES. When not equal to zero the corrolator based signal detect is enabled."] #[inline(always)] pub fn ccacorrcnt(&self) -> CCACORRCNT_R { CCACORRCNT_R::new(((self.bits >> 24) & 0xff) as u8) } } impl W { #[doc = "Bits 0:2 - CCA mode of operation"] #[inline(always)] pub fn ccamode(&mut self) -> CCAMODE_W { CCAMODE_W { w: self } } #[doc = "Bits 8:15 - CCA energy busy threshold. Used in all the CCA modes except CarrierMode."] #[inline(always)] pub fn ccaedthres(&mut self) -> CCAEDTHRES_W { CCAEDTHRES_W { w: self } } #[doc = "Bits 16:23 - CCA correlator busy threshold. Only relevant to CarrierMode, CarrierAndEdMode and CarrierOrEdMode."] #[inline(always)] pub fn ccacorrthres(&mut self) -> CCACORRTHRES_W { CCACORRTHRES_W { w: self } } #[doc = "Bits 24:31 - Limit for occurances above CCACORRTHRES. When not equal to zero the corrolator based signal detect is enabled."] #[inline(always)] pub fn ccacorrcnt(&mut self) -> CCACORRCNT_W { CCACORRCNT_W { w: self } } }
34.637255
138
0.601472
7199e3ac5efa12b0bb0cc2f23e9fa0a9e099e7c3
13,244
//! # OpenTelemetry Span interface //! //! A `Span` represents a single operation within a trace. `Span`s can be nested to form a trace //! tree. Each trace contains a root span, which typically describes the end-to-end latency and, //! optionally, one or more sub-spans for its sub-operations. //! //! The `Span`'s start and end timestamps reflect the elapsed real time of the operation. A `Span`'s //! start time SHOULD be set to the current time on span creation. After the `Span` is created, it //! SHOULD be possible to change its name, set its `Attributes`, and add `Links` and `Events`. //! These MUST NOT be changed after the `Span`'s end time has been set. //! //! `Spans` are not meant to be used to propagate information within a process. To prevent misuse, //! implementations SHOULD NOT provide access to a `Span`'s attributes besides its `SpanContext`. //! //! Vendors may implement the `Span` interface to effect vendor-specific logic. However, alternative //! implementations MUST NOT allow callers to create Spans directly. All `Span`s MUST be created //! via a Tracer. use crate::{trace::SpanContext, KeyValue}; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::error::Error; use std::fmt; use std::time::SystemTime; /// Interface for a single operation within a trace. pub trait Span { /// An API to record events in the context of a given `Span`. /// /// Events have a time associated with the moment when they are /// added to the `Span`. /// /// Events SHOULD preserve the order in which they're set. This will typically match /// the ordering of the events' timestamps. /// /// Note that the OpenTelemetry project documents certain ["standard event names and /// keys"](https://github.com/open-telemetry/opentelemetry-specification/tree/v0.5.0/specification/trace/semantic_conventions/README.md) /// which have prescribed semantic meanings. fn add_event<T>(&mut self, name: T, attributes: Vec<KeyValue>) where T: Into<Cow<'static, str>>, { self.add_event_with_timestamp(name, crate::time::now(), attributes) } /// Convenience method to record an exception/error as an `Event` /// /// An exception SHOULD be recorded as an Event on the span during which it occurred. /// The name of the event MUST be "exception". /// /// The semantic conventions for Errors are described in ["Semantic Conventions for Exceptions"](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/exceptions.md) /// /// For now we will not set `exception.stacktrace` attribute since the `Error::backtrace` /// method is still in nightly. Users can provide a stacktrace by using the /// `record_exception_with_stacktrace` method. /// /// Users can custom the exception message by overriding the `fmt::Display` trait's `fmt` method /// for the error. fn record_exception(&mut self, err: &dyn Error) { let attributes = vec![KeyValue::new("exception.message", err.to_string())]; self.add_event("exception".to_string(), attributes); } /// Convenience method to record a exception/error as an `Event` with custom stacktrace /// /// See `Span:record_exception` method for more details. fn record_exception_with_stacktrace<T>(&mut self, err: &dyn Error, stacktrace: T) where T: Into<Cow<'static, str>>, { let attributes = vec![ KeyValue::new("exception.message", err.to_string()), KeyValue::new("exception.stacktrace", stacktrace.into()), ]; self.add_event("exception".to_string(), attributes); } /// An API to record events at a specific time in the context of a given `Span`. /// /// Events SHOULD preserve the order in which they're set. This will typically match /// the ordering of the events' timestamps. /// /// Note that the OpenTelemetry project documents certain ["standard event names and /// keys"](https://github.com/open-telemetry/opentelemetry-specification/tree/v0.5.0/specification/trace/semantic_conventions/README.md) /// which have prescribed semantic meanings. fn add_event_with_timestamp<T>( &mut self, name: T, timestamp: SystemTime, attributes: Vec<KeyValue>, ) where T: Into<Cow<'static, str>>; /// Returns the `SpanContext` for the given `Span`. The returned value may be used even after /// the `Span is finished. The returned value MUST be the same for the entire `Span` lifetime. fn span_context(&self) -> &SpanContext; /// Returns true if this `Span` is recording information like events with the `add_event` /// operation, attributes using `set_attributes`, status with `set_status`, etc. /// /// This flag SHOULD be used to avoid expensive computations of a `Span` attributes or events in /// case when a `Span` is definitely not recorded. Note that any child span's recording is /// determined independently from the value of this flag (typically based on the sampled flag of /// a `TraceFlag` on `SpanContext`). /// /// This flag may be true despite the entire trace being sampled out. This allows to record and /// process information about the individual Span without sending it to the backend. An example /// of this scenario may be recording and processing of all incoming requests for the processing /// and building of SLA/SLO latency charts while sending only a subset - sampled spans - to the /// backend. See also the sampling section of SDK design. /// /// Users of the API should only access the `is_recording` property when instrumenting code and /// never access `SampledFlag` unless used in context propagators. fn is_recording(&self) -> bool; /// An API to set a single `Attribute` where the attribute properties are passed /// as arguments. To avoid extra allocations some implementations may offer a separate API for /// each of the possible value types. /// /// An `Attribute` is defined as a `KeyValue` pair. /// /// Attributes SHOULD preserve the order in which they're set. Setting an attribute /// with the same key as an existing attribute SHOULD overwrite the existing /// attribute's value. /// /// Note that the OpenTelemetry project documents certain ["standard /// attributes"](https://github.com/open-telemetry/opentelemetry-specification/tree/v0.5.0/specification/trace/semantic_conventions/README.md) /// that have prescribed semantic meanings. fn set_attribute(&mut self, attribute: KeyValue); /// Sets the status of the `Span`. `message` MUST be ignored when the status is `OK` or /// `Unset`. /// /// The order of status is `Ok` > `Error` > `Unset`. That's means set the status /// to `Unset` will always be ignore, set the status to `Error` only works when current /// status is `Unset`, set the status to `Ok` will be consider final and any further call /// to this function will be ignore. fn set_status(&mut self, code: StatusCode, message: String); /// Updates the `Span`'s name. After this update, any sampling behavior based on the /// name will depend on the implementation. /// /// It is highly discouraged to update the name of a `Span` after its creation. /// `Span` name is often used to group, filter and identify the logical groups of /// spans. Often, filtering logic will be implemented before the `Span` creation /// for performance reasons, and the name update may interfere with this logic. /// /// The method name is called `update_name` to differentiate this method from the /// regular property. It emphasizes that this operation signifies a /// major change for a `Span` and may lead to re-calculation of sampling or /// filtering decisions made previously depending on the implementation. fn update_name<T>(&mut self, new_name: T) where T: Into<Cow<'static, str>>; /// Finishes the `Span`. /// /// Implementations MUST ignore all subsequent calls to `end` (there might be /// exceptions when the tracer is streaming events and has no mutable state /// associated with the Span). /// /// Calls to `end` a Span MUST not have any effects on child `Span`s as they may /// still be running and can be ended later. /// /// This API MUST be non-blocking. fn end(&mut self) { self.end_with_timestamp(crate::time::now()); } /// Finishes the `Span` with given timestamp /// /// For more details, refer to [`Span::end`] /// /// [`Span::end`]: Span::end() fn end_with_timestamp(&mut self, timestamp: SystemTime); } /// `SpanKind` describes the relationship between the Span, its parents, /// and its children in a `Trace`. `SpanKind` describes two independent /// properties that benefit tracing systems during analysis. /// /// The first property described by `SpanKind` reflects whether the `Span` /// is a remote child or parent. `Span`s with a remote parent are /// interesting because they are sources of external load. `Span`s with a /// remote child are interesting because they reflect a non-local system /// dependency. /// /// The second property described by `SpanKind` reflects whether a child /// `Span` represents a synchronous call. When a child span is synchronous, /// the parent is expected to wait for it to complete under ordinary /// circumstances. It can be useful for tracing systems to know this /// property, since synchronous `Span`s may contribute to the overall trace /// latency. Asynchronous scenarios can be remote or local. /// /// In order for `SpanKind` to be meaningful, callers should arrange that /// a single `Span` does not serve more than one purpose. For example, a /// server-side span should not be used directly as the parent of another /// remote span. As a simple guideline, instrumentation should create a /// new `Span` prior to extracting and serializing the span context for a /// remote call. /// /// To summarize the interpretation of these kinds: /// /// | `SpanKind` | Synchronous | Asynchronous | Remote Incoming | Remote Outgoing | /// |------------|-----|-----|-----|-----| /// | `Client` | yes | | | yes | /// | `Server` | yes | | yes | | /// | `Producer` | | yes | | yes | /// | `Consumer` | | yes | yes | | /// | `Internal` | | | | | #[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))] #[derive(Clone, Debug, PartialEq)] pub enum SpanKind { /// Indicates that the span describes a synchronous request to /// some remote service. This span is the parent of a remote `Server` /// span and waits for its response. Client, /// Indicates that the span covers server-side handling of a /// synchronous RPC or other remote request. This span is the child of /// a remote `Client` span that was expected to wait for a response. Server, /// Indicates that the span describes the parent of an /// asynchronous request. This parent span is expected to end before /// the corresponding child `Consumer` span, possibly even before the /// child span starts. In messaging scenarios with batching, tracing /// individual messages requires a new `Producer` span per message to /// be created. Producer, /// Indicates that the span describes the child of an /// asynchronous `Producer` request. Consumer, /// Default value. Indicates that the span represents an /// internal operation within an application, as opposed to an /// operations with remote parents or children. Internal, } impl fmt::Display for SpanKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { SpanKind::Client => write!(f, "client"), SpanKind::Server => write!(f, "server"), SpanKind::Producer => write!(f, "producer"), SpanKind::Consumer => write!(f, "consumer"), SpanKind::Internal => write!(f, "internal"), } } } /// The `StatusCode` interface represents the status of a finished `Span`. /// It's composed of a canonical code in conjunction with an optional /// descriptive message. #[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))] #[derive(Clone, Debug, PartialEq, Copy)] pub enum StatusCode { /// The default status. Unset, /// OK is returned on success. Ok, /// The operation contains an error. Error, } impl StatusCode { /// Return a static str that represent the status code pub fn as_str(&self) -> &'static str { match self { StatusCode::Unset => "", StatusCode::Ok => "OK", StatusCode::Error => "ERROR", } } /// Return the priority of the status code. /// Status code with higher priority can override the lower priority one. pub(crate) fn priority(&self) -> i32 { match self { StatusCode::Unset => 0, StatusCode::Error => 1, StatusCode::Ok => 2, } } }
46.307692
230
0.672304
0a5595dc7c46571e5c1a66c9b1410e5d3e9fb9ed
69,520
use internals::symbol::*; use internals::Ctxt; use proc_macro2::{Group, Span, TokenStream, TokenTree}; use quote::ToTokens; use std::borrow::Cow; use std::collections::BTreeSet; use std::str::FromStr; use syn; use syn::parse::{self, Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::Ident; use syn::Meta::{List, NameValue, Path}; use syn::NestedMeta::{Lit, Meta}; // This module handles parsing of `#[serde(...)]` attributes. The entrypoints // are `attr::Container::from_ast`, `attr::Variant::from_ast`, and // `attr::Field::from_ast`. Each returns an instance of the corresponding // struct. Note that none of them return a Result. Unrecognized, malformed, or // duplicated attributes result in a span_err but otherwise are ignored. The // user will see errors simultaneously for all bad attributes in the crate // rather than just the first. pub use internals::case::RenameRule; struct Attr<'c, T> { cx: &'c Ctxt, name: Symbol, tokens: TokenStream, value: Option<T>, } impl<'c, T> Attr<'c, T> { fn none(cx: &'c Ctxt, name: Symbol) -> Self { Attr { cx: cx, name: name, tokens: TokenStream::new(), value: None, } } fn set<A: ToTokens>(&mut self, obj: A, value: T) { let tokens = obj.into_token_stream(); if self.value.is_some() { self.cx .error_spanned_by(tokens, format!("duplicate serde attribute `{}`", self.name)); } else { self.tokens = tokens; self.value = Some(value); } } fn set_opt<A: ToTokens>(&mut self, obj: A, value: Option<T>) { if let Some(value) = value { self.set(obj, value); } } fn set_if_none(&mut self, value: T) { if self.value.is_none() { self.value = Some(value); } } fn get(self) -> Option<T> { self.value } fn get_with_tokens(self) -> Option<(TokenStream, T)> { match self.value { Some(v) => Some((self.tokens, v)), None => None, } } } struct BoolAttr<'c>(Attr<'c, ()>); impl<'c> BoolAttr<'c> { fn none(cx: &'c Ctxt, name: Symbol) -> Self { BoolAttr(Attr::none(cx, name)) } fn set_true<A: ToTokens>(&mut self, obj: A) { self.0.set(obj, ()); } fn get(&self) -> bool { self.0.value.is_some() } } struct VecAttr<'c, T> { cx: &'c Ctxt, name: Symbol, first_dup_tokens: TokenStream, values: Vec<T>, } impl<'c, T> VecAttr<'c, T> { fn none(cx: &'c Ctxt, name: Symbol) -> Self { VecAttr { cx: cx, name: name, first_dup_tokens: TokenStream::new(), values: Vec::new(), } } fn insert<A: ToTokens>(&mut self, obj: A, value: T) { if self.values.len() == 1 { self.first_dup_tokens = obj.into_token_stream(); } self.values.push(value); } fn at_most_one(mut self) -> Result<Option<T>, ()> { if self.values.len() > 1 { let dup_token = self.first_dup_tokens; self.cx.error_spanned_by( dup_token, format!("duplicate serde attribute `{}`", self.name), ); Err(()) } else { Ok(self.values.pop()) } } fn get(self) -> Vec<T> { self.values } } pub struct Name { serialize: String, serialize_renamed: bool, deserialize: String, deserialize_renamed: bool, deserialize_aliases: Vec<String>, } #[allow(deprecated)] fn unraw(ident: &Ident) -> String { // str::trim_start_matches was added in 1.30, trim_left_matches deprecated // in 1.33. We currently support rustc back to 1.15 so we need to continue // to use the deprecated one. ident.to_string().trim_left_matches("r#").to_owned() } impl Name { fn from_attrs( source_name: String, ser_name: Attr<String>, de_name: Attr<String>, de_aliases: Option<VecAttr<String>>, ) -> Name { let deserialize_aliases = match de_aliases { Some(de_aliases) => { let mut alias_list = BTreeSet::new(); for alias_name in de_aliases.get() { alias_list.insert(alias_name); } alias_list.into_iter().collect() } None => Vec::new(), }; let ser_name = ser_name.get(); let ser_renamed = ser_name.is_some(); let de_name = de_name.get(); let de_renamed = de_name.is_some(); Name { serialize: ser_name.unwrap_or_else(|| source_name.clone()), serialize_renamed: ser_renamed, deserialize: de_name.unwrap_or(source_name), deserialize_renamed: de_renamed, deserialize_aliases: deserialize_aliases, } } /// Return the container name for the container when serializing. pub fn serialize_name(&self) -> String { self.serialize.clone() } /// Return the container name for the container when deserializing. pub fn deserialize_name(&self) -> String { self.deserialize.clone() } fn deserialize_aliases(&self) -> Vec<String> { let mut aliases = self.deserialize_aliases.clone(); let main_name = self.deserialize_name(); if !aliases.contains(&main_name) { aliases.push(main_name); } aliases } } pub struct RenameAllRules { serialize: RenameRule, deserialize: RenameRule, } /// Represents struct or enum attribute information. pub struct Container { name: Name, transparent: bool, deny_unknown_fields: bool, default: Default, rename_all_rules: RenameAllRules, ser_bound: Option<Vec<syn::WherePredicate>>, de_bound: Option<Vec<syn::WherePredicate>>, tag: TagType, type_from: Option<syn::Type>, type_try_from: Option<syn::Type>, type_into: Option<syn::Type>, remote: Option<syn::Path>, identifier: Identifier, has_flatten: bool, serde_path: Option<syn::Path>, } /// Styles of representing an enum. pub enum TagType { /// The default. /// /// ```json /// {"variant1": {"key1": "value1", "key2": "value2"}} /// ``` External, /// `#[serde(tag = "type")]` /// /// ```json /// {"type": "variant1", "key1": "value1", "key2": "value2"} /// ``` Internal { tag: String }, /// `#[serde(tag = "t", content = "c")]` /// /// ```json /// {"t": "variant1", "c": {"key1": "value1", "key2": "value2"}} /// ``` Adjacent { tag: String, content: String }, /// `#[serde(untagged)]` /// /// ```json /// {"key1": "value1", "key2": "value2"} /// ``` None, } /// Whether this enum represents the fields of a struct or the variants of an /// enum. #[derive(Copy, Clone)] pub enum Identifier { /// It does not. No, /// This enum represents the fields of a struct. All of the variants must be /// unit variants, except possibly one which is annotated with /// `#[serde(other)]` and is a newtype variant. Field, /// This enum represents the variants of an enum. All of the variants must /// be unit variants. Variant, } impl Identifier { #[cfg(feature = "deserialize_in_place")] pub fn is_some(self) -> bool { match self { Identifier::No => false, Identifier::Field | Identifier::Variant => true, } } } impl Container { /// Extract out the `#[serde(...)]` attributes from an item. pub fn from_ast(cx: &Ctxt, item: &syn::DeriveInput) -> Self { let mut ser_name = Attr::none(cx, RENAME); let mut de_name = Attr::none(cx, RENAME); let mut transparent = BoolAttr::none(cx, TRANSPARENT); let mut deny_unknown_fields = BoolAttr::none(cx, DENY_UNKNOWN_FIELDS); let mut default = Attr::none(cx, DEFAULT); let mut rename_all_ser_rule = Attr::none(cx, RENAME_ALL); let mut rename_all_de_rule = Attr::none(cx, RENAME_ALL); let mut ser_bound = Attr::none(cx, BOUND); let mut de_bound = Attr::none(cx, BOUND); let mut untagged = BoolAttr::none(cx, UNTAGGED); let mut internal_tag = Attr::none(cx, TAG); let mut content = Attr::none(cx, CONTENT); let mut type_from = Attr::none(cx, FROM); let mut type_try_from = Attr::none(cx, TRY_FROM); let mut type_into = Attr::none(cx, INTO); let mut remote = Attr::none(cx, REMOTE); let mut field_identifier = BoolAttr::none(cx, FIELD_IDENTIFIER); let mut variant_identifier = BoolAttr::none(cx, VARIANT_IDENTIFIER); let mut serde_path = Attr::none(cx, CRATE); for meta_item in item .attrs .iter() .flat_map(|attr| get_serde_meta_items(cx, attr)) .flatten() { match &meta_item { // Parse `#[serde(rename = "foo")]` Meta(NameValue(m)) if m.path == RENAME => { if let Ok(s) = get_lit_str(cx, RENAME, &m.lit) { ser_name.set(&m.path, s.value()); de_name.set(&m.path, s.value()); } } // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]` Meta(List(m)) if m.path == RENAME => { if let Ok((ser, de)) = get_renames(cx, &m.nested) { ser_name.set_opt(&m.path, ser.map(syn::LitStr::value)); de_name.set_opt(&m.path, de.map(syn::LitStr::value)); } } // Parse `#[serde(rename_all = "foo")]` Meta(NameValue(m)) if m.path == RENAME_ALL => { if let Ok(s) = get_lit_str(cx, RENAME_ALL, &m.lit) { match RenameRule::from_str(&s.value()) { Ok(rename_rule) => { rename_all_ser_rule.set(&m.path, rename_rule); rename_all_de_rule.set(&m.path, rename_rule); } Err(()) => cx.error_spanned_by( s, format!( "unknown rename rule for #[serde(rename_all = {:?})]", s.value(), ), ), } } } // Parse `#[serde(rename_all(serialize = "foo", deserialize = "bar"))]` Meta(List(m)) if m.path == RENAME_ALL => { if let Ok((ser, de)) = get_renames(cx, &m.nested) { if let Some(ser) = ser { match RenameRule::from_str(&ser.value()) { Ok(rename_rule) => rename_all_ser_rule.set(&m.path, rename_rule), Err(()) => cx.error_spanned_by( ser, format!( "unknown rename rule for #[serde(rename_all = {:?})]", ser.value(), ), ), } } if let Some(de) = de { match RenameRule::from_str(&de.value()) { Ok(rename_rule) => rename_all_de_rule.set(&m.path, rename_rule), Err(()) => cx.error_spanned_by( de, format!( "unknown rename rule for #[serde(rename_all = {:?})]", de.value(), ), ), } } } } // Parse `#[serde(transparent)]` Meta(Path(word)) if word == TRANSPARENT => { transparent.set_true(word); } // Parse `#[serde(deny_unknown_fields)]` Meta(Path(word)) if word == DENY_UNKNOWN_FIELDS => { deny_unknown_fields.set_true(word); } // Parse `#[serde(default)]` Meta(Path(word)) if word == DEFAULT => match &item.data { syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields { syn::Fields::Named(_) => { default.set(word, Default::Default); } syn::Fields::Unnamed(_) | syn::Fields::Unit => cx.error_spanned_by( fields, "#[serde(default)] can only be used on structs with named fields", ), }, syn::Data::Enum(syn::DataEnum { enum_token, .. }) => cx.error_spanned_by( enum_token, "#[serde(default)] can only be used on structs with named fields", ), syn::Data::Union(syn::DataUnion { union_token, .. }) => cx.error_spanned_by( union_token, "#[serde(default)] can only be used on structs with named fields", ), }, // Parse `#[serde(default = "...")]` Meta(NameValue(m)) if m.path == DEFAULT => { if let Ok(path) = parse_lit_into_expr_path(cx, DEFAULT, &m.lit) { match &item.data { syn::Data::Struct(syn::DataStruct { fields, .. }) => { match fields { syn::Fields::Named(_) => { default.set(&m.path, Default::Path(path)); } syn::Fields::Unnamed(_) | syn::Fields::Unit => cx .error_spanned_by( fields, "#[serde(default = \"...\")] can only be used on structs with named fields", ), } } syn::Data::Enum(syn::DataEnum { enum_token, .. }) => cx .error_spanned_by( enum_token, "#[serde(default = \"...\")] can only be used on structs with named fields", ), syn::Data::Union(syn::DataUnion { union_token, .. }) => cx.error_spanned_by( union_token, "#[serde(default = \"...\")] can only be used on structs with named fields", ), } } } // Parse `#[serde(bound = "T: SomeBound")]` Meta(NameValue(m)) if m.path == BOUND => { if let Ok(where_predicates) = parse_lit_into_where(cx, BOUND, BOUND, &m.lit) { ser_bound.set(&m.path, where_predicates.clone()); de_bound.set(&m.path, where_predicates); } } // Parse `#[serde(bound(serialize = "...", deserialize = "..."))]` Meta(List(m)) if m.path == BOUND => { if let Ok((ser, de)) = get_where_predicates(cx, &m.nested) { ser_bound.set_opt(&m.path, ser); de_bound.set_opt(&m.path, de); } } // Parse `#[serde(untagged)]` Meta(Path(word)) if word == UNTAGGED => match item.data { syn::Data::Enum(_) => { untagged.set_true(word); } syn::Data::Struct(syn::DataStruct { struct_token, .. }) => { cx.error_spanned_by( struct_token, "#[serde(untagged)] can only be used on enums", ); } syn::Data::Union(syn::DataUnion { union_token, .. }) => { cx.error_spanned_by( union_token, "#[serde(untagged)] can only be used on enums", ); } }, // Parse `#[serde(tag = "type")]` Meta(NameValue(m)) if m.path == TAG => { if let Ok(s) = get_lit_str(cx, TAG, &m.lit) { match &item.data { syn::Data::Enum(_) => { internal_tag.set(&m.path, s.value()); } syn::Data::Struct(syn::DataStruct { fields, .. }) => match fields { syn::Fields::Named(_) => { internal_tag.set(&m.path, s.value()); } syn::Fields::Unnamed(_) | syn::Fields::Unit => { cx.error_spanned_by( fields, "#[serde(tag = \"...\")] can only be used on enums and structs with named fields", ); } }, syn::Data::Union(syn::DataUnion { union_token, .. }) => { cx.error_spanned_by( union_token, "#[serde(tag = \"...\")] can only be used on enums and structs with named fields", ); } } } } // Parse `#[serde(content = "c")]` Meta(NameValue(m)) if m.path == CONTENT => { if let Ok(s) = get_lit_str(cx, CONTENT, &m.lit) { match &item.data { syn::Data::Enum(_) => { content.set(&m.path, s.value()); } syn::Data::Struct(syn::DataStruct { struct_token, .. }) => { cx.error_spanned_by( struct_token, "#[serde(content = \"...\")] can only be used on enums", ); } syn::Data::Union(syn::DataUnion { union_token, .. }) => { cx.error_spanned_by( union_token, "#[serde(content = \"...\")] can only be used on enums", ); } } } } // Parse `#[serde(from = "Type")] Meta(NameValue(m)) if m.path == FROM => { if let Ok(from_ty) = parse_lit_into_ty(cx, FROM, &m.lit) { type_from.set_opt(&m.path, Some(from_ty)); } } // Parse `#[serde(try_from = "Type")] Meta(NameValue(m)) if m.path == TRY_FROM => { if let Ok(try_from_ty) = parse_lit_into_ty(cx, TRY_FROM, &m.lit) { type_try_from.set_opt(&m.path, Some(try_from_ty)); } } // Parse `#[serde(into = "Type")] Meta(NameValue(m)) if m.path == INTO => { if let Ok(into_ty) = parse_lit_into_ty(cx, INTO, &m.lit) { type_into.set_opt(&m.path, Some(into_ty)); } } // Parse `#[serde(remote = "...")]` Meta(NameValue(m)) if m.path == REMOTE => { if let Ok(path) = parse_lit_into_path(cx, REMOTE, &m.lit) { if is_primitive_path(&path, "Self") { remote.set(&m.path, item.ident.clone().into()); } else { remote.set(&m.path, path); } } } // Parse `#[serde(field_identifier)]` Meta(Path(word)) if word == FIELD_IDENTIFIER => { field_identifier.set_true(word); } // Parse `#[serde(variant_identifier)]` Meta(Path(word)) if word == VARIANT_IDENTIFIER => { variant_identifier.set_true(word); } // Parse `#[serde(crate = "foo")]` Meta(NameValue(m)) if m.path == CRATE => { if let Ok(path) = parse_lit_into_path(cx, CRATE, &m.lit) { serde_path.set(&m.path, path) } } Meta(meta_item) => { let path = meta_item .path() .into_token_stream() .to_string() .replace(' ', ""); cx.error_spanned_by( meta_item.path(), format!("unknown serde container attribute `{}`", path), ); } Lit(lit) => { cx.error_spanned_by(lit, "unexpected literal in serde container attribute"); } } } Container { name: Name::from_attrs(unraw(&item.ident), ser_name, de_name, None), transparent: transparent.get(), deny_unknown_fields: deny_unknown_fields.get(), default: default.get().unwrap_or(Default::None), rename_all_rules: RenameAllRules { serialize: rename_all_ser_rule.get().unwrap_or(RenameRule::None), deserialize: rename_all_de_rule.get().unwrap_or(RenameRule::None), }, ser_bound: ser_bound.get(), de_bound: de_bound.get(), tag: decide_tag(cx, item, untagged, internal_tag, content), type_from: type_from.get(), type_try_from: type_try_from.get(), type_into: type_into.get(), remote: remote.get(), identifier: decide_identifier(cx, item, field_identifier, variant_identifier), has_flatten: false, serde_path: serde_path.get(), } } pub fn name(&self) -> &Name { &self.name } pub fn rename_all_rules(&self) -> &RenameAllRules { &self.rename_all_rules } pub fn transparent(&self) -> bool { self.transparent } pub fn deny_unknown_fields(&self) -> bool { self.deny_unknown_fields } pub fn default(&self) -> &Default { &self.default } pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> { self.ser_bound.as_ref().map(|vec| &vec[..]) } pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> { self.de_bound.as_ref().map(|vec| &vec[..]) } pub fn tag(&self) -> &TagType { &self.tag } pub fn type_from(&self) -> Option<&syn::Type> { self.type_from.as_ref() } pub fn type_try_from(&self) -> Option<&syn::Type> { self.type_try_from.as_ref() } pub fn type_into(&self) -> Option<&syn::Type> { self.type_into.as_ref() } pub fn remote(&self) -> Option<&syn::Path> { self.remote.as_ref() } pub fn identifier(&self) -> Identifier { self.identifier } pub fn has_flatten(&self) -> bool { self.has_flatten } pub fn mark_has_flatten(&mut self) { self.has_flatten = true; } pub fn custom_serde_path(&self) -> Option<&syn::Path> { self.serde_path.as_ref() } pub fn serde_path(&self) -> Cow<syn::Path> { self.custom_serde_path() .map_or_else(|| Cow::Owned(parse_quote!(_serde)), Cow::Borrowed) } } fn decide_tag( cx: &Ctxt, item: &syn::DeriveInput, untagged: BoolAttr, internal_tag: Attr<String>, content: Attr<String>, ) -> TagType { match ( untagged.0.get_with_tokens(), internal_tag.get_with_tokens(), content.get_with_tokens(), ) { (None, None, None) => TagType::External, (Some(_), None, None) => TagType::None, (None, Some((_, tag)), None) => { // Check that there are no tuple variants. if let syn::Data::Enum(data) = &item.data { for variant in &data.variants { match &variant.fields { syn::Fields::Named(_) | syn::Fields::Unit => {} syn::Fields::Unnamed(fields) => { if fields.unnamed.len() != 1 { cx.error_spanned_by( variant, "#[serde(tag = \"...\")] cannot be used with tuple variants", ); break; } } } } } TagType::Internal { tag: tag } } (Some((untagged_tokens, _)), Some((tag_tokens, _)), None) => { cx.error_spanned_by( untagged_tokens, "enum cannot be both untagged and internally tagged", ); cx.error_spanned_by( tag_tokens, "enum cannot be both untagged and internally tagged", ); TagType::External // doesn't matter, will error } (None, None, Some((content_tokens, _))) => { cx.error_spanned_by( content_tokens, "#[serde(tag = \"...\", content = \"...\")] must be used together", ); TagType::External } (Some((untagged_tokens, _)), None, Some((content_tokens, _))) => { cx.error_spanned_by( untagged_tokens, "untagged enum cannot have #[serde(content = \"...\")]", ); cx.error_spanned_by( content_tokens, "untagged enum cannot have #[serde(content = \"...\")]", ); TagType::External } (None, Some((_, tag)), Some((_, content))) => TagType::Adjacent { tag: tag, content: content, }, (Some((untagged_tokens, _)), Some((tag_tokens, _)), Some((content_tokens, _))) => { cx.error_spanned_by( untagged_tokens, "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]", ); cx.error_spanned_by( tag_tokens, "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]", ); cx.error_spanned_by( content_tokens, "untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]", ); TagType::External } } } fn decide_identifier( cx: &Ctxt, item: &syn::DeriveInput, field_identifier: BoolAttr, variant_identifier: BoolAttr, ) -> Identifier { match ( &item.data, field_identifier.0.get_with_tokens(), variant_identifier.0.get_with_tokens(), ) { (_, None, None) => Identifier::No, (_, Some((field_identifier_tokens, _)), Some((variant_identifier_tokens, _))) => { cx.error_spanned_by( field_identifier_tokens, "#[serde(field_identifier)] and #[serde(variant_identifier)] cannot both be set", ); cx.error_spanned_by( variant_identifier_tokens, "#[serde(field_identifier)] and #[serde(variant_identifier)] cannot both be set", ); Identifier::No } (syn::Data::Enum(_), Some(_), None) => Identifier::Field, (syn::Data::Enum(_), None, Some(_)) => Identifier::Variant, (syn::Data::Struct(syn::DataStruct { struct_token, .. }), Some(_), None) => { cx.error_spanned_by( struct_token, "#[serde(field_identifier)] can only be used on an enum", ); Identifier::No } (syn::Data::Union(syn::DataUnion { union_token, .. }), Some(_), None) => { cx.error_spanned_by( union_token, "#[serde(field_identifier)] can only be used on an enum", ); Identifier::No } (syn::Data::Struct(syn::DataStruct { struct_token, .. }), None, Some(_)) => { cx.error_spanned_by( struct_token, "#[serde(variant_identifier)] can only be used on an enum", ); Identifier::No } (syn::Data::Union(syn::DataUnion { union_token, .. }), None, Some(_)) => { cx.error_spanned_by( union_token, "#[serde(variant_identifier)] can only be used on an enum", ); Identifier::No } } } /// Represents variant attribute information pub struct Variant { name: Name, rename_all_rules: RenameAllRules, ser_bound: Option<Vec<syn::WherePredicate>>, de_bound: Option<Vec<syn::WherePredicate>>, skip_deserializing: bool, skip_serializing: bool, other: bool, serialize_with: Option<syn::ExprPath>, deserialize_with: Option<syn::ExprPath>, borrow: Option<syn::Meta>, } impl Variant { pub fn from_ast(cx: &Ctxt, variant: &syn::Variant) -> Self { let mut ser_name = Attr::none(cx, RENAME); let mut de_name = Attr::none(cx, RENAME); let mut de_aliases = VecAttr::none(cx, RENAME); let mut skip_deserializing = BoolAttr::none(cx, SKIP_DESERIALIZING); let mut skip_serializing = BoolAttr::none(cx, SKIP_SERIALIZING); let mut rename_all_ser_rule = Attr::none(cx, RENAME_ALL); let mut rename_all_de_rule = Attr::none(cx, RENAME_ALL); let mut ser_bound = Attr::none(cx, BOUND); let mut de_bound = Attr::none(cx, BOUND); let mut other = BoolAttr::none(cx, OTHER); let mut serialize_with = Attr::none(cx, SERIALIZE_WITH); let mut deserialize_with = Attr::none(cx, DESERIALIZE_WITH); let mut borrow = Attr::none(cx, BORROW); for meta_item in variant .attrs .iter() .flat_map(|attr| get_serde_meta_items(cx, attr)) .flatten() { match &meta_item { // Parse `#[serde(rename = "foo")]` Meta(NameValue(m)) if m.path == RENAME => { if let Ok(s) = get_lit_str(cx, RENAME, &m.lit) { ser_name.set(&m.path, s.value()); de_name.set_if_none(s.value()); de_aliases.insert(&m.path, s.value()); } } // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]` Meta(List(m)) if m.path == RENAME => { if let Ok((ser, de)) = get_multiple_renames(cx, &m.nested) { ser_name.set_opt(&m.path, ser.map(syn::LitStr::value)); for de_value in de { de_name.set_if_none(de_value.value()); de_aliases.insert(&m.path, de_value.value()); } } } // Parse `#[serde(alias = "foo")]` Meta(NameValue(m)) if m.path == ALIAS => { if let Ok(s) = get_lit_str(cx, ALIAS, &m.lit) { de_aliases.insert(&m.path, s.value()); } } // Parse `#[serde(rename_all = "foo")]` Meta(NameValue(m)) if m.path == RENAME_ALL => { if let Ok(s) = get_lit_str(cx, RENAME_ALL, &m.lit) { match RenameRule::from_str(&s.value()) { Ok(rename_rule) => { rename_all_ser_rule.set(&m.path, rename_rule); rename_all_de_rule.set(&m.path, rename_rule); } Err(()) => cx.error_spanned_by( s, format!( "unknown rename rule for #[serde(rename_all = {:?})]", s.value() ), ), } } } // Parse `#[serde(rename_all(serialize = "foo", deserialize = "bar"))]` Meta(List(m)) if m.path == RENAME_ALL => { if let Ok((ser, de)) = get_renames(cx, &m.nested) { if let Some(ser) = ser { match RenameRule::from_str(&ser.value()) { Ok(rename_rule) => rename_all_ser_rule.set(&m.path, rename_rule), Err(()) => cx.error_spanned_by( ser, format!( "unknown rename rule for #[serde(rename_all = {:?})]", ser.value(), ), ), } } if let Some(de) = de { match RenameRule::from_str(&de.value()) { Ok(rename_rule) => rename_all_de_rule.set(&m.path, rename_rule), Err(()) => cx.error_spanned_by( de, format!( "unknown rename rule for #[serde(rename_all = {:?})]", de.value(), ), ), } } } } // Parse `#[serde(skip)]` Meta(Path(word)) if word == SKIP => { skip_serializing.set_true(word); skip_deserializing.set_true(word); } // Parse `#[serde(skip_deserializing)]` Meta(Path(word)) if word == SKIP_DESERIALIZING => { skip_deserializing.set_true(word); } // Parse `#[serde(skip_serializing)]` Meta(Path(word)) if word == SKIP_SERIALIZING => { skip_serializing.set_true(word); } // Parse `#[serde(other)]` Meta(Path(word)) if word == OTHER => { other.set_true(word); } // Parse `#[serde(bound = "T: SomeBound")]` Meta(NameValue(m)) if m.path == BOUND => { if let Ok(where_predicates) = parse_lit_into_where(cx, BOUND, BOUND, &m.lit) { ser_bound.set(&m.path, where_predicates.clone()); de_bound.set(&m.path, where_predicates); } } // Parse `#[serde(bound(serialize = "...", deserialize = "..."))]` Meta(List(m)) if m.path == BOUND => { if let Ok((ser, de)) = get_where_predicates(cx, &m.nested) { ser_bound.set_opt(&m.path, ser); de_bound.set_opt(&m.path, de); } } // Parse `#[serde(with = "...")]` Meta(NameValue(m)) if m.path == WITH => { if let Ok(path) = parse_lit_into_expr_path(cx, WITH, &m.lit) { let mut ser_path = path.clone(); ser_path .path .segments .push(Ident::new("serialize", Span::call_site()).into()); serialize_with.set(&m.path, ser_path); let mut de_path = path; de_path .path .segments .push(Ident::new("deserialize", Span::call_site()).into()); deserialize_with.set(&m.path, de_path); } } // Parse `#[serde(serialize_with = "...")]` Meta(NameValue(m)) if m.path == SERIALIZE_WITH => { if let Ok(path) = parse_lit_into_expr_path(cx, SERIALIZE_WITH, &m.lit) { serialize_with.set(&m.path, path); } } // Parse `#[serde(deserialize_with = "...")]` Meta(NameValue(m)) if m.path == DESERIALIZE_WITH => { if let Ok(path) = parse_lit_into_expr_path(cx, DESERIALIZE_WITH, &m.lit) { deserialize_with.set(&m.path, path); } } // Defer `#[serde(borrow)]` and `#[serde(borrow = "'a + 'b")]` Meta(m) if m.path() == BORROW => match &variant.fields { syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1 => { borrow.set(m.path(), m.clone()); } _ => { cx.error_spanned_by( variant, "#[serde(borrow)] may only be used on newtype variants", ); } }, Meta(meta_item) => { let path = meta_item .path() .into_token_stream() .to_string() .replace(' ', ""); cx.error_spanned_by( meta_item.path(), format!("unknown serde variant attribute `{}`", path), ); } Lit(lit) => { cx.error_spanned_by(lit, "unexpected literal in serde variant attribute"); } } } Variant { name: Name::from_attrs(unraw(&variant.ident), ser_name, de_name, Some(de_aliases)), rename_all_rules: RenameAllRules { serialize: rename_all_ser_rule.get().unwrap_or(RenameRule::None), deserialize: rename_all_de_rule.get().unwrap_or(RenameRule::None), }, ser_bound: ser_bound.get(), de_bound: de_bound.get(), skip_deserializing: skip_deserializing.get(), skip_serializing: skip_serializing.get(), other: other.get(), serialize_with: serialize_with.get(), deserialize_with: deserialize_with.get(), borrow: borrow.get(), } } pub fn name(&self) -> &Name { &self.name } pub fn aliases(&self) -> Vec<String> { self.name.deserialize_aliases() } pub fn rename_by_rules(&mut self, rules: &RenameAllRules) { if !self.name.serialize_renamed { self.name.serialize = rules.serialize.apply_to_variant(&self.name.serialize); } if !self.name.deserialize_renamed { self.name.deserialize = rules.deserialize.apply_to_variant(&self.name.deserialize); } } pub fn rename_all_rules(&self) -> &RenameAllRules { &self.rename_all_rules } pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> { self.ser_bound.as_ref().map(|vec| &vec[..]) } pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> { self.de_bound.as_ref().map(|vec| &vec[..]) } pub fn skip_deserializing(&self) -> bool { self.skip_deserializing } pub fn skip_serializing(&self) -> bool { self.skip_serializing } pub fn other(&self) -> bool { self.other } pub fn serialize_with(&self) -> Option<&syn::ExprPath> { self.serialize_with.as_ref() } pub fn deserialize_with(&self) -> Option<&syn::ExprPath> { self.deserialize_with.as_ref() } } /// Represents field attribute information pub struct Field { name: Name, skip_serializing: bool, skip_deserializing: bool, skip_serializing_if: Option<syn::ExprPath>, default: Default, serialize_with: Option<syn::ExprPath>, deserialize_with: Option<syn::ExprPath>, ser_bound: Option<Vec<syn::WherePredicate>>, de_bound: Option<Vec<syn::WherePredicate>>, borrowed_lifetimes: BTreeSet<syn::Lifetime>, getter: Option<syn::ExprPath>, flatten: bool, transparent: bool, } /// Represents the default to use for a field when deserializing. pub enum Default { /// Field must always be specified because it does not have a default. None, /// The default is given by `std::default::Default::default()`. Default, /// The default is given by this function. Path(syn::ExprPath), } impl Default { pub fn is_none(&self) -> bool { match self { Default::None => true, Default::Default | Default::Path(_) => false, } } } impl Field { /// Extract out the `#[serde(...)]` attributes from a struct field. pub fn from_ast( cx: &Ctxt, index: usize, field: &syn::Field, attrs: Option<&Variant>, container_default: &Default, ) -> Self { let mut ser_name = Attr::none(cx, RENAME); let mut de_name = Attr::none(cx, RENAME); let mut de_aliases = VecAttr::none(cx, RENAME); let mut skip_serializing = BoolAttr::none(cx, SKIP_SERIALIZING); let mut skip_deserializing = BoolAttr::none(cx, SKIP_DESERIALIZING); let mut skip_serializing_if = Attr::none(cx, SKIP_SERIALIZING_IF); let mut default = Attr::none(cx, DEFAULT); let mut serialize_with = Attr::none(cx, SERIALIZE_WITH); let mut deserialize_with = Attr::none(cx, DESERIALIZE_WITH); let mut ser_bound = Attr::none(cx, BOUND); let mut de_bound = Attr::none(cx, BOUND); let mut borrowed_lifetimes = Attr::none(cx, BORROW); let mut getter = Attr::none(cx, GETTER); let mut flatten = BoolAttr::none(cx, FLATTEN); let ident = match &field.ident { Some(ident) => unraw(ident), None => index.to_string(), }; let variant_borrow = attrs .and_then(|variant| variant.borrow.as_ref()) .map(|borrow| Meta(borrow.clone())); for meta_item in field .attrs .iter() .flat_map(|attr| get_serde_meta_items(cx, attr)) .flatten() .chain(variant_borrow) { match &meta_item { // Parse `#[serde(rename = "foo")]` Meta(NameValue(m)) if m.path == RENAME => { if let Ok(s) = get_lit_str(cx, RENAME, &m.lit) { ser_name.set(&m.path, s.value()); de_name.set_if_none(s.value()); de_aliases.insert(&m.path, s.value()); } } // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]` Meta(List(m)) if m.path == RENAME => { if let Ok((ser, de)) = get_multiple_renames(cx, &m.nested) { ser_name.set_opt(&m.path, ser.map(syn::LitStr::value)); for de_value in de { de_name.set_if_none(de_value.value()); de_aliases.insert(&m.path, de_value.value()); } } } // Parse `#[serde(alias = "foo")]` Meta(NameValue(m)) if m.path == ALIAS => { if let Ok(s) = get_lit_str(cx, ALIAS, &m.lit) { de_aliases.insert(&m.path, s.value()); } } // Parse `#[serde(default)]` Meta(Path(word)) if word == DEFAULT => { default.set(word, Default::Default); } // Parse `#[serde(default = "...")]` Meta(NameValue(m)) if m.path == DEFAULT => { if let Ok(path) = parse_lit_into_expr_path(cx, DEFAULT, &m.lit) { default.set(&m.path, Default::Path(path)); } } // Parse `#[serde(skip_serializing)]` Meta(Path(word)) if word == SKIP_SERIALIZING => { skip_serializing.set_true(word); } // Parse `#[serde(skip_deserializing)]` Meta(Path(word)) if word == SKIP_DESERIALIZING => { skip_deserializing.set_true(word); } // Parse `#[serde(skip)]` Meta(Path(word)) if word == SKIP => { skip_serializing.set_true(word); skip_deserializing.set_true(word); } // Parse `#[serde(skip_serializing_if = "...")]` Meta(NameValue(m)) if m.path == SKIP_SERIALIZING_IF => { if let Ok(path) = parse_lit_into_expr_path(cx, SKIP_SERIALIZING_IF, &m.lit) { skip_serializing_if.set(&m.path, path); } } // Parse `#[serde(serialize_with = "...")]` Meta(NameValue(m)) if m.path == SERIALIZE_WITH => { if let Ok(path) = parse_lit_into_expr_path(cx, SERIALIZE_WITH, &m.lit) { serialize_with.set(&m.path, path); } } // Parse `#[serde(deserialize_with = "...")]` Meta(NameValue(m)) if m.path == DESERIALIZE_WITH => { if let Ok(path) = parse_lit_into_expr_path(cx, DESERIALIZE_WITH, &m.lit) { deserialize_with.set(&m.path, path); } } // Parse `#[serde(with = "...")]` Meta(NameValue(m)) if m.path == WITH => { if let Ok(path) = parse_lit_into_expr_path(cx, WITH, &m.lit) { let mut ser_path = path.clone(); ser_path .path .segments .push(Ident::new("serialize", Span::call_site()).into()); serialize_with.set(&m.path, ser_path); let mut de_path = path; de_path .path .segments .push(Ident::new("deserialize", Span::call_site()).into()); deserialize_with.set(&m.path, de_path); } } // Parse `#[serde(bound = "T: SomeBound")]` Meta(NameValue(m)) if m.path == BOUND => { if let Ok(where_predicates) = parse_lit_into_where(cx, BOUND, BOUND, &m.lit) { ser_bound.set(&m.path, where_predicates.clone()); de_bound.set(&m.path, where_predicates); } } // Parse `#[serde(bound(serialize = "...", deserialize = "..."))]` Meta(List(m)) if m.path == BOUND => { if let Ok((ser, de)) = get_where_predicates(cx, &m.nested) { ser_bound.set_opt(&m.path, ser); de_bound.set_opt(&m.path, de); } } // Parse `#[serde(borrow)]` Meta(Path(word)) if word == BORROW => { if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, field) { borrowed_lifetimes.set(word, borrowable); } } // Parse `#[serde(borrow = "'a + 'b")]` Meta(NameValue(m)) if m.path == BORROW => { if let Ok(lifetimes) = parse_lit_into_lifetimes(cx, BORROW, &m.lit) { if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, field) { for lifetime in &lifetimes { if !borrowable.contains(lifetime) { cx.error_spanned_by( field, format!( "field `{}` does not have lifetime {}", ident, lifetime ), ); } } borrowed_lifetimes.set(&m.path, lifetimes); } } } // Parse `#[serde(getter = "...")]` Meta(NameValue(m)) if m.path == GETTER => { if let Ok(path) = parse_lit_into_expr_path(cx, GETTER, &m.lit) { getter.set(&m.path, path); } } // Parse `#[serde(flatten)]` Meta(Path(word)) if word == FLATTEN => { flatten.set_true(word); } Meta(meta_item) => { let path = meta_item .path() .into_token_stream() .to_string() .replace(' ', ""); cx.error_spanned_by( meta_item.path(), format!("unknown serde field attribute `{}`", path), ); } Lit(lit) => { cx.error_spanned_by(lit, "unexpected literal in serde field attribute"); } } } // Is skip_deserializing, initialize the field to Default::default() unless a // different default is specified by `#[serde(default = "...")]` on // ourselves or our container (e.g. the struct we are in). if let Default::None = *container_default { if skip_deserializing.0.value.is_some() { default.set_if_none(Default::Default); } } let mut borrowed_lifetimes = borrowed_lifetimes.get().unwrap_or_default(); if !borrowed_lifetimes.is_empty() { // Cow<str> and Cow<[u8]> never borrow by default: // // impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T> // // A #[serde(borrow)] attribute enables borrowing that corresponds // roughly to these impls: // // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, str> // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, [u8]> if is_cow(&field.ty, is_str) { let mut path = syn::Path { leading_colon: None, segments: Punctuated::new(), }; let span = Span::call_site(); path.segments.push(Ident::new("_serde", span).into()); path.segments.push(Ident::new("private", span).into()); path.segments.push(Ident::new("de", span).into()); path.segments .push(Ident::new("borrow_cow_str", span).into()); let expr = syn::ExprPath { attrs: Vec::new(), qself: None, path: path, }; deserialize_with.set_if_none(expr); } else if is_cow(&field.ty, is_slice_u8) { let mut path = syn::Path { leading_colon: None, segments: Punctuated::new(), }; let span = Span::call_site(); path.segments.push(Ident::new("_serde", span).into()); path.segments.push(Ident::new("private", span).into()); path.segments.push(Ident::new("de", span).into()); path.segments .push(Ident::new("borrow_cow_bytes", span).into()); let expr = syn::ExprPath { attrs: Vec::new(), qself: None, path: path, }; deserialize_with.set_if_none(expr); } } else if is_implicitly_borrowed(&field.ty) { // Types &str and &[u8] are always implicitly borrowed. No need for // a #[serde(borrow)]. collect_lifetimes(&field.ty, &mut borrowed_lifetimes); } Field { name: Name::from_attrs(ident, ser_name, de_name, Some(de_aliases)), skip_serializing: skip_serializing.get(), skip_deserializing: skip_deserializing.get(), skip_serializing_if: skip_serializing_if.get(), default: default.get().unwrap_or(Default::None), serialize_with: serialize_with.get(), deserialize_with: deserialize_with.get(), ser_bound: ser_bound.get(), de_bound: de_bound.get(), borrowed_lifetimes: borrowed_lifetimes, getter: getter.get(), flatten: flatten.get(), transparent: false, } } pub fn name(&self) -> &Name { &self.name } pub fn aliases(&self) -> Vec<String> { self.name.deserialize_aliases() } pub fn rename_by_rules(&mut self, rules: &RenameAllRules) { if !self.name.serialize_renamed { self.name.serialize = rules.serialize.apply_to_field(&self.name.serialize); } if !self.name.deserialize_renamed { self.name.deserialize = rules.deserialize.apply_to_field(&self.name.deserialize); } } pub fn skip_serializing(&self) -> bool { self.skip_serializing } pub fn skip_deserializing(&self) -> bool { self.skip_deserializing } pub fn skip_serializing_if(&self) -> Option<&syn::ExprPath> { self.skip_serializing_if.as_ref() } pub fn default(&self) -> &Default { &self.default } pub fn serialize_with(&self) -> Option<&syn::ExprPath> { self.serialize_with.as_ref() } pub fn deserialize_with(&self) -> Option<&syn::ExprPath> { self.deserialize_with.as_ref() } pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> { self.ser_bound.as_ref().map(|vec| &vec[..]) } pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> { self.de_bound.as_ref().map(|vec| &vec[..]) } pub fn borrowed_lifetimes(&self) -> &BTreeSet<syn::Lifetime> { &self.borrowed_lifetimes } pub fn getter(&self) -> Option<&syn::ExprPath> { self.getter.as_ref() } pub fn flatten(&self) -> bool { self.flatten } pub fn transparent(&self) -> bool { self.transparent } pub fn mark_transparent(&mut self) { self.transparent = true; } } type SerAndDe<T> = (Option<T>, Option<T>); fn get_ser_and_de<'a, 'b, T, F>( cx: &'b Ctxt, attr_name: Symbol, metas: &'a Punctuated<syn::NestedMeta, Token![,]>, f: F, ) -> Result<(VecAttr<'b, T>, VecAttr<'b, T>), ()> where T: 'a, F: Fn(&Ctxt, Symbol, Symbol, &'a syn::Lit) -> Result<T, ()>, { let mut ser_meta = VecAttr::none(cx, attr_name); let mut de_meta = VecAttr::none(cx, attr_name); for meta in metas { match meta { Meta(NameValue(meta)) if meta.path == SERIALIZE => { if let Ok(v) = f(cx, attr_name, SERIALIZE, &meta.lit) { ser_meta.insert(&meta.path, v); } } Meta(NameValue(meta)) if meta.path == DESERIALIZE => { if let Ok(v) = f(cx, attr_name, DESERIALIZE, &meta.lit) { de_meta.insert(&meta.path, v); } } _ => { cx.error_spanned_by( meta, format!( "malformed {0} attribute, expected `{0}(serialize = ..., deserialize = ...)`", attr_name ), ); return Err(()); } } } Ok((ser_meta, de_meta)) } fn get_renames<'a>( cx: &Ctxt, items: &'a Punctuated<syn::NestedMeta, Token![,]>, ) -> Result<SerAndDe<&'a syn::LitStr>, ()> { let (ser, de) = get_ser_and_de(cx, RENAME, items, get_lit_str2)?; Ok((ser.at_most_one()?, de.at_most_one()?)) } fn get_multiple_renames<'a>( cx: &Ctxt, items: &'a Punctuated<syn::NestedMeta, Token![,]>, ) -> Result<(Option<&'a syn::LitStr>, Vec<&'a syn::LitStr>), ()> { let (ser, de) = get_ser_and_de(cx, RENAME, items, get_lit_str2)?; Ok((ser.at_most_one()?, de.get())) } fn get_where_predicates( cx: &Ctxt, items: &Punctuated<syn::NestedMeta, Token![,]>, ) -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> { let (ser, de) = get_ser_and_de(cx, BOUND, items, parse_lit_into_where)?; Ok((ser.at_most_one()?, de.at_most_one()?)) } pub fn get_serde_meta_items(cx: &Ctxt, attr: &syn::Attribute) -> Result<Vec<syn::NestedMeta>, ()> { if attr.path != SERDE { return Ok(Vec::new()); } match attr.parse_meta() { Ok(List(meta)) => Ok(meta.nested.into_iter().collect()), Ok(other) => { cx.error_spanned_by(other, "expected #[serde(...)]"); Err(()) } Err(err) => { cx.syn_error(err); Err(()) } } } fn get_lit_str<'a>(cx: &Ctxt, attr_name: Symbol, lit: &'a syn::Lit) -> Result<&'a syn::LitStr, ()> { get_lit_str2(cx, attr_name, attr_name, lit) } fn get_lit_str2<'a>( cx: &Ctxt, attr_name: Symbol, meta_item_name: Symbol, lit: &'a syn::Lit, ) -> Result<&'a syn::LitStr, ()> { if let syn::Lit::Str(lit) = lit { Ok(lit) } else { cx.error_spanned_by( lit, format!( "expected serde {} attribute to be a string: `{} = \"...\"`", attr_name, meta_item_name ), ); Err(()) } } fn parse_lit_into_path(cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit) -> Result<syn::Path, ()> { let string = get_lit_str(cx, attr_name, lit)?; parse_lit_str(string).map_err(|_| { cx.error_spanned_by(lit, format!("failed to parse path: {:?}", string.value())) }) } fn parse_lit_into_expr_path( cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit, ) -> Result<syn::ExprPath, ()> { let string = get_lit_str(cx, attr_name, lit)?; parse_lit_str(string).map_err(|_| { cx.error_spanned_by(lit, format!("failed to parse path: {:?}", string.value())) }) } fn parse_lit_into_where( cx: &Ctxt, attr_name: Symbol, meta_item_name: Symbol, lit: &syn::Lit, ) -> Result<Vec<syn::WherePredicate>, ()> { let string = get_lit_str2(cx, attr_name, meta_item_name, lit)?; if string.value().is_empty() { return Ok(Vec::new()); } let where_string = syn::LitStr::new(&format!("where {}", string.value()), string.span()); parse_lit_str::<syn::WhereClause>(&where_string) .map(|wh| wh.predicates.into_iter().collect()) .map_err(|err| cx.error_spanned_by(lit, err)) } fn parse_lit_into_ty(cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit) -> Result<syn::Type, ()> { let string = get_lit_str(cx, attr_name, lit)?; parse_lit_str(string).map_err(|_| { cx.error_spanned_by( lit, format!("failed to parse type: {} = {:?}", attr_name, string.value()), ) }) } // Parses a string literal like "'a + 'b + 'c" containing a nonempty list of // lifetimes separated by `+`. fn parse_lit_into_lifetimes( cx: &Ctxt, attr_name: Symbol, lit: &syn::Lit, ) -> Result<BTreeSet<syn::Lifetime>, ()> { let string = get_lit_str(cx, attr_name, lit)?; if string.value().is_empty() { cx.error_spanned_by(lit, "at least one lifetime must be borrowed"); return Err(()); } struct BorrowedLifetimes(Punctuated<syn::Lifetime, Token![+]>); impl Parse for BorrowedLifetimes { fn parse(input: ParseStream) -> parse::Result<Self> { Punctuated::parse_separated_nonempty(input).map(BorrowedLifetimes) } } if let Ok(BorrowedLifetimes(lifetimes)) = parse_lit_str(string) { let mut set = BTreeSet::new(); for lifetime in lifetimes { if !set.insert(lifetime.clone()) { cx.error_spanned_by(lit, format!("duplicate borrowed lifetime `{}`", lifetime)); } } return Ok(set); } cx.error_spanned_by( lit, format!("failed to parse borrowed lifetimes: {:?}", string.value()), ); Err(()) } fn is_implicitly_borrowed(ty: &syn::Type) -> bool { is_implicitly_borrowed_reference(ty) || is_option(ty, is_implicitly_borrowed_reference) } fn is_implicitly_borrowed_reference(ty: &syn::Type) -> bool { is_reference(ty, is_str) || is_reference(ty, is_slice_u8) } // Whether the type looks like it might be `std::borrow::Cow<T>` where elem="T". // This can have false negatives and false positives. // // False negative: // // use std::borrow::Cow as Pig; // // #[derive(Deserialize)] // struct S<'a> { // #[serde(borrow)] // pig: Pig<'a, str>, // } // // False positive: // // type str = [i16]; // // #[derive(Deserialize)] // struct S<'a> { // #[serde(borrow)] // cow: Cow<'a, str>, // } fn is_cow(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool { let path = match ty { syn::Type::Path(ty) => &ty.path, _ => { return false; } }; let seg = match path.segments.last() { Some(seg) => seg, None => { return false; } }; let args = match &seg.arguments { syn::PathArguments::AngleBracketed(bracketed) => &bracketed.args, _ => { return false; } }; seg.ident == "Cow" && args.len() == 2 && match (&args[0], &args[1]) { (syn::GenericArgument::Lifetime(_), syn::GenericArgument::Type(arg)) => elem(arg), _ => false, } } fn is_option(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool { let path = match ty { syn::Type::Path(ty) => &ty.path, _ => { return false; } }; let seg = match path.segments.last() { Some(seg) => seg, None => { return false; } }; let args = match &seg.arguments { syn::PathArguments::AngleBracketed(bracketed) => &bracketed.args, _ => { return false; } }; seg.ident == "Option" && args.len() == 1 && match &args[0] { syn::GenericArgument::Type(arg) => elem(arg), _ => false, } } // Whether the type looks like it might be `&T` where elem="T". This can have // false negatives and false positives. // // False negative: // // type Yarn = str; // // #[derive(Deserialize)] // struct S<'a> { // r: &'a Yarn, // } // // False positive: // // type str = [i16]; // // #[derive(Deserialize)] // struct S<'a> { // r: &'a str, // } fn is_reference(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool { match ty { syn::Type::Reference(ty) => ty.mutability.is_none() && elem(&ty.elem), _ => false, } } fn is_str(ty: &syn::Type) -> bool { is_primitive_type(ty, "str") } fn is_slice_u8(ty: &syn::Type) -> bool { match ty { syn::Type::Slice(ty) => is_primitive_type(&ty.elem, "u8"), _ => false, } } fn is_primitive_type(ty: &syn::Type, primitive: &str) -> bool { match ty { syn::Type::Path(ty) => ty.qself.is_none() && is_primitive_path(&ty.path, primitive), _ => false, } } fn is_primitive_path(path: &syn::Path, primitive: &str) -> bool { path.leading_colon.is_none() && path.segments.len() == 1 && path.segments[0].ident == primitive && path.segments[0].arguments.is_empty() } // All lifetimes that this type could borrow from a Deserializer. // // For example a type `S<'a, 'b>` could borrow `'a` and `'b`. On the other hand // a type `for<'a> fn(&'a str)` could not borrow `'a` from the Deserializer. // // This is used when there is an explicit or implicit `#[serde(borrow)]` // attribute on the field so there must be at least one borrowable lifetime. fn borrowable_lifetimes( cx: &Ctxt, name: &str, field: &syn::Field, ) -> Result<BTreeSet<syn::Lifetime>, ()> { let mut lifetimes = BTreeSet::new(); collect_lifetimes(&field.ty, &mut lifetimes); if lifetimes.is_empty() { cx.error_spanned_by( field, format!("field `{}` has no lifetimes to borrow", name), ); Err(()) } else { Ok(lifetimes) } } fn collect_lifetimes(ty: &syn::Type, out: &mut BTreeSet<syn::Lifetime>) { match ty { syn::Type::Slice(ty) => { collect_lifetimes(&ty.elem, out); } syn::Type::Array(ty) => { collect_lifetimes(&ty.elem, out); } syn::Type::Ptr(ty) => { collect_lifetimes(&ty.elem, out); } syn::Type::Reference(ty) => { out.extend(ty.lifetime.iter().cloned()); collect_lifetimes(&ty.elem, out); } syn::Type::Tuple(ty) => { for elem in &ty.elems { collect_lifetimes(elem, out); } } syn::Type::Path(ty) => { if let Some(qself) = &ty.qself { collect_lifetimes(&qself.ty, out); } for seg in &ty.path.segments { if let syn::PathArguments::AngleBracketed(bracketed) = &seg.arguments { for arg in &bracketed.args { match arg { syn::GenericArgument::Lifetime(lifetime) => { out.insert(lifetime.clone()); } syn::GenericArgument::Type(ty) => { collect_lifetimes(ty, out); } syn::GenericArgument::Binding(binding) => { collect_lifetimes(&binding.ty, out); } syn::GenericArgument::Constraint(_) | syn::GenericArgument::Const(_) => {} } } } } } syn::Type::Paren(ty) => { collect_lifetimes(&ty.elem, out); } syn::Type::Group(ty) => { collect_lifetimes(&ty.elem, out); } syn::Type::BareFn(_) | syn::Type::Never(_) | syn::Type::TraitObject(_) | syn::Type::ImplTrait(_) | syn::Type::Infer(_) | syn::Type::Macro(_) | syn::Type::Verbatim(_) | _ => {} } } fn parse_lit_str<T>(s: &syn::LitStr) -> parse::Result<T> where T: Parse, { let tokens = spanned_tokens(s)?; syn::parse2(tokens) } fn spanned_tokens(s: &syn::LitStr) -> parse::Result<TokenStream> { let stream = syn::parse_str(&s.value())?; Ok(respan_token_stream(stream, s.span())) } fn respan_token_stream(stream: TokenStream, span: Span) -> TokenStream { stream .into_iter() .map(|token| respan_token_tree(token, span)) .collect() } fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree { if let TokenTree::Group(g) = &mut token { *g = Group::new(g.delimiter(), respan_token_stream(g.stream(), span)); } token.set_span(span); token }
35.742931
126
0.466945
3a0b940bbb70154d56205435ac2d3412c0bede8d
4,579
use crate::geom::CurveLinesIterator; use crate::geom::Line; use crate::geom::Point; /// /// See: https://youtu.be/aVwxzDHniEw /// See: https://pomax.github.io/bezierinfo/ /// #[derive(Copy, Clone, Debug, PartialEq)] pub struct BCurve<const N: usize> { pub(crate) points: [Point; N], } #[derive(Copy, Clone, Debug, PartialEq)] struct CurvePoint(pub Line); /// The number of times to chop up a curve when calculating it's length. /// Number picked is entirely arbituary. I have no idea if it's a good / bad number. const LENGTH_SEGMENTS: u32 = 12; impl<const N: usize> BCurve<N> { pub fn new_from_points(points: [Point; N]) -> Self { Self { points } } pub fn as_line(&self) -> Line { Line(self.start(), self.end()) } pub fn start(&self) -> Point { self.points[0] } pub fn end(&self) -> Point { self.points[N - 1] } pub fn interpolation_line(self, start_n: f32, end_n: f32) -> Line { Line( self.interpolation_point(start_n), self.interpolation_point(end_n), ) } pub fn interpolation_point(self, n: f32) -> Point { let mut ps: [Point; N] = self.points.clone(); let mut count = N - 1; while count > 0 { for i in 0..count { ps[i] = Line(ps[i], ps[i + 1]).transition_point(n); } count -= 1; } ps[0] } /// An approximate total length for the curve. pub fn length(self) -> f32 { self.length_by_segments(LENGTH_SEGMENTS) } /// Calculates an approximate length of the curve, /// using the number of segments you provide. /// /// The lower the number of segments, the faster this will run. /// However it will be less accurate. A higher number will be slower, /// but more accurate. fn length_by_segments(self, num_segments: u32) -> f32 { self.iter_interpolation_lines(num_segments) .fold(0.0, |total, line| total + line.hypot()) } pub fn iter_interpolation_lines<'a>(&'a self, num_lines: u32) -> CurveLinesIterator<'a, N> { CurveLinesIterator::new(self, num_lines) } } impl<const N: usize> Into<Line> for BCurve<N> { fn into(self) -> Line { self.as_line() } } #[cfg(test)] mod interpolation_line { use super::*; #[test] fn it_should_return_whole_line_when_from_start_to_end() { let curve = BCurve::new_from_points([ Point(100.0, 100.0), Point(200.0, 200.0), Point(200.0, 400.0), Point(100.0, 500.0), ]); assert_eq!( curve.interpolation_line(0.0, 1.0), Line(Point(100.0, 100.0), Point(100.0, 500.0)), ); } #[test] fn it_should_return_first_half_on_straight_curve() { let curve = BCurve::new_from_points([ Point(1.0, 0.0), Point(1.0, 2.0), Point(1.0, 8.0), Point(1.0, 10.0), ]); assert_eq!( curve.interpolation_line(0.0, 0.5), Line(Point(1.0, 0.0), Point(1.0, 5.0)), ); } } #[cfg(test)] mod interpolation_point { use super::*; #[test] fn it_should_return_first_half_on_straight_curve() { let curve = BCurve::new_from_points([ Point(1.0, 0.0), Point(1.0, 2.0), Point(1.0, 8.0), Point(1.0, 10.0), ]); assert_eq!(curve.interpolation_point(0.5), Point(1.0, 5.0)); } } #[cfg(test)] mod iter_interpolation_lines { use super::*; use crate::geom::Point; #[test] fn it_should_return_number_of_lines_asked_for() { let curve = BCurve::new_from_points([ Point(1.0, 0.0), Point(1.0, 2.0), Point(1.0, 8.0), Point(1.0, 10.0), ]); assert_eq!(13, curve.iter_interpolation_lines(13).count()); } #[test] fn it_should_return_the_lines_we_expect() { let curve = BCurve::new_from_points([ Point(0.0, 0.0), Point(0.0, 0.0), Point(10.0, 10.0), Point(10.0, 10.0), ]); let lines: Vec<Line> = curve.iter_interpolation_lines(4).collect(); assert_eq!( lines, &[ Line(Point(0.0, 0.0), Point(1.5625, 1.5625)), Line(Point(1.5625, 1.5625), Point(5.0, 5.0)), Line(Point(5.0, 5.0), Point(8.4375, 8.4375)), Line(Point(8.4375, 8.4375), Point(10.0, 10.0)) ] ); } }
25.870056
96
0.540948
01abd73da345613f5eb712307b7bd8e41159120f
1,073
// Conditionals -Used to check the condision of something and act //basic if statement syntax use pub fn run(){ let mut age:u8 = 18; let check_id: bool = true; let knows_person_of_age = true; // And operator is the same as other languages if age >= 21 && check_id { println!("Bartender says yes....\n"); } else if age < 21 && check_id{ println!("Bartender says NO!!!!!! \n"); } else { println!("ID please: \n"); } // Or operator is the same as other languages age = 21; println!("...New Section...\n"); if age >= 21 && check_id || knows_person_of_age { println!("Bartender says yes....\n"); } else if age < 21 && check_id{ println!("Bartender says NO!!!!!!\n"); } else { println!("ID please: \n"); } // note: there are no ternary operator in rust but short hand is possible for If statments println!("...New Section...\n"); let is_of_age = if age >= 21 {true} else {false}; println!("Is of age: {}",is_of_age) } //next concept -> loops.rs
30.657143
98
0.577819
f7a92bc0795672631544d48d72304131ca875d21
5,200
use clippy_utils::diagnostics::span_lint_and_help; use rustc_ast::ast::{AssocItemKind, Extern, Fn, FnSig, Impl, Item, ItemKind, Trait, Ty, TyKind}; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::{sym, Span}; declare_clippy_lint! { /// ### What it does /// Checks for excessive /// use of bools in structs. /// /// ### Why is this bad? /// Excessive bools in a struct /// is often a sign that it's used as a state machine, /// which is much better implemented as an enum. /// If it's not the case, excessive bools usually benefit /// from refactoring into two-variant enums for better /// readability and API. /// /// ### Example /// ```rust /// struct S { /// is_pending: bool, /// is_processing: bool, /// is_finished: bool, /// } /// ``` /// /// Use instead: /// ```rust /// enum S { /// Pending, /// Processing, /// Finished, /// } /// ``` #[clippy::version = "1.43.0"] pub STRUCT_EXCESSIVE_BOOLS, pedantic, "using too many bools in a struct" } declare_clippy_lint! { /// ### What it does /// Checks for excessive use of /// bools in function definitions. /// /// ### Why is this bad? /// Calls to such functions /// are confusing and error prone, because it's /// hard to remember argument order and you have /// no type system support to back you up. Using /// two-variant enums instead of bools often makes /// API easier to use. /// /// ### Example /// ```rust,ignore /// fn f(is_round: bool, is_hot: bool) { ... } /// ``` /// /// Use instead: /// ```rust,ignore /// enum Shape { /// Round, /// Spiky, /// } /// /// enum Temperature { /// Hot, /// IceCold, /// } /// /// fn f(shape: Shape, temperature: Temperature) { ... } /// ``` #[clippy::version = "1.43.0"] pub FN_PARAMS_EXCESSIVE_BOOLS, pedantic, "using too many bools in function parameters" } pub struct ExcessiveBools { max_struct_bools: u64, max_fn_params_bools: u64, } impl ExcessiveBools { #[must_use] pub fn new(max_struct_bools: u64, max_fn_params_bools: u64) -> Self { Self { max_struct_bools, max_fn_params_bools, } } fn check_fn_sig(&self, cx: &EarlyContext<'_>, fn_sig: &FnSig, span: Span) { match fn_sig.header.ext { Extern::Implicit | Extern::Explicit(_) => return, Extern::None => (), } let fn_sig_bools = fn_sig .decl .inputs .iter() .filter(|param| is_bool_ty(&param.ty)) .count() .try_into() .unwrap(); if self.max_fn_params_bools < fn_sig_bools { span_lint_and_help( cx, FN_PARAMS_EXCESSIVE_BOOLS, span, &format!("more than {} bools in function parameters", self.max_fn_params_bools), None, "consider refactoring bools into two-variant enums", ); } } } impl_lint_pass!(ExcessiveBools => [STRUCT_EXCESSIVE_BOOLS, FN_PARAMS_EXCESSIVE_BOOLS]); fn is_bool_ty(ty: &Ty) -> bool { if let TyKind::Path(None, path) = &ty.kind { if let [name] = path.segments.as_slice() { return name.ident.name == sym::bool; } } false } impl EarlyLintPass for ExcessiveBools { fn check_item(&mut self, cx: &EarlyContext<'_>, item: &Item) { if item.span.from_expansion() { return; } match &item.kind { ItemKind::Struct(variant_data, _) => { if item.attrs.iter().any(|attr| attr.has_name(sym::repr)) { return; } let struct_bools = variant_data .fields() .iter() .filter(|field| is_bool_ty(&field.ty)) .count() .try_into() .unwrap(); if self.max_struct_bools < struct_bools { span_lint_and_help( cx, STRUCT_EXCESSIVE_BOOLS, item.span, &format!("more than {} bools in a struct", self.max_struct_bools), None, "consider using a state machine or refactoring bools into two-variant enums", ); } }, ItemKind::Impl(box Impl { of_trait: None, items, .. }) | ItemKind::Trait(box Trait { items, .. }) => { for item in items { if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind { self.check_fn_sig(cx, sig, item.span); } } }, ItemKind::Fn(box Fn { sig, .. }) => self.check_fn_sig(cx, sig, item.span), _ => (), } } }
29.378531
101
0.501346
61c8fd3d8e956d860580b1dc851dcf945c9a18d5
1,298
use device_tree::util::SliceRead; use device_tree::Node; use log::*; use rcore_memory::PAGE_SIZE; use virtio_drivers::{DeviceType, VirtIOHeader}; use super::super::block::virtio_blk; use super::super::gpu::virtio_gpu; use super::super::input::virtio_input; use super::super::net::virtio_net; use crate::memory::phys_to_virt; pub fn virtio_probe(node: &Node) { let reg = match node.prop_raw("reg") { Some(reg) => reg, _ => return, }; let paddr = reg.as_slice().read_be_u64(0).unwrap(); let vaddr = phys_to_virt(paddr as usize); let size = reg.as_slice().read_be_u64(8).unwrap(); // assuming one page assert_eq!(size as usize, PAGE_SIZE); let header = unsafe { &mut *(vaddr as *mut VirtIOHeader) }; if !header.verify() { // only support legacy device return; } info!( "Detected virtio device with vendor id: {:#X}", header.vendor_id() ); info!("Device tree node {:?}", node); match header.device_type() { DeviceType::Network => virtio_net::init(header), DeviceType::Block => virtio_blk::init(header), DeviceType::GPU => virtio_gpu::init(header), DeviceType::Input => virtio_input::init(header), t => warn!("Unrecognized virtio device: {:?}", t), } }
31.658537
63
0.6302
e650c68917bf7395e100bf3104e6914473c618c9
1,563
use std::cmp; use std::collections::HashMap; use super::input; pub fn f() { let input = input::read_parse(5, parse); let mut point_count = HashMap::new(); for line in &input { let line_points = line_points(&line); for point in line_points { let p = point_count.entry(point).or_insert(0); *p += 1; } } let mut total = 0; for point in &point_count { if *point.1 >= 2 { total += 1; } } println!("{:?}", total); } #[derive(Debug)] struct Line { start: (i32, i32), end: (i32, i32), } fn parse(s: &str) -> Line { let (startstr, endstr) = s.split_once(" -> ").unwrap(); let start = startstr .split_once(",") .map(|(x, y)| (x.parse().unwrap(), y.parse().unwrap())) .unwrap(); let end = endstr .split_once(",") .map(|(x, y)| (x.parse().unwrap(), y.parse().unwrap())) .unwrap(); Line { start: start, end: end, } } fn line_points(l: &Line) -> Vec<(i32, i32)> { let mut points = Vec::new(); let start = l.start; let end = l.end; let dx: i32 = if start.0 < end.0 { 1 } else if start.0 > end.0 { -1 } else { 0 }; let dy: i32 = if start.1 < end.1 { 1 } else if start.1 > end.1 { -1 } else { 0 }; let mut current = start; while current != end { points.push(current); current.0 += dx; current.1 += dy; } points.push(end); points }
19.060976
63
0.474088
1dbcfd0c7b784025584b3df18499015255922edf
5,032
//! Miscellaneous utility and helper functions use geometric_algebra::{ppga2d, ppga3d, OuterProduct, Transformation, Zero}; use std::convert::TryInto; /// Transmutes a vector. pub fn transmute_vec<S, T>(mut vec: Vec<S>) -> Vec<T> { let ptr = vec.as_mut_ptr() as *mut T; let len = vec.len() * std::mem::size_of::<S>() / std::mem::size_of::<T>(); let capacity = vec.capacity() * std::mem::size_of::<S>() / std::mem::size_of::<T>(); std::mem::forget(vec); unsafe { Vec::from_raw_parts(ptr, len, capacity) } } /// Transmutes a slice. pub fn transmute_slice<S, T>(slice: &[S]) -> &[T] { let ptr = slice.as_ptr() as *const T; let len = slice.len() * std::mem::size_of::<S>() / std::mem::size_of::<T>(); unsafe { std::slice::from_raw_parts(ptr, len) } } /// Transmutes a mutable slice. pub fn transmute_slice_mut<S, T>(slice: &mut [S]) -> &mut [T] { let ptr = slice.as_mut_ptr() as *mut T; let len = slice.len() * std::mem::size_of::<S>() / std::mem::size_of::<T>(); unsafe { std::slice::from_raw_parts_mut(ptr, len) } } /// Returns the intersection point of two 2D lines (origin, direction). pub fn line_line_intersection(a: ppga2d::Plane, b: ppga2d::Plane) -> ppga2d::Point { let p = a.outer_product(b); p / ppga2d::Scalar { g0: p.g0[0] } } /// Rotates a [ppga2d::Plane] 90° clockwise. pub fn rotate_90_degree_clockwise(v: ppga2d::Plane) -> ppga2d::Plane { ppga2d::Plane { g0: [0.0, v.g0[2], -v.g0[1]].into(), } } /// Projects a [ppga2d::Point]. pub fn point_to_vec(p: ppga2d::Point) -> [f32; 2] { [p.g0[1] / p.g0[0], p.g0[2] / p.g0[0]] } /// Creates an unweighted [ppga2d::Point]. pub fn vec_to_point(v: [f32; 2]) -> ppga2d::Point { ppga2d::Point { g0: [1.0, v[0], v[1]].into(), } } /// Creates a weighted [ppga2d::Point]. pub fn weighted_vec_to_point(w: f32, v: [f32; 2]) -> ppga2d::Point { ppga2d::Point { g0: [w, v[0] * w, v[1] * w].into(), } } /// Creates a [ppga3d::Rotor] which represents a rotation by `angle` radians around `axis`. pub fn rotate_around_axis(angle: f32, axis: &[f32; 3]) -> ppga3d::Rotor { let sinus = (angle * 0.5).sin(); ppga3d::Rotor { g0: [(angle * 0.5).cos(), axis[0] * sinus, axis[1] * sinus, axis[2] * sinus].into(), } } /// Converts a [ppga2d::Motor] to a [ppga3d::Motor]. pub fn motor2d_to_motor3d(motor: &ppga2d::Motor) -> ppga3d::Motor { ppga3d::Motor { g0: [motor.g0[0], 0.0, 0.0, motor.g0[1]].into(), g1: [0.0, motor.g0[3], -motor.g0[2], 0.0].into(), } } /// Converts a [ppga2d::Motor] to a 3x3 matrix for WebGPU. pub fn motor2d_to_mat3(motor: &ppga2d::Motor) -> [ppga2d::Point; 3] { let result = [1, 2, 0] .iter() .map(|index| { let mut point = ppga2d::Point::zero(); point.g0[*index] = 1.0; let row = motor.transformation(point); ppga2d::Point { g0: [row.g0[1], row.g0[2], row.g0[0]].into(), } }) .collect::<Vec<_>>(); result.try_into().unwrap() } /// Converts a [ppga3d::Motor] to a 4x4 matrix for WebGPU. pub fn motor3d_to_mat4(motor: &ppga3d::Motor) -> [ppga3d::Point; 4] { let result = [1, 2, 3, 0] .iter() .map(|index| { let mut point = ppga3d::Point::zero(); point.g0[*index] = 1.0; let row = motor.transformation(point); ppga3d::Point { g0: [row.g0[1], row.g0[2], row.g0[3], row.g0[0]].into(), } }) .collect::<Vec<_>>(); result.try_into().unwrap() } /// Creates a 4x4 perspective projection matrix for GLSL. pub fn perspective_projection(field_of_view_y: f32, aspect_ratio: f32, near: f32, far: f32) -> [ppga3d::Point; 4] { let height = 1.0 / (field_of_view_y * 0.5).tan(); let denominator = 1.0 / (near - far); [ ppga3d::Point { g0: [height / aspect_ratio, 0.0, 0.0, 0.0].into(), }, ppga3d::Point { g0: [0.0, height, 0.0, 0.0].into(), }, ppga3d::Point { g0: [0.0, 0.0, -far * denominator, 1.0].into(), }, ppga3d::Point { g0: [0.0, 0.0, near * far * denominator, 0.0].into(), }, ] } /// Calculates the product of two 4x4 matrices for GLSL. pub fn matrix_multiplication(a: &[ppga3d::Point; 4], b: &[ppga3d::Point; 4]) -> [ppga3d::Point; 4] { use ppga3d::Scalar; [ Scalar { g0: b[0].g0[0] } * a[0] + Scalar { g0: b[0].g0[1] } * a[1] + Scalar { g0: b[0].g0[2] } * a[2] + Scalar { g0: b[0].g0[3] } * a[3], Scalar { g0: b[1].g0[0] } * a[0] + Scalar { g0: b[1].g0[1] } * a[1] + Scalar { g0: b[1].g0[2] } * a[2] + Scalar { g0: b[1].g0[3] } * a[3], Scalar { g0: b[2].g0[0] } * a[0] + Scalar { g0: b[2].g0[1] } * a[1] + Scalar { g0: b[2].g0[2] } * a[2] + Scalar { g0: b[2].g0[3] } * a[3], Scalar { g0: b[3].g0[0] } * a[0] + Scalar { g0: b[3].g0[1] } * a[1] + Scalar { g0: b[3].g0[2] } * a[2] + Scalar { g0: b[3].g0[3] } * a[3], ] }
36.201439
146
0.538156
91698b653a8a5e0575fa083b1bc5b2a2a50b7be3
1,150
//! Base Priority Mask Register (conditional write) /// Writes to BASEPRI *if* /// /// - `basepri != 0` AND `basepri::read() == 0`, OR /// - `basepri != 0` AND `basepri < basepri::read()` /// /// **IMPORTANT** If you are using a Cortex-M7 device with revision r0p1 you MUST enable the /// `cm7-r0p1` Cargo feature or this function WILL misbehave. #[inline] pub fn write(_basepri: u8) { match () { #[cfg(all(cortex_m, feature = "inline-asm"))] () => unsafe { match () { #[cfg(not(feature = "cm7-r0p1"))] () => asm!("msr BASEPRI_MAX, $0" :: "r"(_basepri) : "memory" : "volatile"), #[cfg(feature = "cm7-r0p1")] () => ::interrupt::free( |_| asm!("msr BASEPRI_MAX, $0" :: "r"(_basepri) : "memory" : "volatile"), ), } }, #[cfg(all(cortex_m, not(feature = "inline-asm")))] () => unsafe { extern "C" { fn __basepri_max(_: u8); } __basepri_max(_basepri) }, #[cfg(not(cortex_m))] () => unimplemented!(), } }
30.263158
93
0.472174
0a47353683cfb7cfa82483a199c9767260e81183
1,162
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(dead_code)] fn main() { // Original borrow ends at end of function let mut x = 1u; let y = &mut x; let z = &x; //~ ERROR cannot borrow } //~^ NOTE previous borrow ends here fn foo() { match true { true => { // Original borrow ends at end of match arm let mut x = 1u; let y = &x; let z = &mut x; //~ ERROR cannot borrow } //~^ NOTE previous borrow ends here false => () } } fn bar() { // Original borrow ends at end of closure |&:| { let mut x = 1u; let y = &mut x; let z = &mut x; //~ ERROR cannot borrow }; //~^ NOTE previous borrow ends here }
27.666667
68
0.595525
de3ec5c4491a1c957ffea3a03d69ac8cdb070ee5
1,420
//! Shows how to render a polygonal [`Mesh`], generated from a [`Quad`] primitive, in a 2D scene. //! Adds a texture and colored vertices, giving per-vertex tinting. use bevy::{prelude::*, sprite::MaterialMesh2dBundle}; fn main() { App::new() .add_plugins(DefaultPlugins) .add_startup_system(setup) .run(); } fn setup( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<ColorMaterial>>, asset_server: Res<AssetServer>, ) { // Load the Bevy logo as a texture let texture_handle = asset_server.load("branding/banner.png"); // Build a default quad mesh let mut mesh = Mesh::from(shape::Quad::default()); // Build vertex colors for the quad. One entry per vertex (the corners of the quad) let vertex_colors: Vec<[f32; 4]> = vec![ Color::RED.as_rgba_f32(), Color::GREEN.as_rgba_f32(), Color::BLUE.as_rgba_f32(), Color::WHITE.as_rgba_f32(), ]; // Insert the vertex colors as an attribute mesh.insert_attribute(Mesh::ATTRIBUTE_COLOR, vertex_colors); // Spawn commands.spawn_bundle(Camera2dBundle::default()); commands.spawn_bundle(MaterialMesh2dBundle { mesh: meshes.add(mesh).into(), transform: Transform::default().with_scale(Vec3::splat(128.)), material: materials.add(ColorMaterial::from(texture_handle)), ..default() }); }
34.634146
97
0.657746
014646fd1dc9ce53126086f442952538bb28652e
37,738
use ptr::null_mut; use std::convert::TryInto; use std::{ ffi::NulError, ffi::{CStr, CString}, path::Path, ptr, }; use crate::cpl::CslStringList; use crate::errors::*; use crate::raster::RasterCreationOption; use crate::utils::{_last_cpl_err, _last_null_pointer_err, _path_to_c_string, _string}; use crate::vector::sql; use crate::vector::Geometry; use crate::{ gdal_major_object::MajorObject, raster::RasterBand, spatial_ref::SpatialRef, vector::Layer, Driver, Metadata, }; use gdal_sys::OGRGeometryH; use gdal_sys::{ self, CPLErr, GDALAccess, GDALDatasetH, GDALMajorObjectH, OGRErr, OGRLayerH, OGRwkbGeometryType, }; use libc::{c_double, c_int, c_uint}; use bitflags::bitflags; /// A 2-D affine transform mapping pixel coordiates to world /// coordinates. See [GDALGetGeoTransform] for more details. /// /// [GDALGetGeoTransform]: https://gdal.org/api/gdaldataset_cpp.html#classGDALDataset_1a5101119705f5fa2bc1344ab26f66fd1d pub type GeoTransform = [c_double; 6]; /// Wrapper around a [`GDALDataset`][GDALDataset] object. /// /// Represents both a [vector dataset][vector-data-model] /// containing a collection of layers; and a [raster /// dataset][raster-data-model] containing a collection of /// rasterbands. /// /// [vector-data-model]: https://gdal.org/user/vector_data_model.html /// [raster-data-model]: https://gdal.org/user/raster_data_model.html /// [GDALDataset]: https://gdal.org/api/gdaldataset_cpp.html#_CPPv411GDALDataset #[derive(Debug)] pub struct Dataset { c_dataset: GDALDatasetH, } // These are skipped by bindgen and manually updated. #[cfg(major_ge_2)] bitflags! { /// GDal extended open flags used by [`Dataset::open_ex`]. /// /// Used in the `nOpenFlags` argument to [`GDALOpenEx`]. /// /// Note that the `GDAL_OF_SHARED` option is removed /// from the set of allowed option because it subverts /// the [`Send`] implementation that allow passing the /// dataset the another thread. See /// https://github.com/georust/gdal/issues/154. /// /// [`GDALOpenEx`]: https://gdal.org/doxygen/gdal_8h.html#a9cb8585d0b3c16726b08e25bcc94274a pub struct GdalOpenFlags: c_uint { /// Open in read-only mode (default). const GDAL_OF_READONLY = 0x00; /// Open in update mode. const GDAL_OF_UPDATE = 0x01; /// Allow raster and vector drivers to be used. const GDAL_OF_ALL = 0x00; /// Allow raster drivers to be used. const GDAL_OF_RASTER = 0x02; /// Allow vector drivers to be used. const GDAL_OF_VECTOR = 0x04; /// Allow gnm drivers to be used. #[cfg(any( all(major_ge_2,minor_ge_1), major_ge_3 ))] const GDAL_OF_GNM = 0x08; /// Allow multidimensional raster drivers to be used. #[cfg(all(major_ge_3,minor_ge_1))] const GDAL_OF_MULTIDIM_RASTER = 0x10; /// Emit error message in case of failed open. const GDAL_OF_VERBOSE_ERROR = 0x40; /// Open as internal dataset. Such dataset isn't /// registered in the global list of opened dataset. /// Cannot be used with GDAL_OF_SHARED. const GDAL_OF_INTERNAL = 0x80; /// Default strategy for cached blocks. #[cfg(any( all(major_ge_2,minor_ge_1), major_ge_3 ))] const GDAL_OF_DEFAULT_BLOCK_ACCESS = 0; /// Array based strategy for cached blocks. #[cfg(any( all(major_ge_2,minor_ge_1), major_ge_3 ))] const GDAL_OF_ARRAY_BLOCK_ACCESS = 0x100; /// Hashset based strategy for cached blocks. #[cfg(any( all(major_ge_2,minor_ge_1), major_ge_3 ))] const GDAL_OF_HASHSET_BLOCK_ACCESS = 0x200; } } impl Default for GdalOpenFlags { fn default() -> GdalOpenFlags { GdalOpenFlags::GDAL_OF_READONLY } } impl From<GDALAccess::Type> for GdalOpenFlags { fn from(val: GDALAccess::Type) -> GdalOpenFlags { if val == GDALAccess::GA_Update { GdalOpenFlags::GDAL_OF_UPDATE } else { GdalOpenFlags::GDAL_OF_READONLY } } } // Open parameters #[derive(Debug, Default)] pub struct DatasetOptions<'a> { pub open_flags: GdalOpenFlags, pub allowed_drivers: Option<&'a [&'a str]>, pub open_options: Option<&'a [&'a str]>, pub sibling_files: Option<&'a [&'a str]>, } /// Parameters for [`Dataset::create_layer`]. #[derive(Clone, Debug)] pub struct LayerOptions<'a> { /// The name of the newly created layer. May be an empty string. pub name: &'a str, /// The SRS of the newly created layer, or `None` for no SRS. pub srs: Option<&'a SpatialRef>, /// The type of geometry for the new layer. pub ty: OGRwkbGeometryType::Type, /// Additional driver-specific options to pass to GDAL, in the form `name=value`. pub options: Option<&'a [&'a str]>, } const EMPTY_LAYER_NAME: &str = ""; impl<'a> Default for LayerOptions<'a> { /// Returns creation options for a new layer with no name, no SRS and unknown geometry type. fn default() -> Self { LayerOptions { name: EMPTY_LAYER_NAME, srs: None, ty: OGRwkbGeometryType::wkbUnknown, options: None, } } } // GDAL Docs state: The returned dataset should only be accessed by one thread at a time. // See: https://gdal.org/api/raster_c_api.html#_CPPv48GDALOpenPKc10GDALAccess // Additionally, VRT Datasets are not safe before GDAL 2.3. // See: https://gdal.org/drivers/raster/vrt.html#multi-threading-issues #[cfg(any(all(major_is_2, minor_ge_3), major_ge_3))] unsafe impl Send for Dataset {} impl Dataset { /// Returns the wrapped C pointer /// /// # Safety /// This method returns a raw C pointer pub unsafe fn c_dataset(&self) -> GDALDatasetH { self.c_dataset } /// Open a dataset at the given `path` with default /// options. pub fn open<P: AsRef<Path>>(path: P) -> Result<Dataset> { Self::_open_ex(path.as_ref(), DatasetOptions::default()) } /// Open a dataset with extended options. See /// [`GDALOpenEx`]. /// /// [`GDALOpenEx`]: https://gdal.org/doxygen/gdal_8h.html#a9cb8585d0b3c16726b08e25bcc94274a pub fn open_ex<P: AsRef<Path>>(path: P, options: DatasetOptions) -> Result<Dataset> { Self::_open_ex(path.as_ref(), options) } fn _open_ex(path: &Path, options: DatasetOptions) -> Result<Dataset> { crate::driver::_register_drivers(); let c_filename = _path_to_c_string(path)?; let c_open_flags = options.open_flags.bits; // handle driver params: // we need to keep the CStrings and the pointers around let c_allowed_drivers = options.allowed_drivers.map(|d| { d.iter() .map(|&s| CString::new(s)) .collect::<std::result::Result<Vec<CString>, NulError>>() }); let c_drivers_vec = match c_allowed_drivers { Some(Err(e)) => return Err(e.into()), Some(Ok(c_drivers_vec)) => c_drivers_vec, None => Vec::from([]), }; let mut c_drivers_ptrs = c_drivers_vec.iter().map(|s| s.as_ptr()).collect::<Vec<_>>(); c_drivers_ptrs.push(ptr::null()); let c_drivers_ptr = if options.allowed_drivers.is_some() { c_drivers_ptrs.as_ptr() } else { ptr::null() }; // handle open options params: // we need to keep the CStrings and the pointers around let c_open_options = options.open_options.map(|d| { d.iter() .map(|&s| CString::new(s)) .collect::<std::result::Result<Vec<CString>, NulError>>() }); let c_open_options_vec = match c_open_options { Some(Err(e)) => return Err(e.into()), Some(Ok(c_open_options_vec)) => c_open_options_vec, None => Vec::from([]), }; let mut c_open_options_ptrs = c_open_options_vec .iter() .map(|s| s.as_ptr()) .collect::<Vec<_>>(); c_open_options_ptrs.push(ptr::null()); let c_open_options_ptr = if options.open_options.is_some() { c_open_options_ptrs.as_ptr() } else { ptr::null() }; // handle sibling files params: // we need to keep the CStrings and the pointers around let c_sibling_files = options.sibling_files.map(|d| { d.iter() .map(|&s| CString::new(s)) .collect::<std::result::Result<Vec<CString>, NulError>>() }); let c_sibling_files_vec = match c_sibling_files { Some(Err(e)) => return Err(e.into()), Some(Ok(c_sibling_files_vec)) => c_sibling_files_vec, None => Vec::from([]), }; let mut c_sibling_files_ptrs = c_sibling_files_vec .iter() .map(|s| s.as_ptr()) .collect::<Vec<_>>(); c_sibling_files_ptrs.push(ptr::null()); let c_sibling_files_ptr = if options.sibling_files.is_some() { c_sibling_files_ptrs.as_ptr() } else { ptr::null() }; let c_dataset = unsafe { gdal_sys::GDALOpenEx( c_filename.as_ptr(), c_open_flags, c_drivers_ptr, c_open_options_ptr, c_sibling_files_ptr, ) }; if c_dataset.is_null() { return Err(_last_null_pointer_err("GDALOpenEx")); } Ok(Dataset { c_dataset }) } /// Creates a new Dataset by wrapping a C pointer /// /// # Safety /// This method operates on a raw C pointer pub unsafe fn from_c_dataset(c_dataset: GDALDatasetH) -> Dataset { Dataset { c_dataset } } /// Fetch the projection definition string for this dataset. pub fn projection(&self) -> String { let rv = unsafe { gdal_sys::GDALGetProjectionRef(self.c_dataset) }; _string(rv) } /// Set the projection reference string for this dataset. pub fn set_projection(&mut self, projection: &str) -> Result<()> { let c_projection = CString::new(projection)?; unsafe { gdal_sys::GDALSetProjection(self.c_dataset, c_projection.as_ptr()) }; Ok(()) } #[cfg(major_ge_3)] /// Get the spatial reference system for this dataset. pub fn spatial_ref(&self) -> Result<SpatialRef> { unsafe { SpatialRef::from_c_obj(gdal_sys::GDALGetSpatialRef(self.c_dataset)) } } #[cfg(major_ge_3)] /// Set the spatial reference system for this dataset. pub fn set_spatial_ref(&mut self, spatial_ref: &SpatialRef) -> Result<()> { let rv = unsafe { gdal_sys::GDALSetSpatialRef(self.c_dataset, spatial_ref.to_c_hsrs()) }; if rv != CPLErr::CE_None { return Err(_last_cpl_err(rv)); } Ok(()) } pub fn create_copy<P: AsRef<Path>>( &self, driver: &Driver, filename: P, options: &[RasterCreationOption], ) -> Result<Dataset> { Self::_create_copy(self, driver, filename.as_ref(), options) } fn _create_copy( &self, driver: &Driver, filename: &Path, options: &[RasterCreationOption], ) -> Result<Dataset> { let c_filename = _path_to_c_string(filename)?; let mut c_options = CslStringList::new(); for option in options { c_options.set_name_value(option.key, option.value)?; } let c_dataset = unsafe { gdal_sys::GDALCreateCopy( driver.c_driver(), c_filename.as_ptr(), self.c_dataset, 0, c_options.as_ptr(), None, ptr::null_mut(), ) }; if c_dataset.is_null() { return Err(_last_null_pointer_err("GDALCreateCopy")); } Ok(unsafe { Dataset::from_c_dataset(c_dataset) }) } /// Fetch the driver to which this dataset relates. pub fn driver(&self) -> Driver { unsafe { let c_driver = gdal_sys::GDALGetDatasetDriver(self.c_dataset); Driver::from_c_driver(c_driver) } } /// Fetch a band object for a dataset. /// /// Applies to raster datasets, and fetches the /// rasterband at the given _1-based_ index. pub fn rasterband(&self, band_index: isize) -> Result<RasterBand> { unsafe { let c_band = gdal_sys::GDALGetRasterBand(self.c_dataset, band_index as c_int); if c_band.is_null() { return Err(_last_null_pointer_err("GDALGetRasterBand")); } Ok(RasterBand::from_c_rasterband(self, c_band)) } } /// Builds overviews for the current `Dataset`. See [`GDALBuildOverviews`]. /// /// # Arguments /// * `resampling` - resampling method, as accepted by GDAL, e.g. `"CUBIC"` /// * `overviews` - list of overview decimation factors, e.g. `&[2, 4, 8, 16, 32]` /// * `bands` - list of bands to build the overviews for, or empty for all bands /// /// [`GDALBuildOverviews`]: https://gdal.org/doxygen/gdal_8h.html#a767f4456a6249594ee18ea53f68b7e80 pub fn build_overviews( &mut self, resampling: &str, overviews: &[i32], bands: &[i32], ) -> Result<()> { let c_resampling = CString::new(resampling)?; let rv = unsafe { gdal_sys::GDALBuildOverviews( self.c_dataset, c_resampling.as_ptr(), overviews.len() as i32, overviews.as_ptr() as *mut i32, bands.len() as i32, bands.as_ptr() as *mut i32, None, null_mut(), ) }; if rv != CPLErr::CE_None { return Err(_last_cpl_err(rv)); } Ok(()) } fn child_layer(&self, c_layer: OGRLayerH) -> Layer { unsafe { Layer::from_c_layer(self, c_layer) } } /// Get the number of layers in this dataset. pub fn layer_count(&self) -> isize { (unsafe { gdal_sys::OGR_DS_GetLayerCount(self.c_dataset) }) as isize } /// Fetch a layer by index. /// /// Applies to vector datasets, and fetches by the given /// _0-based_ index. pub fn layer(&self, idx: isize) -> Result<Layer> { let c_layer = unsafe { gdal_sys::OGR_DS_GetLayer(self.c_dataset, idx as c_int) }; if c_layer.is_null() { return Err(_last_null_pointer_err("OGR_DS_GetLayer")); } Ok(self.child_layer(c_layer)) } /// Fetch a layer by name. pub fn layer_by_name(&self, name: &str) -> Result<Layer> { let c_name = CString::new(name)?; let c_layer = unsafe { gdal_sys::OGR_DS_GetLayerByName(self.c_dataset(), c_name.as_ptr()) }; if c_layer.is_null() { return Err(_last_null_pointer_err("OGR_DS_GetLayerByName")); } Ok(self.child_layer(c_layer)) } /// Returns an iterator over the layers of the dataset. pub fn layers(&self) -> LayerIterator { LayerIterator::with_dataset(self) } /// Fetch the number of raster bands on this dataset. pub fn raster_count(&self) -> isize { (unsafe { gdal_sys::GDALGetRasterCount(self.c_dataset) }) as isize } /// Returns the raster dimensions: (width, height). pub fn raster_size(&self) -> (usize, usize) { let size_x = unsafe { gdal_sys::GDALGetRasterXSize(self.c_dataset) } as usize; let size_y = unsafe { gdal_sys::GDALGetRasterYSize(self.c_dataset) } as usize; (size_x, size_y) } /// Creates a new layer. The [`LayerOptions`] struct implements `Default`, so you only need to /// specify those options that deviate from the default. /// /// # Examples /// /// Create a new layer with an empty name, no spatial reference, and unknown geometry type: /// /// ``` /// # use gdal::Driver; /// # let driver = Driver::get("GPKG").unwrap(); /// # let mut dataset = driver.create_vector_only("/vsimem/example.gpkg").unwrap(); /// let blank_layer = dataset.create_layer(Default::default()).unwrap(); /// ``` /// /// Create a new named line string layer using WGS84: /// /// ``` /// # use gdal::{Driver, LayerOptions}; /// # use gdal::spatial_ref::SpatialRef; /// # let driver = Driver::get("GPKG").unwrap(); /// # let mut dataset = driver.create_vector_only("/vsimem/example.gpkg").unwrap(); /// let roads = dataset.create_layer(LayerOptions { /// name: "roads", /// srs: Some(&SpatialRef::from_epsg(4326).unwrap()), /// ty: gdal_sys::OGRwkbGeometryType::wkbLineString, /// ..Default::default() /// }).unwrap(); /// ``` pub fn create_layer<'a>(&mut self, options: LayerOptions<'a>) -> Result<Layer> { let c_name = CString::new(options.name)?; let c_srs = match options.srs { Some(srs) => srs.to_c_hsrs(), None => null_mut(), }; // Handle string options: we need to keep the CStrings and the pointers around. let c_options = options.options.map(|d| { d.iter() .map(|&s| CString::new(s)) .collect::<std::result::Result<Vec<CString>, NulError>>() }); let c_options_vec = match c_options { Some(Err(e)) => return Err(e.into()), Some(Ok(c_options_vec)) => c_options_vec, None => Vec::from([]), }; let mut c_options_ptrs = c_options_vec.iter().map(|s| s.as_ptr()).collect::<Vec<_>>(); c_options_ptrs.push(ptr::null()); let c_options_ptr = if options.options.is_some() { c_options_ptrs.as_ptr() } else { ptr::null() }; let c_layer = unsafe { // The C function takes `char **papszOptions` without mention of `const`, and this is // propagated to the gdal_sys wrapper. The lack of `const` seems like a mistake in the // GDAL API, so we just do a cast here. gdal_sys::OGR_DS_CreateLayer( self.c_dataset, c_name.as_ptr(), c_srs, options.ty, c_options_ptr as *mut *mut libc::c_char, ) }; if c_layer.is_null() { return Err(_last_null_pointer_err("OGR_DS_CreateLayer")); }; Ok(self.child_layer(c_layer)) } /// Affine transformation called geotransformation. /// /// This is like a linear transformation preserves points, straight lines and planes. /// Also, sets of parallel lines remain parallel after an affine transformation. /// # Arguments /// * transformation - coeficients of transformations /// /// x-coordinate of the top-left corner pixel (x-offset) /// width of a pixel (x-resolution) /// row rotation (typically zero) /// y-coordinate of the top-left corner pixel /// column rotation (typically zero) /// height of a pixel (y-resolution, typically negative) pub fn set_geo_transform(&mut self, transformation: &GeoTransform) -> Result<()> { assert_eq!(transformation.len(), 6); let rv = unsafe { gdal_sys::GDALSetGeoTransform(self.c_dataset, transformation.as_ptr() as *mut f64) }; if rv != CPLErr::CE_None { return Err(_last_cpl_err(rv)); } Ok(()) } /// Get affine transformation coefficients. /// /// x-coordinate of the top-left corner pixel (x-offset) /// width of a pixel (x-resolution) /// row rotation (typically zero) /// y-coordinate of the top-left corner pixel /// column rotation (typically zero) /// height of a pixel (y-resolution, typically negative) pub fn geo_transform(&self) -> Result<GeoTransform> { let mut transformation = GeoTransform::default(); let rv = unsafe { gdal_sys::GDALGetGeoTransform(self.c_dataset, transformation.as_mut_ptr()) }; // check if the dataset has a GeoTransform if rv != CPLErr::CE_None { return Err(_last_cpl_err(rv)); } Ok(transformation) } /// For datasources which support transactions, this creates a transaction. /// /// During the transaction, the dataset can be mutably borrowed using /// [`Transaction::dataset_mut`] to make changes. All changes done after the start of the /// transaction are applied to the datasource when [`commit`](Transaction::commit) is called. /// They may be canceled by calling [`rollback`](Transaction::rollback) instead, or by dropping /// the `Transaction` without calling `commit`. /// /// Depending on the driver, using a transaction can give a huge performance improvement when /// creating a lot of geometry at once. This is because the driver doesn't need to commit every /// feature to disk individually. /// /// If starting the transaction fails, this function will return [`OGRErr::OGRERR_FAILURE`]. /// For datasources that do not support transactions, this function will always return /// [`OGRErr::OGRERR_UNSUPPORTED_OPERATION`]. /// /// Limitations: /// /// * Datasources which do not support efficient transactions natively may use less efficient /// emulation of transactions instead; as of GDAL 3.1, this only applies to the closed-source /// FileGDB driver, which (unlike OpenFileGDB) is not available in a GDAL build by default. /// /// * At the time of writing, transactions only apply on vector layers. /// /// * Nested transactions are not supported. /// /// * If an error occurs after a successful `start_transaction`, the whole transaction may or /// may not be implicitly canceled, depending on the driver. For example, the PG driver will /// cancel it, but the SQLite and GPKG drivers will not. /// /// Example: /// /// ``` /// # use gdal::{Dataset, LayerOptions}; /// # /// fn create_point_grid(dataset: &mut Dataset) -> gdal::errors::Result<()> { /// use gdal::vector::Geometry; /// /// // Start the transaction. /// let mut txn = dataset.start_transaction()?; /// /// let mut layer = txn.dataset_mut().create_layer(LayerOptions { /// name: "grid", /// ty: gdal_sys::OGRwkbGeometryType::wkbPoint, /// ..Default::default() /// })?; /// for y in 0..100 { /// for x in 0..100 { /// let wkt = format!("POINT ({} {})", x, y); /// layer.create_feature(Geometry::from_wkt(&wkt)?)?; /// } /// } /// /// // We got through without errors. Commit the transaction and return. /// txn.commit()?; /// Ok(()) /// } /// # /// # fn main() -> gdal::errors::Result<()> { /// # let driver = gdal::Driver::get("SQLite")?; /// # let mut dataset = driver.create_vector_only(":memory:")?; /// # create_point_grid(&mut dataset)?; /// # assert_eq!(dataset.layer(0)?.features().count(), 10000); /// # Ok(()) /// # } /// ``` pub fn start_transaction(&mut self) -> Result<Transaction<'_>> { let force = 1; let rv = unsafe { gdal_sys::GDALDatasetStartTransaction(self.c_dataset, force) }; if rv != OGRErr::OGRERR_NONE { return Err(GdalError::OgrError { err: rv, method_name: "GDALDatasetStartTransaction", }); } Ok(Transaction::new(self)) } /// Execute a SQL query against the Dataset. It is equivalent to calling /// [`GDALDatasetExecuteSQL`](https://gdal.org/api/raster_c_api.html#_CPPv421GDALDatasetExecuteSQL12GDALDatasetHPKc12OGRGeometryHPKc). /// Returns a [`sql::ResultSet`], which can be treated just as any other [`Layer`]. /// /// Queries such as `ALTER TABLE`, `CREATE INDEX`, etc. have no [`sql::ResultSet`], and return /// `None`, which is distinct from an empty [`sql::ResultSet`]. /// /// # Arguments /// /// * `query`: The SQL query /// * `spatial_filter`: Limit results of the query to features that intersect the given /// [`Geometry`] /// * `dialect`: The dialect of SQL to use. See /// <https://gdal.org/user/ogr_sql_sqlite_dialect.html> /// /// # Example /// /// ``` /// # use gdal::Dataset; /// # use std::path::Path; /// use gdal::vector::sql; /// /// let ds = Dataset::open(Path::new("fixtures/roads.geojson")).unwrap(); /// let query = "SELECT kind, is_bridge, highway FROM roads WHERE highway = 'pedestrian'"; /// let mut result_set = ds.execute_sql(query, None, sql::Dialect::DEFAULT).unwrap().unwrap(); /// /// assert_eq!(10, result_set.feature_count()); /// /// for feature in result_set.features() { /// let highway = feature /// .field("highway") /// .unwrap() /// .unwrap() /// .into_string() /// .unwrap(); /// /// assert_eq!("pedestrian", highway); /// } /// ``` pub fn execute_sql<S: AsRef<str>>( &self, query: S, spatial_filter: Option<&Geometry>, dialect: sql::Dialect, ) -> Result<Option<sql::ResultSet>> { let query = CString::new(query.as_ref())?; let dialect_c_str = match dialect { sql::Dialect::DEFAULT => None, sql::Dialect::OGR => Some(unsafe { CStr::from_bytes_with_nul_unchecked(sql::OGRSQL) }), sql::Dialect::SQLITE => { Some(unsafe { CStr::from_bytes_with_nul_unchecked(sql::SQLITE) }) } }; self._execute_sql(query, spatial_filter, dialect_c_str) } fn _execute_sql( &self, query: CString, spatial_filter: Option<&Geometry>, dialect_c_str: Option<&CStr>, ) -> Result<Option<sql::ResultSet>> { let mut filter_geom: OGRGeometryH = std::ptr::null_mut(); let dialect_ptr = match dialect_c_str { None => std::ptr::null(), Some(d) => d.as_ptr(), }; if let Some(spatial_filter) = spatial_filter { filter_geom = unsafe { spatial_filter.c_geometry() }; } let c_dataset = unsafe { self.c_dataset() }; unsafe { gdal_sys::CPLErrorReset() }; let c_layer = unsafe { gdal_sys::GDALDatasetExecuteSQL(c_dataset, query.as_ptr(), filter_geom, dialect_ptr) }; let cpl_err = unsafe { gdal_sys::CPLGetLastErrorType() }; if cpl_err != CPLErr::CE_None { return Err(_last_cpl_err(cpl_err)); } if c_layer.is_null() { return Ok(None); } let layer = unsafe { Layer::from_c_layer(self, c_layer) }; Ok(Some(sql::ResultSet { layer, dataset: c_dataset, })) } } pub struct LayerIterator<'a> { dataset: &'a Dataset, idx: isize, count: isize, } impl<'a> Iterator for LayerIterator<'a> { type Item = Layer<'a>; #[inline] fn next(&mut self) -> Option<Layer<'a>> { let idx = self.idx; if idx < self.count { self.idx += 1; let c_layer = unsafe { gdal_sys::OGR_DS_GetLayer(self.dataset.c_dataset, idx as c_int) }; if !c_layer.is_null() { let layer = unsafe { Layer::from_c_layer(self.dataset, c_layer) }; return Some(layer); } } None } fn size_hint(&self) -> (usize, Option<usize>) { match Some(self.count).map(|s| s.try_into().ok()).flatten() { Some(size) => (size, Some(size)), None => (0, None), } } } impl<'a> LayerIterator<'a> { pub fn with_dataset(dataset: &'a Dataset) -> LayerIterator<'a> { LayerIterator { dataset, idx: 0, count: dataset.layer_count(), } } } impl MajorObject for Dataset { unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH { self.c_dataset } } impl Metadata for Dataset {} impl Drop for Dataset { fn drop(&mut self) { unsafe { gdal_sys::GDALClose(self.c_dataset); } } } /// Represents an in-flight transaction on a dataset. /// /// It can either be committed by calling [`commit`](Transaction::commit) or rolled back by calling /// [`rollback`](Transaction::rollback). /// /// If the transaction is not explicitly committed when it is dropped, it is implicitly rolled /// back. /// /// The transaction holds a mutable borrow on the `Dataset` that it was created from, so during the /// lifetime of the transaction you will need to access the dataset through /// [`Transaction::dataset`] or [`Transaction::dataset_mut`]. #[derive(Debug)] pub struct Transaction<'a> { dataset: &'a mut Dataset, rollback_on_drop: bool, } impl<'a> Transaction<'a> { fn new(dataset: &'a mut Dataset) -> Self { Transaction { dataset, rollback_on_drop: true, } } /// Returns a reference to the dataset from which this `Transaction` was created. pub fn dataset(&self) -> &Dataset { self.dataset } /// Returns a mutable reference to the dataset from which this `Transaction` was created. pub fn dataset_mut(&mut self) -> &mut Dataset { self.dataset } /// Commits this transaction. /// /// If the commit fails, will return [`OGRErr::OGRERR_FAILURE`]. /// /// Depending on drivers, this may or may not abort layer sequential readings that are active. pub fn commit(mut self) -> Result<()> { let rv = unsafe { gdal_sys::GDALDatasetCommitTransaction(self.dataset.c_dataset) }; self.rollback_on_drop = false; if rv != OGRErr::OGRERR_NONE { return Err(GdalError::OgrError { err: rv, method_name: "GDALDatasetCommitTransaction", }); } Ok(()) } /// Rolls back the dataset to its state before the start of this transaction. /// /// If the rollback fails, will return [`OGRErr::OGRERR_FAILURE`]. pub fn rollback(mut self) -> Result<()> { let rv = unsafe { gdal_sys::GDALDatasetRollbackTransaction(self.dataset.c_dataset) }; self.rollback_on_drop = false; if rv != OGRErr::OGRERR_NONE { return Err(GdalError::OgrError { err: rv, method_name: "GDALDatasetRollbackTransaction", }); } Ok(()) } } impl<'a> Drop for Transaction<'a> { fn drop(&mut self) { if self.rollback_on_drop { // We silently swallow any errors, because we have no way to report them from a drop // function apart from panicking. unsafe { gdal_sys::GDALDatasetRollbackTransaction(self.dataset.c_dataset) }; } } } #[cfg(test)] mod tests { use super::*; use crate::vector::Geometry; use tempfile::TempPath; macro_rules! fixture { ($name:expr) => { Path::new(file!()) .parent() .unwrap() .parent() .unwrap() .join("fixtures") .as_path() .join($name) .as_path() }; } /// Copies the given file to a temporary file and opens it for writing. When the returned /// `TempPath` is dropped, the file is deleted. fn open_gpkg_for_update(path: &Path) -> (TempPath, Dataset) { use std::fs; use std::io::Write; let input_data = fs::read(path).unwrap(); let (mut file, temp_path) = tempfile::Builder::new() .suffix(".gpkg") .tempfile() .unwrap() .into_parts(); file.write_all(&input_data).unwrap(); // Close the temporary file so that Dataset can open it safely even if the filesystem uses // exclusive locking (Windows?). drop(file); let ds = Dataset::open_ex( &temp_path, DatasetOptions { open_flags: GDALAccess::GA_Update.into(), allowed_drivers: Some(&["GPKG"]), ..DatasetOptions::default() }, ) .unwrap(); (temp_path, ds) } fn polygon() -> Geometry { Geometry::from_wkt("POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))").unwrap() } #[test] fn test_open_vector() { Dataset::open(fixture!("roads.geojson")).unwrap(); } #[test] fn test_open_ex_ro_vector() { Dataset::open_ex( fixture!("roads.geojson"), DatasetOptions { open_flags: GDALAccess::GA_ReadOnly.into(), ..DatasetOptions::default() }, ) .unwrap(); } #[test] fn test_open_ex_update_vector() { Dataset::open_ex( fixture!("roads.geojson"), DatasetOptions { open_flags: GDALAccess::GA_Update.into(), ..DatasetOptions::default() }, ) .unwrap(); } #[test] fn test_open_ex_allowed_driver_vector() { Dataset::open_ex( fixture!("roads.geojson"), DatasetOptions { allowed_drivers: Some(&["GeoJSON"]), ..DatasetOptions::default() }, ) .unwrap(); } #[test] fn test_open_ex_allowed_driver_vector_fail() { Dataset::open_ex( fixture!("roads.geojson"), DatasetOptions { allowed_drivers: Some(&["TIFF"]), ..DatasetOptions::default() }, ) .unwrap_err(); } #[test] fn test_open_ex_open_option() { Dataset::open_ex( fixture!("roads.geojson"), DatasetOptions { open_options: Some(&["FLATTEN_NESTED_ATTRIBUTES=YES"]), ..DatasetOptions::default() }, ) .unwrap(); } #[test] fn test_open_ex_extended_flags_vector() { Dataset::open_ex( fixture!("roads.geojson"), DatasetOptions { open_flags: GdalOpenFlags::GDAL_OF_UPDATE | GdalOpenFlags::GDAL_OF_VECTOR, ..DatasetOptions::default() }, ) .unwrap(); } #[test] fn test_open_ex_extended_flags_vector_fail() { Dataset::open_ex( fixture!("roads.geojson"), DatasetOptions { open_flags: GdalOpenFlags::GDAL_OF_UPDATE | GdalOpenFlags::GDAL_OF_RASTER, ..DatasetOptions::default() }, ) .unwrap_err(); } #[test] fn test_layer_count() { let ds = Dataset::open(fixture!("roads.geojson")).unwrap(); assert_eq!(ds.layer_count(), 1); } #[test] fn test_raster_count_on_vector() { let ds = Dataset::open(fixture!("roads.geojson")).unwrap(); assert_eq!(ds.raster_count(), 0); } #[test] fn test_create_layer_options() { use gdal_sys::OGRwkbGeometryType::wkbPoint; let (_temp_path, mut ds) = open_gpkg_for_update(fixture!("poly.gpkg")); let mut options = LayerOptions { name: "new", ty: wkbPoint, ..Default::default() }; ds.create_layer(options.clone()).unwrap(); assert!(ds.create_layer(options.clone()).is_err()); options.options = Some(&["OVERWRITE=YES"]); assert!(ds.create_layer(options).is_ok()); } #[test] fn test_start_transaction() { let (_temp_path, mut ds) = open_gpkg_for_update(fixture!("poly.gpkg")); let txn = ds.start_transaction(); assert!(txn.is_ok()); } #[test] fn test_transaction_commit() { let (_temp_path, mut ds) = open_gpkg_for_update(fixture!("poly.gpkg")); let orig_feature_count = ds.layer(0).unwrap().feature_count(); let mut txn = ds.start_transaction().unwrap(); let mut layer = txn.dataset_mut().layer(0).unwrap(); layer.create_feature(polygon()).unwrap(); assert!(txn.commit().is_ok()); assert_eq!(ds.layer(0).unwrap().feature_count(), orig_feature_count + 1); } #[test] fn test_transaction_rollback() { let (_temp_path, mut ds) = open_gpkg_for_update(fixture!("poly.gpkg")); let orig_feature_count = ds.layer(0).unwrap().feature_count(); let mut txn = ds.start_transaction().unwrap(); let mut layer = txn.dataset_mut().layer(0).unwrap(); layer.create_feature(polygon()).unwrap(); assert!(txn.rollback().is_ok()); assert_eq!(ds.layer(0).unwrap().feature_count(), orig_feature_count); } #[test] fn test_transaction_implicit_rollback() { let (_temp_path, mut ds) = open_gpkg_for_update(fixture!("poly.gpkg")); let orig_feature_count = ds.layer(0).unwrap().feature_count(); { let mut txn = ds.start_transaction().unwrap(); let mut layer = txn.dataset_mut().layer(0).unwrap(); layer.create_feature(polygon()).unwrap(); } // txn is dropped here. assert_eq!(ds.layer(0).unwrap().feature_count(), orig_feature_count); } #[test] fn test_start_transaction_unsupported() { let mut ds = Dataset::open(fixture!("roads.geojson")).unwrap(); assert!(ds.start_transaction().is_err()); } }
34.090334
138
0.581509
d93b2452c94428882ec06446baca93a15d63bd05
32,263
use crate::roots::newton_polynomial; use nalgebra::{ComplexField, RealField}; use num_complex::Complex; use num_traits::{FromPrimitive, One, Zero}; use std::collections::VecDeque; use std::{any::TypeId, f64, iter::FromIterator, ops}; /// Polynomial on a ComplexField. #[derive(Debug, Clone)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] pub struct Polynomial<N: ComplexField> { // Index 0 is constant, 1 is linear, etc. coefficients: Vec<N>, tolerance: <N as ComplexField>::RealField, } #[macro_export] macro_rules! polynomial { ( $( $x:expr ),* ) => { $crate::polynomial::Polynomial::from_slice(&[$($x),*]) } } impl<N: ComplexField> Polynomial<N> { /// Returns the zero polynomial on a given field pub fn new() -> Self { Polynomial { coefficients: vec![N::from_f64(0.0).unwrap()], tolerance: N::RealField::from_f64(1e-10).unwrap(), } } pub fn with_tolerance(tolerance: <N as ComplexField>::RealField) -> Result<Self, String> { if !tolerance.is_sign_positive() { return Err("Polynomial with_tolerance: Tolerance must be positive".to_owned()); } Ok(Polynomial { coefficients: vec![N::from_f64(0.0).unwrap()], tolerance, }) } /// Returns the zero polynomial on a given field with preallocated memory pub fn with_capacity(capacity: usize) -> Self { let mut coefficients = Vec::with_capacity(capacity); coefficients.push(N::zero()); coefficients.iter().copied().collect() } /// Create a polynomial from a slice, with the first element of the slice being the highest power pub fn from_slice(data: &[N]) -> Self { if data.is_empty() { return Polynomial { coefficients: vec![N::zero()], tolerance: N::RealField::from_f64(1e-10).unwrap(), }; } Polynomial { coefficients: data.iter().rev().copied().collect(), tolerance: N::RealField::from_f64(1e-10).unwrap(), } } pub fn set_tolerance( &mut self, tolerance: <N as ComplexField>::RealField, ) -> Result<(), String> { if !tolerance.is_sign_positive() { return Err("Polynomial set_tolerance: tolerance must be positive".to_owned()); } self.tolerance = tolerance; Ok(()) } pub fn get_tolerance(&self) -> <N as ComplexField>::RealField { self.tolerance } /// Get the order of the polynomial pub fn order(&self) -> usize { self.coefficients.len() - 1 } /// Returns the coefficients in the correct order to recreate the polynomial with Polynomial::from_slice(data: &[N]); pub fn get_coefficients(&self) -> Vec<N> { let mut cln = self.coefficients.clone(); cln.reverse(); cln } /// Get the coefficient of a power pub fn get_coefficient(&self, ind: usize) -> N { if ind >= self.coefficients.len() { N::zero() } else { self.coefficients[ind] } } /// Make a polynomial complex pub fn make_complex(&self) -> Polynomial<Complex<<N as ComplexField>::RealField>> { let mut coefficients: Vec<Complex<N::RealField>> = Vec::with_capacity(self.coefficients.len()); for val in &self.coefficients { coefficients.push(Complex::<N::RealField>::new(val.real(), val.imaginary())); } Polynomial { coefficients, tolerance: self.tolerance, } } /// Evaluate a polynomial at a value pub fn evaluate(&self, x: N) -> N { let mut acc = *self.coefficients.last().unwrap(); for val in self.coefficients.iter().rev().skip(1) { acc *= x; acc += *val; } acc } /// Evaluate a polynomial and its derivative at a value pub fn evaluate_derivative(&self, x: N) -> (N, N) { if self.coefficients.len() == 1 { return (self.coefficients[0], N::zero()); } // Start with biggest coefficients let mut acc_eval = *self.coefficients.last().unwrap(); let mut acc_deriv = *self.coefficients.last().unwrap(); // For every coefficient except the constant and largest for val in self.coefficients.iter().skip(1).rev().skip(1) { acc_eval = acc_eval * x + *val; acc_deriv = acc_deriv * x + acc_eval; } // Do the constant for the polynomial evaluation acc_eval = x * acc_eval + self.coefficients[0]; (acc_eval, acc_deriv) } /// Set a coefficient of a power in the polynomial pub fn set_coefficient(&mut self, power: u32, coefficient: N) { while (power + 1) > self.coefficients.len() as u32 { self.coefficients.push(N::from_f64(0.0).unwrap()); } self.coefficients[power as usize] = coefficient; } /// Remove the coefficient of a power in the polynomial pub fn purge_coefficient(&mut self, power: usize) { match self.coefficients.len() { len if len == power && len != 1 => { self.coefficients.pop(); } _ => { self.coefficients[power] = N::from_f64(0.0).unwrap(); } }; } /// Remove all leading 0 coefficients pub fn purge_leading(&mut self) { while self.coefficients.len() > 1 && self.coefficients.last().unwrap().real().abs() <= self.tolerance && self.coefficients.last().unwrap().imaginary().abs() <= self.tolerance { self.coefficients.pop(); } } /// Get the derivative of the polynomial pub fn derivative(&self) -> Self { if self.coefficients.len() == 1 { return Polynomial { coefficients: vec![N::from_f64(0.0).unwrap()], tolerance: self.tolerance, }; } let mut deriv_coeff = Vec::with_capacity(self.coefficients.len() - 1); for (i, val) in self.coefficients.iter().enumerate().skip(1) { deriv_coeff.push(N::from_f64(i as f64).unwrap() * *val); } Polynomial { coefficients: deriv_coeff, tolerance: self.tolerance, } } /// Get the antiderivative of the polynomial with specified constant pub fn antiderivative(&self, constant: N) -> Self { let mut coefficients = Vec::with_capacity(self.coefficients.len() + 1); coefficients.push(constant); for (ind, val) in self.coefficients.iter().enumerate() { coefficients.push(*val * N::from_f64(1.0 / (ind + 1) as f64).unwrap()); } Polynomial { coefficients, tolerance: self.tolerance, } } /// Integrate this polynomial between to starting points pub fn integrate(&self, lower: N, upper: N) -> N { let poly_anti = self.antiderivative(N::zero()); poly_anti.evaluate(upper) - poly_anti.evaluate(lower) } /// Divide this polynomial by another, getting a quotient and remainder, using tol to check for 0 pub fn divide(&self, divisor: &Polynomial<N>) -> Result<(Self, Self), String> { if divisor.coefficients.len() == 1 && divisor.coefficients[0].real().abs() < self.tolerance && divisor.coefficients[0].imaginary().abs() < self.tolerance { return Err("Polynomial division: Can not divide by 0".to_owned()); } let mut quotient = Polynomial::with_tolerance(self.tolerance)?; let mut remainder = Polynomial::from_iter(self.coefficients.iter().copied()); remainder.tolerance = self.tolerance; remainder.purge_leading(); let mut temp = Polynomial::new(); if divisor.coefficients.len() == 1 { let idivisor = N::from_f64(1.0).unwrap() / divisor.coefficients[0]; return Ok(( remainder .coefficients .iter() .map(|c| *c * idivisor) .collect(), Polynomial::new(), )); } while remainder.coefficients.len() >= divisor.coefficients.len() && !(remainder.coefficients.len() == 1 && remainder.coefficients[0].real().abs() < self.tolerance && remainder.coefficients[0].imaginary().abs() < self.tolerance) { // Get the power left over from dividing lead terms let order = remainder.coefficients.len() - divisor.coefficients.len(); // Make a vector that is just the lead coefficients divided at the right power temp.coefficients = vec![N::zero(); order + 1]; temp.coefficients[order] = *remainder.coefficients.last().unwrap() / *divisor.coefficients.last().unwrap(); // Add the division to the quotient quotient += &temp; // Get the amount to shift divisor by let padding = temp.coefficients.len() - 1; // Multiply every coefficient in divisor by temp's coefficient temp = divisor .coefficients .iter() .map(|c| *c * *temp.coefficients.last().unwrap()) .collect(); // Shift the coefficients to multiply by the right power of x for _ in 0..padding { temp.coefficients.insert(0, N::zero()); } // remainder -= temp x d; remainder -= &temp; while remainder.coefficients.len() > 1 && remainder.coefficients.last().unwrap().real().abs() < self.tolerance && remainder.coefficients.last().unwrap().imaginary().abs() < self.tolerance { remainder.coefficients.pop(); } } Ok((quotient, remainder)) } /// Get the n (possibly including repeats) of the polynomial given n using Laguerre's method pub fn roots( &self, tol: <N as ComplexField>::RealField, n_max: usize, ) -> Result<VecDeque<Complex<<N as ComplexField>::RealField>>, String> { if self.coefficients.len() > 1 && self.coefficients.last().unwrap().real().abs() < tol && self.coefficients.last().unwrap().imaginary().abs() < tol { return Err("Polynomial roots: Leading 0 coefficient!".to_owned()); } match self.coefficients.len() { 1 => { // Only constant, root only if constant is 0 if self.coefficients[0].real().abs() < tol && self.coefficients[0].imaginary().abs() < tol { return Ok(VecDeque::from(vec![Complex::<N::RealField>::zero()])); } return Err("Polynomial roots: Non-zero constant has no root".to_owned()); } 2 => { // Linear term, root easy let division = -self.coefficients[0] / self.coefficients[1]; return Ok(VecDeque::from(vec![Complex::<N::RealField>::new( division.real(), division.imaginary(), )])); } 3 => { // Use quadratic formula and return in right order let determinant = self.coefficients[1].powi(2) - N::from_f64(4.0).unwrap() * self.coefficients[2] * self.coefficients[0]; let determinant = Complex::<N::RealField>::new(determinant.real(), determinant.imaginary()) .sqrt(); let leading = self.coefficients[2]; let leading = Complex::<N::RealField>::new(leading.real(), leading.imaginary()); let leading = leading * Complex::<N::RealField>::new( N::from_f64(2.0).unwrap().real(), N::zero().real(), ); let secondary = self.coefficients[1]; let secondary = Complex::<N::RealField>::new(secondary.real(), secondary.imaginary()); let positive = (-secondary + determinant) / leading; let negative = (-secondary - determinant) / leading; return Ok(VecDeque::from(vec![positive, negative])); } _ => {} } let complex = self.make_complex(); let derivative = complex.derivative(); let mut guess = Complex::<N::RealField>::zero(); let mut k = 0; 'out: while k < n_max { let val = complex.evaluate(guess); if val.abs() < tol { break 'out; } let (deriv, second_deriv) = derivative.evaluate_derivative(guess); let deriv_quotient = deriv / val; let g_sq = deriv_quotient.powi(2); let second_deriv_quotient = g_sq - second_deriv / val; let order = Complex::<N::RealField>::from_usize(self.coefficients.len() - 1).unwrap(); let sqrt = ((order - Complex::<N::RealField>::one()) * (order * second_deriv_quotient - g_sq)) .sqrt(); let plus = deriv_quotient + sqrt; let minus = deriv_quotient - sqrt; let a = if plus.abs() > minus.abs() { order / plus } else { order / minus }; guess -= a; k += 1; } if k == n_max { return Err("Polynomial roots: maximum iterations exceeded".to_owned()); } let divisor = polynomial![Complex::<N::RealField>::one(), -guess]; let (quotient, _) = complex.divide(&divisor)?; let mut roots = quotient.roots(tol, n_max)?; roots.push_front(guess); let mut corrected_roots = VecDeque::with_capacity(roots.len()); for root in roots.iter() { corrected_roots.push_back(newton_polynomial(*root, &complex, tol, n_max)?); } Ok(corrected_roots) } // Pad to the smallest power of two less than or equal to size fn pad_power_of_two(&mut self, size: usize) { let mut power: usize = 1; while power < size { power <<= 1; } while self.coefficients.len() < power { self.coefficients.push(N::zero()); } } /// Get the polynomial in point form evaluated at roots of unity at k points /// where k is the smallest power of 2 greater than or equal to size pub fn dft(&self, size: usize) -> Vec<Complex<<N as ComplexField>::RealField>> { let mut poly = self.make_complex(); poly.pad_power_of_two(size); let mut working = bit_reverse_copy(&poly.coefficients); let len = working.len(); for s in 1..(len as f64).log2() as usize + 1 { let m = 1 << s; let angle = 2.0 * f64::consts::PI / m as f64; let angle = N::RealField::from_f64(angle).unwrap(); let root_of_unity = Complex::<N::RealField>::new(angle.cos(), angle.sin()); let mut w = Complex::<N::RealField>::new(N::RealField::one(), N::RealField::zero()); for j in 0..m / 2 { for k in (j..len).step_by(m) { let temp = w * working[k + m / 2]; let u = working[k]; working[k] = u + temp; working[k + m / 2] = u - temp; } w *= root_of_unity; } } working } // Assumes power of 2 pub fn idft( vec: &[Complex<<N as ComplexField>::RealField>], tol: <N as ComplexField>::RealField, ) -> Self { let mut working = bit_reverse_copy(vec); let len = working.len(); for s in 1..(len as f64).log2() as usize + 1 { let m = 1 << s; let angle = -2.0 * f64::consts::PI / m as f64; let angle = N::RealField::from_f64(angle).unwrap(); let root_of_unity = Complex::<N::RealField>::new(angle.cos(), angle.sin()); let mut w = Complex::<N::RealField>::new(N::RealField::one(), N::RealField::zero()); for j in 0..m / 2 { for k in (j..len).step_by(m) { let temp = w * working[k + m / 2]; let u = working[k]; working[k] = u + temp; working[k + m / 2] = u - temp; } w *= root_of_unity; } } let ilen = Complex::<N::RealField>::new( N::from_f64(1.0 / len as f64).unwrap().real(), N::zero().real(), ); for val in &mut working { *val *= ilen; } let coefficients = if TypeId::of::<N::RealField>() == TypeId::of::<N>() { working .iter() .map(|c| N::from_real(c.re)) .collect::<Vec<_>>() } else { working .iter() .map(|c| N::from_real(c.re) + (-N::one()).sqrt() * N::from_real(c.im)) .collect::<Vec<_>>() }; let mut poly = Polynomial { coefficients, tolerance: tol, }; poly.purge_leading(); poly } } fn bit_reverse(mut k: usize, num_bits: usize) -> usize { let mut result: usize = 0; for _ in 0..num_bits { result |= k & 1; result <<= 1; k >>= 1; } result >>= 1; result } // Assumes vec is a power of 2 length fn bit_reverse_copy<N: RealField>(vec: &[Complex<N>]) -> Vec<Complex<N>> { let len = vec.len(); let mut result = vec![Complex::new(N::zero(), N::zero()); len]; let num_bits = (len as f64).log2() as usize; for k in 0..len { result[bit_reverse(k, num_bits)] = vec[k]; } result } impl<N: ComplexField> FromIterator<N> for Polynomial<N> { fn from_iter<I: IntoIterator<Item = N>>(iter: I) -> Polynomial<N> { Polynomial { coefficients: Vec::from_iter(iter), tolerance: N::RealField::from_f64(1e-10).unwrap(), } } } impl<N: ComplexField> Default for Polynomial<N> { fn default() -> Self { Self::new() } } impl<N: ComplexField> Zero for Polynomial<N> { fn zero() -> Polynomial<N> { Polynomial::new() } fn is_zero(&self) -> bool { for val in &self.coefficients { if !val.is_zero() { return false; } } true } } // Operator overloading impl<N: ComplexField> ops::Add<N> for Polynomial<N> { type Output = Polynomial<N>; fn add(mut self, rhs: N) -> Polynomial<N> { self.coefficients[0] += rhs; self } } impl<N: ComplexField> ops::Add<N> for &Polynomial<N> { type Output = Polynomial<N>; fn add(self, rhs: N) -> Polynomial<N> { let mut coefficients = Vec::from(self.coefficients.as_slice()); coefficients[0] += rhs; Polynomial { coefficients, tolerance: self.tolerance, } } } impl<N: ComplexField> ops::Add<Polynomial<N>> for Polynomial<N> { type Output = Polynomial<N>; fn add(mut self, rhs: Polynomial<N>) -> Polynomial<N> { let min_order = self.coefficients.len().min(rhs.coefficients.len()); for (ind, val) in self.coefficients.iter_mut().take(min_order).enumerate() { *val += rhs.coefficients[ind]; } for val in rhs.coefficients.iter().skip(min_order) { self.coefficients.push(*val); } self } } impl<N: ComplexField> ops::Add<&Polynomial<N>> for Polynomial<N> { type Output = Polynomial<N>; fn add(mut self, rhs: &Polynomial<N>) -> Polynomial<N> { let min_order = self.coefficients.len().min(rhs.coefficients.len()); for (ind, val) in self.coefficients.iter_mut().take(min_order).enumerate() { *val += rhs.coefficients[ind]; } // Will only run if rhs has higher order for val in rhs.coefficients.iter().skip(min_order) { self.coefficients.push(*val); } self } } impl<N: ComplexField> ops::Add<Polynomial<N>> for &Polynomial<N> { type Output = Polynomial<N>; fn add(self, rhs: Polynomial<N>) -> Polynomial<N> { let min_order = self.coefficients.len().min(rhs.coefficients.len()); let mut coefficients = Vec::with_capacity(self.coefficients.len().max(rhs.coefficients.len())); for (ind, val) in self.coefficients.iter().take(min_order).enumerate() { coefficients.push(*val + rhs.coefficients[ind]); } // Only one loop will run for val in self.coefficients.iter().skip(min_order) { coefficients.push(*val); } for val in rhs.coefficients.iter().skip(min_order) { coefficients.push(*val); } Polynomial { coefficients, tolerance: self.tolerance, } } } impl<N: ComplexField> ops::Add<&Polynomial<N>> for &Polynomial<N> { type Output = Polynomial<N>; fn add(self, rhs: &Polynomial<N>) -> Polynomial<N> { let min_order = self.coefficients.len().min(rhs.coefficients.len()); let mut coefficients = Vec::with_capacity(self.coefficients.len().max(rhs.coefficients.len())); for (ind, val) in self.coefficients.iter().take(min_order).enumerate() { coefficients.push(*val + rhs.coefficients[ind]); } // Only one loop will run for val in self.coefficients.iter().skip(min_order) { coefficients.push(*val); } for val in rhs.coefficients.iter().skip(min_order) { coefficients.push(*val); } Polynomial { coefficients, tolerance: self.tolerance, } } } impl<N: ComplexField> ops::AddAssign<N> for Polynomial<N> { fn add_assign(&mut self, rhs: N) { self.coefficients[0] += rhs; } } impl<N: ComplexField> ops::AddAssign<Polynomial<N>> for Polynomial<N> { fn add_assign(&mut self, rhs: Polynomial<N>) { let min_order = self.coefficients.len().min(rhs.coefficients.len()); for (ind, val) in self.coefficients.iter_mut().take(min_order).enumerate() { *val += rhs.coefficients[ind]; } for val in rhs.coefficients.iter().skip(min_order) { self.coefficients.push(*val); } } } impl<N: ComplexField> ops::AddAssign<&Polynomial<N>> for Polynomial<N> { fn add_assign(&mut self, rhs: &Polynomial<N>) { let min_order = self.coefficients.len().min(rhs.coefficients.len()); for (ind, val) in self.coefficients.iter_mut().take(min_order).enumerate() { *val += rhs.coefficients[ind]; } for val in rhs.coefficients.iter().skip(min_order) { self.coefficients.push(*val); } } } impl<N: ComplexField> ops::Sub<N> for Polynomial<N> { type Output = Polynomial<N>; fn sub(mut self, rhs: N) -> Polynomial<N> { self.coefficients[0] -= rhs; self } } impl<N: ComplexField> ops::Sub<N> for &Polynomial<N> { type Output = Polynomial<N>; fn sub(self, rhs: N) -> Polynomial<N> { let mut coefficients = Vec::from(self.coefficients.as_slice()); coefficients[0] -= rhs; Polynomial { coefficients, tolerance: self.tolerance, } } } impl<N: ComplexField> ops::Sub<Polynomial<N>> for Polynomial<N> { type Output = Polynomial<N>; fn sub(mut self, rhs: Polynomial<N>) -> Polynomial<N> { let min_order = self.coefficients.len().min(rhs.coefficients.len()); for (ind, val) in self.coefficients.iter_mut().take(min_order).enumerate() { *val -= rhs.coefficients[ind]; } for val in rhs.coefficients.iter().skip(min_order) { self.coefficients.push(-*val); } self } } impl<N: ComplexField> ops::Sub<Polynomial<N>> for &Polynomial<N> { type Output = Polynomial<N>; fn sub(self, rhs: Polynomial<N>) -> Polynomial<N> { let min_order = self.coefficients.len().min(rhs.coefficients.len()); let mut coefficients = Vec::with_capacity(self.coefficients.len().max(rhs.coefficients.len())); for (ind, val) in self.coefficients.iter().take(min_order).enumerate() { coefficients.push(*val - rhs.coefficients[ind]); } // Only one for loop runs for val in self.coefficients.iter().skip(min_order) { coefficients.push(*val); } for val in rhs.coefficients.iter().skip(min_order) { coefficients.push(-*val); } Polynomial { coefficients, tolerance: self.tolerance, } } } impl<N: ComplexField> ops::Sub<&Polynomial<N>> for Polynomial<N> { type Output = Polynomial<N>; fn sub(mut self, rhs: &Polynomial<N>) -> Polynomial<N> { let min_order = self.coefficients.len().min(rhs.coefficients.len()); for (ind, val) in self.coefficients.iter_mut().take(min_order).enumerate() { *val -= rhs.coefficients[ind]; } for val in rhs.coefficients.iter().skip(min_order) { self.coefficients.push(-*val); } self } } impl<N: ComplexField> ops::Sub<&Polynomial<N>> for &Polynomial<N> { type Output = Polynomial<N>; fn sub(self, rhs: &Polynomial<N>) -> Polynomial<N> { let min_order = self.coefficients.len().min(rhs.coefficients.len()); let mut coefficients = Vec::with_capacity(self.coefficients.len().max(rhs.coefficients.len())); for (ind, val) in self.coefficients.iter().take(min_order).enumerate() { coefficients.push(*val - rhs.coefficients[ind]); } // Only one for loop runs for val in self.coefficients.iter().skip(min_order) { coefficients.push(*val); } for val in rhs.coefficients.iter().skip(min_order) { coefficients.push(-*val); } Polynomial { coefficients, tolerance: self.tolerance, } } } impl<N: ComplexField> ops::SubAssign<N> for Polynomial<N> { fn sub_assign(&mut self, rhs: N) { self.coefficients[0] -= rhs; } } impl<N: ComplexField> ops::SubAssign<Polynomial<N>> for Polynomial<N> { fn sub_assign(&mut self, rhs: Polynomial<N>) { let min_order = self.coefficients.len().min(rhs.coefficients.len()); for (ind, val) in self.coefficients.iter_mut().take(min_order).enumerate() { *val -= rhs.coefficients[ind]; } for val in rhs.coefficients.iter().skip(min_order) { self.coefficients.push(-*val); } } } impl<N: ComplexField> ops::SubAssign<&Polynomial<N>> for Polynomial<N> { fn sub_assign(&mut self, rhs: &Polynomial<N>) { let min_order = self.coefficients.len().min(rhs.coefficients.len()); for (ind, val) in self.coefficients.iter_mut().take(min_order).enumerate() { *val -= rhs.coefficients[ind]; } for val in rhs.coefficients.iter().skip(min_order) { self.coefficients.push(-*val); } } } impl<N: ComplexField> ops::Mul<N> for Polynomial<N> { type Output = Polynomial<N>; fn mul(mut self, rhs: N) -> Polynomial<N> { for val in &mut self.coefficients { *val *= rhs; } self } } impl<N: ComplexField> ops::Mul<N> for &Polynomial<N> { type Output = Polynomial<N>; fn mul(self, rhs: N) -> Polynomial<N> { let mut coefficients = Vec::with_capacity(self.coefficients.len()); for val in &self.coefficients { coefficients.push(*val * rhs); } Polynomial { coefficients, tolerance: self.tolerance, } } } fn multiply<N: ComplexField>(lhs: &Polynomial<N>, rhs: &Polynomial<N>) -> Polynomial<N> { // Do scalar multiplication if one side has no powers if rhs.coefficients.len() == 1 { return lhs * rhs.coefficients[0]; } if lhs.coefficients.len() == 1 { return rhs * lhs.coefficients[0]; } // Special case linear term multiplication if rhs.coefficients.len() == 2 { let mut shifted = lhs * rhs.coefficients[1]; shifted.coefficients.insert(0, N::zero()); return shifted + lhs * rhs.coefficients[0]; } if lhs.coefficients.len() == 2 { let mut shifted = rhs * lhs.coefficients[1]; shifted.coefficients.insert(0, N::zero()); return shifted + rhs * lhs.coefficients[0]; } let bound = lhs.coefficients.len().max(rhs.coefficients.len()) * 2; let left_points = lhs.dft(bound); let right_points = rhs.dft(bound); let product_points: Vec<_> = left_points .iter() .zip(right_points.iter()) .map(|(l_p, r_p)| *l_p * r_p) .collect(); Polynomial::<N>::idft(&product_points, lhs.tolerance) } impl<N: ComplexField> ops::Mul<Polynomial<N>> for Polynomial<N> { type Output = Polynomial<N>; fn mul(self, rhs: Polynomial<N>) -> Polynomial<N> { multiply(&self, &rhs) } } impl<N: ComplexField> ops::Mul<&Polynomial<N>> for Polynomial<N> { type Output = Polynomial<N>; fn mul(self, rhs: &Polynomial<N>) -> Polynomial<N> { multiply(&self, &rhs) } } impl<N: ComplexField> ops::Mul<Polynomial<N>> for &Polynomial<N> { type Output = Polynomial<N>; fn mul(self, rhs: Polynomial<N>) -> Polynomial<N> { multiply(&self, &rhs) } } impl<N: ComplexField> ops::Mul<&Polynomial<N>> for &Polynomial<N> { type Output = Polynomial<N>; fn mul(self, rhs: &Polynomial<N>) -> Polynomial<N> { multiply(&self, &rhs) } } impl<N: ComplexField> ops::MulAssign<N> for Polynomial<N> { fn mul_assign(&mut self, rhs: N) { for val in self.coefficients.iter_mut() { *val *= rhs; } } } impl<N: ComplexField> ops::MulAssign<Polynomial<N>> for Polynomial<N> { fn mul_assign(&mut self, rhs: Polynomial<N>) { self.coefficients = multiply(&self, &rhs).coefficients; } } impl<N: ComplexField> ops::MulAssign<&Polynomial<N>> for Polynomial<N> { fn mul_assign(&mut self, rhs: &Polynomial<N>) { self.coefficients = multiply(&self, &rhs).coefficients; } } impl<N: ComplexField> ops::Div<N> for Polynomial<N> { type Output = Polynomial<N>; fn div(mut self, rhs: N) -> Polynomial<N> { for val in &mut self.coefficients { *val /= rhs; } self } } impl<N: ComplexField> ops::Div<N> for &Polynomial<N> { type Output = Polynomial<N>; fn div(self, rhs: N) -> Polynomial<N> { let mut coefficients = Vec::from(self.coefficients.as_slice()); for val in &mut coefficients { *val /= rhs; } Polynomial { coefficients, tolerance: self.tolerance, } } } impl<N: ComplexField> ops::DivAssign<N> for Polynomial<N> { fn div_assign(&mut self, rhs: N) { for val in &mut self.coefficients { *val /= rhs; } } } impl<N: ComplexField> ops::Neg for Polynomial<N> { type Output = Polynomial<N>; fn neg(mut self) -> Polynomial<N> { for val in &mut self.coefficients { *val = -*val; } self } } impl<N: ComplexField> ops::Neg for &Polynomial<N> { type Output = Polynomial<N>; fn neg(self) -> Polynomial<N> { Polynomial { coefficients: self.coefficients.iter().map(|c| -*c).collect(), tolerance: self.tolerance, } } } impl<N: ComplexField> From<N> for Polynomial<N> { fn from(n: N) -> Polynomial<N> { polynomial![n] } } impl<N: RealField> From<Polynomial<N>> for Polynomial<Complex<N>> { fn from(poly: Polynomial<N>) -> Polynomial<Complex<N>> { poly.make_complex() } }
32.820956
121
0.552119
3aef9fd020d812d5a30372352c820a73e6f18462
968
use engine_test_support::{ internal::{ExecuteRequestBuilder, InMemoryWasmTestBuilder, DEFAULT_RUN_GENESIS_REQUEST}, DEFAULT_ACCOUNT_ADDR, }; const CONTRACT_EE_401_REGRESSION: &str = "ee_401_regression.wasm"; const CONTRACT_EE_401_REGRESSION_CALL: &str = "ee_401_regression_call.wasm"; #[ignore] #[test] fn should_execute_contracts_which_provide_extra_urefs() { let exec_request_1 = ExecuteRequestBuilder::standard(DEFAULT_ACCOUNT_ADDR, CONTRACT_EE_401_REGRESSION, ()) .build(); let exec_request_2 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_EE_401_REGRESSION_CALL, (DEFAULT_ACCOUNT_ADDR,), ) .build(); let _result = InMemoryWasmTestBuilder::default() .run_genesis(&DEFAULT_RUN_GENESIS_REQUEST) .exec(exec_request_1) .expect_success() .commit() .exec(exec_request_2) .expect_success() .commit() .finish(); }
30.25
93
0.704545
f9a43ccfbace182f71b5e5f9dd824338d17f986a
161,332
// ignore-tidy-filelength //! This module contains the "cleaned" pieces of the AST, and the functions //! that clean them. pub mod inline; pub mod cfg; mod simplify; mod auto_trait; mod blanket_impl; use rustc_data_structures::indexed_vec::{IndexVec, Idx}; use rustc_data_structures::sync::Lrc; use rustc_target::spec::abi::Abi; use rustc_typeck::hir_ty_to_ty; use rustc::infer::region_constraints::{RegionConstraintData, Constraint}; use rustc::middle::resolve_lifetime as rl; use rustc::middle::lang_items; use rustc::middle::stability; use rustc::mir::interpret::{GlobalId, ConstValue}; use rustc::hir::{self, HirVec}; use rustc::hir::def::{self, Res, DefKind, CtorKind}; use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc::ty::subst::{InternalSubsts, SubstsRef, UnpackedKind}; use rustc::ty::{self, DefIdTree, TyCtxt, Region, RegionVid, Ty, AdtKind}; use rustc::ty::fold::TypeFolder; use rustc::ty::layout::VariantIdx; use rustc::util::nodemap::{FxHashMap, FxHashSet}; use syntax::ast::{self, AttrStyle, Ident}; use syntax::attr; use syntax::ext::base::MacroKind; use syntax::source_map::{dummy_spanned, Spanned}; use syntax::ptr::P; use syntax::symbol::keywords::{self, Keyword}; use syntax::symbol::{Symbol, sym}; use syntax::symbol::InternedString; use syntax_pos::{self, Pos, FileName}; use std::collections::hash_map::Entry; use std::fmt; use std::hash::{Hash, Hasher}; use std::default::Default; use std::{mem, slice, vec}; use std::iter::{FromIterator, once}; use std::rc::Rc; use std::str::FromStr; use std::cell::RefCell; use std::sync::Arc; use std::u32; use parking_lot::ReentrantMutex; use crate::core::{self, DocContext}; use crate::doctree; use crate::visit_ast; use crate::html::render::{cache, ExternalLocation}; use crate::html::item_type::ItemType; use self::cfg::Cfg; use self::auto_trait::AutoTraitFinder; use self::blanket_impl::BlanketImplFinder; pub use self::Type::*; pub use self::Mutability::*; pub use self::ItemEnum::*; pub use self::SelfTy::*; pub use self::FunctionRetTy::*; pub use self::Visibility::{Public, Inherited}; thread_local!(pub static MAX_DEF_ID: RefCell<FxHashMap<CrateNum, DefId>> = Default::default()); const FN_OUTPUT_NAME: &'static str = "Output"; // extract the stability index for a node from tcx, if possible fn get_stability(cx: &DocContext<'_>, def_id: DefId) -> Option<Stability> { cx.tcx.lookup_stability(def_id).clean(cx) } fn get_deprecation(cx: &DocContext<'_>, def_id: DefId) -> Option<Deprecation> { cx.tcx.lookup_deprecation(def_id).clean(cx) } pub trait Clean<T> { fn clean(&self, cx: &DocContext<'_>) -> T; } impl<T: Clean<U>, U> Clean<Vec<U>> for [T] { fn clean(&self, cx: &DocContext<'_>) -> Vec<U> { self.iter().map(|x| x.clean(cx)).collect() } } impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> { fn clean(&self, cx: &DocContext<'_>) -> IndexVec<V, U> { self.iter().map(|x| x.clean(cx)).collect() } } impl<T: Clean<U>, U> Clean<U> for P<T> { fn clean(&self, cx: &DocContext<'_>) -> U { (**self).clean(cx) } } impl<T: Clean<U>, U> Clean<U> for Rc<T> { fn clean(&self, cx: &DocContext<'_>) -> U { (**self).clean(cx) } } impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> { fn clean(&self, cx: &DocContext<'_>) -> Option<U> { self.as_ref().map(|v| v.clean(cx)) } } impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> { fn clean(&self, cx: &DocContext<'_>) -> U { self.skip_binder().clean(cx) } } impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> { fn clean(&self, cx: &DocContext<'_>) -> Vec<U> { self.iter().map(|x| x.clean(cx)).collect() } } #[derive(Clone, Debug)] pub struct Crate { pub name: String, pub version: Option<String>, pub src: FileName, pub module: Option<Item>, pub externs: Vec<(CrateNum, ExternalCrate)>, pub primitives: Vec<(DefId, PrimitiveType, Attributes)>, // These are later on moved into `CACHEKEY`, leaving the map empty. // Only here so that they can be filtered through the rustdoc passes. pub external_traits: Arc<ReentrantMutex<RefCell<FxHashMap<DefId, Trait>>>>, pub masked_crates: FxHashSet<CrateNum>, } impl<'a, 'tcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx> { fn clean(&self, cx: &DocContext<'_>) -> Crate { use crate::visit_lib::LibEmbargoVisitor; { let mut r = cx.renderinfo.borrow_mut(); r.deref_trait_did = cx.tcx.lang_items().deref_trait(); r.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait(); r.owned_box_did = cx.tcx.lang_items().owned_box(); } let mut externs = Vec::new(); for &cnum in cx.tcx.crates().iter() { externs.push((cnum, cnum.clean(cx))); // Analyze doc-reachability for extern items LibEmbargoVisitor::new(cx).visit_lib(cnum); } externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b)); // Clean the crate, translating the entire libsyntax AST to one that is // understood by rustdoc. let mut module = self.module.clean(cx); let mut masked_crates = FxHashSet::default(); match module.inner { ModuleItem(ref module) => { for it in &module.items { // `compiler_builtins` should be masked too, but we can't apply // `#[doc(masked)]` to the injected `extern crate` because it's unstable. if it.is_extern_crate() && (it.attrs.has_doc_flag(sym::masked) || self.cx.tcx.is_compiler_builtins(it.def_id.krate)) { masked_crates.insert(it.def_id.krate); } } } _ => unreachable!(), } let ExternalCrate { name, src, primitives, keywords, .. } = LOCAL_CRATE.clean(cx); { let m = match module.inner { ModuleItem(ref mut m) => m, _ => unreachable!(), }; m.items.extend(primitives.iter().map(|&(def_id, prim, ref attrs)| { Item { source: Span::empty(), name: Some(prim.to_url_str().to_string()), attrs: attrs.clone(), visibility: Some(Public), stability: get_stability(cx, def_id), deprecation: get_deprecation(cx, def_id), def_id, inner: PrimitiveItem(prim), } })); m.items.extend(keywords.into_iter().map(|(def_id, kw, attrs)| { Item { source: Span::empty(), name: Some(kw.clone()), attrs: attrs, visibility: Some(Public), stability: get_stability(cx, def_id), deprecation: get_deprecation(cx, def_id), def_id, inner: KeywordItem(kw), } })); } Crate { name, version: None, src, module: Some(module), externs, primitives, external_traits: cx.external_traits.clone(), masked_crates, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct ExternalCrate { pub name: String, pub src: FileName, pub attrs: Attributes, pub primitives: Vec<(DefId, PrimitiveType, Attributes)>, pub keywords: Vec<(DefId, String, Attributes)>, } impl Clean<ExternalCrate> for CrateNum { fn clean(&self, cx: &DocContext<'_>) -> ExternalCrate { let root = DefId { krate: *self, index: CRATE_DEF_INDEX }; let krate_span = cx.tcx.def_span(root); let krate_src = cx.sess().source_map().span_to_filename(krate_span); // Collect all inner modules which are tagged as implementations of // primitives. // // Note that this loop only searches the top-level items of the crate, // and this is intentional. If we were to search the entire crate for an // item tagged with `#[doc(primitive)]` then we would also have to // search the entirety of external modules for items tagged // `#[doc(primitive)]`, which is a pretty inefficient process (decoding // all that metadata unconditionally). // // In order to keep the metadata load under control, the // `#[doc(primitive)]` feature is explicitly designed to only allow the // primitive tags to show up as the top level items in a crate. // // Also note that this does not attempt to deal with modules tagged // duplicately for the same primitive. This is handled later on when // rendering by delegating everything to a hash map. let as_primitive = |res: Res| { if let Res::Def(DefKind::Mod, def_id) = res { let attrs = cx.tcx.get_attrs(def_id).clean(cx); let mut prim = None; for attr in attrs.lists(sym::doc) { if let Some(v) = attr.value_str() { if attr.check_name(sym::primitive) { prim = PrimitiveType::from_str(&v.as_str()); if prim.is_some() { break; } // FIXME: should warn on unknown primitives? } } } return prim.map(|p| (def_id, p, attrs)); } None }; let primitives = if root.is_local() { cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| { let item = cx.tcx.hir().expect_item_by_hir_id(id.id); match item.node { hir::ItemKind::Mod(_) => { as_primitive(Res::Def( DefKind::Mod, cx.tcx.hir().local_def_id_from_hir_id(id.id), )) } hir::ItemKind::Use(ref path, hir::UseKind::Single) if item.vis.node.is_pub() => { as_primitive(path.res).map(|(_, prim, attrs)| { // Pretend the primitive is local. (cx.tcx.hir().local_def_id_from_hir_id(id.id), prim, attrs) }) } _ => None } }).collect() } else { cx.tcx.item_children(root).iter().map(|item| item.res) .filter_map(as_primitive).collect() }; let as_keyword = |res: Res| { if let Res::Def(DefKind::Mod, def_id) = res { let attrs = cx.tcx.get_attrs(def_id).clean(cx); let mut keyword = None; for attr in attrs.lists(sym::doc) { if let Some(v) = attr.value_str() { if attr.check_name(sym::keyword) { keyword = Keyword::from_str(&v.as_str()).ok() .map(|x| x.name().to_string()); if keyword.is_some() { break } // FIXME: should warn on unknown keywords? } } } return keyword.map(|p| (def_id, p, attrs)); } None }; let keywords = if root.is_local() { cx.tcx.hir().krate().module.item_ids.iter().filter_map(|&id| { let item = cx.tcx.hir().expect_item_by_hir_id(id.id); match item.node { hir::ItemKind::Mod(_) => { as_keyword(Res::Def( DefKind::Mod, cx.tcx.hir().local_def_id_from_hir_id(id.id), )) } hir::ItemKind::Use(ref path, hir::UseKind::Single) if item.vis.node.is_pub() => { as_keyword(path.res).map(|(_, prim, attrs)| { (cx.tcx.hir().local_def_id_from_hir_id(id.id), prim, attrs) }) } _ => None } }).collect() } else { cx.tcx.item_children(root).iter().map(|item| item.res) .filter_map(as_keyword).collect() }; ExternalCrate { name: cx.tcx.crate_name(*self).to_string(), src: krate_src, attrs: cx.tcx.get_attrs(root).clean(cx), primitives, keywords, } } } /// Anything with a source location and set of attributes and, optionally, a /// name. That is, anything that can be documented. This doesn't correspond /// directly to the AST's concept of an item; it's a strict superset. #[derive(Clone, RustcEncodable, RustcDecodable)] pub struct Item { /// Stringified span pub source: Span, /// Not everything has a name. E.g., impls pub name: Option<String>, pub attrs: Attributes, pub inner: ItemEnum, pub visibility: Option<Visibility>, pub def_id: DefId, pub stability: Option<Stability>, pub deprecation: Option<Deprecation>, } impl fmt::Debug for Item { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let fake = MAX_DEF_ID.with(|m| m.borrow().get(&self.def_id.krate) .map(|id| self.def_id >= *id).unwrap_or(false)); let def_id: &dyn fmt::Debug = if fake { &"**FAKE**" } else { &self.def_id }; fmt.debug_struct("Item") .field("source", &self.source) .field("name", &self.name) .field("attrs", &self.attrs) .field("inner", &self.inner) .field("visibility", &self.visibility) .field("def_id", def_id) .field("stability", &self.stability) .field("deprecation", &self.deprecation) .finish() } } impl Item { /// Finds the `doc` attribute as a NameValue and returns the corresponding /// value found. pub fn doc_value<'a>(&'a self) -> Option<&'a str> { self.attrs.doc_value() } /// Finds all `doc` attributes as NameValues and returns their corresponding values, joined /// with newlines. pub fn collapsed_doc_value(&self) -> Option<String> { self.attrs.collapsed_doc_value() } pub fn links(&self) -> Vec<(String, String)> { self.attrs.links(&self.def_id.krate) } pub fn is_crate(&self) -> bool { match self.inner { StrippedItem(box ModuleItem(Module { is_crate: true, ..})) | ModuleItem(Module { is_crate: true, ..}) => true, _ => false, } } pub fn is_mod(&self) -> bool { self.type_() == ItemType::Module } pub fn is_trait(&self) -> bool { self.type_() == ItemType::Trait } pub fn is_struct(&self) -> bool { self.type_() == ItemType::Struct } pub fn is_enum(&self) -> bool { self.type_() == ItemType::Enum } pub fn is_variant(&self) -> bool { self.type_() == ItemType::Variant } pub fn is_associated_type(&self) -> bool { self.type_() == ItemType::AssociatedType } pub fn is_associated_const(&self) -> bool { self.type_() == ItemType::AssociatedConst } pub fn is_method(&self) -> bool { self.type_() == ItemType::Method } pub fn is_ty_method(&self) -> bool { self.type_() == ItemType::TyMethod } pub fn is_typedef(&self) -> bool { self.type_() == ItemType::Typedef } pub fn is_primitive(&self) -> bool { self.type_() == ItemType::Primitive } pub fn is_union(&self) -> bool { self.type_() == ItemType::Union } pub fn is_import(&self) -> bool { self.type_() == ItemType::Import } pub fn is_extern_crate(&self) -> bool { self.type_() == ItemType::ExternCrate } pub fn is_keyword(&self) -> bool { self.type_() == ItemType::Keyword } pub fn is_stripped(&self) -> bool { match self.inner { StrippedItem(..) => true, _ => false } } pub fn has_stripped_fields(&self) -> Option<bool> { match self.inner { StructItem(ref _struct) => Some(_struct.fields_stripped), UnionItem(ref union) => Some(union.fields_stripped), VariantItem(Variant { kind: VariantKind::Struct(ref vstruct)} ) => { Some(vstruct.fields_stripped) }, _ => None, } } pub fn stability_class(&self) -> Option<String> { self.stability.as_ref().and_then(|ref s| { let mut classes = Vec::with_capacity(2); if s.level == stability::Unstable { classes.push("unstable"); } if s.deprecation.is_some() { classes.push("deprecated"); } if classes.len() != 0 { Some(classes.join(" ")) } else { None } }) } pub fn stable_since(&self) -> Option<&str> { self.stability.as_ref().map(|s| &s.since[..]) } pub fn is_non_exhaustive(&self) -> bool { self.attrs.other_attrs.iter() .any(|a| a.check_name(sym::non_exhaustive)) } /// Returns a documentation-level item type from the item. pub fn type_(&self) -> ItemType { ItemType::from(self) } /// Returns the info in the item's `#[deprecated]` or `#[rustc_deprecated]` attributes. /// /// If the item is not deprecated, returns `None`. pub fn deprecation(&self) -> Option<&Deprecation> { self.deprecation .as_ref() .or_else(|| self.stability.as_ref().and_then(|s| s.deprecation.as_ref())) } pub fn is_default(&self) -> bool { match self.inner { ItemEnum::MethodItem(ref meth) => { if let Some(defaultness) = meth.defaultness { defaultness.has_value() && !defaultness.is_final() } else { false } } _ => false, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum ItemEnum { ExternCrateItem(String, Option<String>), ImportItem(Import), StructItem(Struct), UnionItem(Union), EnumItem(Enum), FunctionItem(Function), ModuleItem(Module), TypedefItem(Typedef, bool /* is associated type */), ExistentialItem(Existential, bool /* is associated type */), StaticItem(Static), ConstantItem(Constant), TraitItem(Trait), TraitAliasItem(TraitAlias), ImplItem(Impl), /// A method signature only. Used for required methods in traits (ie, /// non-default-methods). TyMethodItem(TyMethod), /// A method with a body. MethodItem(Method), StructFieldItem(Type), VariantItem(Variant), /// `fn`s from an extern block ForeignFunctionItem(Function), /// `static`s from an extern block ForeignStaticItem(Static), /// `type`s from an extern block ForeignTypeItem, MacroItem(Macro), ProcMacroItem(ProcMacro), PrimitiveItem(PrimitiveType), AssociatedConstItem(Type, Option<String>), AssociatedTypeItem(Vec<GenericBound>, Option<Type>), /// An item that has been stripped by a rustdoc pass StrippedItem(Box<ItemEnum>), KeywordItem(String), } impl ItemEnum { pub fn generics(&self) -> Option<&Generics> { Some(match *self { ItemEnum::StructItem(ref s) => &s.generics, ItemEnum::EnumItem(ref e) => &e.generics, ItemEnum::FunctionItem(ref f) => &f.generics, ItemEnum::TypedefItem(ref t, _) => &t.generics, ItemEnum::ExistentialItem(ref t, _) => &t.generics, ItemEnum::TraitItem(ref t) => &t.generics, ItemEnum::ImplItem(ref i) => &i.generics, ItemEnum::TyMethodItem(ref i) => &i.generics, ItemEnum::MethodItem(ref i) => &i.generics, ItemEnum::ForeignFunctionItem(ref f) => &f.generics, ItemEnum::TraitAliasItem(ref ta) => &ta.generics, _ => return None, }) } pub fn is_associated(&self) -> bool { match *self { ItemEnum::TypedefItem(_, _) | ItemEnum::AssociatedTypeItem(_, _) => true, _ => false, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Module { pub items: Vec<Item>, pub is_crate: bool, } impl Clean<Item> for doctree::Module { fn clean(&self, cx: &DocContext<'_>) -> Item { let name = if self.name.is_some() { self.name.expect("No name provided").clean(cx) } else { String::new() }; // maintain a stack of mod ids, for doc comment path resolution // but we also need to resolve the module's own docs based on whether its docs were written // inside or outside the module, so check for that let attrs = self.attrs.clean(cx); let mut items: Vec<Item> = vec![]; items.extend(self.extern_crates.iter().flat_map(|x| x.clean(cx))); items.extend(self.imports.iter().flat_map(|x| x.clean(cx))); items.extend(self.structs.iter().map(|x| x.clean(cx))); items.extend(self.unions.iter().map(|x| x.clean(cx))); items.extend(self.enums.iter().map(|x| x.clean(cx))); items.extend(self.fns.iter().map(|x| x.clean(cx))); items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx))); items.extend(self.mods.iter().map(|x| x.clean(cx))); items.extend(self.typedefs.iter().map(|x| x.clean(cx))); items.extend(self.existentials.iter().map(|x| x.clean(cx))); items.extend(self.statics.iter().map(|x| x.clean(cx))); items.extend(self.constants.iter().map(|x| x.clean(cx))); items.extend(self.traits.iter().map(|x| x.clean(cx))); items.extend(self.impls.iter().flat_map(|x| x.clean(cx))); items.extend(self.macros.iter().map(|x| x.clean(cx))); items.extend(self.proc_macros.iter().map(|x| x.clean(cx))); items.extend(self.trait_aliases.iter().map(|x| x.clean(cx))); // determine if we should display the inner contents or // the outer `mod` item for the source code. let whence = { let cm = cx.sess().source_map(); let outer = cm.lookup_char_pos(self.where_outer.lo()); let inner = cm.lookup_char_pos(self.where_inner.lo()); if outer.file.start_pos == inner.file.start_pos { // mod foo { ... } self.where_outer } else { // mod foo; (and a separate SourceFile for the contents) self.where_inner } }; Item { name: Some(name), attrs, source: whence.clean(cx), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), def_id: cx.tcx.hir().local_def_id(self.id), inner: ModuleItem(Module { is_crate: self.is_crate, items, }) } } } pub struct ListAttributesIter<'a> { attrs: slice::Iter<'a, ast::Attribute>, current_list: vec::IntoIter<ast::NestedMetaItem>, name: Symbol, } impl<'a> Iterator for ListAttributesIter<'a> { type Item = ast::NestedMetaItem; fn next(&mut self) -> Option<Self::Item> { if let Some(nested) = self.current_list.next() { return Some(nested); } for attr in &mut self.attrs { if let Some(list) = attr.meta_item_list() { if attr.check_name(self.name) { self.current_list = list.into_iter(); if let Some(nested) = self.current_list.next() { return Some(nested); } } } } None } fn size_hint(&self) -> (usize, Option<usize>) { let lower = self.current_list.len(); (lower, None) } } pub trait AttributesExt { /// Finds an attribute as List and returns the list of attributes nested inside. fn lists<'a>(&'a self, name: Symbol) -> ListAttributesIter<'a>; } impl AttributesExt for [ast::Attribute] { fn lists<'a>(&'a self, name: Symbol) -> ListAttributesIter<'a> { ListAttributesIter { attrs: self.iter(), current_list: Vec::new().into_iter(), name, } } } pub trait NestedAttributesExt { /// Returns `true` if the attribute list contains a specific `Word` fn has_word(self, word: Symbol) -> bool; } impl<I: IntoIterator<Item=ast::NestedMetaItem>> NestedAttributesExt for I { fn has_word(self, word: Symbol) -> bool { self.into_iter().any(|attr| attr.is_word() && attr.check_name(word)) } } /// A portion of documentation, extracted from a `#[doc]` attribute. /// /// Each variant contains the line number within the complete doc-comment where the fragment /// starts, as well as the Span where the corresponding doc comment or attribute is located. /// /// Included files are kept separate from inline doc comments so that proper line-number /// information can be given when a doctest fails. Sugared doc comments and "raw" doc comments are /// kept separate because of issue #42760. #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum DocFragment { /// A doc fragment created from a `///` or `//!` doc comment. SugaredDoc(usize, syntax_pos::Span, String), /// A doc fragment created from a "raw" `#[doc=""]` attribute. RawDoc(usize, syntax_pos::Span, String), /// A doc fragment created from a `#[doc(include="filename")]` attribute. Contains both the /// given filename and the file contents. Include(usize, syntax_pos::Span, String, String), } impl DocFragment { pub fn as_str(&self) -> &str { match *self { DocFragment::SugaredDoc(_, _, ref s) => &s[..], DocFragment::RawDoc(_, _, ref s) => &s[..], DocFragment::Include(_, _, _, ref s) => &s[..], } } pub fn span(&self) -> syntax_pos::Span { match *self { DocFragment::SugaredDoc(_, span, _) | DocFragment::RawDoc(_, span, _) | DocFragment::Include(_, span, _, _) => span, } } } impl<'a> FromIterator<&'a DocFragment> for String { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = &'a DocFragment> { iter.into_iter().fold(String::new(), |mut acc, frag| { if !acc.is_empty() { acc.push('\n'); } match *frag { DocFragment::SugaredDoc(_, _, ref docs) | DocFragment::RawDoc(_, _, ref docs) | DocFragment::Include(_, _, _, ref docs) => acc.push_str(docs), } acc }) } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Default)] pub struct Attributes { pub doc_strings: Vec<DocFragment>, pub other_attrs: Vec<ast::Attribute>, pub cfg: Option<Arc<Cfg>>, pub span: Option<syntax_pos::Span>, /// map from Rust paths to resolved defs and potential URL fragments pub links: Vec<(String, Option<DefId>, Option<String>)>, pub inner_docs: bool, } impl Attributes { /// Extracts the content from an attribute `#[doc(cfg(content))]`. fn extract_cfg(mi: &ast::MetaItem) -> Option<&ast::MetaItem> { use syntax::ast::NestedMetaItem::MetaItem; if let ast::MetaItemKind::List(ref nmis) = mi.node { if nmis.len() == 1 { if let MetaItem(ref cfg_mi) = nmis[0] { if cfg_mi.check_name(sym::cfg) { if let ast::MetaItemKind::List(ref cfg_nmis) = cfg_mi.node { if cfg_nmis.len() == 1 { if let MetaItem(ref content_mi) = cfg_nmis[0] { return Some(content_mi); } } } } } } } None } /// Reads a `MetaItem` from within an attribute, looks for whether it is a /// `#[doc(include="file")]`, and returns the filename and contents of the file as loaded from /// its expansion. fn extract_include(mi: &ast::MetaItem) -> Option<(String, String)> { mi.meta_item_list().and_then(|list| { for meta in list { if meta.check_name(sym::include) { // the actual compiled `#[doc(include="filename")]` gets expanded to // `#[doc(include(file="filename", contents="file contents")]` so we need to // look for that instead return meta.meta_item_list().and_then(|list| { let mut filename: Option<String> = None; let mut contents: Option<String> = None; for it in list { if it.check_name(sym::file) { if let Some(name) = it.value_str() { filename = Some(name.to_string()); } } else if it.check_name(sym::contents) { if let Some(docs) = it.value_str() { contents = Some(docs.to_string()); } } } if let (Some(filename), Some(contents)) = (filename, contents) { Some((filename, contents)) } else { None } }); } } None }) } pub fn has_doc_flag(&self, flag: Symbol) -> bool { for attr in &self.other_attrs { if !attr.check_name(sym::doc) { continue; } if let Some(items) = attr.meta_item_list() { if items.iter().filter_map(|i| i.meta_item()).any(|it| it.check_name(flag)) { return true; } } } false } pub fn from_ast(diagnostic: &::errors::Handler, attrs: &[ast::Attribute]) -> Attributes { let mut doc_strings = vec![]; let mut sp = None; let mut cfg = Cfg::True; let mut doc_line = 0; let other_attrs = attrs.iter().filter_map(|attr| { attr.with_desugared_doc(|attr| { if attr.check_name(sym::doc) { if let Some(mi) = attr.meta() { if let Some(value) = mi.value_str() { // Extracted #[doc = "..."] let value = value.to_string(); let line = doc_line; doc_line += value.lines().count(); if attr.is_sugared_doc { doc_strings.push(DocFragment::SugaredDoc(line, attr.span, value)); } else { doc_strings.push(DocFragment::RawDoc(line, attr.span, value)); } if sp.is_none() { sp = Some(attr.span); } return None; } else if let Some(cfg_mi) = Attributes::extract_cfg(&mi) { // Extracted #[doc(cfg(...))] match Cfg::parse(cfg_mi) { Ok(new_cfg) => cfg &= new_cfg, Err(e) => diagnostic.span_err(e.span, e.msg), } return None; } else if let Some((filename, contents)) = Attributes::extract_include(&mi) { let line = doc_line; doc_line += contents.lines().count(); doc_strings.push(DocFragment::Include(line, attr.span, filename, contents)); } } } Some(attr.clone()) }) }).collect(); // treat #[target_feature(enable = "feat")] attributes as if they were // #[doc(cfg(target_feature = "feat"))] attributes as well for attr in attrs.lists(sym::target_feature) { if attr.check_name(sym::enable) { if let Some(feat) = attr.value_str() { let meta = attr::mk_name_value_item_str(Ident::from_str("target_feature"), dummy_spanned(feat)); if let Ok(feat_cfg) = Cfg::parse(&meta) { cfg &= feat_cfg; } } } } let inner_docs = attrs.iter() .filter(|a| a.check_name(sym::doc)) .next() .map_or(true, |a| a.style == AttrStyle::Inner); Attributes { doc_strings, other_attrs, cfg: if cfg == Cfg::True { None } else { Some(Arc::new(cfg)) }, span: sp, links: vec![], inner_docs, } } /// Finds the `doc` attribute as a NameValue and returns the corresponding /// value found. pub fn doc_value<'a>(&'a self) -> Option<&'a str> { self.doc_strings.first().map(|s| s.as_str()) } /// Finds all `doc` attributes as NameValues and returns their corresponding values, joined /// with newlines. pub fn collapsed_doc_value(&self) -> Option<String> { if !self.doc_strings.is_empty() { Some(self.doc_strings.iter().collect()) } else { None } } /// Gets links as a vector /// /// Cache must be populated before call pub fn links(&self, krate: &CrateNum) -> Vec<(String, String)> { use crate::html::format::href; self.links.iter().filter_map(|&(ref s, did, ref fragment)| { match did { Some(did) => { if let Some((mut href, ..)) = href(did) { if let Some(ref fragment) = *fragment { href.push_str("#"); href.push_str(fragment); } Some((s.clone(), href)) } else { None } } None => { if let Some(ref fragment) = *fragment { let cache = cache(); let url = match cache.extern_locations.get(krate) { Some(&(_, ref src, ExternalLocation::Local)) => src.to_str().expect("invalid file path"), Some(&(_, _, ExternalLocation::Remote(ref s))) => s, Some(&(_, _, ExternalLocation::Unknown)) | None => "https://doc.rust-lang.org/nightly", }; // This is a primitive so the url is done "by hand". let tail = fragment.find('#').unwrap_or_else(|| fragment.len()); Some((s.clone(), format!("{}{}std/primitive.{}.html{}", url, if !url.ends_with('/') { "/" } else { "" }, &fragment[..tail], &fragment[tail..]))) } else { panic!("This isn't a primitive?!"); } } } }).collect() } } impl PartialEq for Attributes { fn eq(&self, rhs: &Self) -> bool { self.doc_strings == rhs.doc_strings && self.cfg == rhs.cfg && self.span == rhs.span && self.links == rhs.links && self.other_attrs.iter().map(|attr| attr.id).eq(rhs.other_attrs.iter().map(|attr| attr.id)) } } impl Eq for Attributes {} impl Hash for Attributes { fn hash<H: Hasher>(&self, hasher: &mut H) { self.doc_strings.hash(hasher); self.cfg.hash(hasher); self.span.hash(hasher); self.links.hash(hasher); for attr in &self.other_attrs { attr.id.hash(hasher); } } } impl AttributesExt for Attributes { fn lists<'a>(&'a self, name: Symbol) -> ListAttributesIter<'a> { self.other_attrs.lists(name) } } impl Clean<Attributes> for [ast::Attribute] { fn clean(&self, cx: &DocContext<'_>) -> Attributes { Attributes::from_ast(cx.sess().diagnostic(), self) } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum GenericBound { TraitBound(PolyTrait, hir::TraitBoundModifier), Outlives(Lifetime), } impl GenericBound { fn maybe_sized(cx: &DocContext<'_>) -> GenericBound { let did = cx.tcx.require_lang_item(lang_items::SizedTraitLangItem); let empty = cx.tcx.intern_substs(&[]); let path = external_path(cx, &cx.tcx.item_name(did).as_str(), Some(did), false, vec![], empty); inline::record_extern_fqn(cx, did, TypeKind::Trait); GenericBound::TraitBound(PolyTrait { trait_: ResolvedPath { path, param_names: None, did, is_generic: false, }, generic_params: Vec::new(), }, hir::TraitBoundModifier::Maybe) } fn is_sized_bound(&self, cx: &DocContext<'_>) -> bool { use rustc::hir::TraitBoundModifier as TBM; if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self { if trait_.def_id() == cx.tcx.lang_items().sized_trait() { return true; } } false } fn get_poly_trait(&self) -> Option<PolyTrait> { if let GenericBound::TraitBound(ref p, _) = *self { return Some(p.clone()) } None } fn get_trait_type(&self) -> Option<Type> { if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self { Some(trait_.clone()) } else { None } } } impl Clean<GenericBound> for hir::GenericBound { fn clean(&self, cx: &DocContext<'_>) -> GenericBound { match *self { hir::GenericBound::Outlives(lt) => GenericBound::Outlives(lt.clean(cx)), hir::GenericBound::Trait(ref t, modifier) => { GenericBound::TraitBound(t.clean(cx), modifier) } } } } fn external_generic_args( cx: &DocContext<'_>, trait_did: Option<DefId>, has_self: bool, bindings: Vec<TypeBinding>, substs: SubstsRef<'_>, ) -> GenericArgs { let mut skip_self = has_self; let mut ty_sty = None; let args: Vec<_> = substs.iter().filter_map(|kind| match kind.unpack() { UnpackedKind::Lifetime(lt) => { lt.clean(cx).and_then(|lt| Some(GenericArg::Lifetime(lt))) } UnpackedKind::Type(_) if skip_self => { skip_self = false; None } UnpackedKind::Type(ty) => { ty_sty = Some(&ty.sty); Some(GenericArg::Type(ty.clean(cx))) } UnpackedKind::Const(ct) => Some(GenericArg::Const(ct.clean(cx))), }).collect(); match trait_did { // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C Some(did) if cx.tcx.lang_items().fn_trait_kind(did).is_some() => { assert!(ty_sty.is_some()); let inputs = match ty_sty { Some(ty::Tuple(ref tys)) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(), _ => return GenericArgs::AngleBracketed { args, bindings }, }; let output = None; // FIXME(#20299) return type comes from a projection now // match types[1].sty { // ty::Tuple(ref v) if v.is_empty() => None, // -> () // _ => Some(types[1].clean(cx)) // }; GenericArgs::Parenthesized { inputs, output } }, _ => { GenericArgs::AngleBracketed { args, bindings } } } } // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar // from Fn<(A, B,), C> to Fn(A, B) -> C fn external_path(cx: &DocContext<'_>, name: &str, trait_did: Option<DefId>, has_self: bool, bindings: Vec<TypeBinding>, substs: SubstsRef<'_>) -> Path { Path { global: false, res: Res::Err, segments: vec![PathSegment { name: name.to_string(), args: external_generic_args(cx, trait_did, has_self, bindings, substs) }], } } impl<'a, 'tcx> Clean<GenericBound> for (&'a ty::TraitRef<'tcx>, Vec<TypeBinding>) { fn clean(&self, cx: &DocContext<'_>) -> GenericBound { let (trait_ref, ref bounds) = *self; inline::record_extern_fqn(cx, trait_ref.def_id, TypeKind::Trait); let path = external_path(cx, &cx.tcx.item_name(trait_ref.def_id).as_str(), Some(trait_ref.def_id), true, bounds.clone(), trait_ref.substs); debug!("ty::TraitRef\n subst: {:?}\n", trait_ref.substs); // collect any late bound regions let mut late_bounds = vec![]; for ty_s in trait_ref.input_types().skip(1) { if let ty::Tuple(ts) = ty_s.sty { for &ty_s in ts { if let ty::Ref(ref reg, _, _) = ty_s.expect_ty().sty { if let &ty::RegionKind::ReLateBound(..) = *reg { debug!(" hit an ReLateBound {:?}", reg); if let Some(Lifetime(name)) = reg.clean(cx) { late_bounds.push(GenericParamDef { name, kind: GenericParamDefKind::Lifetime, }); } } } } } } GenericBound::TraitBound( PolyTrait { trait_: ResolvedPath { path, param_names: None, did: trait_ref.def_id, is_generic: false, }, generic_params: late_bounds, }, hir::TraitBoundModifier::None ) } } impl<'tcx> Clean<GenericBound> for ty::TraitRef<'tcx> { fn clean(&self, cx: &DocContext<'_>) -> GenericBound { (self, vec![]).clean(cx) } } impl<'tcx> Clean<Option<Vec<GenericBound>>> for InternalSubsts<'tcx> { fn clean(&self, cx: &DocContext<'_>) -> Option<Vec<GenericBound>> { let mut v = Vec::new(); v.extend(self.regions().filter_map(|r| r.clean(cx)).map(GenericBound::Outlives)); v.extend(self.types().map(|t| GenericBound::TraitBound(PolyTrait { trait_: t.clean(cx), generic_params: Vec::new(), }, hir::TraitBoundModifier::None))); if !v.is_empty() {Some(v)} else {None} } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct Lifetime(String); impl Lifetime { pub fn get_ref<'a>(&'a self) -> &'a str { let Lifetime(ref s) = *self; let s: &'a str = s; s } pub fn statik() -> Lifetime { Lifetime("'static".to_string()) } } impl Clean<Lifetime> for hir::Lifetime { fn clean(&self, cx: &DocContext<'_>) -> Lifetime { if self.hir_id != hir::DUMMY_HIR_ID { let def = cx.tcx.named_region(self.hir_id); match def { Some(rl::Region::EarlyBound(_, node_id, _)) | Some(rl::Region::LateBound(_, node_id, _)) | Some(rl::Region::Free(_, node_id)) => { if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() { return lt; } } _ => {} } } Lifetime(self.name.ident().to_string()) } } impl Clean<Lifetime> for hir::GenericParam { fn clean(&self, _: &DocContext<'_>) -> Lifetime { match self.kind { hir::GenericParamKind::Lifetime { .. } => { if self.bounds.len() > 0 { let mut bounds = self.bounds.iter().map(|bound| match bound { hir::GenericBound::Outlives(lt) => lt, _ => panic!(), }); let name = bounds.next().expect("no more bounds").name.ident(); let mut s = format!("{}: {}", self.name.ident(), name); for bound in bounds { s.push_str(&format!(" + {}", bound.name.ident())); } Lifetime(s) } else { Lifetime(self.name.ident().to_string()) } } _ => panic!(), } } } impl Clean<Constant> for hir::ConstArg { fn clean(&self, cx: &DocContext<'_>) -> Constant { Constant { type_: cx.tcx.type_of(cx.tcx.hir().body_owner_def_id(self.value.body)).clean(cx), expr: print_const_expr(cx, self.value.body), } } } impl<'tcx> Clean<Lifetime> for ty::GenericParamDef { fn clean(&self, _cx: &DocContext<'_>) -> Lifetime { Lifetime(self.name.to_string()) } } impl Clean<Option<Lifetime>> for ty::RegionKind { fn clean(&self, cx: &DocContext<'_>) -> Option<Lifetime> { match *self { ty::ReStatic => Some(Lifetime::statik()), ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())), ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))), ty::ReLateBound(..) | ty::ReFree(..) | ty::ReScope(..) | ty::ReVar(..) | ty::RePlaceholder(..) | ty::ReEmpty | ty::ReClosureBound(_) | ty::ReErased => { debug!("Cannot clean region {:?}", self); None } } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum WherePredicate { BoundPredicate { ty: Type, bounds: Vec<GenericBound> }, RegionPredicate { lifetime: Lifetime, bounds: Vec<GenericBound> }, EqPredicate { lhs: Type, rhs: Type }, } impl WherePredicate { pub fn get_bounds(&self) -> Option<&[GenericBound]> { match *self { WherePredicate::BoundPredicate { ref bounds, .. } => Some(bounds), WherePredicate::RegionPredicate { ref bounds, .. } => Some(bounds), _ => None, } } } impl Clean<WherePredicate> for hir::WherePredicate { fn clean(&self, cx: &DocContext<'_>) -> WherePredicate { match *self { hir::WherePredicate::BoundPredicate(ref wbp) => { WherePredicate::BoundPredicate { ty: wbp.bounded_ty.clean(cx), bounds: wbp.bounds.clean(cx) } } hir::WherePredicate::RegionPredicate(ref wrp) => { WherePredicate::RegionPredicate { lifetime: wrp.lifetime.clean(cx), bounds: wrp.bounds.clean(cx) } } hir::WherePredicate::EqPredicate(ref wrp) => { WherePredicate::EqPredicate { lhs: wrp.lhs_ty.clean(cx), rhs: wrp.rhs_ty.clean(cx) } } } } } impl<'a> Clean<Option<WherePredicate>> for ty::Predicate<'a> { fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> { use rustc::ty::Predicate; match *self { Predicate::Trait(ref pred) => Some(pred.clean(cx)), Predicate::Subtype(ref pred) => Some(pred.clean(cx)), Predicate::RegionOutlives(ref pred) => pred.clean(cx), Predicate::TypeOutlives(ref pred) => pred.clean(cx), Predicate::Projection(ref pred) => Some(pred.clean(cx)), Predicate::WellFormed(..) | Predicate::ObjectSafe(..) | Predicate::ClosureKind(..) | Predicate::ConstEvaluatable(..) => panic!("not user writable"), } } } impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> { fn clean(&self, cx: &DocContext<'_>) -> WherePredicate { WherePredicate::BoundPredicate { ty: self.trait_ref.self_ty().clean(cx), bounds: vec![self.trait_ref.clean(cx)] } } } impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> { fn clean(&self, _cx: &DocContext<'_>) -> WherePredicate { panic!("subtype predicates are an internal rustc artifact \ and should not be seen by rustdoc") } } impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<ty::Region<'tcx>,ty::Region<'tcx>> { fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> { let ty::OutlivesPredicate(ref a, ref b) = *self; match (a, b) { (ty::ReEmpty, ty::ReEmpty) => { return None; }, _ => {} } Some(WherePredicate::RegionPredicate { lifetime: a.clean(cx).expect("failed to clean lifetime"), bounds: vec![GenericBound::Outlives(b.clean(cx).expect("failed to clean bounds"))] }) } } impl<'tcx> Clean<Option<WherePredicate>> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> { fn clean(&self, cx: &DocContext<'_>) -> Option<WherePredicate> { let ty::OutlivesPredicate(ref ty, ref lt) = *self; match lt { ty::ReEmpty => return None, _ => {} } Some(WherePredicate::BoundPredicate { ty: ty.clean(cx), bounds: vec![GenericBound::Outlives(lt.clean(cx).expect("failed to clean lifetimes"))] }) } } impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> { fn clean(&self, cx: &DocContext<'_>) -> WherePredicate { WherePredicate::EqPredicate { lhs: self.projection_ty.clean(cx), rhs: self.ty.clean(cx) } } } impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> { fn clean(&self, cx: &DocContext<'_>) -> Type { let trait_ = match self.trait_ref(cx.tcx).clean(cx) { GenericBound::TraitBound(t, _) => t.trait_, GenericBound::Outlives(_) => panic!("cleaning a trait got a lifetime"), }; Type::QPath { name: cx.tcx.associated_item(self.item_def_id).ident.name.clean(cx), self_type: box self.self_ty().clean(cx), trait_: box trait_ } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum GenericParamDefKind { Lifetime, Type { did: DefId, bounds: Vec<GenericBound>, default: Option<Type>, synthetic: Option<hir::SyntheticTyParamKind>, }, Const { did: DefId, ty: Type, }, } impl GenericParamDefKind { pub fn is_type(&self) -> bool { match *self { GenericParamDefKind::Type { .. } => true, _ => false, } } pub fn get_type(&self, cx: &DocContext<'_>) -> Option<Type> { match *self { GenericParamDefKind::Type { did, .. } => { rustc_typeck::checked_type_of(cx.tcx, did, false).map(|t| t.clean(cx)) } GenericParamDefKind::Const { ref ty, .. } => Some(ty.clone()), GenericParamDefKind::Lifetime => None, } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct GenericParamDef { pub name: String, pub kind: GenericParamDefKind, } impl GenericParamDef { pub fn is_synthetic_type_param(&self) -> bool { match self.kind { GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => false, GenericParamDefKind::Type { ref synthetic, .. } => synthetic.is_some(), } } pub fn is_type(&self) -> bool { self.kind.is_type() } pub fn get_type(&self, cx: &DocContext<'_>) -> Option<Type> { self.kind.get_type(cx) } pub fn get_bounds(&self) -> Option<&[GenericBound]> { match self.kind { GenericParamDefKind::Type { ref bounds, .. } => Some(bounds), _ => None, } } } impl Clean<GenericParamDef> for ty::GenericParamDef { fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef { let (name, kind) = match self.kind { ty::GenericParamDefKind::Lifetime => { (self.name.to_string(), GenericParamDefKind::Lifetime) } ty::GenericParamDefKind::Type { has_default, .. } => { cx.renderinfo.borrow_mut().external_param_names .insert(self.def_id, self.name.clean(cx)); let default = if has_default { Some(cx.tcx.type_of(self.def_id).clean(cx)) } else { None }; (self.name.clean(cx), GenericParamDefKind::Type { did: self.def_id, bounds: vec![], // These are filled in from the where-clauses. default, synthetic: None, }) } ty::GenericParamDefKind::Const { .. } => { (self.name.clean(cx), GenericParamDefKind::Const { did: self.def_id, ty: cx.tcx.type_of(self.def_id).clean(cx), }) } }; GenericParamDef { name, kind, } } } impl Clean<GenericParamDef> for hir::GenericParam { fn clean(&self, cx: &DocContext<'_>) -> GenericParamDef { let (name, kind) = match self.kind { hir::GenericParamKind::Lifetime { .. } => { let name = if self.bounds.len() > 0 { let mut bounds = self.bounds.iter().map(|bound| match bound { hir::GenericBound::Outlives(lt) => lt, _ => panic!(), }); let name = bounds.next().expect("no more bounds").name.ident(); let mut s = format!("{}: {}", self.name.ident(), name); for bound in bounds { s.push_str(&format!(" + {}", bound.name.ident())); } s } else { self.name.ident().to_string() }; (name, GenericParamDefKind::Lifetime) } hir::GenericParamKind::Type { ref default, synthetic } => { (self.name.ident().name.clean(cx), GenericParamDefKind::Type { did: cx.tcx.hir().local_def_id_from_hir_id(self.hir_id), bounds: self.bounds.clean(cx), default: default.clean(cx), synthetic: synthetic, }) } hir::GenericParamKind::Const { ref ty } => { (self.name.ident().name.clean(cx), GenericParamDefKind::Const { did: cx.tcx.hir().local_def_id_from_hir_id(self.hir_id), ty: ty.clean(cx), }) } }; GenericParamDef { name, kind, } } } // maybe use a Generic enum and use Vec<Generic>? #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Default, Hash)] pub struct Generics { pub params: Vec<GenericParamDef>, pub where_predicates: Vec<WherePredicate>, } impl Clean<Generics> for hir::Generics { fn clean(&self, cx: &DocContext<'_>) -> Generics { // Synthetic type-parameters are inserted after normal ones. // In order for normal parameters to be able to refer to synthetic ones, // scans them first. fn is_impl_trait(param: &hir::GenericParam) -> bool { match param.kind { hir::GenericParamKind::Type { synthetic, .. } => { synthetic == Some(hir::SyntheticTyParamKind::ImplTrait) } _ => false, } } let impl_trait_params = self.params .iter() .filter(|param| is_impl_trait(param)) .map(|param| { let param: GenericParamDef = param.clean(cx); match param.kind { GenericParamDefKind::Lifetime => unreachable!(), GenericParamDefKind::Type { did, ref bounds, .. } => { cx.impl_trait_bounds.borrow_mut().insert(did, bounds.clone()); } GenericParamDefKind::Const { .. } => unreachable!(), } param }) .collect::<Vec<_>>(); let mut params = Vec::with_capacity(self.params.len()); for p in self.params.iter().filter(|p| !is_impl_trait(p)) { let p = p.clean(cx); params.push(p); } params.extend(impl_trait_params); let mut generics = Generics { params, where_predicates: self.where_clause.predicates.clean(cx), }; // Some duplicates are generated for ?Sized bounds between type params and where // predicates. The point in here is to move the bounds definitions from type params // to where predicates when such cases occur. for where_pred in &mut generics.where_predicates { match *where_pred { WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => { if bounds.is_empty() { for param in &mut generics.params { match param.kind { GenericParamDefKind::Lifetime => {} GenericParamDefKind::Type { bounds: ref mut ty_bounds, .. } => { if &param.name == name { mem::swap(bounds, ty_bounds); break } } GenericParamDefKind::Const { .. } => {} } } } } _ => continue, } } generics } } impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, &'a Lrc<ty::GenericPredicates<'tcx>>) { fn clean(&self, cx: &DocContext<'_>) -> Generics { use self::WherePredicate as WP; let (gens, preds) = *self; // Bounds in the type_params and lifetimes fields are repeated in the // predicates field (see rustc_typeck::collect::ty_generics), so remove // them. let stripped_typarams = gens.params.iter().filter_map(|param| match param.kind { ty::GenericParamDefKind::Lifetime => None, ty::GenericParamDefKind::Type { .. } => { if param.name == keywords::SelfUpper.name().as_str() { assert_eq!(param.index, 0); return None; } Some(param.clean(cx)) } ty::GenericParamDefKind::Const { .. } => None, }).collect::<Vec<GenericParamDef>>(); let mut where_predicates = preds.predicates.iter() .flat_map(|(p, _)| p.clean(cx)) .collect::<Vec<_>>(); // Type parameters and have a Sized bound by default unless removed with // ?Sized. Scan through the predicates and mark any type parameter with // a Sized bound, removing the bounds as we find them. // // Note that associated types also have a sized bound by default, but we // don't actually know the set of associated types right here so that's // handled in cleaning associated types let mut sized_params = FxHashSet::default(); where_predicates.retain(|pred| { match *pred { WP::BoundPredicate { ty: Generic(ref g), ref bounds } => { if bounds.iter().any(|b| b.is_sized_bound(cx)) { sized_params.insert(g.clone()); false } else { true } } _ => true, } }); // Run through the type parameters again and insert a ?Sized // unbound for any we didn't find to be Sized. for tp in &stripped_typarams { if !sized_params.contains(&tp.name) { where_predicates.push(WP::BoundPredicate { ty: Type::Generic(tp.name.clone()), bounds: vec![GenericBound::maybe_sized(cx)], }) } } // It would be nice to collect all of the bounds on a type and recombine // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a` // and instead see `where T: Foo + Bar + Sized + 'a` Generics { params: gens.params .iter() .flat_map(|param| match param.kind { ty::GenericParamDefKind::Lifetime => Some(param.clean(cx)), ty::GenericParamDefKind::Type { .. } => None, ty::GenericParamDefKind::Const { .. } => Some(param.clean(cx)), }).chain(simplify::ty_params(stripped_typarams).into_iter()) .collect(), where_predicates: simplify::where_clauses(cx, where_predicates), } } } /// The point of this function is to replace bounds with types. /// /// i.e. `[T, U]` when you have the following bounds: `T: Display, U: Option<T>` will return /// `[Display, Option]` (we just returns the list of the types, we don't care about the /// wrapped types in here). fn get_real_types( generics: &Generics, arg: &Type, cx: &DocContext<'_>, recurse: i32, ) -> FxHashSet<Type> { let arg_s = arg.to_string(); let mut res = FxHashSet::default(); if recurse >= 10 { // FIXME: remove this whole recurse thing when the recursion bug is fixed return res; } if arg.is_full_generic() { if let Some(where_pred) = generics.where_predicates.iter().find(|g| { match g { &WherePredicate::BoundPredicate { ref ty, .. } => ty.def_id() == arg.def_id(), _ => false, } }) { let bounds = where_pred.get_bounds().unwrap_or_else(|| &[]); for bound in bounds.iter() { match *bound { GenericBound::TraitBound(ref poly_trait, _) => { for x in poly_trait.generic_params.iter() { if !x.is_type() { continue } if let Some(ty) = x.get_type(cx) { let adds = get_real_types(generics, &ty, cx, recurse + 1); if !adds.is_empty() { res.extend(adds); } else if !ty.is_full_generic() { res.insert(ty); } } } } _ => {} } } } if let Some(bound) = generics.params.iter().find(|g| { g.is_type() && g.name == arg_s }) { for bound in bound.get_bounds().unwrap_or_else(|| &[]) { if let Some(ty) = bound.get_trait_type() { let adds = get_real_types(generics, &ty, cx, recurse + 1); if !adds.is_empty() { res.extend(adds); } else if !ty.is_full_generic() { res.insert(ty.clone()); } } } } } else { res.insert(arg.clone()); if let Some(gens) = arg.generics() { for gen in gens.iter() { if gen.is_full_generic() { let adds = get_real_types(generics, gen, cx, recurse + 1); if !adds.is_empty() { res.extend(adds); } } else { res.insert(gen.clone()); } } } } res } /// Return the full list of types when bounds have been resolved. /// /// i.e. `fn foo<A: Display, B: Option<A>>(x: u32, y: B)` will return /// `[u32, Display, Option]`. pub fn get_all_types( generics: &Generics, decl: &FnDecl, cx: &DocContext<'_>, ) -> (Vec<Type>, Vec<Type>) { let mut all_types = FxHashSet::default(); for arg in decl.inputs.values.iter() { if arg.type_.is_self_type() { continue; } let args = get_real_types(generics, &arg.type_, cx, 0); if !args.is_empty() { all_types.extend(args); } else { all_types.insert(arg.type_.clone()); } } let ret_types = match decl.output { FunctionRetTy::Return(ref return_type) => { let mut ret = get_real_types(generics, &return_type, cx, 0); if ret.is_empty() { ret.insert(return_type.clone()); } ret.into_iter().collect() } _ => Vec::new(), }; (all_types.into_iter().collect(), ret_types) } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Method { pub generics: Generics, pub decl: FnDecl, pub header: hir::FnHeader, pub defaultness: Option<hir::Defaultness>, pub all_types: Vec<Type>, pub ret_types: Vec<Type>, } impl<'a> Clean<Method> for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId, Option<hir::Defaultness>) { fn clean(&self, cx: &DocContext<'_>) -> Method { let (generics, decl) = enter_impl_trait(cx, || { (self.1.clean(cx), (&*self.0.decl, self.2).clean(cx)) }); let (all_types, ret_types) = get_all_types(&generics, &decl, cx); Method { decl, generics, header: self.0.header, defaultness: self.3, all_types, ret_types, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct TyMethod { pub header: hir::FnHeader, pub decl: FnDecl, pub generics: Generics, pub all_types: Vec<Type>, pub ret_types: Vec<Type>, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Function { pub decl: FnDecl, pub generics: Generics, pub header: hir::FnHeader, pub all_types: Vec<Type>, pub ret_types: Vec<Type>, } impl Clean<Item> for doctree::Function { fn clean(&self, cx: &DocContext<'_>) -> Item { let (generics, decl) = enter_impl_trait(cx, || { (self.generics.clean(cx), (&self.decl, self.body).clean(cx)) }); let did = cx.tcx.hir().local_def_id_from_hir_id(self.id); let constness = if cx.tcx.is_min_const_fn(did) { hir::Constness::Const } else { hir::Constness::NotConst }; let (all_types, ret_types) = get_all_types(&generics, &decl, cx); Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), source: self.whence.clean(cx), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), def_id: did, inner: FunctionItem(Function { decl, generics, header: hir::FnHeader { constness, ..self.header }, all_types, ret_types, }), } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct FnDecl { pub inputs: Arguments, pub output: FunctionRetTy, pub attrs: Attributes, } impl FnDecl { pub fn self_type(&self) -> Option<SelfTy> { self.inputs.values.get(0).and_then(|v| v.to_self()) } /// Returns the sugared return type for an async function. /// /// For example, if the return type is `impl std::future::Future<Output = i32>`, this function /// will return `i32`. /// /// # Panics /// /// This function will panic if the return type does not match the expected sugaring for async /// functions. pub fn sugared_async_return_type(&self) -> FunctionRetTy { match &self.output { FunctionRetTy::Return(Type::ImplTrait(bounds)) => { match &bounds[0] { GenericBound::TraitBound(PolyTrait { trait_, .. }, ..) => { let bindings = trait_.bindings().unwrap(); FunctionRetTy::Return(bindings[0].ty.clone()) } _ => panic!("unexpected desugaring of async function"), } } _ => panic!("unexpected desugaring of async function"), } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct Arguments { pub values: Vec<Argument>, } impl<'a> Clean<Arguments> for (&'a [hir::Ty], &'a [ast::Ident]) { fn clean(&self, cx: &DocContext<'_>) -> Arguments { Arguments { values: self.0.iter().enumerate().map(|(i, ty)| { let mut name = self.1.get(i).map(|ident| ident.to_string()) .unwrap_or(String::new()); if name.is_empty() { name = "_".to_string(); } Argument { name, type_: ty.clean(cx), } }).collect() } } } impl<'a> Clean<Arguments> for (&'a [hir::Ty], hir::BodyId) { fn clean(&self, cx: &DocContext<'_>) -> Arguments { let body = cx.tcx.hir().body(self.1); Arguments { values: self.0.iter().enumerate().map(|(i, ty)| { Argument { name: name_from_pat(&body.arguments[i].original_pat()), type_: ty.clean(cx), } }).collect() } } } impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A) where (&'a [hir::Ty], A): Clean<Arguments> { fn clean(&self, cx: &DocContext<'_>) -> FnDecl { FnDecl { inputs: (&self.0.inputs[..], self.1).clean(cx), output: self.0.output.clean(cx), attrs: Attributes::default(), } } } impl<'a, 'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) { fn clean(&self, cx: &DocContext<'_>) -> FnDecl { let (did, sig) = *self; let mut names = if cx.tcx.hir().as_local_hir_id(did).is_some() { vec![].into_iter() } else { cx.tcx.fn_arg_names(did).into_iter() }; FnDecl { output: Return(sig.skip_binder().output().clean(cx)), attrs: Attributes::default(), inputs: Arguments { values: sig.skip_binder().inputs().iter().map(|t| { Argument { type_: t.clean(cx), name: names.next().map_or(String::new(), |name| name.to_string()), } }).collect(), }, } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct Argument { pub type_: Type, pub name: String, } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)] pub enum SelfTy { SelfValue, SelfBorrowed(Option<Lifetime>, Mutability), SelfExplicit(Type), } impl Argument { pub fn to_self(&self) -> Option<SelfTy> { if self.name != "self" { return None; } if self.type_.is_self_type() { return Some(SelfValue); } match self.type_ { BorrowedRef{ref lifetime, mutability, ref type_} if type_.is_self_type() => { Some(SelfBorrowed(lifetime.clone(), mutability)) } _ => Some(SelfExplicit(self.type_.clone())) } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum FunctionRetTy { Return(Type), DefaultReturn, } impl Clean<FunctionRetTy> for hir::FunctionRetTy { fn clean(&self, cx: &DocContext<'_>) -> FunctionRetTy { match *self { hir::Return(ref typ) => Return(typ.clean(cx)), hir::DefaultReturn(..) => DefaultReturn, } } } impl GetDefId for FunctionRetTy { fn def_id(&self) -> Option<DefId> { match *self { Return(ref ty) => ty.def_id(), DefaultReturn => None, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Trait { pub auto: bool, pub unsafety: hir::Unsafety, pub items: Vec<Item>, pub generics: Generics, pub bounds: Vec<GenericBound>, pub is_spotlight: bool, pub is_auto: bool, } impl Clean<Item> for doctree::Trait { fn clean(&self, cx: &DocContext<'_>) -> Item { let attrs = self.attrs.clean(cx); let is_spotlight = attrs.has_doc_flag(sym::spotlight); Item { name: Some(self.name.clean(cx)), attrs: attrs, source: self.whence.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), inner: TraitItem(Trait { auto: self.is_auto.clean(cx), unsafety: self.unsafety, items: self.items.clean(cx), generics: self.generics.clean(cx), bounds: self.bounds.clean(cx), is_spotlight, is_auto: self.is_auto.clean(cx), }), } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct TraitAlias { pub generics: Generics, pub bounds: Vec<GenericBound>, } impl Clean<Item> for doctree::TraitAlias { fn clean(&self, cx: &DocContext<'_>) -> Item { let attrs = self.attrs.clean(cx); Item { name: Some(self.name.clean(cx)), attrs, source: self.whence.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), inner: TraitAliasItem(TraitAlias { generics: self.generics.clean(cx), bounds: self.bounds.clean(cx), }), } } } impl Clean<bool> for hir::IsAuto { fn clean(&self, _: &DocContext<'_>) -> bool { match *self { hir::IsAuto::Yes => true, hir::IsAuto::No => false, } } } impl Clean<Type> for hir::TraitRef { fn clean(&self, cx: &DocContext<'_>) -> Type { resolve_type(cx, self.path.clean(cx), self.hir_ref_id) } } impl Clean<PolyTrait> for hir::PolyTraitRef { fn clean(&self, cx: &DocContext<'_>) -> PolyTrait { PolyTrait { trait_: self.trait_ref.clean(cx), generic_params: self.bound_generic_params.clean(cx) } } } impl Clean<Item> for hir::TraitItem { fn clean(&self, cx: &DocContext<'_>) -> Item { let inner = match self.node { hir::TraitItemKind::Const(ref ty, default) => { AssociatedConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e))) } hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => { MethodItem((sig, &self.generics, body, None).clean(cx)) } hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => { let (generics, decl) = enter_impl_trait(cx, || { (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx)) }); let (all_types, ret_types) = get_all_types(&generics, &decl, cx); TyMethodItem(TyMethod { header: sig.header, decl, generics, all_types, ret_types, }) } hir::TraitItemKind::Type(ref bounds, ref default) => { AssociatedTypeItem(bounds.clean(cx), default.clean(cx)) } }; let local_did = cx.tcx.hir().local_def_id_from_hir_id(self.hir_id); Item { name: Some(self.ident.name.clean(cx)), attrs: self.attrs.clean(cx), source: self.span.clean(cx), def_id: local_did, visibility: None, stability: get_stability(cx, local_did), deprecation: get_deprecation(cx, local_did), inner, } } } impl Clean<Item> for hir::ImplItem { fn clean(&self, cx: &DocContext<'_>) -> Item { let inner = match self.node { hir::ImplItemKind::Const(ref ty, expr) => { AssociatedConstItem(ty.clean(cx), Some(print_const_expr(cx, expr))) } hir::ImplItemKind::Method(ref sig, body) => { MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx)) } hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef { type_: ty.clean(cx), generics: Generics::default(), }, true), hir::ImplItemKind::Existential(ref bounds) => ExistentialItem(Existential { bounds: bounds.clean(cx), generics: Generics::default(), }, true), }; let local_did = cx.tcx.hir().local_def_id_from_hir_id(self.hir_id); Item { name: Some(self.ident.name.clean(cx)), source: self.span.clean(cx), attrs: self.attrs.clean(cx), def_id: local_did, visibility: self.vis.clean(cx), stability: get_stability(cx, local_did), deprecation: get_deprecation(cx, local_did), inner, } } } impl<'tcx> Clean<Item> for ty::AssociatedItem { fn clean(&self, cx: &DocContext<'_>) -> Item { let inner = match self.kind { ty::AssociatedKind::Const => { let ty = cx.tcx.type_of(self.def_id); let default = if self.defaultness.has_value() { Some(inline::print_inlined_const(cx, self.def_id)) } else { None }; AssociatedConstItem(ty.clean(cx), default) } ty::AssociatedKind::Method => { let generics = (cx.tcx.generics_of(self.def_id), &cx.tcx.explicit_predicates_of(self.def_id)).clean(cx); let sig = cx.tcx.fn_sig(self.def_id); let mut decl = (self.def_id, sig).clean(cx); if self.method_has_self_argument { let self_ty = match self.container { ty::ImplContainer(def_id) => { cx.tcx.type_of(def_id) } ty::TraitContainer(_) => cx.tcx.mk_self_type() }; let self_arg_ty = *sig.input(0).skip_binder(); if self_arg_ty == self_ty { decl.inputs.values[0].type_ = Generic(String::from("Self")); } else if let ty::Ref(_, ty, _) = self_arg_ty.sty { if ty == self_ty { match decl.inputs.values[0].type_ { BorrowedRef{ref mut type_, ..} => { **type_ = Generic(String::from("Self")) } _ => unreachable!(), } } } } let provided = match self.container { ty::ImplContainer(_) => true, ty::TraitContainer(_) => self.defaultness.has_value() }; let (all_types, ret_types) = get_all_types(&generics, &decl, cx); if provided { let constness = if cx.tcx.is_min_const_fn(self.def_id) { hir::Constness::Const } else { hir::Constness::NotConst }; let defaultness = match self.container { ty::ImplContainer(_) => Some(self.defaultness), ty::TraitContainer(_) => None, }; MethodItem(Method { generics, decl, header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness: hir::IsAsync::NotAsync, }, defaultness, all_types, ret_types, }) } else { TyMethodItem(TyMethod { generics, decl, header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness: hir::Constness::NotConst, asyncness: hir::IsAsync::NotAsync, }, all_types, ret_types, }) } } ty::AssociatedKind::Type => { let my_name = self.ident.name.clean(cx); if let ty::TraitContainer(did) = self.container { // When loading a cross-crate associated type, the bounds for this type // are actually located on the trait/impl itself, so we need to load // all of the generics from there and then look for bounds that are // applied to this associated type in question. let predicates = cx.tcx.explicit_predicates_of(did); let generics = (cx.tcx.generics_of(did), &predicates).clean(cx); let mut bounds = generics.where_predicates.iter().filter_map(|pred| { let (name, self_type, trait_, bounds) = match *pred { WherePredicate::BoundPredicate { ty: QPath { ref name, ref self_type, ref trait_ }, ref bounds } => (name, self_type, trait_, bounds), _ => return None, }; if *name != my_name { return None } match **trait_ { ResolvedPath { did, .. } if did == self.container.id() => {} _ => return None, } match **self_type { Generic(ref s) if *s == "Self" => {} _ => return None, } Some(bounds) }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>(); // Our Sized/?Sized bound didn't get handled when creating the generics // because we didn't actually get our whole set of bounds until just now // (some of them may have come from the trait). If we do have a sized // bound, we remove it, and if we don't then we add the `?Sized` bound // at the end. match bounds.iter().position(|b| b.is_sized_bound(cx)) { Some(i) => { bounds.remove(i); } None => bounds.push(GenericBound::maybe_sized(cx)), } let ty = if self.defaultness.has_value() { Some(cx.tcx.type_of(self.def_id)) } else { None }; AssociatedTypeItem(bounds, ty.clean(cx)) } else { TypedefItem(Typedef { type_: cx.tcx.type_of(self.def_id).clean(cx), generics: Generics { params: Vec::new(), where_predicates: Vec::new(), }, }, true) } } ty::AssociatedKind::Existential => unimplemented!(), }; let visibility = match self.container { ty::ImplContainer(_) => self.vis.clean(cx), ty::TraitContainer(_) => None, }; Item { name: Some(self.ident.name.clean(cx)), visibility, stability: get_stability(cx, self.def_id), deprecation: get_deprecation(cx, self.def_id), def_id: self.def_id, attrs: inline::load_attrs(cx, self.def_id), source: cx.tcx.def_span(self.def_id).clean(cx), inner, } } } /// A trait reference, which may have higher ranked lifetimes. #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct PolyTrait { pub trait_: Type, pub generic_params: Vec<GenericParamDef>, } /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original /// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly /// it does not preserve mutability or boxes. #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum Type { /// Structs/enums/traits (most that'd be an `hir::TyKind::Path`). ResolvedPath { path: Path, param_names: Option<Vec<GenericBound>>, did: DefId, /// `true` if is a `T::Name` path for associated types. is_generic: bool, }, /// For parameterized types, so the consumer of the JSON don't go /// looking for types which don't exist anywhere. Generic(String), /// Primitives are the fixed-size numeric types (plus int/usize/float), char, /// arrays, slices, and tuples. Primitive(PrimitiveType), /// extern "ABI" fn BareFunction(Box<BareFunctionDecl>), Tuple(Vec<Type>), Slice(Box<Type>), Array(Box<Type>, String), Never, CVarArgs, Unique(Box<Type>), RawPointer(Mutability, Box<Type>), BorrowedRef { lifetime: Option<Lifetime>, mutability: Mutability, type_: Box<Type>, }, // <Type as Trait>::Name QPath { name: String, self_type: Box<Type>, trait_: Box<Type> }, // _ Infer, // impl TraitA+TraitB ImplTrait(Vec<GenericBound>), } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)] pub enum PrimitiveType { Isize, I8, I16, I32, I64, I128, Usize, U8, U16, U32, U64, U128, F32, F64, Char, Bool, Str, Slice, Array, Tuple, Unit, RawPointer, Reference, Fn, Never, CVarArgs, } #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)] pub enum TypeKind { Enum, Function, Module, Const, Static, Struct, Union, Trait, Variant, Typedef, Foreign, Macro, Attr, Derive, TraitAlias, } pub trait GetDefId { fn def_id(&self) -> Option<DefId>; } impl<T: GetDefId> GetDefId for Option<T> { fn def_id(&self) -> Option<DefId> { self.as_ref().and_then(|d| d.def_id()) } } impl Type { pub fn primitive_type(&self) -> Option<PrimitiveType> { match *self { Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p), Slice(..) | BorrowedRef { type_: box Slice(..), .. } => Some(PrimitiveType::Slice), Array(..) | BorrowedRef { type_: box Array(..), .. } => Some(PrimitiveType::Array), Tuple(ref tys) => if tys.is_empty() { Some(PrimitiveType::Unit) } else { Some(PrimitiveType::Tuple) }, RawPointer(..) => Some(PrimitiveType::RawPointer), BorrowedRef { type_: box Generic(..), .. } => Some(PrimitiveType::Reference), BareFunction(..) => Some(PrimitiveType::Fn), Never => Some(PrimitiveType::Never), _ => None, } } pub fn is_generic(&self) -> bool { match *self { ResolvedPath { is_generic, .. } => is_generic, _ => false, } } pub fn is_self_type(&self) -> bool { match *self { Generic(ref name) => name == "Self", _ => false } } pub fn generics(&self) -> Option<Vec<Type>> { match *self { ResolvedPath { ref path, .. } => { path.segments.last().and_then(|seg| { if let GenericArgs::AngleBracketed { ref args, .. } = seg.args { Some(args.iter().filter_map(|arg| match arg { GenericArg::Type(ty) => Some(ty.clone()), _ => None, }).collect()) } else { None } }) } _ => None, } } pub fn bindings(&self) -> Option<&[TypeBinding]> { match *self { ResolvedPath { ref path, .. } => { path.segments.last().and_then(|seg| { if let GenericArgs::AngleBracketed { ref bindings, .. } = seg.args { Some(&**bindings) } else { None } }) } _ => None } } pub fn is_full_generic(&self) -> bool { match *self { Type::Generic(_) => true, _ => false, } } } impl GetDefId for Type { fn def_id(&self) -> Option<DefId> { match *self { ResolvedPath { did, .. } => Some(did), Primitive(p) => crate::html::render::cache().primitive_locations.get(&p).cloned(), BorrowedRef { type_: box Generic(..), .. } => Primitive(PrimitiveType::Reference).def_id(), BorrowedRef { ref type_, .. } => type_.def_id(), Tuple(ref tys) => if tys.is_empty() { Primitive(PrimitiveType::Unit).def_id() } else { Primitive(PrimitiveType::Tuple).def_id() }, BareFunction(..) => Primitive(PrimitiveType::Fn).def_id(), Never => Primitive(PrimitiveType::Never).def_id(), Slice(..) => Primitive(PrimitiveType::Slice).def_id(), Array(..) => Primitive(PrimitiveType::Array).def_id(), RawPointer(..) => Primitive(PrimitiveType::RawPointer).def_id(), QPath { ref self_type, .. } => self_type.def_id(), _ => None, } } } impl PrimitiveType { fn from_str(s: &str) -> Option<PrimitiveType> { match s { "isize" => Some(PrimitiveType::Isize), "i8" => Some(PrimitiveType::I8), "i16" => Some(PrimitiveType::I16), "i32" => Some(PrimitiveType::I32), "i64" => Some(PrimitiveType::I64), "i128" => Some(PrimitiveType::I128), "usize" => Some(PrimitiveType::Usize), "u8" => Some(PrimitiveType::U8), "u16" => Some(PrimitiveType::U16), "u32" => Some(PrimitiveType::U32), "u64" => Some(PrimitiveType::U64), "u128" => Some(PrimitiveType::U128), "bool" => Some(PrimitiveType::Bool), "char" => Some(PrimitiveType::Char), "str" => Some(PrimitiveType::Str), "f32" => Some(PrimitiveType::F32), "f64" => Some(PrimitiveType::F64), "array" => Some(PrimitiveType::Array), "slice" => Some(PrimitiveType::Slice), "tuple" => Some(PrimitiveType::Tuple), "unit" => Some(PrimitiveType::Unit), "pointer" => Some(PrimitiveType::RawPointer), "reference" => Some(PrimitiveType::Reference), "fn" => Some(PrimitiveType::Fn), "never" => Some(PrimitiveType::Never), _ => None, } } pub fn as_str(&self) -> &'static str { use self::PrimitiveType::*; match *self { Isize => "isize", I8 => "i8", I16 => "i16", I32 => "i32", I64 => "i64", I128 => "i128", Usize => "usize", U8 => "u8", U16 => "u16", U32 => "u32", U64 => "u64", U128 => "u128", F32 => "f32", F64 => "f64", Str => "str", Bool => "bool", Char => "char", Array => "array", Slice => "slice", Tuple => "tuple", Unit => "unit", RawPointer => "pointer", Reference => "reference", Fn => "fn", Never => "never", CVarArgs => "...", } } pub fn to_url_str(&self) -> &'static str { self.as_str() } } impl From<ast::IntTy> for PrimitiveType { fn from(int_ty: ast::IntTy) -> PrimitiveType { match int_ty { ast::IntTy::Isize => PrimitiveType::Isize, ast::IntTy::I8 => PrimitiveType::I8, ast::IntTy::I16 => PrimitiveType::I16, ast::IntTy::I32 => PrimitiveType::I32, ast::IntTy::I64 => PrimitiveType::I64, ast::IntTy::I128 => PrimitiveType::I128, } } } impl From<ast::UintTy> for PrimitiveType { fn from(uint_ty: ast::UintTy) -> PrimitiveType { match uint_ty { ast::UintTy::Usize => PrimitiveType::Usize, ast::UintTy::U8 => PrimitiveType::U8, ast::UintTy::U16 => PrimitiveType::U16, ast::UintTy::U32 => PrimitiveType::U32, ast::UintTy::U64 => PrimitiveType::U64, ast::UintTy::U128 => PrimitiveType::U128, } } } impl From<ast::FloatTy> for PrimitiveType { fn from(float_ty: ast::FloatTy) -> PrimitiveType { match float_ty { ast::FloatTy::F32 => PrimitiveType::F32, ast::FloatTy::F64 => PrimitiveType::F64, } } } impl Clean<Type> for hir::Ty { fn clean(&self, cx: &DocContext<'_>) -> Type { use rustc::hir::*; match self.node { TyKind::Never => Never, TyKind::CVarArgs(_) => CVarArgs, TyKind::Ptr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)), TyKind::Rptr(ref l, ref m) => { let lifetime = if l.is_elided() { None } else { Some(l.clean(cx)) }; BorrowedRef {lifetime: lifetime, mutability: m.mutbl.clean(cx), type_: box m.ty.clean(cx)} } TyKind::Slice(ref ty) => Slice(box ty.clean(cx)), TyKind::Array(ref ty, ref length) => { let def_id = cx.tcx.hir().local_def_id_from_hir_id(length.hir_id); let param_env = cx.tcx.param_env(def_id); let substs = InternalSubsts::identity_for_item(cx.tcx, def_id); let cid = GlobalId { instance: ty::Instance::new(def_id, substs), promoted: None }; let length = match cx.tcx.const_eval(param_env.and(cid)) { Ok(length) => print_const(cx, length), Err(_) => "_".to_string(), }; Array(box ty.clean(cx), length) }, TyKind::Tup(ref tys) => Tuple(tys.clean(cx)), TyKind::Def(item_id, _) => { let item = cx.tcx.hir().expect_item_by_hir_id(item_id.id); if let hir::ItemKind::Existential(ref ty) = item.node { ImplTrait(ty.bounds.clean(cx)) } else { unreachable!() } } TyKind::Path(hir::QPath::Resolved(None, ref path)) => { if let Res::Def(DefKind::TyParam, did) = path.res { if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() { return new_ty; } if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did) { return ImplTrait(bounds); } } let mut alias = None; if let Res::Def(DefKind::TyAlias, def_id) = path.res { // Substitute private type aliases if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) { if !cx.renderinfo.borrow().access_levels.is_exported(def_id) { alias = Some(&cx.tcx.hir().expect_item_by_hir_id(hir_id).node); } } }; if let Some(&hir::ItemKind::Ty(ref ty, ref generics)) = alias { let provided_params = &path.segments.last().expect("segments were empty"); let mut ty_substs = FxHashMap::default(); let mut lt_substs = FxHashMap::default(); let mut ct_substs = FxHashMap::default(); provided_params.with_generic_args(|generic_args| { let mut indices: GenericParamCount = Default::default(); for param in generics.params.iter() { match param.kind { hir::GenericParamKind::Lifetime { .. } => { let mut j = 0; let lifetime = generic_args.args.iter().find_map(|arg| { match arg { hir::GenericArg::Lifetime(lt) => { if indices.lifetimes == j { return Some(lt); } j += 1; None } _ => None, } }); if let Some(lt) = lifetime.cloned() { if !lt.is_elided() { let lt_def_id = cx.tcx.hir().local_def_id_from_hir_id(param.hir_id); lt_substs.insert(lt_def_id, lt.clean(cx)); } } indices.lifetimes += 1; } hir::GenericParamKind::Type { ref default, .. } => { let ty_param_def_id = cx.tcx.hir().local_def_id_from_hir_id(param.hir_id); let mut j = 0; let type_ = generic_args.args.iter().find_map(|arg| { match arg { hir::GenericArg::Type(ty) => { if indices.types == j { return Some(ty); } j += 1; None } _ => None, } }); if let Some(ty) = type_.cloned() { ty_substs.insert(ty_param_def_id, ty.clean(cx)); } else if let Some(default) = default.clone() { ty_substs.insert(ty_param_def_id, default.into_inner().clean(cx)); } indices.types += 1; } hir::GenericParamKind::Const { .. } => { let const_param_def_id = cx.tcx.hir().local_def_id_from_hir_id(param.hir_id); let mut j = 0; let const_ = generic_args.args.iter().find_map(|arg| { match arg { hir::GenericArg::Const(ct) => { if indices.consts == j { return Some(ct); } j += 1; None } _ => None, } }); if let Some(ct) = const_.cloned() { ct_substs.insert(const_param_def_id, ct.clean(cx)); } // FIXME(const_generics:defaults) indices.consts += 1; } } } }); return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx)); } resolve_type(cx, path.clean(cx), self.hir_id) } TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => { let mut segments: Vec<_> = p.segments.clone().into(); segments.pop(); let trait_path = hir::Path { span: p.span, res: Res::Def( DefKind::Trait, cx.tcx.associated_item(p.res.def_id()).container.id(), ), segments: segments.into(), }; Type::QPath { name: p.segments.last().expect("segments were empty").ident.name.clean(cx), self_type: box qself.clean(cx), trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id) } } TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => { let mut res = Res::Err; let ty = hir_ty_to_ty(cx.tcx, self); if let ty::Projection(proj) = ty.sty { res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id); } let trait_path = hir::Path { span: self.span, res, segments: vec![].into(), }; Type::QPath { name: segment.ident.name.clean(cx), self_type: box qself.clean(cx), trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id) } } TyKind::TraitObject(ref bounds, ref lifetime) => { match bounds[0].clean(cx).trait_ { ResolvedPath { path, param_names: None, did, is_generic } => { let mut bounds: Vec<self::GenericBound> = bounds[1..].iter().map(|bound| { self::GenericBound::TraitBound(bound.clean(cx), hir::TraitBoundModifier::None) }).collect(); if !lifetime.is_elided() { bounds.push(self::GenericBound::Outlives(lifetime.clean(cx))); } ResolvedPath { path, param_names: Some(bounds), did, is_generic, } } _ => Infer // shouldn't happen } } TyKind::BareFn(ref barefn) => BareFunction(box barefn.clean(cx)), TyKind::Infer | TyKind::Err => Infer, TyKind::Typeof(..) => panic!("Unimplemented type {:?}", self.node), } } } impl<'tcx> Clean<Type> for Ty<'tcx> { fn clean(&self, cx: &DocContext<'_>) -> Type { debug!("cleaning type: {:?}", self); match self.sty { ty::Never => Never, ty::Bool => Primitive(PrimitiveType::Bool), ty::Char => Primitive(PrimitiveType::Char), ty::Int(int_ty) => Primitive(int_ty.into()), ty::Uint(uint_ty) => Primitive(uint_ty.into()), ty::Float(float_ty) => Primitive(float_ty.into()), ty::Str => Primitive(PrimitiveType::Str), ty::Slice(ty) => Slice(box ty.clean(cx)), ty::Array(ty, n) => { let mut n = *cx.tcx.lift(&n).expect("array lift failed"); if let ConstValue::Unevaluated(def_id, substs) = n.val { let param_env = cx.tcx.param_env(def_id); let cid = GlobalId { instance: ty::Instance::new(def_id, substs), promoted: None }; if let Ok(new_n) = cx.tcx.const_eval(param_env.and(cid)) { n = new_n; } }; let n = print_const(cx, n); Array(box ty.clean(cx), n) } ty::RawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)), ty::Ref(r, ty, mutbl) => BorrowedRef { lifetime: r.clean(cx), mutability: mutbl.clean(cx), type_: box ty.clean(cx), }, ty::FnDef(..) | ty::FnPtr(_) => { let ty = cx.tcx.lift(self).expect("FnPtr lift failed"); let sig = ty.fn_sig(cx.tcx); BareFunction(box BareFunctionDecl { unsafety: sig.unsafety(), generic_params: Vec::new(), decl: (cx.tcx.hir().local_def_id(ast::CRATE_NODE_ID), sig).clean(cx), abi: sig.abi(), }) } ty::Adt(def, substs) => { let did = def.did; let kind = match def.adt_kind() { AdtKind::Struct => TypeKind::Struct, AdtKind::Union => TypeKind::Union, AdtKind::Enum => TypeKind::Enum, }; inline::record_extern_fqn(cx, did, kind); let path = external_path(cx, &cx.tcx.item_name(did).as_str(), None, false, vec![], substs); ResolvedPath { path, param_names: None, did, is_generic: false, } } ty::Foreign(did) => { inline::record_extern_fqn(cx, did, TypeKind::Foreign); let path = external_path(cx, &cx.tcx.item_name(did).as_str(), None, false, vec![], InternalSubsts::empty()); ResolvedPath { path: path, param_names: None, did: did, is_generic: false, } } ty::Dynamic(ref obj, ref reg) => { // HACK: pick the first `did` as the `did` of the trait object. Someone // might want to implement "native" support for marker-trait-only // trait objects. let mut dids = obj.principal_def_id().into_iter().chain(obj.auto_traits()); let did = dids.next().unwrap_or_else(|| { panic!("found trait object `{:?}` with no traits?", self) }); let substs = match obj.principal() { Some(principal) => principal.skip_binder().substs, // marker traits have no substs. _ => cx.tcx.intern_substs(&[]) }; inline::record_extern_fqn(cx, did, TypeKind::Trait); let mut param_names = vec![]; reg.clean(cx).map(|b| param_names.push(GenericBound::Outlives(b))); for did in dids { let empty = cx.tcx.intern_substs(&[]); let path = external_path(cx, &cx.tcx.item_name(did).as_str(), Some(did), false, vec![], empty); inline::record_extern_fqn(cx, did, TypeKind::Trait); let bound = GenericBound::TraitBound(PolyTrait { trait_: ResolvedPath { path, param_names: None, did, is_generic: false, }, generic_params: Vec::new(), }, hir::TraitBoundModifier::None); param_names.push(bound); } let mut bindings = vec![]; for pb in obj.projection_bounds() { bindings.push(TypeBinding { name: cx.tcx.associated_item(pb.item_def_id()).ident.name.clean(cx), ty: pb.skip_binder().ty.clean(cx) }); } let path = external_path(cx, &cx.tcx.item_name(did).as_str(), Some(did), false, bindings, substs); ResolvedPath { path, param_names: Some(param_names), did, is_generic: false, } } ty::Tuple(ref t) => { Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx)) } ty::Projection(ref data) => data.clean(cx), ty::Param(ref p) => Generic(p.name.to_string()), ty::Opaque(def_id, substs) => { // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`, // by looking up the projections associated with the def_id. let predicates_of = cx.tcx.explicit_predicates_of(def_id); let substs = cx.tcx.lift(&substs).expect("Opaque lift failed"); let bounds = predicates_of.instantiate(cx.tcx, substs); let mut regions = vec![]; let mut has_sized = false; let mut bounds = bounds.predicates.iter().filter_map(|predicate| { let trait_ref = if let Some(tr) = predicate.to_opt_poly_trait_ref() { tr } else if let ty::Predicate::TypeOutlives(pred) = *predicate { // these should turn up at the end pred.skip_binder().1.clean(cx).map(|r| { regions.push(GenericBound::Outlives(r)) }); return None; } else { return None; }; if let Some(sized) = cx.tcx.lang_items().sized_trait() { if trait_ref.def_id() == sized { has_sized = true; return None; } } let bounds = bounds.predicates.iter().filter_map(|pred| if let ty::Predicate::Projection(proj) = *pred { let proj = proj.skip_binder(); if proj.projection_ty.trait_ref(cx.tcx) == *trait_ref.skip_binder() { Some(TypeBinding { name: cx.tcx.associated_item(proj.projection_ty.item_def_id) .ident.name.clean(cx), ty: proj.ty.clean(cx), }) } else { None } } else { None } ).collect(); Some((trait_ref.skip_binder(), bounds).clean(cx)) }).collect::<Vec<_>>(); bounds.extend(regions); if !has_sized && !bounds.is_empty() { bounds.insert(0, GenericBound::maybe_sized(cx)); } ImplTrait(bounds) } ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton) ty::Bound(..) => panic!("Bound"), ty::Placeholder(..) => panic!("Placeholder"), ty::UnnormalizedProjection(..) => panic!("UnnormalizedProjection"), ty::GeneratorWitness(..) => panic!("GeneratorWitness"), ty::Infer(..) => panic!("Infer"), ty::Error => panic!("Error"), } } } impl<'tcx> Clean<Constant> for ty::Const<'tcx> { fn clean(&self, cx: &DocContext<'_>) -> Constant { Constant { type_: self.ty.clean(cx), expr: format!("{:?}", self.val), // FIXME(const_generics) } } } impl Clean<Item> for hir::StructField { fn clean(&self, cx: &DocContext<'_>) -> Item { let local_did = cx.tcx.hir().local_def_id_from_hir_id(self.hir_id); Item { name: Some(self.ident.name).clean(cx), attrs: self.attrs.clean(cx), source: self.span.clean(cx), visibility: self.vis.clean(cx), stability: get_stability(cx, local_did), deprecation: get_deprecation(cx, local_did), def_id: local_did, inner: StructFieldItem(self.ty.clean(cx)), } } } impl<'tcx> Clean<Item> for ty::FieldDef { fn clean(&self, cx: &DocContext<'_>) -> Item { Item { name: Some(self.ident.name).clean(cx), attrs: cx.tcx.get_attrs(self.did).clean(cx), source: cx.tcx.def_span(self.did).clean(cx), visibility: self.vis.clean(cx), stability: get_stability(cx, self.did), deprecation: get_deprecation(cx, self.did), def_id: self.did, inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)), } } } #[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)] pub enum Visibility { Public, Inherited, Crate, Restricted(DefId, Path), } impl Clean<Option<Visibility>> for hir::Visibility { fn clean(&self, cx: &DocContext<'_>) -> Option<Visibility> { Some(match self.node { hir::VisibilityKind::Public => Visibility::Public, hir::VisibilityKind::Inherited => Visibility::Inherited, hir::VisibilityKind::Crate(_) => Visibility::Crate, hir::VisibilityKind::Restricted { ref path, .. } => { let path = path.clean(cx); let did = register_res(cx, path.res); Visibility::Restricted(did, path) } }) } } impl Clean<Option<Visibility>> for ty::Visibility { fn clean(&self, _: &DocContext<'_>) -> Option<Visibility> { Some(if *self == ty::Visibility::Public { Public } else { Inherited }) } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Struct { pub struct_type: doctree::StructType, pub generics: Generics, pub fields: Vec<Item>, pub fields_stripped: bool, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Union { pub struct_type: doctree::StructType, pub generics: Generics, pub fields: Vec<Item>, pub fields_stripped: bool, } impl Clean<Item> for doctree::Struct { fn clean(&self, cx: &DocContext<'_>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), source: self.whence.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), inner: StructItem(Struct { struct_type: self.struct_type, generics: self.generics.clean(cx), fields: self.fields.clean(cx), fields_stripped: false, }), } } } impl Clean<Item> for doctree::Union { fn clean(&self, cx: &DocContext<'_>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), source: self.whence.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), inner: UnionItem(Union { struct_type: self.struct_type, generics: self.generics.clean(cx), fields: self.fields.clean(cx), fields_stripped: false, }), } } } /// This is a more limited form of the standard Struct, different in that /// it lacks the things most items have (name, id, parameterization). Found /// only as a variant in an enum. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct VariantStruct { pub struct_type: doctree::StructType, pub fields: Vec<Item>, pub fields_stripped: bool, } impl Clean<VariantStruct> for ::rustc::hir::VariantData { fn clean(&self, cx: &DocContext<'_>) -> VariantStruct { VariantStruct { struct_type: doctree::struct_type_from_def(self), fields: self.fields().iter().map(|x| x.clean(cx)).collect(), fields_stripped: false, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Enum { pub variants: IndexVec<VariantIdx, Item>, pub generics: Generics, pub variants_stripped: bool, } impl Clean<Item> for doctree::Enum { fn clean(&self, cx: &DocContext<'_>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), source: self.whence.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), inner: EnumItem(Enum { variants: self.variants.iter().map(|v| v.clean(cx)).collect(), generics: self.generics.clean(cx), variants_stripped: false, }), } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Variant { pub kind: VariantKind, } impl Clean<Item> for doctree::Variant { fn clean(&self, cx: &DocContext<'_>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), source: self.whence.clean(cx), visibility: None, stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), inner: VariantItem(Variant { kind: self.def.clean(cx), }), } } } impl<'tcx> Clean<Item> for ty::VariantDef { fn clean(&self, cx: &DocContext<'_>) -> Item { let kind = match self.ctor_kind { CtorKind::Const => VariantKind::CLike, CtorKind::Fn => { VariantKind::Tuple( self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect() ) } CtorKind::Fictive => { VariantKind::Struct(VariantStruct { struct_type: doctree::Plain, fields_stripped: false, fields: self.fields.iter().map(|field| { Item { source: cx.tcx.def_span(field.did).clean(cx), name: Some(field.ident.name.clean(cx)), attrs: cx.tcx.get_attrs(field.did).clean(cx), visibility: field.vis.clean(cx), def_id: field.did, stability: get_stability(cx, field.did), deprecation: get_deprecation(cx, field.did), inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx)) } }).collect() }) } }; Item { name: Some(self.ident.clean(cx)), attrs: inline::load_attrs(cx, self.def_id), source: cx.tcx.def_span(self.def_id).clean(cx), visibility: Some(Inherited), def_id: self.def_id, inner: VariantItem(Variant { kind }), stability: get_stability(cx, self.def_id), deprecation: get_deprecation(cx, self.def_id), } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum VariantKind { CLike, Tuple(Vec<Type>), Struct(VariantStruct), } impl Clean<VariantKind> for hir::VariantData { fn clean(&self, cx: &DocContext<'_>) -> VariantKind { match self { hir::VariantData::Struct(..) => VariantKind::Struct(self.clean(cx)), hir::VariantData::Tuple(..) => VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect()), hir::VariantData::Unit(..) => VariantKind::CLike, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Span { pub filename: FileName, pub loline: usize, pub locol: usize, pub hiline: usize, pub hicol: usize, } impl Span { pub fn empty() -> Span { Span { filename: FileName::Anon(0), loline: 0, locol: 0, hiline: 0, hicol: 0, } } } impl Clean<Span> for syntax_pos::Span { fn clean(&self, cx: &DocContext<'_>) -> Span { if self.is_dummy() { return Span::empty(); } let cm = cx.sess().source_map(); let filename = cm.span_to_filename(*self); let lo = cm.lookup_char_pos(self.lo()); let hi = cm.lookup_char_pos(self.hi()); Span { filename, loline: lo.line, locol: lo.col.to_usize(), hiline: hi.line, hicol: hi.col.to_usize(), } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct Path { pub global: bool, pub res: Res, pub segments: Vec<PathSegment>, } impl Path { pub fn last_name(&self) -> &str { self.segments.last().expect("segments were empty").name.as_str() } } impl Clean<Path> for hir::Path { fn clean(&self, cx: &DocContext<'_>) -> Path { Path { global: self.is_global(), res: self.res, segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx), } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum GenericArg { Lifetime(Lifetime), Type(Type), Const(Constant), } impl fmt::Display for GenericArg { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { GenericArg::Lifetime(lt) => lt.fmt(f), GenericArg::Type(ty) => ty.fmt(f), GenericArg::Const(ct) => ct.fmt(f), } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub enum GenericArgs { AngleBracketed { args: Vec<GenericArg>, bindings: Vec<TypeBinding>, }, Parenthesized { inputs: Vec<Type>, output: Option<Type>, } } impl Clean<GenericArgs> for hir::GenericArgs { fn clean(&self, cx: &DocContext<'_>) -> GenericArgs { if self.parenthesized { let output = self.bindings[0].ty.clean(cx); GenericArgs::Parenthesized { inputs: self.inputs().clean(cx), output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None } } } else { let elide_lifetimes = self.args.iter().all(|arg| match arg { hir::GenericArg::Lifetime(lt) => lt.is_elided(), _ => true, }); GenericArgs::AngleBracketed { args: self.args.iter().filter_map(|arg| match arg { hir::GenericArg::Lifetime(lt) if !elide_lifetimes => { Some(GenericArg::Lifetime(lt.clean(cx))) } hir::GenericArg::Lifetime(_) => None, hir::GenericArg::Type(ty) => Some(GenericArg::Type(ty.clean(cx))), hir::GenericArg::Const(ct) => Some(GenericArg::Const(ct.clean(cx))), }).collect(), bindings: self.bindings.clean(cx), } } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct PathSegment { pub name: String, pub args: GenericArgs, } impl Clean<PathSegment> for hir::PathSegment { fn clean(&self, cx: &DocContext<'_>) -> PathSegment { PathSegment { name: self.ident.name.clean(cx), args: self.with_generic_args(|generic_args| generic_args.clean(cx)) } } } fn strip_type(ty: Type) -> Type { match ty { Type::ResolvedPath { path, param_names, did, is_generic } => { Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic } } Type::Tuple(inner_tys) => { Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect()) } Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))), Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s), Type::Unique(inner_ty) => Type::Unique(Box::new(strip_type(*inner_ty))), Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))), Type::BorrowedRef { lifetime, mutability, type_ } => { Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) } } Type::QPath { name, self_type, trait_ } => { Type::QPath { name, self_type: Box::new(strip_type(*self_type)), trait_: Box::new(strip_type(*trait_)) } } _ => ty } } fn strip_path(path: &Path) -> Path { let segments = path.segments.iter().map(|s| { PathSegment { name: s.name.clone(), args: GenericArgs::AngleBracketed { args: vec![], bindings: vec![], } } }).collect(); Path { global: path.global, res: path.res.clone(), segments, } } fn qpath_to_string(p: &hir::QPath) -> String { let segments = match *p { hir::QPath::Resolved(_, ref path) => &path.segments, hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(), }; let mut s = String::new(); for (i, seg) in segments.iter().enumerate() { if i > 0 { s.push_str("::"); } if seg.ident.name != keywords::PathRoot.name() { s.push_str(&*seg.ident.as_str()); } } s } impl Clean<String> for Ident { #[inline] fn clean(&self, cx: &DocContext<'_>) -> String { self.name.clean(cx) } } impl Clean<String> for ast::Name { #[inline] fn clean(&self, _: &DocContext<'_>) -> String { self.to_string() } } impl Clean<String> for InternedString { #[inline] fn clean(&self, _: &DocContext<'_>) -> String { self.to_string() } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Typedef { pub type_: Type, pub generics: Generics, } impl Clean<Item> for doctree::Typedef { fn clean(&self, cx: &DocContext<'_>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), source: self.whence.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), inner: TypedefItem(Typedef { type_: self.ty.clean(cx), generics: self.gen.clean(cx), }, false), } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Existential { pub bounds: Vec<GenericBound>, pub generics: Generics, } impl Clean<Item> for doctree::Existential { fn clean(&self, cx: &DocContext<'_>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), source: self.whence.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), inner: ExistentialItem(Existential { bounds: self.exist_ty.bounds.clean(cx), generics: self.exist_ty.generics.clean(cx), }, false), } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)] pub struct BareFunctionDecl { pub unsafety: hir::Unsafety, pub generic_params: Vec<GenericParamDef>, pub decl: FnDecl, pub abi: Abi, } impl Clean<BareFunctionDecl> for hir::BareFnTy { fn clean(&self, cx: &DocContext<'_>) -> BareFunctionDecl { let (generic_params, decl) = enter_impl_trait(cx, || { (self.generic_params.clean(cx), (&*self.decl, &self.arg_names[..]).clean(cx)) }); BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Static { pub type_: Type, pub mutability: Mutability, /// It's useful to have the value of a static documented, but I have no /// desire to represent expressions (that'd basically be all of the AST, /// which is huge!). So, have a string. pub expr: String, } impl Clean<Item> for doctree::Static { fn clean(&self, cx: &DocContext<'_>) -> Item { debug!("cleaning static {}: {:?}", self.name.clean(cx), self); Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), source: self.whence.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), inner: StaticItem(Static { type_: self.type_.clean(cx), mutability: self.mutability.clean(cx), expr: print_const_expr(cx, self.expr), }), } } } #[derive(Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)] pub struct Constant { pub type_: Type, pub expr: String, } impl Clean<Item> for doctree::Constant { fn clean(&self, cx: &DocContext<'_>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), source: self.whence.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), inner: ConstantItem(Constant { type_: self.type_.clean(cx), expr: print_const_expr(cx, self.expr), }), } } } #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Copy, Hash)] pub enum Mutability { Mutable, Immutable, } impl Clean<Mutability> for hir::Mutability { fn clean(&self, _: &DocContext<'_>) -> Mutability { match self { &hir::MutMutable => Mutable, &hir::MutImmutable => Immutable, } } } #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Copy, Debug, Hash)] pub enum ImplPolarity { Positive, Negative, } impl Clean<ImplPolarity> for hir::ImplPolarity { fn clean(&self, _: &DocContext<'_>) -> ImplPolarity { match self { &hir::ImplPolarity::Positive => ImplPolarity::Positive, &hir::ImplPolarity::Negative => ImplPolarity::Negative, } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Impl { pub unsafety: hir::Unsafety, pub generics: Generics, pub provided_trait_methods: FxHashSet<String>, pub trait_: Option<Type>, pub for_: Type, pub items: Vec<Item>, pub polarity: Option<ImplPolarity>, pub synthetic: bool, pub blanket_impl: Option<Type>, } pub fn get_auto_trait_and_blanket_impls( cx: &DocContext<'tcx>, ty: Ty<'tcx>, param_env_def_id: DefId, ) -> impl Iterator<Item = Item> { AutoTraitFinder::new(cx).get_auto_trait_impls(ty, param_env_def_id).into_iter() .chain(BlanketImplFinder::new(cx).get_blanket_impls(ty, param_env_def_id)) } impl Clean<Vec<Item>> for doctree::Impl { fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> { let mut ret = Vec::new(); let trait_ = self.trait_.clean(cx); let items = self.items.clean(cx); // If this impl block is an implementation of the Deref trait, then we // need to try inlining the target's inherent impl blocks as well. if trait_.def_id() == cx.tcx.lang_items().deref_trait() { build_deref_target_impls(cx, &items, &mut ret); } let provided = trait_.def_id().map(|did| { cx.tcx.provided_trait_methods(did) .into_iter() .map(|meth| meth.ident.to_string()) .collect() }).unwrap_or_default(); ret.push(Item { name: None, attrs: self.attrs.clean(cx), source: self.whence.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), visibility: self.vis.clean(cx), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), inner: ImplItem(Impl { unsafety: self.unsafety, generics: self.generics.clean(cx), provided_trait_methods: provided, trait_, for_: self.for_.clean(cx), items, polarity: Some(self.polarity.clean(cx)), synthetic: false, blanket_impl: None, }) }); ret } } fn build_deref_target_impls(cx: &DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) { use self::PrimitiveType::*; let tcx = cx.tcx; for item in items { let target = match item.inner { TypedefItem(ref t, true) => &t.type_, _ => continue, }; let primitive = match *target { ResolvedPath { did, .. } if did.is_local() => continue, ResolvedPath { did, .. } => { ret.extend(inline::build_impls(cx, did)); continue } _ => match target.primitive_type() { Some(prim) => prim, None => continue, } }; let did = match primitive { Isize => tcx.lang_items().isize_impl(), I8 => tcx.lang_items().i8_impl(), I16 => tcx.lang_items().i16_impl(), I32 => tcx.lang_items().i32_impl(), I64 => tcx.lang_items().i64_impl(), I128 => tcx.lang_items().i128_impl(), Usize => tcx.lang_items().usize_impl(), U8 => tcx.lang_items().u8_impl(), U16 => tcx.lang_items().u16_impl(), U32 => tcx.lang_items().u32_impl(), U64 => tcx.lang_items().u64_impl(), U128 => tcx.lang_items().u128_impl(), F32 => tcx.lang_items().f32_impl(), F64 => tcx.lang_items().f64_impl(), Char => tcx.lang_items().char_impl(), Bool => None, Str => tcx.lang_items().str_impl(), Slice => tcx.lang_items().slice_impl(), Array => tcx.lang_items().slice_impl(), Tuple => None, Unit => None, RawPointer => tcx.lang_items().const_ptr_impl(), Reference => None, Fn => None, Never => None, CVarArgs => tcx.lang_items().va_list(), }; if let Some(did) = did { if !did.is_local() { inline::build_impl(cx, did, ret); } } } } impl Clean<Vec<Item>> for doctree::ExternCrate { fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> { let please_inline = self.vis.node.is_pub() && self.attrs.iter().any(|a| { a.check_name(sym::doc) && match a.meta_item_list() { Some(l) => attr::list_contains_name(&l, sym::inline), None => false, } }); if please_inline { let mut visited = FxHashSet::default(); let res = Res::Def( DefKind::Mod, DefId { krate: self.cnum, index: CRATE_DEF_INDEX, }, ); if let Some(items) = inline::try_inline(cx, res, self.name, &mut visited) { return items; } } vec![Item { name: None, attrs: self.attrs.clean(cx), source: self.whence.clean(cx), def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX }, visibility: self.vis.clean(cx), stability: None, deprecation: None, inner: ExternCrateItem(self.name.clean(cx), self.path.clone()) }] } } impl Clean<Vec<Item>> for doctree::Import { fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> { // We consider inlining the documentation of `pub use` statements, but we // forcefully don't inline if this is not public or if the // #[doc(no_inline)] attribute is present. // Don't inline doc(hidden) imports so they can be stripped at a later stage. let mut denied = !self.vis.node.is_pub() || self.attrs.iter().any(|a| { a.check_name(sym::doc) && match a.meta_item_list() { Some(l) => attr::list_contains_name(&l, sym::no_inline) || attr::list_contains_name(&l, sym::hidden), None => false, } }); // Also check whether imports were asked to be inlined, in case we're trying to re-export a // crate in Rust 2018+ let please_inline = self.attrs.lists(sym::doc).has_word(sym::inline); let path = self.path.clean(cx); let inner = if self.glob { if !denied { let mut visited = FxHashSet::default(); if let Some(items) = inline::try_inline_glob(cx, path.res, &mut visited) { return items; } } Import::Glob(resolve_use_source(cx, path)) } else { let name = self.name; if !please_inline { match path.res { Res::Def(DefKind::Mod, did) => { if !did.is_local() && did.index == CRATE_DEF_INDEX { // if we're `pub use`ing an extern crate root, don't inline it unless we // were specifically asked for it denied = true; } } _ => {} } } if !denied { let mut visited = FxHashSet::default(); if let Some(items) = inline::try_inline(cx, path.res, name, &mut visited) { return items; } } Import::Simple(name.clean(cx), resolve_use_source(cx, path)) }; vec![Item { name: None, attrs: self.attrs.clean(cx), source: self.whence.clean(cx), def_id: cx.tcx.hir().local_def_id(ast::CRATE_NODE_ID), visibility: self.vis.clean(cx), stability: None, deprecation: None, inner: ImportItem(inner) }] } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum Import { // use source as str; Simple(String, ImportSource), // use source::*; Glob(ImportSource) } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct ImportSource { pub path: Path, pub did: Option<DefId>, } impl Clean<Vec<Item>> for hir::ForeignMod { fn clean(&self, cx: &DocContext<'_>) -> Vec<Item> { let mut items = self.items.clean(cx); for item in &mut items { if let ForeignFunctionItem(ref mut f) = item.inner { f.header.abi = self.abi; } } items } } impl Clean<Item> for hir::ForeignItem { fn clean(&self, cx: &DocContext<'_>) -> Item { let inner = match self.node { hir::ForeignItemKind::Fn(ref decl, ref names, ref generics) => { let (generics, decl) = enter_impl_trait(cx, || { (generics.clean(cx), (&**decl, &names[..]).clean(cx)) }); let (all_types, ret_types) = get_all_types(&generics, &decl, cx); ForeignFunctionItem(Function { decl, generics, header: hir::FnHeader { unsafety: hir::Unsafety::Unsafe, abi: Abi::Rust, constness: hir::Constness::NotConst, asyncness: hir::IsAsync::NotAsync, }, all_types, ret_types, }) } hir::ForeignItemKind::Static(ref ty, mutbl) => { ForeignStaticItem(Static { type_: ty.clean(cx), mutability: mutbl.clean(cx), expr: String::new(), }) } hir::ForeignItemKind::Type => { ForeignTypeItem } }; let local_did = cx.tcx.hir().local_def_id_from_hir_id(self.hir_id); Item { name: Some(self.ident.clean(cx)), attrs: self.attrs.clean(cx), source: self.span.clean(cx), def_id: local_did, visibility: self.vis.clean(cx), stability: get_stability(cx, local_did), deprecation: get_deprecation(cx, local_did), inner, } } } // Utilities pub trait ToSource { fn to_src(&self, cx: &DocContext<'_>) -> String; } impl ToSource for syntax_pos::Span { fn to_src(&self, cx: &DocContext<'_>) -> String { debug!("converting span {:?} to snippet", self.clean(cx)); let sn = match cx.sess().source_map().span_to_snippet(*self) { Ok(x) => x, Err(_) => String::new() }; debug!("got snippet {}", sn); sn } } fn name_from_pat(p: &hir::Pat) -> String { use rustc::hir::*; debug!("Trying to get a name from pattern: {:?}", p); match p.node { PatKind::Wild => "_".to_string(), PatKind::Binding(_, _, ident, _) => ident.to_string(), PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p), PatKind::Struct(ref name, ref fields, etc) => { format!("{} {{ {}{} }}", qpath_to_string(name), fields.iter().map(|&Spanned { node: ref fp, .. }| format!("{}: {}", fp.ident, name_from_pat(&*fp.pat))) .collect::<Vec<String>>().join(", "), if etc { ", .." } else { "" } ) } PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p)) .collect::<Vec<String>>().join(", ")), PatKind::Box(ref p) => name_from_pat(&**p), PatKind::Ref(ref p, _) => name_from_pat(&**p), PatKind::Lit(..) => { warn!("tried to get argument name from PatKind::Lit, \ which is silly in function arguments"); "()".to_string() }, PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \ which is not allowed in function arguments"), PatKind::Slice(ref begin, ref mid, ref end) => { let begin = begin.iter().map(|p| name_from_pat(&**p)); let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter(); let end = end.iter().map(|p| name_from_pat(&**p)); format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", ")) }, } } fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String { match n.val { ConstValue::Unevaluated(def_id, _) => { if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) { print_const_expr(cx, cx.tcx.hir().body_owned_by(hir_id)) } else { inline::print_inlined_const(cx, def_id) } }, _ => { let mut s = String::new(); ::rustc::mir::fmt_const_val(&mut s, n).expect("fmt_const_val failed"); // array lengths are obviously usize if s.ends_with("usize") { let n = s.len() - "usize".len(); s.truncate(n); } s }, } } fn print_const_expr(cx: &DocContext<'_>, body: hir::BodyId) -> String { cx.tcx.hir().hir_to_pretty_string(body.hir_id) } /// Given a type Path, resolve it to a Type using the TyCtxt fn resolve_type(cx: &DocContext<'_>, path: Path, id: hir::HirId) -> Type { if id == hir::DUMMY_HIR_ID { debug!("resolve_type({:?})", path); } else { debug!("resolve_type({:?},{:?})", path, id); } let is_generic = match path.res { Res::PrimTy(p) => match p { hir::Str => return Primitive(PrimitiveType::Str), hir::Bool => return Primitive(PrimitiveType::Bool), hir::Char => return Primitive(PrimitiveType::Char), hir::Int(int_ty) => return Primitive(int_ty.into()), hir::Uint(uint_ty) => return Primitive(uint_ty.into()), hir::Float(float_ty) => return Primitive(float_ty.into()), }, Res::SelfTy(..) if path.segments.len() == 1 => { return Generic(keywords::SelfUpper.name().to_string()); } Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => { return Generic(format!("{:#}", path)); } Res::SelfTy(..) | Res::Def(DefKind::TyParam, _) | Res::Def(DefKind::AssociatedTy, _) => true, _ => false, }; let did = register_res(&*cx, path.res); ResolvedPath { path: path, param_names: None, did: did, is_generic: is_generic } } pub fn register_res(cx: &DocContext<'_>, res: Res) -> DefId { debug!("register_res({:?})", res); let (did, kind) = match res { Res::Def(DefKind::Fn, i) => (i, TypeKind::Function), Res::Def(DefKind::TyAlias, i) => (i, TypeKind::Typedef), Res::Def(DefKind::Enum, i) => (i, TypeKind::Enum), Res::Def(DefKind::Trait, i) => (i, TypeKind::Trait), Res::Def(DefKind::Struct, i) => (i, TypeKind::Struct), Res::Def(DefKind::Union, i) => (i, TypeKind::Union), Res::Def(DefKind::Mod, i) => (i, TypeKind::Module), Res::Def(DefKind::ForeignTy, i) => (i, TypeKind::Foreign), Res::Def(DefKind::Const, i) => (i, TypeKind::Const), Res::Def(DefKind::Static, i) => (i, TypeKind::Static), Res::Def(DefKind::Variant, i) => (cx.tcx.parent(i).expect("cannot get parent def id"), TypeKind::Enum), Res::Def(DefKind::Macro(mac_kind), i) => match mac_kind { MacroKind::Bang => (i, TypeKind::Macro), MacroKind::Attr => (i, TypeKind::Attr), MacroKind::Derive => (i, TypeKind::Derive), MacroKind::ProcMacroStub => unreachable!(), }, Res::Def(DefKind::TraitAlias, i) => (i, TypeKind::TraitAlias), Res::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait), Res::SelfTy(_, Some(impl_def_id)) => return impl_def_id, _ => return res.def_id() }; if did.is_local() { return did } inline::record_extern_fqn(cx, did, kind); if let TypeKind::Trait = kind { inline::record_extern_trait(cx, did); } did } fn resolve_use_source(cx: &DocContext<'_>, path: Path) -> ImportSource { ImportSource { did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) }, path, } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Macro { pub source: String, pub imported_from: Option<String>, } impl Clean<Item> for doctree::Macro { fn clean(&self, cx: &DocContext<'_>) -> Item { let name = self.name.clean(cx); Item { name: Some(name.clone()), attrs: self.attrs.clean(cx), source: self.whence.clean(cx), visibility: Some(Public), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), def_id: self.def_id, inner: MacroItem(Macro { source: format!("macro_rules! {} {{\n{}}}", name, self.matchers.iter().map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) }).collect::<String>()), imported_from: self.imported_from.clean(cx), }), } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct ProcMacro { pub kind: MacroKind, pub helpers: Vec<String>, } impl Clean<Item> for doctree::ProcMacro { fn clean(&self, cx: &DocContext<'_>) -> Item { Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), source: self.whence.clean(cx), visibility: Some(Public), stability: self.stab.clean(cx), deprecation: self.depr.clean(cx), def_id: cx.tcx.hir().local_def_id_from_hir_id(self.id), inner: ProcMacroItem(ProcMacro { kind: self.kind, helpers: self.helpers.clean(cx), }), } } } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Stability { pub level: stability::StabilityLevel, pub feature: Option<String>, pub since: String, pub deprecation: Option<Deprecation>, pub unstable_reason: Option<String>, pub issue: Option<u32>, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Deprecation { pub since: Option<String>, pub note: Option<String>, } impl Clean<Stability> for attr::Stability { fn clean(&self, _: &DocContext<'_>) -> Stability { Stability { level: stability::StabilityLevel::from_attr_level(&self.level), feature: Some(self.feature.to_string()).filter(|f| !f.is_empty()), since: match self.level { attr::Stable {ref since} => since.to_string(), _ => String::new(), }, deprecation: self.rustc_depr.as_ref().map(|d| { Deprecation { note: Some(d.reason.to_string()).filter(|r| !r.is_empty()), since: Some(d.since.to_string()).filter(|d| !d.is_empty()), } }), unstable_reason: match self.level { attr::Unstable { reason: Some(ref reason), .. } => Some(reason.to_string()), _ => None, }, issue: match self.level { attr::Unstable {issue, ..} => Some(issue), _ => None, } } } } impl<'a> Clean<Stability> for &'a attr::Stability { fn clean(&self, dc: &DocContext<'_>) -> Stability { (**self).clean(dc) } } impl Clean<Deprecation> for attr::Deprecation { fn clean(&self, _: &DocContext<'_>) -> Deprecation { Deprecation { since: self.since.map(|s| s.to_string()).filter(|s| !s.is_empty()), note: self.note.map(|n| n.to_string()).filter(|n| !n.is_empty()), } } } /// An equality constraint on an associated type, e.g., `A = Bar` in `Foo<A = Bar>` #[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug, Hash)] pub struct TypeBinding { pub name: String, pub ty: Type } impl Clean<TypeBinding> for hir::TypeBinding { fn clean(&self, cx: &DocContext<'_>) -> TypeBinding { TypeBinding { name: self.ident.name.clean(cx), ty: self.ty.clean(cx) } } } pub fn def_id_to_path( cx: &DocContext<'_>, did: DefId, name: Option<String> ) -> Vec<String> { let crate_name = name.unwrap_or_else(|| cx.tcx.crate_name(did.krate).to_string()); let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| { // extern blocks have an empty name let s = elem.data.to_string(); if !s.is_empty() { Some(s) } else { None } }); once(crate_name).chain(relative).collect() } pub fn enter_impl_trait<F, R>(cx: &DocContext<'_>, f: F) -> R where F: FnOnce() -> R, { let old_bounds = mem::replace(&mut *cx.impl_trait_bounds.borrow_mut(), Default::default()); let r = f(); assert!(cx.impl_trait_bounds.borrow().is_empty()); *cx.impl_trait_bounds.borrow_mut() = old_bounds; r } // Start of code copied from rust-clippy pub fn path_to_def_local(tcx: TyCtxt<'_, '_, '_>, path: &[Symbol]) -> Option<DefId> { let krate = tcx.hir().krate(); let mut items = krate.module.item_ids.clone(); let mut path_it = path.iter().peekable(); loop { let segment = path_it.next()?; for item_id in mem::replace(&mut items, HirVec::new()).iter() { let item = tcx.hir().expect_item_by_hir_id(item_id.id); if item.ident.name == *segment { if path_it.peek().is_none() { return Some(tcx.hir().local_def_id_from_hir_id(item_id.id)) } items = match &item.node { &hir::ItemKind::Mod(ref m) => m.item_ids.clone(), _ => panic!("Unexpected item {:?} in path {:?} path") }; break; } } } } pub fn path_to_def(tcx: TyCtxt<'_, '_, '_>, path: &[Symbol]) -> Option<DefId> { let crates = tcx.crates(); let krate = crates .iter() .find(|&&krate| tcx.crate_name(krate) == path[0]); if let Some(krate) = krate { let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX, }; let mut items = tcx.item_children(krate); let mut path_it = path.iter().skip(1).peekable(); loop { let segment = path_it.next()?; for item in mem::replace(&mut items, Lrc::new(vec![])).iter() { if item.ident.name == *segment { if path_it.peek().is_none() { return match item.res { def::Res::Def(DefKind::Trait, did) => Some(did), _ => None, } } items = tcx.item_children(item.res.def_id()); break; } } } } else { None } } // End of code copied from rust-clippy #[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)] enum RegionTarget<'tcx> { Region(Region<'tcx>), RegionVid(RegionVid) } #[derive(Default, Debug, Clone)] struct RegionDeps<'tcx> { larger: FxHashSet<RegionTarget<'tcx>>, smaller: FxHashSet<RegionTarget<'tcx>> } #[derive(Eq, PartialEq, Hash, Debug)] enum SimpleBound { TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParamDef>, hir::TraitBoundModifier), Outlives(Lifetime), } impl From<GenericBound> for SimpleBound { fn from(bound: GenericBound) -> Self { match bound.clone() { GenericBound::Outlives(l) => SimpleBound::Outlives(l), GenericBound::TraitBound(t, mod_) => match t.trait_ { Type::ResolvedPath { path, param_names, .. } => { SimpleBound::TraitBound(path.segments, param_names .map_or_else(|| Vec::new(), |v| v.iter() .map(|p| SimpleBound::from(p.clone())) .collect()), t.generic_params, mod_) } _ => panic!("Unexpected bound {:?}", bound), } } } }
35.955427
100
0.497037
e84f697c00cd98e6b37a20ed81ca136a2cb8c5ad
14,675
//! multipart/form-data //! //! To send a `multipart/form-data` body, a [`Form`](crate::multipart::Form) is built up, adding //! fields or customized [`Part`](crate::multipart::Part)s, and then calling the //! [`multipart`][builder] method on the `RequestBuilder`. //! //! # Example //! //! ``` //! use reqwest::blocking::multipart; //! //! # fn run() -> Result<(), Box<dyn std::error::Error>> { //! let form = multipart::Form::new() //! // Adding just a simple text field... //! .text("username", "seanmonstar") //! // And a file... //! .file("photo", "/path/to/photo.png")?; //! //! // Customize all the details of a Part if needed... //! let bio = multipart::Part::text("hallo peeps") //! .file_name("bio.txt") //! .mime_str("text/plain")?; //! //! // Add the custom part to our form... //! let form = form.part("biography", bio); //! //! // And finally, send the form //! let client = reqwest::blocking::Client::new(); //! let resp = client //! .post("http://localhost:8080/user") //! .multipart(form) //! .send()?; //! # Ok(()) //! # } //! # fn main() {} //! ``` //! //! [builder]: ../struct.RequestBuilder.html#method.multipart use std::borrow::Cow; use std::fmt; use std::fs::File; use std::io::{self, Cursor, Read}; use std::path::Path; use mime_guess::{self, Mime}; use super::Body; use crate::async_impl::multipart::{FormParts, PartMetadata, PartProps}; /// A multipart/form-data request. pub struct Form { inner: FormParts<Part>, } /// A field in a multipart form. pub struct Part { meta: PartMetadata, value: Body, } impl Default for Form { fn default() -> Self { Self::new() } } impl Form { /// Creates a new Form without any content. pub fn new() -> Form { Form { inner: FormParts::new(), } } /// Get the boundary that this form will use. #[inline] pub fn boundary(&self) -> &str { self.inner.boundary() } /// Add a data field with supplied name and value. /// /// # Examples /// /// ``` /// let form = reqwest::blocking::multipart::Form::new() /// .text("username", "seanmonstar") /// .text("password", "secret"); /// ``` pub fn text<T, U>(self, name: T, value: U) -> Form where T: Into<Cow<'static, str>>, U: Into<Cow<'static, str>>, { self.part(name, Part::text(value)) } /// Adds a file field. /// /// The path will be used to try to guess the filename and mime. /// /// # Examples /// /// ```no_run /// # fn run() -> std::io::Result<()> { /// let files = reqwest::blocking::multipart::Form::new() /// .file("key", "/path/to/file")?; /// # Ok(()) /// # } /// ``` /// /// # Errors /// /// Errors when the file cannot be opened. pub fn file<T, U>(self, name: T, path: U) -> io::Result<Form> where T: Into<Cow<'static, str>>, U: AsRef<Path>, { Ok(self.part(name, Part::file(path)?)) } /// Adds a customized Part. pub fn part<T>(self, name: T, part: Part) -> Form where T: Into<Cow<'static, str>>, { self.with_inner(move |inner| inner.part(name, part)) } /// Configure this `Form` to percent-encode using the `path-segment` rules. pub fn percent_encode_path_segment(self) -> Form { self.with_inner(|inner| inner.percent_encode_path_segment()) } /// Configure this `Form` to percent-encode using the `attr-char` rules. pub fn percent_encode_attr_chars(self) -> Form { self.with_inner(|inner| inner.percent_encode_attr_chars()) } /// Configure this `Form` to skip percent-encoding pub fn percent_encode_noop(self) -> Form { self.with_inner(|inner| inner.percent_encode_noop()) } pub(crate) fn reader(self) -> Reader { Reader::new(self) } // If predictable, computes the length the request will have // The length should be preditable if only String and file fields have been added, // but not if a generic reader has been added; pub(crate) fn compute_length(&mut self) -> Option<u64> { self.inner.compute_length() } fn with_inner<F>(self, func: F) -> Self where F: FnOnce(FormParts<Part>) -> FormParts<Part>, { Form { inner: func(self.inner), } } } impl fmt::Debug for Form { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.inner.fmt_fields("Form", f) } } impl Part { /// Makes a text parameter. pub fn text<T>(value: T) -> Part where T: Into<Cow<'static, str>>, { let body = match value.into() { Cow::Borrowed(slice) => Body::from(slice), Cow::Owned(string) => Body::from(string), }; Part::new(body) } /// Makes a new parameter from arbitrary bytes. pub fn bytes<T>(value: T) -> Part where T: Into<Cow<'static, [u8]>>, { let body = match value.into() { Cow::Borrowed(slice) => Body::from(slice), Cow::Owned(vec) => Body::from(vec), }; Part::new(body) } /// Adds a generic reader. /// /// Does not set filename or mime. pub fn reader<T: Read + Send + 'static>(value: T) -> Part { Part::new(Body::new(value)) } /// Adds a generic reader with known length. /// /// Does not set filename or mime. pub fn reader_with_length<T: Read + Send + 'static>(value: T, length: u64) -> Part { Part::new(Body::sized(value, length)) } /// Makes a file parameter. /// /// # Errors /// /// Errors when the file cannot be opened. pub fn file<T: AsRef<Path>>(path: T) -> io::Result<Part> { let path = path.as_ref(); let file_name = path .file_name() .map(|filename| filename.to_string_lossy().into_owned()); let ext = path.extension().and_then(|ext| ext.to_str()).unwrap_or(""); let mime = mime_guess::from_ext(ext).first_or_octet_stream(); let file = File::open(path)?; let field = Part::new(Body::from(file)).mime(mime); Ok(if let Some(file_name) = file_name { field.file_name(file_name) } else { field }) } fn new(value: Body) -> Part { Part { meta: PartMetadata::new(), value, } } /// Tries to set the mime of this part. pub fn mime_str(self, mime: &str) -> crate::Result<Part> { Ok(self.mime(mime.parse().map_err(crate::error::builder)?)) } // Re-export when mime 0.4 is available, with split MediaType/MediaRange. fn mime(self, mime: Mime) -> Part { self.with_inner(move |inner| inner.mime(mime)) } /// Sets the filename, builder style. pub fn file_name<T>(self, filename: T) -> Part where T: Into<Cow<'static, str>>, { self.with_inner(move |inner| inner.file_name(filename)) } fn with_inner<F>(self, func: F) -> Self where F: FnOnce(PartMetadata) -> PartMetadata, { Part { meta: func(self.meta), value: self.value, } } } impl fmt::Debug for Part { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut dbg = f.debug_struct("Part"); dbg.field("value", &self.value); self.meta.fmt_fields(&mut dbg); dbg.finish() } } impl PartProps for Part { fn value_len(&self) -> Option<u64> { self.value.len() } fn metadata(&self) -> &PartMetadata { &self.meta } } pub(crate) struct Reader { form: Form, active_reader: Option<Box<dyn Read + Send>>, } impl fmt::Debug for Reader { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Reader").field("form", &self.form).finish() } } impl Reader { fn new(form: Form) -> Reader { let mut reader = Reader { form, active_reader: None, }; reader.next_reader(); reader } fn next_reader(&mut self) { self.active_reader = if !self.form.inner.fields.is_empty() { // We need to move out of the vector here because we are consuming the field's reader let (name, field) = self.form.inner.fields.remove(0); let boundary = Cursor::new(format!("--{}\r\n", self.form.boundary())); let header = Cursor::new({ // Try to use cached headers created by compute_length let mut h = if !self.form.inner.computed_headers.is_empty() { self.form.inner.computed_headers.remove(0) } else { self.form .inner .percent_encoding .encode_headers(&name, field.metadata()) }; h.extend_from_slice(b"\r\n\r\n"); h }); let reader = boundary .chain(header) .chain(field.value.into_reader()) .chain(Cursor::new("\r\n")); // According to https://tools.ietf.org/html/rfc2046#section-5.1.1 // the very last field has a special boundary if !self.form.inner.fields.is_empty() { Some(Box::new(reader)) } else { Some(Box::new(reader.chain(Cursor::new(format!( "--{}--\r\n", self.form.boundary() ))))) } } else { None } } } impl Read for Reader { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let mut total_bytes_read = 0usize; let mut last_read_bytes; loop { match self.active_reader { Some(ref mut reader) => { last_read_bytes = reader.read(&mut buf[total_bytes_read..])?; total_bytes_read += last_read_bytes; if total_bytes_read == buf.len() { return Ok(total_bytes_read); } } None => return Ok(total_bytes_read), }; if last_read_bytes == 0 && !buf.is_empty() { self.next_reader(); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn form_empty() { let mut output = Vec::new(); let mut form = Form::new(); let length = form.compute_length(); form.reader().read_to_end(&mut output).unwrap(); assert_eq!(output, b""); assert_eq!(length.unwrap(), 0); } #[test] fn read_to_end() { let mut output = Vec::new(); let mut form = Form::new() .part("reader1", Part::reader(std::io::empty())) .part("key1", Part::text("value1")) .part("key2", Part::text("value2").mime(mime::IMAGE_BMP)) .part("reader2", Part::reader(std::io::empty())) .part("key3", Part::text("value3").file_name("filename")); form.inner.boundary = "boundary".to_string(); let length = form.compute_length(); let expected = "--boundary\r\n\ Content-Disposition: form-data; name=\"reader1\"\r\n\r\n\ \r\n\ --boundary\r\n\ Content-Disposition: form-data; name=\"key1\"\r\n\r\n\ value1\r\n\ --boundary\r\n\ Content-Disposition: form-data; name=\"key2\"\r\n\ Content-Type: image/bmp\r\n\r\n\ value2\r\n\ --boundary\r\n\ Content-Disposition: form-data; name=\"reader2\"\r\n\r\n\ \r\n\ --boundary\r\n\ Content-Disposition: form-data; name=\"key3\"; filename=\"filename\"\r\n\r\n\ value3\r\n--boundary--\r\n"; form.reader().read_to_end(&mut output).unwrap(); // These prints are for debug purposes in case the test fails println!( "START REAL\n{}\nEND REAL", std::str::from_utf8(&output).unwrap() ); println!("START EXPECTED\n{}\nEND EXPECTED", expected); assert_eq!(std::str::from_utf8(&output).unwrap(), expected); assert!(length.is_none()); } #[test] fn read_to_end_with_length() { let mut output = Vec::new(); let mut form = Form::new() .text("key1", "value1") .part("key2", Part::text("value2").mime(mime::IMAGE_BMP)) .part("key3", Part::text("value3").file_name("filename")); form.inner.boundary = "boundary".to_string(); let length = form.compute_length(); let expected = "--boundary\r\n\ Content-Disposition: form-data; name=\"key1\"\r\n\r\n\ value1\r\n\ --boundary\r\n\ Content-Disposition: form-data; name=\"key2\"\r\n\ Content-Type: image/bmp\r\n\r\n\ value2\r\n\ --boundary\r\n\ Content-Disposition: form-data; name=\"key3\"; filename=\"filename\"\r\n\r\n\ value3\r\n--boundary--\r\n"; form.reader().read_to_end(&mut output).unwrap(); // These prints are for debug purposes in case the test fails println!( "START REAL\n{}\nEND REAL", std::str::from_utf8(&output).unwrap() ); println!("START EXPECTED\n{}\nEND EXPECTED", expected); assert_eq!(std::str::from_utf8(&output).unwrap(), expected); assert_eq!(length.unwrap(), expected.len() as u64); } #[test] fn read_to_end_with_header() { let mut output = Vec::new(); let mut part = Part::text("value2").mime(mime::IMAGE_BMP); part.meta.headers.insert("Hdr3", "/a/b/c".parse().unwrap()); let mut form = Form::new().part("key2", part); form.inner.boundary = "boundary".to_string(); let expected = "--boundary\r\n\ Content-Disposition: form-data; name=\"key2\"\r\n\ Content-Type: image/bmp\r\n\ hdr3: /a/b/c\r\n\ \r\n\ value2\r\n\ --boundary--\r\n"; form.reader().read_to_end(&mut output).unwrap(); // These prints are for debug purposes in case the test fails println!( "START REAL\n{}\nEND REAL", std::str::from_utf8(&output).unwrap() ); println!("START EXPECTED\n{}\nEND EXPECTED", expected); assert_eq!(std::str::from_utf8(&output).unwrap(), expected); } }
30.829832
97
0.528654
e5e6f0f9341c178d9857da870db9100f1f81b6b1
9,448
use crate::{parser, InputValueType, Pos, Value}; use serde::Serialize; use std::collections::BTreeMap; use std::fmt::{self, Debug, Display, Formatter}; use std::marker::PhantomData; use thiserror::Error; /// Extensions to the error. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Default)] #[serde(transparent)] pub struct ErrorExtensionValues(BTreeMap<String, Value>); impl ErrorExtensionValues { /// Set an extension value. pub fn set(&mut self, name: impl AsRef<str>, value: impl Into<Value>) { self.0.insert(name.as_ref().to_string(), value.into()); } } /// An error in a GraphQL server. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct ServerError { /// An explanatory message of the error. pub message: String, /// Where the error occurred. #[serde(skip_serializing_if = "Vec::is_empty")] pub locations: Vec<Pos>, /// If the error occurred in a resolver, the path to the error. #[serde(skip_serializing_if = "Vec::is_empty")] pub path: Vec<PathSegment>, /// Extensions to the error. #[serde(skip_serializing_if = "error_extensions_is_empty")] pub extensions: Option<ErrorExtensionValues>, } fn error_extensions_is_empty(values: &Option<ErrorExtensionValues>) -> bool { match values { Some(values) => values.0.is_empty(), None => true, } } impl ServerError { /// Create a new server error with the message. pub fn new(message: impl Into<String>) -> Self { Self { message: message.into(), locations: Vec::new(), path: Vec::new(), extensions: None, } } /// Add a position to the error. pub fn at(mut self, at: Pos) -> Self { self.locations.push(at); self } /// Prepend a path to the error. pub fn path(mut self, path: PathSegment) -> Self { self.path.insert(0, path); self } } impl Display for ServerError { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.write_str(&self.message) } } impl From<ServerError> for Vec<ServerError> { fn from(single: ServerError) -> Self { vec![single] } } impl From<Error> for ServerError { fn from(e: Error) -> Self { e.into_server_error() } } impl From<parser::Error> for ServerError { fn from(e: parser::Error) -> Self { Self { message: e.to_string(), locations: e.positions().collect(), path: Vec::new(), extensions: None, } } } /// A segment of path to a resolver. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(untagged)] pub enum PathSegment { /// A field in an object. Field(String), /// An index in a list. Index(usize), } /// Alias for `Result<T, ServerError>`. pub type ServerResult<T> = std::result::Result<T, ServerError>; /// An error parsing an input value. /// /// This type is generic over T as it uses T's type name when converting to a regular error. #[derive(Debug)] pub struct InputValueError<T> { message: String, phantom: PhantomData<T>, } impl<T: InputValueType> InputValueError<T> { fn new(message: String) -> Self { Self { message, phantom: PhantomData, } } /// The expected input type did not match the actual input type. #[must_use] pub fn expected_type(actual: Value) -> Self { Self::new(format!( r#"Expected input type "{}", found {}."#, T::type_name(), actual )) } /// A custom error message. /// /// Any type that implements `Display` is automatically converted to this if you use the `?` /// operator. #[must_use] pub fn custom(msg: impl Display) -> Self { Self::new(format!(r#"Failed to parse "{}": {}"#, T::type_name(), msg)) } /// Propagate the error message to a different type. pub fn propagate<U: InputValueType>(self) -> InputValueError<U> { InputValueError::new(format!( r#"{} (occurred while parsing "{}")"#, self.message, U::type_name() )) } /// Convert the error into a server error. pub fn into_server_error(self) -> ServerError { ServerError::new(self.message) } } impl<T: InputValueType, E: Display> From<E> for InputValueError<T> { fn from(error: E) -> Self { Self::custom(error) } } /// An error parsing a value of type `T`. pub type InputValueResult<T> = Result<T, InputValueError<T>>; /// An error with a message and optional extensions. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct Error { /// The error message. pub message: String, /// Extensions to the error. #[serde(skip_serializing_if = "error_extensions_is_empty")] pub extensions: Option<ErrorExtensionValues>, } impl Error { /// Create an error from the given error message. pub fn new(message: impl Into<String>) -> Self { Self { message: message.into(), extensions: None, } } /// Convert the error to a server error. #[must_use] pub fn into_server_error(self) -> ServerError { ServerError { message: self.message, locations: Vec::new(), path: Vec::new(), extensions: self.extensions, } } } impl<T: Display> From<T> for Error { fn from(e: T) -> Self { Self { message: e.to_string(), extensions: None, } } } /// An alias for `Result<T, Error>`. pub type Result<T, E = Error> = std::result::Result<T, E>; /// An error parsing the request. #[derive(Debug, Error)] #[non_exhaustive] pub enum ParseRequestError { /// An IO error occurred. #[error("{0}")] Io(#[from] std::io::Error), /// The request's syntax was invalid. #[error("Invalid request: {0}")] InvalidRequest(serde_json::Error), /// The request's files map was invalid. #[error("Invalid files map: {0}")] InvalidFilesMap(serde_json::Error), /// The request's multipart data was invalid. #[error("Invalid multipart data")] #[cfg(feature = "multipart")] #[cfg_attr(feature = "nightly", doc(cfg(feature = "multipart")))] InvalidMultipart(multer::Error), /// Missing "operators" part for multipart request. #[error("Missing \"operators\" part")] MissingOperatorsPart, /// Missing "map" part for multipart request. #[error("Missing \"map\" part")] MissingMapPart, /// It's not an upload operation #[error("It's not an upload operation")] NotUpload, /// Files were missing the request. #[error("Missing files")] MissingFiles, /// The request's payload is too large, and this server rejected it. #[error("Payload too large")] PayloadTooLarge, /// The request is a batch request, but the server does not support batch requests. #[error("Batch requests are not supported")] UnsupportedBatch, } #[cfg(feature = "multipart")] impl From<multer::Error> for ParseRequestError { fn from(err: multer::Error) -> Self { match err { multer::Error::FieldSizeExceeded { .. } | multer::Error::StreamSizeExceeded { .. } => { ParseRequestError::PayloadTooLarge } _ => ParseRequestError::InvalidMultipart(err), } } } /// An error which can be extended into a `FieldError`. pub trait ErrorExtensions: Sized { /// Convert the error to a `Error`. fn extend(&self) -> Error; /// Add extensions to the error, using a callback to make the extensions. fn extend_with<C>(self, cb: C) -> Error where C: FnOnce(&Self, &mut ErrorExtensionValues), { let message = self.extend().message; let mut extensions = self.extend().extensions.unwrap_or_default(); cb(&self, &mut extensions); Error { message, extensions: Some(extensions), } } } impl ErrorExtensions for Error { fn extend(&self) -> Error { self.clone() } } // implementing for &E instead of E gives the user the possibility to implement for E which does // not conflict with this implementation acting as a fallback. impl<E: std::fmt::Display> ErrorExtensions for &E { fn extend(&self) -> Error { Error { message: format!("{}", self), extensions: None, } } } /// Extend a `Result`'s error value with [`ErrorExtensions`](trait.ErrorExtensions.html). pub trait ResultExt<T, E>: Sized { /// Extend the error value of the result with the callback. fn extend_err<C>(self, cb: C) -> Result<T> where C: FnOnce(&E, &mut ErrorExtensionValues); /// Extend the result to a `Result`. fn extend(self) -> Result<T>; } // This is implemented on E and not &E which means it cannot be used on foreign types. // (see example). impl<T, E> ResultExt<T, E> for std::result::Result<T, E> where E: ErrorExtensions + Send + Sync + 'static, { fn extend_err<C>(self, cb: C) -> Result<T> where C: FnOnce(&E, &mut ErrorExtensionValues), { match self { Err(err) => Err(err.extend_with(|e, ee| cb(e, ee))), Ok(value) => Ok(value), } } fn extend(self) -> Result<T> { match self { Err(err) => Err(err.extend()), Ok(value) => Ok(value), } } }
27.625731
99
0.599704
d5165750f9c234d3d168e0a98e128d13c2478a3f
2,218
//#![deny(warnings, missing_docs, missing_debug_implementations)] #![allow(unused_mut, unused_imports, unused_macros)] //! Fast and easy to use wrapper for League of Legends REST API and DDragon static data API. //! //! Narwhalol bundles both Riot League of Legends and DDragon wrapper clients in itself. extern crate hyper; pub mod api; #[cfg_attr(tarpaulin, skip)] pub mod constants; pub mod ddragon; #[cfg_attr(tarpaulin, skip)] #[allow(missing_docs)] pub mod dto; #[allow(missing_docs)] pub mod error; pub(crate) mod types; pub(crate) mod utils; pub use { api::LeagueClient, constants::{LanguageCode, RankedQueue, Region}, dto::api::*, dto::ddragon::*, }; #[cfg(test)] mod tests { use crate::{Summoner, LeagueClient, Region}; use std::time::Duration; #[test] #[cfg(feature = "async_std_rt")] fn ensure_different_runtimes_work_with_lib() { pretty_env_logger::try_init().unwrap_or(()); let lapi = LeagueClient::new(Region::RU).unwrap(); let sum = async_std::task::block_on(async { lapi.get_summoner_by_name("Vetro").await.unwrap() }); log::debug!("summoner from async_std: {:?}", sum); assert_eq!("Vetro", &sum.name); std::thread::sleep(Duration::from_secs(10)); } #[test] #[cfg(feature = "tokio_rt")] fn ensure_different_runtimes_work_with_lib() { pretty_env_logger::try_init().unwrap_or(()); let mut rt = tokio::runtime::Runtime::new().unwrap(); println!("in tokio rt"); let sum = rt.block_on(async { let sum = get_summoner_vetro().await; sum }); println!("summoner from tokio: {:?}", sum); assert_eq!("Vetro", &sum.name); std::thread::sleep(Duration::from_secs(10)); } #[test] #[cfg(feature = "smol_rt")] fn ensure_different_runtimes_work_with_lib() { pretty_env_logger::try_init().unwrap_or(()); let sum = smol::run(async { let sum = get_summoner_vetro().await; sum }); log::debug!("summoner from smol_rt: {:?}", sum); assert_eq!("Vetro", &sum.name); std::thread::sleep(Duration::from_secs(10)); } }
28.075949
92
0.616772
8fbafb6e6405712b7220c3bd84be8688b53bdefb
371
use crate::infrastructure::presentation::api_actix_web::models::Link; use actix_web::{HttpResponse, Responder}; pub async fn home() -> impl Responder { let links = vec![Link::new( "gets a todo by id".to_string(), "/users/{id}".to_string(), )]; HttpResponse::Ok() .set_header("content-type", "application/json") .json(links) }
28.538462
69
0.625337
1107b10fd2002920e62f0de5e1ffbf395fc75c7d
17,643
mod raw; use bitflags::bitflags; use itertools::Itertools; use std::ops::Range; macro_rules! round_to_next { ($num:expr, $round_to:expr) => {{ let n = $num; let to = $round_to; n + ((to - n % to) % to) }}; } pub struct Xbe { pub header: Header, pub sections: Vec<Section>, library_versions: Vec<raw::LibraryVersion>, logo_bitmap: raw::LogoBitmap, } impl Xbe { pub fn new(bytes: &[u8]) -> Result<Self, std::io::Error> { Ok(Self::from_raw(raw::Xbe::load(bytes)?)) } pub fn serialize(&self) -> Result<Vec<u8>, std::io::Error> { self.convert_to_raw().serialize() } pub fn get_next_virtual_address(&self) -> u32 { match self.sections.last() { None => 0, Some(s) => { let end = s.virtual_address + s.virtual_size; round_to_next!(end, 0x20) } } } pub fn get_next_virtual_address_after(&self, after: u32) -> u32 { round_to_next!(after, 0x20) } pub fn add_section( &mut self, name: String, flags: SectionFlags, data: Vec<u8>, virtual_address: u32, virtual_size: u32, ) { let raw_address = self .sections .iter() .sorted_by(|a, b| a.raw_address.cmp(&b.raw_address)) .last() // TODO: this assumes raw_size == virtual_size .map(|a| round_to_next!(a.raw_address + a.virtual_size, 0x1000)) .unwrap_or(0); let section = Section { name, flags, data, virtual_address, virtual_size, raw_address, digest: None, }; self.sections.push(section); } // TODO #[allow(dead_code)] pub fn get_bytes(&self, virtual_range: Range<u32>) -> Option<&[u8]> { let section = self.sections.iter().find(|s| { s.virtual_address <= virtual_range.start && s.virtual_address + s.virtual_size >= virtual_range.end })?; let start = (virtual_range.start - section.virtual_address) as usize; let end = (virtual_range.end - section.virtual_address) as usize; Some(&section.data[start..end]) } pub fn get_bytes_mut(&mut self, virtual_range: Range<u32>) -> Option<&mut [u8]> { let section = self.sections.iter_mut().find(|s| { s.virtual_address <= virtual_range.start && s.virtual_address + s.virtual_size >= virtual_range.end })?; let start = (virtual_range.start - section.virtual_address) as usize; let end = (virtual_range.end - section.virtual_address) as usize; Some(&mut section.data[start..end]) } fn convert_to_raw(&self) -> raw::Xbe { let base_address = 0x10000; let image_header_size = 0x184; let certificate = raw::Certificate { size: raw::Certificate::SIZE, time_date: self.header.cert_time_date, title_id: self.header.title_id.unwrap_or(0), title_name: self.header.title_name, alternate_title_ids: [0u8; 0x40], allowed_media: self.header.allowed_media.bits, game_region: self.header.game_region.bits, game_ratings: self.header.game_ratings.unwrap_or(0xFFFFFFFF), disk_number: 0, version: self.header.cert_version, lan_key: self.header.lan_key.unwrap_or([0u8; 0x10]), signature_key: self.header.signature_key.unwrap_or([0u8; 0x10]), alternate_signature_keys: self.header.alternate_signature_keys.unwrap_or([0u8; 0x100]), unknown: self.header.unknown.clone(), }; let certificate_size = raw::Certificate::SIZE; let mut section_names_size = 0; let mut section_name_offsets = vec![]; let section_names: Vec<String> = self .sections .iter() .map(|s| { section_name_offsets.push(section_names_size); section_names_size += s.name.len() as u32; s.name.clone() }) .collect(); section_names_size = round_to_next!(section_names_size, 4); // Size of sections headers plus size of head/tail reference pages let section_headers_size = self.sections.len() as u32 * 0x38; let section_page_reference_size = self.sections.len() as u32 * 2 + 2; // TODO: This assumes the header will never grow past 0x1000 bytes // Fixing this requires managing more pointers like TLS, Kernel Thunk, // and Entry Point, as it will move the vanilla sections // (Actually these may all be virtual addresses, entry point certainly is, investigate more) let section_headers: Vec<raw::SectionHeader> = self .sections .iter() .enumerate() .map(|(i, s)| raw::SectionHeader { section_flags: s.flags.bits, virtual_address: s.virtual_address, virtual_size: s.virtual_size, raw_address: s.raw_address, raw_size: s.data.len() as u32, section_name_address: base_address + image_header_size + certificate_size + section_headers_size + section_page_reference_size + section_name_offsets[i], section_name_reference_count: 0, head_shared_page_reference_count_address: base_address + image_header_size + certificate_size + section_headers_size + i as u32 * 2, tail_shared_page_reference_count_address: base_address + image_header_size + certificate_size + section_headers_size + i as u32 * 2 + 2, section_digest: s.digest.unwrap_or([0u8; 0x14]), }) .collect(); let library_versions = self.library_versions.clone(); let kernel_index = library_versions .iter() .position(|l| l.library_name.eq(b"XBOXKRNL")) .expect("No Kernel Library!"); let xapi_index = library_versions .iter() .position(|l| l.library_name.eq(b"XAPILIB\0")) .expect("No XAPILIB!"); let library_versions_size = library_versions.len() as u32 * 0x10; let sections: Vec<raw::Section> = self .sections .iter() .map(|s| raw::Section { bytes: s.data.clone(), }) .collect(); let size_of_image = section_headers .iter() .sorted_by(|a, b| a.virtual_address.cmp(&b.virtual_address)) .last() .map(|x| round_to_next!(x.virtual_address + x.virtual_size, 0x20)) .unwrap_or(base_address) - base_address; // pathname and filename are part of the same string, so it's not added to the total let debug_strings_size = self.header.debug_unicode_filename.len() as u32 * 2 + self.header.debug_pathname.len() as u32; let debug_unicode_filename_address = image_header_size + certificate_size + section_headers_size + section_page_reference_size + section_names_size + library_versions_size + base_address; let debug_pathname_address = debug_unicode_filename_address + self.header.debug_unicode_filename.len() as u32 * 2; let debug_filename_address = debug_pathname_address + self .header .debug_pathname .rfind('\\') .expect("Malformed debug path") as u32 + 1; let logo_bitmap_size = self.logo_bitmap.bitmap.len() as u32; let mut size_of_headers = image_header_size + certificate_size + section_headers_size + section_page_reference_size + section_names_size + library_versions_size + debug_strings_size + logo_bitmap_size; size_of_headers = round_to_next!(size_of_headers, 4); let image_header = raw::ImageHeader { magic_number: b"XBEH".to_owned(), digital_signature: self.header.digital_signature.unwrap_or([0u8; 256]), base_address, size_of_headers, size_of_image, size_of_image_header: image_header_size, time_date: self.header.image_time_date, certificate_address: image_header_size + base_address, number_of_sections: self.sections.len() as u32, section_headers_address: image_header_size + certificate_size + base_address, initialization_flags: 5, entry_point: self.header.entry_point, tls_address: self.header.tls_address, pe_stack_commit: self.header.pe.stack_commit, pe_heap_reserve: self.header.pe.heap_reserve, pe_head_commit: self.header.pe.head_commit, pe_base_address: self.header.pe.base_address, pe_size_of_image: self.header.pe.size_of_image, pe_checksum: self.header.pe.checksum, pe_time_date: self.header.pe.timedate, debug_pathname_address, debug_filename_address, debug_unicode_filename_address, kernel_image_thunk_address: self.header.kernel_image_thunk_address, non_kernel_import_directory_address: 0, number_of_library_versions: self.library_versions.len() as u32, library_versions_address: image_header_size + certificate_size + section_headers_size + section_page_reference_size + section_names_size + base_address, kernel_library_version_address: image_header_size + certificate_size + section_headers_size + section_page_reference_size + section_names_size + kernel_index as u32 * 0x10 + base_address, xapi_library_version_address: image_header_size + certificate_size + section_headers_size + section_page_reference_size + section_names_size + xapi_index as u32 * 0x10 + base_address, logo_bitmap_address: image_header_size + certificate_size + section_headers_size + section_page_reference_size + section_names_size + library_versions_size + debug_strings_size + base_address, logo_bitmap_size, }; raw::Xbe { image_header, certificate, section_headers, section_names, library_versions, debug_pathname: self.header.debug_pathname.clone(), debug_filename: self.header.debug_filename.clone(), debug_unicode_filename: self.header.debug_unicode_filename.clone(), logo_bitmap: self.logo_bitmap.clone(), sections, } } fn from_raw(xbe: raw::Xbe) -> Self { let pe = PE { stack_commit: xbe.image_header.pe_stack_commit, heap_reserve: xbe.image_header.pe_heap_reserve, head_commit: xbe.image_header.pe_head_commit, base_address: xbe.image_header.pe_base_address, size_of_image: xbe.image_header.pe_size_of_image, checksum: xbe.image_header.pe_checksum, timedate: xbe.image_header.pe_time_date, }; let header = Header { digital_signature: Some(xbe.image_header.digital_signature), debug_pathname: xbe.debug_pathname, debug_filename: xbe.debug_filename, debug_unicode_filename: xbe.debug_unicode_filename, image_time_date: xbe.image_header.time_date, entry_point: xbe.image_header.entry_point, tls_address: xbe.image_header.tls_address, pe, kernel_image_thunk_address: xbe.image_header.kernel_image_thunk_address, cert_time_date: xbe.certificate.time_date, title_id: Some(xbe.certificate.title_id), title_name: xbe.certificate.title_name, allowed_media: AllowedMedia::from_bits_truncate(xbe.certificate.allowed_media), game_ratings: Some(xbe.certificate.game_ratings), game_region: GameRegion::from_bits_truncate(xbe.certificate.game_region), cert_version: xbe.certificate.version, lan_key: Some(xbe.certificate.lan_key), signature_key: Some(xbe.certificate.signature_key), alternate_signature_keys: Some(xbe.certificate.alternate_signature_keys), unknown: xbe.certificate.unknown, }; let sections = xbe .sections .into_iter() .zip(xbe.section_headers.into_iter()) .zip(xbe.section_names.into_iter()) .map(|((sec, hdr), name)| Section { name, flags: SectionFlags::from_bits_truncate(hdr.section_flags), virtual_address: hdr.virtual_address, virtual_size: hdr.virtual_size, data: sec.bytes, raw_address: hdr.raw_address, digest: Some(hdr.section_digest), }) .collect(); Xbe { header, sections, library_versions: xbe.library_versions, logo_bitmap: xbe.logo_bitmap, } } } pub struct Header { pub digital_signature: Option<[u8; 0x100]>, pub debug_pathname: String, pub debug_filename: String, pub debug_unicode_filename: Vec<u16>, pub image_time_date: u32, pub entry_point: u32, pub tls_address: u32, pub pe: PE, pub kernel_image_thunk_address: u32, pub cert_time_date: u32, pub title_id: Option<u32>, pub title_name: [u8; 0x50], pub allowed_media: AllowedMedia, pub game_ratings: Option<u32>, pub game_region: GameRegion, pub cert_version: u32, pub lan_key: Option<[u8; 0x10]>, pub signature_key: Option<[u8; 0x10]>, pub alternate_signature_keys: Option<[u8; 0x100]>, pub unknown: Vec<u8>, } pub struct PE { stack_commit: u32, heap_reserve: u32, head_commit: u32, base_address: u32, size_of_image: u32, checksum: u32, timedate: u32, } bitflags! { pub struct AllowedMedia : u32 { const XBEIMAGE_MEDIA_TYPE_HARD_DISK = 0x00000001; const XBEIMAGE_MEDIA_TYPE_DVD_X2 = 0x00000002; const XBEIMAGE_MEDIA_TYPE_DVD_CD = 0x00000004; const XBEIMAGE_MEDIA_TYPE_CD = 0x00000008; const XBEIMAGE_MEDIA_TYPE_DVD_5_RO = 0x00000010; const XBEIMAGE_MEDIA_TYPE_DVD_9_RO = 0x00000020; const XBEIMAGE_MEDIA_TYPE_DVD_5_RW = 0x00000040; const XBEIMAGE_MEDIA_TYPE_DVD_9_RW = 0x00000080; const XBEIMAGE_MEDIA_TYPE_DONGLE = 0x00000100; const XBEIMAGE_MEDIA_TYPE_MEDIA_BOARD = 0x00000200; const XBEIMAGE_MEDIA_TYPE_NONSECURE_HARD_DISK = 0x40000000; const XBEIMAGE_MEDIA_TYPE_NONSECURE_MODE = 0x80000000; const XBEIMAGE_MEDIA_TYPE_MEDIA_MASK = 0x00FFFFFF; } } bitflags! { pub struct GameRegion : u32 { const REGION_NA = 0x1; const REGION_JAPAN = 0x2; const REGION_REST_OF_WORLD = 0x4; const REGION_MANUFACTURING = 0x80000000; } } pub struct Section { pub name: String, pub flags: SectionFlags, pub data: Vec<u8>, pub virtual_address: u32, pub virtual_size: u32, raw_address: u32, digest: Option<[u8; 0x14]>, } impl std::fmt::Debug for Section { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { f.debug_struct("Section") .field("Name", &self.name) .field("Virtual Address", &self.virtual_address) .field("Virtual Size", &self.virtual_size) .field("Raw Address", &self.raw_address) .finish() } } bitflags! { pub struct SectionFlags : u32 { const WRITABLE = 0x1; const PRELOAD = 0x2; const EXECUTABLE= 0x4; const INSERTED_FILE = 0x8; const HEAD_PAGE_READ_ONLY = 0x10; const TAIL_PAGE_READ_ONLY = 0x20; } } #[cfg(test)] mod tests { use super::*; #[test] /// Read an xbe and immediately serialize it to a new file, asserting that both files /// are identical fn vanilla_serialization() -> Result<(), std::io::Error> { use sha1::{Digest, Sha1}; let default_bytes = std::fs::read("test/bin/default.xbe")?; let default_hash = { let mut hasher = Sha1::new(); hasher.update(&default_bytes); hasher.finalize() }; let xbe = Xbe::new(&default_bytes)?; let bytes = xbe.serialize()?; let output_hash = { let mut hasher = Sha1::new(); hasher.update(&bytes); hasher.finalize() }; assert_eq!(*default_hash, *output_hash); Ok(()) } }
36.679834
100
0.586692
38f64b667587cea8185391bbb7424bfdcbabfefd
546
pub mod condition_resolvers; pub mod conditions; pub mod ir_helpers; mod collections; mod print; mod print_items; mod printer; #[cfg(feature = "tracing")] mod tracing; mod write_items; mod writer; pub(crate) mod id; pub mod tokens; pub mod utils; pub use print::format; pub use print::print; #[cfg(feature = "tracing")] pub use print::trace_printing; pub use print::PrintOptions; #[cfg(feature = "tracing")] pub use print::TracingResult; pub use print_items::*; use printer::*; #[cfg(feature = "tracing")] use tracing::*; use write_items::*;
17.612903
30
0.725275
d541969a697a32046e22c0810ab5bedb19ec38ea
3,841
use crate::resources::market::Currency; use oxygengine_core::id::ID; use std::collections::HashMap; pub type BankAccountId = ID<BankAccount<()>>; #[derive(Debug, Clone)] pub enum BankError<T> where T: Currency, { AccountDoesNotExists(BankAccountId), CouldNotDeposit(BankAccountId, T), CouldNotWithdraw(BankAccountId, T), CouldNotTransfer(BankAccountId, BankAccountId, T), } #[derive(Debug, Default, Clone)] pub struct BankAccount<T> where T: Currency + std::fmt::Debug + Default + Clone + Send + Sync, { pub value: T, } #[derive(Debug, Clone)] pub struct Bank<T> where T: Currency + std::fmt::Debug + Default + Clone + Send + Sync, { accounts: HashMap<BankAccountId, BankAccount<T>>, } impl<T> Default for Bank<T> where T: Currency + std::fmt::Debug + Default + Clone + Send + Sync, { fn default() -> Self { Self { accounts: Default::default(), } } } impl<T> Bank<T> where T: Currency + std::fmt::Debug + Default + Clone + Send + Sync, { pub fn create_account(&mut self) -> BankAccountId { let id = BankAccountId::new(); self.accounts.insert(id, Default::default()); id } pub fn remove_account(&mut self, id: BankAccountId) -> Result<T, BankError<T>> { match self.accounts.remove(&id) { Some(account) => Ok(account.value), None => Err(BankError::AccountDoesNotExists(id)), } } pub fn accounts(&self) -> impl Iterator<Item = (BankAccountId, &BankAccount<T>)> { self.accounts.iter().map(|(id, account)| (*id, account)) } pub fn deposit(&mut self, id: BankAccountId, value: T) -> Result<(), BankError<T>> { match self.accounts.get_mut(&id) { Some(account) => match account.value.accumulate(value) { Ok(value) => { account.value = value; Ok(()) } Err(_) => Err(BankError::CouldNotDeposit(id, value)), }, None => Err(BankError::AccountDoesNotExists(id)), } } pub fn withdraw(&mut self, id: BankAccountId, value: T) -> Result<T, BankError<T>> { match self.accounts.get_mut(&id) { Some(account) => match account.value.take(value) { Ok((left, taken)) => { account.value = left; Ok(taken) } Err(_) => Err(BankError::CouldNotDeposit(id, value)), }, None => Err(BankError::AccountDoesNotExists(id)), } } pub fn transfer( &mut self, from: BankAccountId, to: BankAccountId, value: T, ) -> Result<(), BankError<T>> { if from == to { return Ok(()); } let from_value = match self.accounts.get(&from) { Some(from) => from.value, None => return Err(BankError::AccountDoesNotExists(from)), }; let to_value = match self.accounts.get(&to) { Some(to) => to.value, None => return Err(BankError::AccountDoesNotExists(to)), }; let (from_value, to_value) = match from_value.exchange(to_value, value) { Ok(result) => result, Err(_) => return Err(BankError::CouldNotTransfer(from, to, value)), }; self.accounts.get_mut(&from).unwrap().value = from_value; self.accounts.get_mut(&to).unwrap().value = to_value; Ok(()) } pub fn batched_transfers<'a>( &'a mut self, iter: impl Iterator<Item = (BankAccountId, BankAccountId, T)> + 'a, ) -> impl Iterator<Item = BankError<T>> + 'a { iter.filter_map(|(from, to, value)| match self.transfer(from, to, value) { Ok(_) => None, Err(error) => Some(error), }) } }
30.007813
88
0.554022
ffc1aeaab8f15b75f97bc79f96b8bb97058477c2
19,682
use std::collections::{HashMap, BTreeSet, HashSet}; use std::fs; use std::path::{PathBuf, Path}; use std::str; use std::sync::{Mutex, Arc}; use std::process::{Stdio, Output}; use core::PackageId; use util::{CargoResult, Human}; use util::{internal, ChainError, profile, paths}; use util::{Freshness, ProcessBuilder, read2}; use util::errors::{process_error, ProcessError}; use super::job::Work; use super::job_queue::JobState; use super::{fingerprint, Kind, Context, Unit}; use super::CommandType; /// Contains the parsed output of a custom build script. #[derive(Clone, Debug, Hash)] pub struct BuildOutput { /// Paths to pass to rustc with the `-L` flag pub library_paths: Vec<PathBuf>, /// Names and link kinds of libraries, suitable for the `-l` flag pub library_links: Vec<String>, /// Various `--cfg` flags to pass to the compiler pub cfgs: Vec<String>, /// Metadata to pass to the immediate dependencies pub metadata: Vec<(String, String)>, /// Glob paths to trigger a rerun of this build script. pub rerun_if_changed: Vec<String>, /// Warnings generated by this build, pub warnings: Vec<String>, } pub type BuildMap = HashMap<(PackageId, Kind), BuildOutput>; pub struct BuildState { pub outputs: Mutex<BuildMap>, overrides: HashMap<(String, Kind), BuildOutput>, } #[derive(Default)] pub struct BuildScripts { // Cargo will use this `to_link` vector to add -L flags to compiles as we // propagate them upwards towards the final build. Note, however, that we // need to preserve the ordering of `to_link` to be topologically sorted. // This will ensure that build scripts which print their paths properly will // correctly pick up the files they generated (if there are duplicates // elsewhere). // // To preserve this ordering, the (id, kind) is stored in two places, once // in the `Vec` and once in `seen_to_link` for a fast lookup. We maintain // this as we're building interactively below to ensure that the memory // usage here doesn't blow up too much. // // For more information, see #2354 pub to_link: Vec<(PackageId, Kind)>, seen_to_link: HashSet<(PackageId, Kind)>, pub plugins: BTreeSet<PackageId>, } /// Prepares a `Work` that executes the target as a custom build script. /// /// The `req` given is the requirement which this run of the build script will /// prepare work for. If the requirement is specified as both the target and the /// host platforms it is assumed that the two are equal and the build script is /// only run once (not twice). pub fn prepare<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CargoResult<(Work, Work, Freshness)> { let _p = profile::start(format!("build script prepare: {}/{}", unit.pkg, unit.target.name())); let overridden = cx.build_state.has_override(unit); let (work_dirty, work_fresh) = if overridden { (Work::new(|_| Ok(())), Work::new(|_| Ok(()))) } else { try!(build_work(cx, unit)) }; // Now that we've prep'd our work, build the work needed to manage the // fingerprint and then start returning that upwards. let (freshness, dirty, fresh) = try!(fingerprint::prepare_build_cmd(cx, unit)); Ok((work_dirty.then(dirty), work_fresh.then(fresh), freshness)) } fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CargoResult<(Work, Work)> { let host_unit = Unit { kind: Kind::Host, ..*unit }; let (script_output, build_output) = { (cx.layout(&host_unit).build(unit.pkg), cx.layout(unit).build_out(unit.pkg)) }; // Building the command to execute let to_exec = script_output.join(unit.target.name()); // Start preparing the process to execute, starting out with some // environment variables. Note that the profile-related environment // variables are not set with this the build script's profile but rather the // package's library profile. let profile = cx.lib_profile(unit.pkg.package_id()); let to_exec = to_exec.into_os_string(); let mut p = try!(super::process(CommandType::Host(to_exec), unit.pkg, cx)); p.env("OUT_DIR", &build_output) .env("CARGO_MANIFEST_DIR", unit.pkg.root()) .env("NUM_JOBS", &cx.jobs().to_string()) .env("TARGET", &match unit.kind { Kind::Host => cx.host_triple(), Kind::Target => cx.target_triple(), }) .env("DEBUG", &profile.debuginfo.to_string()) .env("OPT_LEVEL", &profile.opt_level) .env("PROFILE", if cx.build_config.release {"release"} else {"debug"}) .env("HOST", cx.host_triple()) .env("RUSTC", &try!(cx.config.rustc()).path) .env("RUSTDOC", &*try!(cx.config.rustdoc())); if let Some(links) = unit.pkg.manifest().links(){ p.env("CARGO_MANIFEST_LINKS", links); } // Be sure to pass along all enabled features for this package, this is the // last piece of statically known information that we have. if let Some(features) = cx.resolve.features(unit.pkg.package_id()) { for feat in features.iter() { p.env(&format!("CARGO_FEATURE_{}", super::envify(feat)), "1"); } } // Gather the set of native dependencies that this package has along with // some other variables to close over. // // This information will be used at build-time later on to figure out which // sorts of variables need to be discovered at that time. let lib_deps = { try!(cx.dep_run_custom_build(unit)).iter().filter_map(|unit| { if unit.profile.run_custom_build { Some((unit.pkg.manifest().links().unwrap().to_string(), unit.pkg.package_id().clone())) } else { None } }).collect::<Vec<_>>() }; let pkg_name = unit.pkg.to_string(); let build_state = cx.build_state.clone(); let id = unit.pkg.package_id().clone(); let output_file = build_output.parent().unwrap().join("output"); let all = (id.clone(), pkg_name.clone(), build_state.clone(), output_file.clone()); let build_scripts = super::load_build_deps(cx, unit); let kind = unit.kind; // Check to see if the build script as already run, and if it has keep // track of whether it has told us about some explicit dependencies let prev_output = BuildOutput::parse_file(&output_file, &pkg_name).ok(); let rerun_if_changed = match prev_output { Some(ref prev) => prev.rerun_if_changed.clone(), None => Vec::new(), }; cx.build_explicit_deps.insert(*unit, (output_file.clone(), rerun_if_changed)); try!(fs::create_dir_all(&cx.layout(&host_unit).build(unit.pkg))); try!(fs::create_dir_all(&cx.layout(unit).build(unit.pkg))); // Prepare the unit of "dirty work" which will actually run the custom build // command. // // Note that this has to do some extra work just before running the command // to determine extra environment variables and such. let dirty = Work::new(move |state| { // Make sure that OUT_DIR exists. // // If we have an old build directory, then just move it into place, // otherwise create it! if fs::metadata(&build_output).is_err() { try!(fs::create_dir(&build_output).chain_error(|| { internal("failed to create script output directory for \ build command") })); } // For all our native lib dependencies, pick up their metadata to pass // along to this custom build command. We're also careful to augment our // dynamic library search path in case the build script depended on any // native dynamic libraries. { let build_state = build_state.outputs.lock().unwrap(); for (name, id) in lib_deps { let key = (id.clone(), kind); let state = try!(build_state.get(&key).chain_error(|| { internal(format!("failed to locate build state for env \ vars: {}/{:?}", id, kind)) })); let data = &state.metadata; for &(ref key, ref value) in data.iter() { p.env(&format!("DEP_{}_{}", super::envify(&name), super::envify(key)), value); } } if let Some(build_scripts) = build_scripts { try!(super::add_plugin_deps(&mut p, &build_state, &build_scripts)); } } // And now finally, run the build command itself! state.running(&p); let cmd = p.into_process_builder(); let output = try!(stream_output(state, &cmd).map_err(|mut e| { e.desc = format!("failed to run custom build command for `{}`\n{}", pkg_name, e.desc); Human(e) })); try!(paths::write(&output_file, &output.stdout)); // After the build command has finished running, we need to be sure to // remember all of its output so we can later discover precisely what it // was, even if we don't run the build command again (due to freshness). // // This is also the location where we provide feedback into the build // state informing what variables were discovered via our script as // well. let parsed_output = try!(BuildOutput::parse(&output.stdout, &pkg_name)); build_state.insert(id, kind, parsed_output); Ok(()) }); // Now that we've prepared our work-to-do, we need to prepare the fresh work // itself to run when we actually end up just discarding what we calculated // above. let fresh = Work::new(move |_tx| { let (id, pkg_name, build_state, output_file) = all; let output = match prev_output { Some(output) => output, None => try!(BuildOutput::parse_file(&output_file, &pkg_name)), }; build_state.insert(id, kind, output); Ok(()) }); Ok((dirty, fresh)) } impl BuildState { pub fn new(config: &super::BuildConfig) -> BuildState { let mut overrides = HashMap::new(); let i1 = config.host.overrides.iter().map(|p| (p, Kind::Host)); let i2 = config.target.overrides.iter().map(|p| (p, Kind::Target)); for ((name, output), kind) in i1.chain(i2) { overrides.insert((name.clone(), kind), output.clone()); } BuildState { outputs: Mutex::new(HashMap::new()), overrides: overrides, } } fn insert(&self, id: PackageId, kind: Kind, output: BuildOutput) { self.outputs.lock().unwrap().insert((id, kind), output); } fn has_override(&self, unit: &Unit) -> bool { let key = unit.pkg.manifest().links().map(|l| (l.to_string(), unit.kind)); match key.and_then(|k| self.overrides.get(&k)) { Some(output) => { self.insert(unit.pkg.package_id().clone(), unit.kind, output.clone()); true } None => false, } } } impl BuildOutput { pub fn parse_file(path: &Path, pkg_name: &str) -> CargoResult<BuildOutput> { let contents = try!(paths::read_bytes(path)); BuildOutput::parse(&contents, pkg_name) } // Parses the output of a script. // The `pkg_name` is used for error messages. pub fn parse(input: &[u8], pkg_name: &str) -> CargoResult<BuildOutput> { let mut library_paths = Vec::new(); let mut library_links = Vec::new(); let mut cfgs = Vec::new(); let mut metadata = Vec::new(); let mut rerun_if_changed = Vec::new(); let mut warnings = Vec::new(); let whence = format!("build script of `{}`", pkg_name); for line in input.split(|b| *b == b'\n') { let line = match str::from_utf8(line) { Ok(line) => line.trim(), Err(..) => continue, }; let mut iter = line.splitn(2, ':'); if iter.next() != Some("cargo") { // skip this line since it doesn't start with "cargo:" continue; } let data = match iter.next() { Some(val) => val, None => continue }; // getting the `key=value` part of the line let mut iter = data.splitn(2, '='); let key = iter.next(); let value = iter.next(); let (key, value) = match (key, value) { (Some(a), Some(b)) => (a, b.trim_right()), // line started with `cargo:` but didn't match `key=value` _ => bail!("Wrong output in {}: `{}`", whence, line), }; match key { "rustc-flags" => { let (libs, links) = try!( BuildOutput::parse_rustc_flags(value, &whence) ); library_links.extend(links.into_iter()); library_paths.extend(libs.into_iter()); } "rustc-link-lib" => library_links.push(value.to_string()), "rustc-link-search" => library_paths.push(PathBuf::from(value)), "rustc-cfg" => cfgs.push(value.to_string()), "warning" => warnings.push(value.to_string()), "rerun-if-changed" => rerun_if_changed.push(value.to_string()), _ => metadata.push((key.to_string(), value.to_string())), } } Ok(BuildOutput { library_paths: library_paths, library_links: library_links, cfgs: cfgs, metadata: metadata, rerun_if_changed: rerun_if_changed, warnings: warnings, }) } pub fn parse_rustc_flags(value: &str, whence: &str) -> CargoResult<(Vec<PathBuf>, Vec<String>)> { let value = value.trim(); let mut flags_iter = value.split(|c: char| c.is_whitespace()) .filter(|w| w.chars().any(|c| !c.is_whitespace())); let (mut library_links, mut library_paths) = (Vec::new(), Vec::new()); loop { let flag = match flags_iter.next() { Some(f) => f, None => break }; if flag != "-l" && flag != "-L" { bail!("Only `-l` and `-L` flags are allowed in {}: `{}`", whence, value) } let value = match flags_iter.next() { Some(v) => v, None => bail!("Flag in rustc-flags has no value in {}: `{}`", whence, value) }; match flag { "-l" => library_links.push(value.to_string()), "-L" => library_paths.push(PathBuf::from(value)), // was already checked above _ => bail!("only -l and -L flags are allowed") }; } Ok((library_paths, library_links)) } } /// Compute the `build_scripts` map in the `Context` which tracks what build /// scripts each package depends on. /// /// The global `build_scripts` map lists for all (package, kind) tuples what set /// of packages' build script outputs must be considered. For example this lists /// all dependencies' `-L` flags which need to be propagated transitively. /// /// The given set of targets to this function is the initial set of /// targets/profiles which are being built. pub fn build_map<'b, 'cfg>(cx: &mut Context<'b, 'cfg>, units: &[Unit<'b>]) -> CargoResult<()> { let mut ret = HashMap::new(); for unit in units { try!(build(&mut ret, cx, unit)); } cx.build_scripts.extend(ret.into_iter().map(|(k, v)| { (k, Arc::new(v)) })); return Ok(()); // Recursive function to build up the map we're constructing. This function // memoizes all of its return values as it goes along. fn build<'a, 'b, 'cfg>(out: &'a mut HashMap<Unit<'b>, BuildScripts>, cx: &Context<'b, 'cfg>, unit: &Unit<'b>) -> CargoResult<&'a BuildScripts> { // Do a quick pre-flight check to see if we've already calculated the // set of dependencies. if out.contains_key(unit) { return Ok(&out[unit]) } let mut ret = BuildScripts::default(); if !unit.target.is_custom_build() && unit.pkg.has_custom_build() { add_to_link(&mut ret, unit.pkg.package_id(), unit.kind); } for unit in try!(cx.dep_targets(unit)).iter() { let dep_scripts = try!(build(out, cx, unit)); if unit.target.for_host() { ret.plugins.extend(dep_scripts.to_link.iter() .map(|p| &p.0).cloned()); } else if unit.target.linkable() { for &(ref pkg, kind) in dep_scripts.to_link.iter() { add_to_link(&mut ret, pkg, kind); } } } let prev = out.entry(*unit).or_insert(BuildScripts::default()); for (pkg, kind) in ret.to_link { add_to_link(prev, &pkg, kind); } prev.plugins.extend(ret.plugins); Ok(prev) } // When adding an entry to 'to_link' we only actually push it on if the // script hasn't seen it yet (e.g. we don't push on duplicates). fn add_to_link(scripts: &mut BuildScripts, pkg: &PackageId, kind: Kind) { if scripts.seen_to_link.insert((pkg.clone(), kind)) { scripts.to_link.push((pkg.clone(), kind)); } } } fn stream_output(state: &JobState, cmd: &ProcessBuilder) -> Result<Output, ProcessError> { let mut stdout = Vec::new(); let mut stderr = Vec::new(); let status = try!((|| { let mut cmd = cmd.build_command(); cmd.stdout(Stdio::piped()) .stderr(Stdio::piped()) .stdin(Stdio::null()); let mut child = try!(cmd.spawn()); let out = child.stdout.take().unwrap(); let err = child.stderr.take().unwrap(); try!(read2(out, err, &mut |is_out, data, eof| { let idx = if eof { data.len() } else { match data.iter().rposition(|b| *b == b'\n') { Some(i) => i + 1, None => return, } }; let data = data.drain(..idx); let dst = if is_out {&mut stdout} else {&mut stderr}; let start = dst.len(); dst.extend(data); let s = String::from_utf8_lossy(&dst[start..]); if is_out { state.stdout(&s); } else { state.stderr(&s); } })); child.wait() })().map_err(|e| { let msg = format!("could not exeute process {}", cmd); process_error(&msg, Some(e), None, None) })); let output = Output { stdout: stdout, stderr: stderr, status: status, }; if !output.status.success() { let msg = format!("process didn't exit successfully: {}", cmd); Err(process_error(&msg, None, Some(&status), Some(&output))) } else { Ok(output) } }
39.522088
85
0.558277
ed3a6eedd69ac7c01ee2f9cb46e0e85e96e0c249
5,195
//! BIP39 mnemonic phrases use super::{ bits::{BitWriter, IterExt}, language::Language, }; use crate::{Error, KeyMaterial, Path, KEY_SIZE}; use alloc::string::String; use core::convert::TryInto; use rand_core::{CryptoRng, RngCore}; use sha2::{Digest, Sha256}; use zeroize::{Zeroize, Zeroizing}; #[cfg(feature = "bip39")] use { super::seed::{Seed, SEED_SIZE}, hmac::Hmac, sha2::Sha512, }; /// Number of PBKDF2 rounds to perform when deriving the seed #[cfg(feature = "bip39")] const PBKDF2_ROUNDS: u32 = 2048; /// Source entropy for a BIP39 mnemonic phrase pub type Entropy = [u8; KEY_SIZE]; /// BIP39 mnemonic phrases: sequences of words representing cryptographic keys. #[derive(Clone)] pub struct Phrase { /// Language language: Language, /// Source entropy for this phrase entropy: Entropy, /// Mnemonic phrase phrase: String, } impl Phrase { /// Create a random BIP39 mnemonic phrase. pub fn random(mut rng: impl RngCore + CryptoRng, language: Language) -> Self { let mut entropy = Entropy::default(); rng.fill_bytes(&mut entropy); Self::from_entropy(entropy, language) } /// Create a new BIP39 mnemonic phrase from the given entropy pub fn from_entropy(entropy: Entropy, language: Language) -> Self { let wordlist = language.wordlist(); let checksum_byte = Sha256::digest(entropy.as_ref()).as_slice()[0]; // First, create a byte iterator for the given entropy and the first byte of the // hash of the entropy that will serve as the checksum (up to 8 bits for biggest // entropy source). // // Then we transform that into a bits iterator that returns 11 bits at a // time (as u16), which we can map to the words on the `wordlist`. // // Given the entropy is of correct size, this ought to give us the correct word // count. let phrase = entropy .iter() .chain(Some(&checksum_byte)) .bits() .map(|bits| wordlist.get_word(bits)) .join(" "); Phrase { phrase, language, entropy, } } /// Create a new BIP39 mnemonic phrase from the given string. /// /// The phrase supplied will be checked for word length and validated /// according to the checksum specified in BIP0039. pub fn new<S>(phrase: S, language: Language) -> Result<Self, Error> where S: AsRef<str>, { let phrase = phrase.as_ref(); let wordmap = language.wordmap(); // Preallocate enough space for the longest possible word list let mut bits = BitWriter::with_capacity(264); for word in phrase.split(" ") { bits.push(wordmap.get_bits(&word)?); } let mut entropy = Zeroizing::new(bits.into_bytes()); if entropy.len() != KEY_SIZE + 1 { return Err(Error); } let actual_checksum = entropy[KEY_SIZE]; // Truncate to get rid of the byte containing the checksum entropy.truncate(KEY_SIZE); let expected_checksum = Sha256::digest(&entropy).as_slice()[0]; if actual_checksum != expected_checksum { Err(Error)?; } Ok(Self::from_entropy( entropy.as_slice().try_into().unwrap(), language, )) } /// Get source entropy for this phrase. pub fn entropy(&self) -> &Entropy { &self.entropy } /// Get the mnemonic phrase as a string reference. pub fn phrase(&self) -> &str { &self.phrase } /// Language this phrase's wordlist is for pub fn language(&self) -> Language { self.language } /// Convert this mnemonic phrase's entropy directly into key material. /// If you are looking for the shortest path between a mnemonic phrase /// and a key derivation hierarchy, this is it. /// /// Note: that this does not follow the normal BIP39 derivation, which /// first applies PBKDF2 along with a secondary password. Use `to_seed` /// if you are interested in BIP39 compatibility. /// Derive a BIP32 subkey from this seed pub fn derive_subkey(self, path: impl AsRef<Path>) -> KeyMaterial { KeyMaterial::from(self).derive_subkey(path) } /// Convert this mnemonic phrase into the BIP39 seed value. /// /// This is only available when the `bip39` Cargo feature is enabled. #[cfg(feature = "bip39")] pub fn to_seed(&self, password: &str) -> Seed { let salt = Zeroizing::new(format!("mnemonic{}", password)); let mut seed = [0u8; SEED_SIZE]; pbkdf2::pbkdf2::<Hmac<Sha512>>( &self.phrase.as_bytes(), salt.as_bytes(), PBKDF2_ROUNDS, &mut seed, ); Seed(seed) } } impl From<Phrase> for KeyMaterial { /// Convert to `KeyMaterial` using an empty password fn from(phrase: Phrase) -> KeyMaterial { KeyMaterial::from_bytes(&phrase.entropy).unwrap() } } impl Drop for Phrase { fn drop(&mut self) { self.phrase.zeroize(); self.entropy.zeroize(); } }
29.685714
88
0.608662
9b3b698324096e03ec38ae7f982ba3a449f76d95
166
#![deny(broken_intra_doc_links)] // @has primitive_disambiguators/index.html // @has - '//a/@href' '{{channel}}/std/primitive.str.html#method.trim' //! [str::trim()]
33.2
70
0.680723
1dbd6b0f3a320288a956031030fc5ad2e9bb63d1
2,706
extern crate crossbeam_epoch as epoch; extern crate crossbeam_utils as utils; use std::mem::ManuallyDrop; use std::ptr; use std::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use epoch::{Atomic, Owned}; use utils::thread::scope; /// Treiber's lock-free stack. /// /// Usable with any number of producers and consumers. #[derive(Debug)] pub struct TreiberStack<T> { head: Atomic<Node<T>>, } #[derive(Debug)] struct Node<T> { data: ManuallyDrop<T>, next: Atomic<Node<T>>, } impl<T> TreiberStack<T> { /// Creates a new, empty stack. pub fn new() -> TreiberStack<T> { TreiberStack { head: Atomic::null(), } } /// Pushes a value on top of the stack. pub fn push(&self, t: T) { let mut n = Owned::new(Node { data: ManuallyDrop::new(t), next: Atomic::null(), }); let guard = epoch::pin(); loop { let head = self.head.load(Relaxed, &guard); n.next.store(head, Relaxed); match self.head.compare_and_set(head, n, Release, &guard) { Ok(_) => break, Err(e) => n = e.new, } } } /// Attempts to pop the top element from the stack. /// /// Returns `None` if the stack is empty. pub fn pop(&self) -> Option<T> { let guard = epoch::pin(); loop { let head = self.head.load(Acquire, &guard); match unsafe { head.as_ref() } { Some(h) => { let next = h.next.load(Relaxed, &guard); if self .head .compare_and_set(head, next, Release, &guard) .is_ok() { unsafe { guard.defer_destroy(head); return Some(ManuallyDrop::into_inner(ptr::read(&(*h).data))); } } } None => return None, } } } /// Returns `true` if the stack is empty. pub fn is_empty(&self) -> bool { let guard = epoch::pin(); self.head.load(Acquire, &guard).is_null() } } impl<T> Drop for TreiberStack<T> { fn drop(&mut self) { while self.pop().is_some() {} } } fn main() { let stack = TreiberStack::new(); scope(|scope| { for _ in 0..10 { scope.spawn(|_| { for i in 0..10_000 { stack.push(i); assert!(stack.pop().is_some()); } }); } }).unwrap(); assert!(stack.pop().is_none()); }
24.6
89
0.468588
db8752ca28f0a30174d75feb3c6c310cda5723c6
22,533
use std::collections::BTreeMap; use std::sync::Arc; use std::{fmt, result}; use crate::crypto::{PublicKey, SecretKey, Signature}; use bincode; use derivative::Derivative; use log::debug; use rand::Rng; use serde::{de::DeserializeOwned, Serialize}; use super::votes::{SignedVote, VoteCounter}; use super::{ Batch, Change, ChangeState, DynamicHoneyBadgerBuilder, EncryptionSchedule, Error, FaultKind, Input, InternalContrib, JoinPlan, KeyGenMessage, KeyGenState, Message, Params, Result, SignedKeyGenMsg, Step, }; use crate::fault_log::{Fault, FaultLog}; use crate::honey_badger::{self, HoneyBadger, Message as HbMessage}; use crate::sync_key_gen::{Ack, AckOutcome, Part, PartOutcome, SyncKeyGen}; use crate::util; use crate::{ConsensusProtocol, Contribution, Epoched, NetworkInfo, NodeIdT, Target}; /// A Honey Badger instance that can handle adding and removing nodes. #[derive(Derivative)] #[derivative(Debug)] pub struct DynamicHoneyBadger<C, N: Ord> { /// Shared network data. pub(super) netinfo: NetworkInfo<N>, /// The maximum number of future epochs for which we handle messages simultaneously. pub(super) max_future_epochs: u64, /// The first epoch after the latest node change. pub(super) era: u64, /// The buffer and counter for the pending and committed change votes. pub(super) vote_counter: VoteCounter<N>, /// Pending node transactions that we will propose in the next epoch. pub(super) key_gen_msg_buffer: Vec<SignedKeyGenMsg<N>>, /// The `HoneyBadger` instance with the current set of nodes. pub(super) honey_badger: HoneyBadger<InternalContrib<C, N>, N>, /// The current key generation process, and the change it applies to. pub(super) key_gen_state: Option<KeyGenState<N>>, } impl<C, N> ConsensusProtocol for DynamicHoneyBadger<C, N> where C: Contribution + Serialize + DeserializeOwned, N: NodeIdT + Serialize + DeserializeOwned, { type NodeId = N; type Input = Input<C, N>; type Output = Batch<C, N>; type Message = Message<N>; type Error = Error; type FaultKind = FaultKind; fn handle_input<R: Rng>(&mut self, input: Self::Input, rng: &mut R) -> Result<Step<C, N>> { // User contributions are forwarded to `HoneyBadger` right away. Votes are signed and // broadcast. match input { Input::User(contrib) => self.propose(contrib, rng), Input::Change(change) => self.vote_for(change), } } fn handle_message<R: Rng>( &mut self, sender_id: &Self::NodeId, msg: Self::Message, rng: &mut R, ) -> Result<Step<C, N>> { self.handle_message(sender_id, msg, rng) } fn terminated(&self) -> bool { false } fn our_id(&self) -> &N { self.netinfo.our_id() } } impl<C, N> DynamicHoneyBadger<C, N> where C: Contribution + Serialize + DeserializeOwned, N: NodeIdT + Serialize + DeserializeOwned, { /// Returns a new `DynamicHoneyBadgerBuilder`. pub fn builder() -> DynamicHoneyBadgerBuilder<C, N> { DynamicHoneyBadgerBuilder::new() } /// Creates a new `DynamicHoneyBadger` ready to join the network specified in the `JoinPlan`. pub fn new_joining<R: Rng>( our_id: N, secret_key: SecretKey, join_plan: JoinPlan<N>, rng: &mut R, ) -> Result<(Self, Step<C, N>)> { let netinfo = NetworkInfo::new( our_id, None, join_plan.pub_key_set, secret_key, join_plan.pub_keys, ); let max_future_epochs = join_plan.params.max_future_epochs; let arc_netinfo = Arc::new(netinfo.clone()); let honey_badger = HoneyBadger::builder(arc_netinfo.clone()) .session_id(join_plan.era) .params(join_plan.params) .build(); let mut dhb = DynamicHoneyBadger { netinfo, max_future_epochs, era: join_plan.era, vote_counter: VoteCounter::new(arc_netinfo, join_plan.era), key_gen_msg_buffer: Vec::new(), honey_badger, key_gen_state: None, }; let step = match join_plan.change { ChangeState::InProgress(ref change) => match change { Change::NodeChange(change) => dhb.update_key_gen(join_plan.era, change, rng)?, _ => Step::default(), }, ChangeState::None | ChangeState::Complete(..) => Step::default(), }; Ok((dhb, step)) } /// Returns `true` if input for the current epoch has already been provided. pub fn has_input(&self) -> bool { self.honey_badger.has_input() } /// Proposes a contribution in the current epoch. /// /// Returns an error if we already made a proposal in this epoch. /// /// If we are the only validator, this will immediately output a batch, containing our /// proposal. pub fn propose<R: Rng>(&mut self, contrib: C, rng: &mut R) -> Result<Step<C, N>> { let key_gen_messages = self .key_gen_msg_buffer .iter() .filter(|kg_msg| kg_msg.era() == self.era) .cloned() .collect(); let contrib = InternalContrib { contrib, key_gen_messages, votes: self.vote_counter.pending_votes().cloned().collect(), }; let step = self .honey_badger .propose(&contrib, rng) .map_err(Error::ProposeHoneyBadger)?; self.process_output(step, rng) } /// Casts a vote to change the set of validators or parameters. /// /// This stores a pending vote for the change. It will be included in some future batch, and /// once enough validators have been voted for the same change, it will take effect. pub fn vote_for(&mut self, change: Change<N>) -> Result<Step<C, N>> { if !self.netinfo.is_validator() { return Ok(Step::default()); // TODO: Return an error? } let signed_vote = self.vote_counter.sign_vote_for(change)?.clone(); let msg = Message::SignedVote(signed_vote); Ok(Target::all().message(msg).into()) } /// Casts a vote to add a node as a validator. /// /// This stores a pending vote for the change. It will be included in some future batch, and /// once enough validators have been voted for the same change, it will take effect. pub fn vote_to_add(&mut self, node_id: N, pub_key: PublicKey) -> Result<Step<C, N>> { let mut pub_keys = self.netinfo.public_key_map().clone(); pub_keys.insert(node_id, pub_key); self.vote_for(Change::NodeChange(pub_keys)) } /// Casts a vote to demote a validator to observer. /// /// This stores a pending vote for the change. It will be included in some future batch, and /// once enough validators have been voted for the same change, it will take effect. pub fn vote_to_remove(&mut self, node_id: &N) -> Result<Step<C, N>> { let mut pub_keys = self.netinfo.public_key_map().clone(); pub_keys.remove(node_id); self.vote_for(Change::NodeChange(pub_keys)) } /// Handles a message received from `sender_id`. /// /// This must be called with every message we receive from another node. pub fn handle_message<R: Rng>( &mut self, sender_id: &N, message: Message<N>, rng: &mut R, ) -> Result<Step<C, N>> { if message.era() == self.era { match message { Message::HoneyBadger(_, hb_msg) => { self.handle_honey_badger_message(sender_id, hb_msg, rng) } Message::KeyGen(_, kg_msg, sig) => self .handle_key_gen_message(sender_id, kg_msg, *sig) .map(FaultLog::into), Message::SignedVote(signed_vote) => self .vote_counter .add_pending_vote(sender_id, signed_vote) .map(FaultLog::into), } } else if message.era() > self.era { Ok(Fault::new(sender_id.clone(), FaultKind::UnexpectedDhbMessageEra).into()) } else { // The message is late; discard it. Ok(Step::default()) } } /// Returns the information about the node IDs in the network, and the cryptographic keys. pub fn netinfo(&self) -> &NetworkInfo<N> { &self.netinfo } /// Returns a reference to the internal managed `HoneyBadger` instance. pub fn honey_badger(&self) -> &HoneyBadger<InternalContrib<C, N>, N> { &self.honey_badger } /// Returns `true` if we should make our contribution for the next epoch, even if we don't have /// content ourselves, to avoid stalling the network. /// /// By proposing only if this returns `true`, you can prevent an adversary from making the /// network output empty baches indefinitely, but it also means that the network won't advance /// if fewer than _f + 1_ nodes have pending contributions. pub fn should_propose(&self) -> bool { if self.has_input() { return false; // We have already proposed. } if self.honey_badger.received_proposals() > self.netinfo.num_faulty() { return true; // At least one correct node wants to move on to the next epoch. } let is_our_vote = |signed_vote: &SignedVote<_>| signed_vote.voter() == self.our_id(); if self.vote_counter.pending_votes().any(is_our_vote) { return true; // We have pending input to vote for a validator change. } // If we have a pending key gen message, we should propose. !self.key_gen_msg_buffer.is_empty() } /// The epoch of the next batch that will be output. pub fn next_epoch(&self) -> u64 { self.era + self.honey_badger.next_epoch() } /// Handles a message for the `HoneyBadger` instance. fn handle_honey_badger_message<R: Rng>( &mut self, sender_id: &N, message: HbMessage<N>, rng: &mut R, ) -> Result<Step<C, N>> { if !self.netinfo.is_node_validator(sender_id) { return Err(Error::UnknownSender); } // Handle the message. let step = self .honey_badger .handle_message(sender_id, message) .map_err(Error::HandleHoneyBadgerMessage)?; self.process_output(step, rng) } /// Handles a vote or key generation message and tries to commit it as a transaction. These /// messages are only handled once they appear in a batch output from Honey Badger. fn handle_key_gen_message( &mut self, sender_id: &N, kg_msg: KeyGenMessage, sig: Signature, ) -> Result<FaultLog<N, FaultKind>> { if !self.verify_signature(sender_id, &sig, &kg_msg)? { let fault_kind = FaultKind::InvalidKeyGenMessageSignature; return Ok(Fault::new(sender_id.clone(), fault_kind).into()); } let kgs = match self.key_gen_state { Some(ref mut kgs) => kgs, None => { return Ok( Fault::new(sender_id.clone(), FaultKind::UnexpectedKeyGenMessage).into(), ); } }; // If the sender is correct, it will send at most _N + 1_ key generation messages: // one `Part`, and for each validator an `Ack`. _N_ is the node number _after_ the change. if kgs.count_messages(sender_id) > kgs.key_gen.num_nodes() + 1 { let fault_kind = FaultKind::TooManyKeyGenMessages; return Ok(Fault::new(sender_id.clone(), fault_kind).into()); } let tx = SignedKeyGenMsg(self.era, sender_id.clone(), kg_msg, sig); self.key_gen_msg_buffer.push(tx); Ok(FaultLog::default()) } /// Processes all pending batches output by Honey Badger. fn process_output<R: Rng>( &mut self, hb_step: honey_badger::Step<InternalContrib<C, N>, N>, rng: &mut R, ) -> Result<Step<C, N>> { let mut step: Step<C, N> = Step::default(); let output = step.extend_with(hb_step, FaultKind::HbFault, |hb_msg| { Message::HoneyBadger(self.era, hb_msg) }); for hb_batch in output { let batch_era = self.era; let batch_epoch = hb_batch.epoch + batch_era; let mut batch_contributions = BTreeMap::new(); // Add the user transactions to `batch` and handle votes and DKG messages. for (id, int_contrib) in hb_batch.contributions { let InternalContrib { votes, key_gen_messages, contrib, } = int_contrib; step.fault_log .extend(self.vote_counter.add_committed_votes(&id, votes)?); batch_contributions.insert(id.clone(), contrib); self.key_gen_msg_buffer .retain(|skgm| !key_gen_messages.contains(skgm)); for SignedKeyGenMsg(era, s_id, kg_msg, sig) in key_gen_messages { if era != self.era { let fault_kind = FaultKind::InvalidKeyGenMessageEra; step.fault_log.append(id.clone(), fault_kind); } else if !self.verify_signature(&s_id, &sig, &kg_msg)? { let fault_kind = FaultKind::InvalidKeyGenMessageSignature; step.fault_log.append(id.clone(), fault_kind); } else { step.extend(match kg_msg { KeyGenMessage::Part(part) => self.handle_part(&s_id, part, rng)?, KeyGenMessage::Ack(ack) => self.handle_ack(&s_id, ack)?, }); } } } let change = if let Some(kgs) = self.take_ready_key_gen() { // If DKG completed, apply the change, restart Honey Badger, and inform the user. debug!("{}: DKG for complete for: {:?}", self, kgs.public_keys()); self.netinfo = kgs.key_gen.into_network_info().map_err(Error::SyncKeyGen)?; let params = self.honey_badger.params().clone(); self.restart_honey_badger(batch_epoch + 1, params); ChangeState::Complete(Change::NodeChange(self.netinfo.public_key_map().clone())) } else if let Some(change) = self.vote_counter.compute_winner().cloned() { // If there is a new change, restart DKG. Inform the user about the current change. match change { Change::NodeChange(ref pub_keys) => { step.extend(self.update_key_gen(batch_epoch + 1, pub_keys, rng)?); } Change::EncryptionSchedule(schedule) => { self.update_encryption_schedule(batch_epoch + 1, schedule); } } match change { Change::NodeChange(_) => ChangeState::InProgress(change), Change::EncryptionSchedule(_) => ChangeState::Complete(change), } } else { ChangeState::None }; step.output.push(Batch { epoch: batch_epoch, era: batch_era, change, netinfo: Arc::new(self.netinfo.clone()), contributions: batch_contributions, params: self.honey_badger.params().clone(), }); } Ok(step) } /// Restarts Honey Badger with the new encryption schedule. pub(super) fn update_encryption_schedule(&mut self, era: u64, schedule: EncryptionSchedule) { let mut params = self.honey_badger.params().clone(); params.encryption_schedule = schedule; self.restart_honey_badger(era, params); } /// If the winner of the vote has changed, restarts Key Generation for the set of nodes implied /// by the current change. pub(super) fn update_key_gen<R: Rng>( &mut self, era: u64, pub_keys: &BTreeMap<N, PublicKey>, rng: &mut R, ) -> Result<Step<C, N>> { if self.key_gen_state.as_ref().map(KeyGenState::public_keys) == Some(pub_keys) { return Ok(Step::default()); // The change is the same as before. Continue DKG as is. } debug!("{}: Restarting DKG for {:?}.", self, pub_keys); let params = self.honey_badger.params().clone(); self.restart_honey_badger(era, params); let threshold = util::max_faulty(pub_keys.len()); let sk = self.netinfo.secret_key().clone(); let our_id = self.our_id().clone(); let (key_gen, part) = SyncKeyGen::new(our_id, sk, pub_keys.clone(), threshold, rng) .map_err(Error::SyncKeyGen)?; self.key_gen_state = Some(KeyGenState::new(key_gen)); if let Some(part) = part { self.send_transaction(KeyGenMessage::Part(part)) } else { Ok(Step::default()) } } /// Starts a new `HoneyBadger` instance and resets the vote counter. fn restart_honey_badger(&mut self, era: u64, params: Params) { self.era = era; self.key_gen_msg_buffer.retain(|kg_msg| kg_msg.0 >= era); let netinfo = Arc::new(self.netinfo.clone()); self.vote_counter = VoteCounter::new(netinfo.clone(), era); self.honey_badger = HoneyBadger::builder(netinfo) .session_id(era) .params(params) .build(); } /// Handles a `Part` message that was output by Honey Badger. fn handle_part<R: Rng>( &mut self, sender_id: &N, part: Part, rng: &mut R, ) -> Result<Step<C, N>> { let outcome = if let Some(kgs) = self.key_gen_state.as_mut() { kgs.key_gen .handle_part(&sender_id, part, rng) .map_err(Error::SyncKeyGen)? } else { // No key generation ongoing. let fault_kind = FaultKind::UnexpectedKeyGenPart; return Ok(Fault::new(sender_id.clone(), fault_kind).into()); }; match outcome { PartOutcome::Valid(Some(ack)) => self.send_transaction(KeyGenMessage::Ack(ack)), PartOutcome::Valid(None) => Ok(Step::default()), PartOutcome::Invalid(fault) => { let fault_kind = FaultKind::SyncKeyGenPart(fault); Ok(Fault::new(sender_id.clone(), fault_kind).into()) } } } /// Handles an `Ack` message that was output by Honey Badger. fn handle_ack(&mut self, sender_id: &N, ack: Ack) -> Result<Step<C, N>> { let outcome = if let Some(kgs) = self.key_gen_state.as_mut() { kgs.key_gen .handle_ack(sender_id, ack) .map_err(Error::SyncKeyGen)? } else { // No key generation ongoing. let fault_kind = FaultKind::UnexpectedKeyGenAck; return Ok(Fault::new(sender_id.clone(), fault_kind).into()); }; match outcome { AckOutcome::Valid => Ok(Step::default()), AckOutcome::Invalid(fault) => { let fault_kind = FaultKind::SyncKeyGenAck(fault); Ok(Fault::new(sender_id.clone(), fault_kind).into()) } } } /// Signs and sends a `KeyGenMessage` and also tries to commit it. fn send_transaction(&mut self, kg_msg: KeyGenMessage) -> Result<Step<C, N>> { let ser = bincode::serialize(&kg_msg).map_err(|err| Error::SerializeKeyGen(*err))?; let sig = Box::new(self.netinfo.secret_key().sign(ser)); if self.netinfo.is_validator() { let our_id = self.our_id().clone(); let signed_msg = SignedKeyGenMsg(self.era, our_id, kg_msg.clone(), *sig.clone()); self.key_gen_msg_buffer.push(signed_msg); } let msg = Message::KeyGen(self.era, kg_msg, sig); Ok(Target::all().message(msg).into()) } /// If the current Key Generation process is ready, returns the `KeyGenState`. /// /// We require the minimum number of completed proposals (`SyncKeyGen::is_ready`) and if a new /// node is joining, we require in addition that the new node's proposal is complete. That way /// the new node knows that it's key is secret, without having to trust any number of nodes. fn take_ready_key_gen(&mut self) -> Option<KeyGenState<N>> { if self .key_gen_state .as_ref() .map_or(false, KeyGenState::is_ready) { self.key_gen_state.take() } else { None } } /// Returns `true` if the signature of `kg_msg` by the node with the specified ID is valid. /// Returns an error if the payload fails to serialize. /// /// This accepts signatures from both validators and currently joining candidates, if any. fn verify_signature( &self, node_id: &N, sig: &Signature, kg_msg: &KeyGenMessage, ) -> Result<bool> { let ser = bincode::serialize(kg_msg).map_err(|err| Error::SerializeKeyGen(*err))?; let verify = |opt_pk: Option<&PublicKey>| opt_pk.map_or(false, |pk| pk.verify(&sig, &ser)); let kgs = self.key_gen_state.as_ref(); let current_key = self.netinfo.public_key(node_id); let candidate_key = kgs.and_then(|kgs| kgs.public_keys().get(node_id)); Ok(verify(current_key) || verify(candidate_key)) } /// Returns the maximum future epochs of the Honey Badger algorithm instance. pub fn max_future_epochs(&self) -> u64 { self.max_future_epochs } } impl<C, N> fmt::Display for DynamicHoneyBadger<C, N> where C: Contribution + Serialize + DeserializeOwned, N: NodeIdT + Serialize + DeserializeOwned, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> result::Result<(), fmt::Error> { write!(f, "{:?} DHB(era: {})", self.our_id(), self.era) } } impl<C, N> Epoched for DynamicHoneyBadger<C, N> where C: Contribution + Serialize + DeserializeOwned, N: NodeIdT + Serialize + DeserializeOwned, { type Epoch = (u64, u64); fn epoch(&self) -> (u64, u64) { (self.era, self.honey_badger.epoch()) } }
40.094306
99
0.590379
87866273b3319c1231fcc198462d7506dd04ec58
1,402
//! Filesystem utilities //! //! These are will be parallel if the `parallel` feature is enabled, at the expense of compiling additional dependencies //! along with runtime costs for maintaining a global [`rayon`](https://docs.rs/rayon) thread pool. //! //! For information on how to use the [`WalkDir`] type, have a look at //! * [`jwalk::WalkDir`](https://docs.rs/jwalk/0.5.1/jwalk/type.WalkDir.html) if `parallel` feature is enabled //! * [walkdir::WalkDir](https://docs.rs/walkdir/2.3.1/walkdir/struct.WalkDir.html) otherwise #[cfg(feature = "parallel")] /// pub mod walkdir { pub use jwalk::{DirEntry as DirEntryGeneric, Error, WalkDir}; use std::path::Path; /// An alias for an uncustomized directory entry to match the one of the non-parallel version offered by `walkdir`. pub type DirEntry = DirEntryGeneric<((), ())>; /// Instantiate a new directory iterator which will not skip hidden files. pub fn walkdir_new(root: impl AsRef<Path>) -> WalkDir { WalkDir::new(root).skip_hidden(false) } } #[cfg(not(feature = "parallel"))] /// pub mod walkdir { use std::path::Path; pub use walkdir::{DirEntry, Error, WalkDir}; /// Instantiate a new directory iterator which will not skip hidden files. pub fn walkdir_new(root: impl AsRef<Path>) -> WalkDir { WalkDir::new(root) } } pub use self::walkdir::{walkdir_new, DirEntry, WalkDir};
37.891892
120
0.685449
87a6c4442732596a248952f8e1202b5c09db16da
421
use rand::seq::SliceRandom; fn main() { let mut nums = vec![]; for i in 1..=75 { nums.push(i); } // shuffle let mut rng = rand::thread_rng(); nums.shuffle(&mut rng); // show cards for i in 0..25 { if i == 12 { print!(" *,"); } else { print!("{:3},", nums[i]); } if i % 5 == 4 { println!(""); } } }
17.541667
37
0.380048
2986731f2774a2b5f8a104148b8dd1c033fae8bd
26,681
// Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors // SPDX-License-Identifier: MIT use std::{collections::HashMap, convert::TryInto, num::TryFromIntError, time::Instant}; use crypto::blake2b::{self, Blake2bError}; use redux_rs::{ActionWithMeta, Store}; use slog::debug; use storage::{cycle_storage::CycleData, num_from_slice}; use tezos_messages::base::{ signature_public_key::{SignaturePublicKey, SignaturePublicKeyHash}, ConversionError, }; use crate::{ rights::Delegate, storage::{ kv_block_additional_data, kv_block_header, kv_constants, kv_cycle_eras, kv_cycle_meta, }, Action, Service, State, }; use super::{ utils::get_cycle, EndorsingRights, EndorsingRightsRequest, ProtocolConstants, RightsEndorsingRightsBlockHeaderReadyAction, RightsEndorsingRightsCalculateAction, RightsEndorsingRightsCycleDataReadyAction, RightsEndorsingRightsCycleErasReadyAction, RightsEndorsingRightsCycleReadyAction, RightsEndorsingRightsErrorAction, RightsEndorsingRightsGetBlockHeaderAction, RightsEndorsingRightsGetCycleAction, RightsEndorsingRightsGetCycleDataAction, RightsEndorsingRightsGetCycleErasAction, RightsEndorsingRightsGetProtocolConstantsAction, RightsEndorsingRightsGetProtocolHashAction, RightsEndorsingRightsProtocolConstantsReadyAction, RightsEndorsingRightsProtocolHashReadyAction, RightsEndorsingRightsReadyAction, RightsGetEndorsingRightsAction, }; pub fn rights_effects<S>(store: &mut Store<State, S, Action>, action: &ActionWithMeta<Action>) where S: Service, { let endorsing_rights_state = &store.state.get().rights.endorsing_rights; match &action.action { /* Action::BlockApplied(BlockAppliedAction { chain_id: _, block, is_bootstrapped, }) => { if *is_bootstrapped { store.dispatch( RightsGetEndorsingRightsAction { key: EndorsingRightsKey { current_block_hash: block.hs block_header_with_hash.hash.clone(), level: None, }, }, ); } } */ Action::RightsGetEndorsingRights(RightsGetEndorsingRightsAction { key }) => { if let Some(EndorsingRightsRequest::Init { .. }) = endorsing_rights_state.get(key) { store.dispatch(RightsEndorsingRightsGetBlockHeaderAction { key: key.clone() }); } } // get block header from kv store Action::RightsEndorsingRightsGetBlockHeader( RightsEndorsingRightsGetBlockHeaderAction { key }, ) => { if let Some(EndorsingRightsRequest::PendingBlockHeader { .. }) = endorsing_rights_state.get(key) { store.dispatch(kv_block_header::StorageBlockHeaderGetAction { key: key.current_block_hash.clone().into(), }); } } Action::StorageBlockHeaderOk(kv_block_header::StorageBlockHeaderOkAction { key, value, }) => { for key in endorsing_rights_state .iter() .filter_map(|(rights_key, _)| { if &rights_key.current_block_hash == &key.0 { Some(rights_key) } else { None } }) .cloned() .collect::<Vec<_>>() { store.dispatch(RightsEndorsingRightsBlockHeaderReadyAction { key, block_header: value.clone(), }); } } Action::StorageBlockHeaderError(kv_block_header::StorageBlockHeaderErrorAction { key, error, }) => { for key in endorsing_rights_state .iter() .filter_map(|(rights_key, _)| { if &rights_key.current_block_hash == &key.0 { Some(rights_key) } else { None } }) .cloned() .collect::<Vec<_>>() { store.dispatch(RightsEndorsingRightsErrorAction { key, error: error.clone().into(), }); } } Action::RightsEndorsingRightsBlockHeaderReady( RightsEndorsingRightsBlockHeaderReadyAction { key, .. }, ) => { if let Some(EndorsingRightsRequest::BlockHeaderReady { .. }) = endorsing_rights_state.get(key) { store.dispatch(RightsEndorsingRightsGetProtocolHashAction { key: key.clone() }); } } // get protocol hash as a part of additional block data from kv store Action::RightsEndorsingRightsGetProtocolHash( RightsEndorsingRightsGetProtocolHashAction { key, .. }, ) => { if let Some(EndorsingRightsRequest::PendingProtocolHash { .. }) = endorsing_rights_state.get(key) { store.dispatch( kv_block_additional_data::StorageBlockAdditionalDataGetAction::new( key.current_block_hash.clone(), ), ); } } Action::StorageBlockAdditionalDataOk( kv_block_additional_data::StorageBlockAdditionalDataOkAction { key, value }, ) => { let rights_keys: Vec<_> = endorsing_rights_state .iter() .filter_map(|(rights_key, _)| { if &rights_key.current_block_hash == &key.0 { Some(rights_key) } else { None } }) .cloned() .collect(); for rights_key in rights_keys { store.dispatch(RightsEndorsingRightsProtocolHashReadyAction { key: rights_key.clone(), proto_hash: value.next_protocol_hash.clone(), }); } } Action::StorageBlockAdditionalDataError( kv_block_additional_data::StorageBlockAdditionalDataErrorAction { key, error }, ) => { for key in endorsing_rights_state .iter() .filter_map(|(rights_key, _)| { if &rights_key.current_block_hash == &key.0 { Some(rights_key) } else { None } }) .cloned() .collect::<Vec<_>>() { store.dispatch(RightsEndorsingRightsErrorAction { key, error: error.clone().into(), }); } } Action::RightsEndorsingRightsProtocolHashReady( RightsEndorsingRightsProtocolHashReadyAction { key, .. }, ) => { if let Some(EndorsingRightsRequest::ProtocolHashReady { .. }) = endorsing_rights_state.get(key) { store .dispatch(RightsEndorsingRightsGetProtocolConstantsAction { key: key.clone() }); } } // get protocol constants from kv store Action::RightsEndorsingRightsGetProtocolConstants( RightsEndorsingRightsGetProtocolConstantsAction { key }, ) => { if let Some(EndorsingRightsRequest::PendingProtocolConstants { proto_hash: data_proto_hash, .. }) = endorsing_rights_state.get(key) { let key = data_proto_hash.clone(); store.dispatch(kv_constants::StorageConstantsGetAction::new(key)); } } Action::StorageConstantsOk(kv_constants::StorageConstantsOkAction { key, value }) => { for key in endorsing_rights_state .iter() .filter_map(|(rights_key, request)| { if let EndorsingRightsRequest::PendingProtocolConstants { proto_hash: data_proto_hash, .. } = request { if data_proto_hash == &key.0 { Some(rights_key) } else { None } } else { None } }) .cloned() .collect::<Vec<_>>() { match serde_json::from_str::<ProtocolConstants>(value) { Ok(constants) => { store.dispatch(RightsEndorsingRightsProtocolConstantsReadyAction { key, constants, }); } Err(err) => { store.dispatch(RightsEndorsingRightsErrorAction { key, error: err.into(), }); } } } } Action::StorageConstantsError(kv_constants::StorageConstantsErrorAction { key, error }) => { let rights_keys: Vec<_> = endorsing_rights_state .iter() .filter_map(|(rights_key, request)| { if let EndorsingRightsRequest::PendingProtocolConstants { proto_hash: data_proto_hash, .. } = request { if data_proto_hash == &key.0 { Some(rights_key) } else { None } } else { None } }) .cloned() .collect(); for rights_key in rights_keys { store.dispatch(RightsEndorsingRightsErrorAction { key: rights_key, error: error.clone().into(), }); } } Action::RightsEndorsingRightsProtocolConstantsReady( RightsEndorsingRightsProtocolConstantsReadyAction { key, .. }, ) => { if let Some(EndorsingRightsRequest::ProtocolConstantsReady { .. }) = endorsing_rights_state.get(key) { store.dispatch(RightsEndorsingRightsGetCycleErasAction { key: key.clone() }); } } // get cycle eras from kv store Action::RightsEndorsingRightsGetCycleEras(RightsEndorsingRightsGetCycleErasAction { key, }) => { if let Some(EndorsingRightsRequest::PendingCycleEras { proto_hash: data_proto_hash, .. }) = endorsing_rights_state.get(key) { let key = data_proto_hash.clone(); store.dispatch(kv_cycle_eras::StorageCycleErasGetAction::new(key)); } } Action::StorageCycleErasOk(kv_cycle_eras::StorageCycleErasOkAction { key, value }) => { for key in endorsing_rights_state .iter() .filter_map(|(rights_key, request)| { if let EndorsingRightsRequest::PendingCycleEras { proto_hash: data_proto_hash, .. } = request { if data_proto_hash == &key.0 { Some(rights_key) } else { None } } else { None } }) .cloned() .collect::<Vec<_>>() { store.dispatch(RightsEndorsingRightsCycleErasReadyAction { key, cycle_eras: value.clone(), }); } } Action::StorageCycleErasError(kv_cycle_eras::StorageCycleErasErrorAction { key, error, }) => { for key in endorsing_rights_state .iter() .filter_map(|(rights_key, request)| { if let EndorsingRightsRequest::PendingCycleEras { proto_hash: data_proto_hash, .. } = request { if data_proto_hash == &key.0 { Some(rights_key) } else { None } } else { None } }) .cloned() .collect::<Vec<_>>() { store.dispatch(RightsEndorsingRightsErrorAction { key, error: error.clone().into(), }); } } Action::RightsEndorsingRightsCycleErasReady( RightsEndorsingRightsCycleErasReadyAction { key, .. }, ) => { store.dispatch(RightsEndorsingRightsGetCycleAction { key: key.clone() }); } // get cycle for the requested block Action::RightsEndorsingRightsGetCycle(RightsEndorsingRightsGetCycleAction { key }) => { if let Some(EndorsingRightsRequest::PendingCycle { block_header: data_block_header, cycle_eras: data_cycle_eras, protocol_constants: data_protocol_constants, .. }) = endorsing_rights_state.get(key) { let block_level = data_block_header.level(); let get_cycle = get_cycle( block_level, key.level, data_cycle_eras, data_protocol_constants.preserved_cycles, ); match get_cycle { Ok((cycle, position)) => { store.dispatch(RightsEndorsingRightsCycleReadyAction { key: key.clone(), cycle, position, }) } Err(err) => store.dispatch(RightsEndorsingRightsErrorAction { key: key.clone(), error: err.into(), }), }; } } Action::RightsEndorsingRightsCycleReady(RightsEndorsingRightsCycleReadyAction { key, .. }) => { if let Some(EndorsingRightsRequest::CycleReady { .. }) = endorsing_rights_state.get(key) { store.dispatch(RightsEndorsingRightsGetCycleDataAction { key: key.clone() }); } } // get cycle data kv store Action::RightsEndorsingRightsGetCycleData(RightsEndorsingRightsGetCycleDataAction { key, }) => { if let Some(EndorsingRightsRequest::PendingCycleData { cycle: data_cycle, .. }) = endorsing_rights_state.get(key) { let key = *data_cycle; store.dispatch(kv_cycle_meta::StorageCycleMetaGetAction::new(key)); } } Action::StorageCycleMetaOk(kv_cycle_meta::StorageCycleMetaOkAction { key, value }) => { for key in endorsing_rights_state .iter() .filter_map(|(rights_key, request)| { if let EndorsingRightsRequest::PendingCycleData { cycle: data_cycle, .. } = request { if data_cycle == &key.0 { Some(rights_key) } else { None } } else { None } }) .cloned() .collect::<Vec<_>>() { store.dispatch(RightsEndorsingRightsCycleDataReadyAction { key, cycle_data: value.clone(), }); } } Action::StorageCycleMetaError(kv_cycle_meta::StorageCycleMetaErrorAction { key, error, }) => { for key in endorsing_rights_state .iter() .filter_map(|(rights_key, request)| { if let EndorsingRightsRequest::PendingCycleData { cycle: data_cycle, .. } = request { if data_cycle == &key.0 { Some(rights_key) } else { None } } else { None } }) .cloned() .collect::<Vec<_>>() { store.dispatch(RightsEndorsingRightsErrorAction { key, error: error.clone().into(), }); } } Action::RightsEndorsingRightsCycleDataReady( RightsEndorsingRightsCycleDataReadyAction { key, .. }, ) => { store.dispatch(RightsEndorsingRightsCalculateAction { key: key.clone() }); } Action::RightsEndorsingRightsCalculate(RightsEndorsingRightsCalculateAction { key }) => { if let Some(EndorsingRightsRequest::PendingRights { cycle_data: in_cycle_data, position: in_position, protocol_constants: in_protocol_constants, start, }) = endorsing_rights_state.get(key) { let prereq_dur = action.id.duration_since(*start); let time = Instant::now(); let endorsing_rights = calculate_endorsing_rights(in_cycle_data, in_protocol_constants, *in_position); let dur = Instant::now() - time; match endorsing_rights { Ok(endorsing_rights) => { let log = &store.state.get().log; debug!(log, "Endorsing rights successfully calculated"; "prerequisites duration" => prereq_dur.as_millis(), "duration" => dur.as_millis() ); for (delegate, slots) in &endorsing_rights.delegate_to_slots { let pkh: SignaturePublicKeyHash = delegate.clone().try_into().unwrap(); debug!(log, "Endorsing rights"; "pk" => delegate.to_string_representation(), "pkh" => pkh.to_string_representation(), "slots" => format!("{:?}", slots) ); } store.dispatch(RightsEndorsingRightsReadyAction { key: key.clone(), endorsing_rights: endorsing_rights.clone(), }); } Err(err) => { store.dispatch(RightsEndorsingRightsErrorAction { key: key.clone(), error: err.into(), }); } } } } _ => (), } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, thiserror::Error)] pub enum EndorsingRightsCalculationError { #[error("Integer conversion error: {0}")] FromInt(String), #[error("Digest error: {0}")] Blake2b(#[from] Blake2bError), #[error("Signature conversion error: {0}")] Conversion(#[from] ConversionError), #[error("Value of bound(last_roll) `{0}` is not correct")] BoundNotCorrect(i32), } impl From<TryFromIntError> for EndorsingRightsCalculationError { fn from(error: TryFromIntError) -> Self { Self::FromInt(error.to_string()) } } fn calculate_endorsing_rights( cycle_meta_data: &CycleData, constants: &ProtocolConstants, cycle_position: i32, ) -> Result<EndorsingRights, EndorsingRightsCalculationError> { // build a reverse map of rols so we have access in O(1) let mut rolls_map = HashMap::new(); for (delegate, rolls) in cycle_meta_data.rolls_data() { for roll in rolls { rolls_map.insert( *roll, SignaturePublicKey::from_tagged_bytes(delegate.to_vec())?, ); } } let endorsers_slots = get_endorsers_slots(constants, cycle_meta_data, &rolls_map, cycle_position)?; let mut endorser_to_slots = HashMap::new(); for (slot, delegate) in endorsers_slots.iter().enumerate() { endorser_to_slots .entry(delegate.clone()) .or_insert_with(|| Vec::new()) .push(slot.try_into()?); } Ok(EndorsingRights { delegate_to_slots: endorser_to_slots, slot_to_delegate: endorsers_slots, }) } /// Use tezos PRNG to collect all slots for each endorser by public key hash (for later ordering of endorsers) /// /// # Arguments /// /// * `constants` - Context constants used in baking and endorsing rights [RightsConstants](RightsConstants::parse_rights_constants). /// * `cycle_meta_data` - Data from context list used in baking and endorsing rights generation filled in [RightsContextData](RightsContextData::prepare_context_data_for_rights). /// * `level` - Level to feed Tezos PRNG. #[inline] fn get_endorsers_slots( constants: &ProtocolConstants, cycle_meta_data: &CycleData, rolls_map: &HashMap<i32, Delegate>, cycle_position: i32, ) -> Result<Vec<Delegate>, EndorsingRightsCalculationError> { // special byte string used in Tezos PRNG const ENDORSEMENT_USE_STRING: &[u8] = b"level endorsement:"; // prepare helper variable let mut endorsers_slots: Vec<Delegate> = Vec::new(); for endorser_slot in 0..constants.endorsers_per_block { // generate PRNG per endorsement slot and take delegates by roll number from context_rolls // if roll number is not found then reroll with new state till roll nuber is found in context_rolls let mut state = init_prng( cycle_meta_data, constants, ENDORSEMENT_USE_STRING, cycle_position, endorser_slot.into(), )?; loop { let (random_num, sequence) = get_prng_number(state, *cycle_meta_data.last_roll())?; if let Some(delegate) = rolls_map.get(&random_num) { endorsers_slots.push(delegate.clone()); break; } else { state = sequence; } } } Ok(endorsers_slots) } type RandomSeedState = Vec<u8>; type TezosPRNGResult = Result<(i32, RandomSeedState), EndorsingRightsCalculationError>; /// Initialize Tezos PRNG /// /// # Arguments /// /// * `state` - RandomSeedState, initially the random seed. /// * `nonce_size` - Nonce_length from current protocol constants. /// * `blocks_per_cycle` - Blocks_per_cycle from current protocol context constants /// * `use_string_bytes` - String converted to bytes, i.e. endorsing rights use b"level endorsement:". /// * `level` - block level /// * `offset` - For baking priority, for endorsing slot /// /// Return first random sequence state to use in [get_prng_number](`get_prng_number`) #[inline] pub fn init_prng( cycle_meta_data: &CycleData, constants: &ProtocolConstants, use_string_bytes: &[u8], cycle_position: i32, offset: i32, ) -> Result<RandomSeedState, EndorsingRightsCalculationError> { // a safe way to convert betwwen types is to use try_from let nonce_size = usize::from(constants.nonce_length); let state = cycle_meta_data.seed_bytes(); let zero_bytes: Vec<u8> = vec![0; nonce_size]; // take the state (initially the random seed), zero bytes, the use string and the blocks position in the cycle as bytes, merge them together and hash the result let rd = blake2b::digest_256( &[ state, &zero_bytes, use_string_bytes, &cycle_position.to_be_bytes(), ] .concat(), )?; // take the 4 highest bytes and xor them with the priority/slot (offset) let higher = num_from_slice!(rd, 0, i32) ^ offset; // set the 4 highest bytes to the result of the xor operation let sequence = blake2b::digest_256(&[&higher.to_be_bytes(), &rd[4..]].concat())?; Ok(sequence) } /// Get pseudo random nuber using Tezos PRNG /// /// # Arguments /// /// * `state` - RandomSeedState, initially the random seed. /// * `bound` - Last possible roll nuber that have meaning to be generated taken from [RightsContextData.last_roll](`RightsContextData.last_roll`). /// /// Return pseudo random generated roll number and RandomSeedState for next roll generation if the roll provided is missing from the roll list #[inline] pub fn get_prng_number(state: RandomSeedState, bound: i32) -> TezosPRNGResult { if bound < 1 { return Err(EndorsingRightsCalculationError::BoundNotCorrect(bound)); } let v: i32; // Note: this part aims to be similar // hash once again and take the 4 highest bytes and we got our random number let mut sequence = state; loop { let hashed = blake2b::digest_256(&sequence)?.to_vec(); // computation for overflow check let drop_if_over = i32::max_value() - (i32::max_value() % bound); // 4 highest bytes let r = num_from_slice!(hashed, 0, i32).abs(); // potentional overflow, keep the state of the generator and do one more iteration sequence = hashed; if r >= drop_if_over { continue; // use the remainder(mod) operation to get a number from a desired interval } else { v = r % bound; break; }; } Ok((v, sequence)) }
37.84539
178
0.51546
c17ae7377f31f169d6db81242a2abe0d14762dba
4,374
// // Copyright 2021 The Sigstore Authors. // // 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 olpc_cjson::CanonicalFormatter; use serde::{Deserialize, Serialize}; use std::cmp::PartialEq; use crate::crypto::{verify_signature, CosignVerificationKey}; use crate::errors::{Result, SigstoreError}; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Bundle { pub signed_entry_timestamp: String, pub payload: Payload, } impl Bundle { /// Create a new verified `Bundle` /// /// **Note well:** The bundle will be returned only if it can be verified /// using the supplied `rekor_pub_key` public key. pub(crate) fn new_verified(raw: &str, rekor_pub_key: &CosignVerificationKey) -> Result<Self> { let bundle: Bundle = serde_json::from_str(raw).map_err(|e| { SigstoreError::UnexpectedError(format!("Cannot parse bundle |{}|: {:?}", raw, e)) })?; let mut buf = Vec::new(); let mut ser = serde_json::Serializer::with_formatter(&mut buf, CanonicalFormatter::new()); bundle.payload.serialize(&mut ser).map_err(|e| { SigstoreError::UnexpectedError(format!( "Cannot create canonical JSON representation of bundle: {:?}", e )) })?; verify_signature(rekor_pub_key, &bundle.signed_entry_timestamp, &buf)?; Ok(bundle) } } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Payload { pub body: String, pub integrated_time: i64, pub log_index: i64, #[serde(rename = "logID")] pub log_id: String, } #[cfg(test)] mod tests { use super::*; use serde_json::json; use crate::cosign::tests::get_rekor_public_key; use crate::crypto; fn build_correct_bundle() -> String { let bundle_json = json!({ "SignedEntryTimestamp": "MEUCIDx9M+yRpD0O47/Mzm8NAPCbtqy4uiTkLWWexW0bo4jZAiEA1wwueIW8XzJWNkut5y9snYj7UOfbMmUXp7fH3CzJmWg=", "Payload": { "body": "eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoicmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiIzYWY0NDE0ZDIwYzllMWNiNzZjY2M3MmFhZThiMjQyMTY2ZGFiZTZhZjUzMWE0YTc5MGRiOGUyZjBlNWVlN2M5In19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FWUNJUURXV3hQUWEzWEZVc1BieVRZK24rYlp1LzZQd2hnNVd3eVlEUXRFZlFobzl3SWhBUGtLVzdldWI4YjdCWCtZYmJSYWM4VHd3SXJLNUt4dmR0UTZOdW9EK2l2VyIsImZvcm1hdCI6Ing1MDkiLCJwdWJsaWNLZXkiOnsiY29udGVudCI6IkxTMHRMUzFDUlVkSlRpQlFWVUpNU1VNZ1MwVlpMUzB0TFMwS1RVWnJkMFYzV1VoTGIxcEplbW93UTBGUldVbExiMXBKZW1vd1JFRlJZMFJSWjBGRlRFdG9SRGRHTlU5TGVUYzNXalU0TWxrMmFEQjFNVW96UjA1Qkt3cHJkbFZ6YURSbFMzQmtNV3gzYTBSQmVtWkdSSE0zZVZoRlJYaHpSV3RRVUhWcFVVcENaV3hFVkRZNGJqZFFSRWxYUWk5UlJWazNiWEpCUFQwS0xTMHRMUzFGVGtRZ1VGVkNURWxESUV0RldTMHRMUzB0Q2c9PSJ9fX19", "integratedTime": 1634714179, "logIndex": 783606, "logID": "c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d" } }); serde_json::to_string(&bundle_json).unwrap() } #[test] fn bundle_new_verified_success() { let rekor_pub_key = get_rekor_public_key(); let bundle_json = build_correct_bundle(); let bundle = Bundle::new_verified(&bundle_json, &rekor_pub_key); assert!(bundle.is_ok()); } #[test] fn bundle_new_verified_failure() { let public_key = r#"-----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAENptdY/l3nB0yqkXLBWkZWQwo6+cu OSWS1X9vPavpiQOoTTGC0xX57OojUadxF1cdQmrsiReWg2Wn4FneJfa8xw== -----END PUBLIC KEY-----"#; let not_rekor_pub_key = crypto::new_verification_key(public_key).unwrap(); let bundle_json = build_correct_bundle(); let bundle = Bundle::new_verified(&bundle_json, &not_rekor_pub_key); assert!(bundle.is_err()); } }
40.12844
779
0.724051
1dc412faf14f56d42112925cf95363a3b7dca3db
14,452
use std::fmt; use std::io; use std::net::Shutdown; use std::time::Duration; use crate::protocol::block::{Block, ServerBlock}; use crate::protocol::command::{CommandSink, ResponseStream}; use crate::protocol::insert::InsertSink; use crate::protocol::packet::Response; use crate::protocol::packet::{Execute, Hello, Ping}; use crate::protocol::query::Query; use crate::protocol::ServerWriter; use crate::{ errors::{DriverError, Result}, pool::{ options::{CompressionMethod, Options}, Pool, }, }; use chrono_tz::Tz; use futures::Future; use log::{debug, info, warn}; use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; use tokio::net::TcpStream; const DEF_OUT_BUF_SIZE: usize = 512; const DEFAULT_QUERY_BUF_SIZE: usize = 8 * 1024; /// Connection state flags const FLAG_DETERIORATED: u8 = 0x01; const FLAG_PENDING: u8 = 0x02; pub trait AsyncReadWrite: AsyncWrite + AsyncRead + Send + Unpin {} impl<T: AsyncWrite + AsyncRead + Send + Unpin> AsyncReadWrite for T {} #[derive(Debug)] pub(super) struct ServerInfo { pub(crate) revision: u32, pub(crate) readonly: u8, pub(crate) flag: u8, pub(crate) compression: CompressionMethod, pub(crate) timezone: Tz, } impl ServerInfo { #[inline] pub(crate) fn set_deteriorated(&mut self) { self.flag |= FLAG_DETERIORATED; } #[inline] pub(crate) fn set_pending(&mut self) { self.flag |= FLAG_PENDING; } #[inline] pub(crate) fn clear_pending(&mut self) { self.flag &= !FLAG_PENDING; } #[inline] pub(crate) fn is_pending(&self) -> bool { (self.flag & FLAG_PENDING) == FLAG_PENDING } } /// Implement established connection (active or idle) pub(super) struct Inner { pub(crate) socket: Option<TcpStream>, pub(crate) info: ServerInfo, } pub(super) type InnerConnection = Inner; pub struct QueryResult<'a, R: AsyncRead> { pub(crate) inner: ResponseStream<'a, R>, } impl<'a, R: AsyncWrite + AsyncRead + Unpin + Send> QueryResult<'a, R> { pub fn cancel(&'a mut self) -> impl Future<Output = Result<()>> + 'a { self.inner.cancel() } } impl<'a, R: AsyncRead + Unpin + Send> QueryResult<'a, R> { pub async fn next(&mut self) -> Result<Option<ServerBlock>> { while let Some(packet) = self.inner.next().await? { if let Response::Data(block) = packet { return Ok(Some(block)); } else { //println!("packet {:?}", packet); } } Ok(None) } #[inline] pub fn is_pending(&self) -> bool { self.inner.is_pending() } } impl<'a, R: AsyncRead> Drop for QueryResult<'a, R> { fn drop(&mut self) {} } impl Default for Inner { fn default() -> Inner { Inner { socket: None, info: ServerInfo { flag: 0, revision: crate::CLICK_HOUSE_REVISION as u32, timezone: chrono_tz::UTC, compression: CompressionMethod::None, readonly: 0, }, } } } impl ServerContext for Inner { #[inline] fn info(&self) -> &ServerInfo { &self.info } } impl Inner { #[inline] /// Return true if the connection is not initialized yet fn is_null(&self) -> bool { self.socket.is_none() } /// Check if the socket is connected to a peer pub(super) fn is_ok(&self) -> bool { self.socket .as_ref() .map_or(false, |socket| socket.peer_addr().is_ok()) } /// Split self into Stream and ServerInfo #[inline] pub(super) fn split(&mut self) -> Option<(&mut (dyn AsyncReadWrite + '_), &mut ServerInfo)> { let info = &mut self.info as *mut ServerInfo; // SAFETY: This can be risky if caller use returned values inside Connection // or InnerConnection methods. Never do it. match self.socket { None => None, Some(ref mut socket) => unsafe { Some((socket, &mut *info)) }, } } /// Establish a connection to a Clickhouse server pub(super) async fn init(options: &Options, addr: &str) -> Result<Box<Inner>> { let socket = TcpStream::connect(addr).await?; Inner::setup_stream(&socket, &options)?; info!( "connection established to: {}", socket.peer_addr().unwrap() ); // TODO: Tls handshake for secure connection like // https://github.com/tokio-rs/tls/blob/master/tokio-native-tls/examples/download-rust-lang.rs let conn = Inner::handshake(socket, &options).await?; Ok(conn) } /// Negotiate connection parameters such as timezone, revision, compression async fn handshake(mut socket: TcpStream, options: &Options) -> Result<Box<Self>> { let mut inner: Box<Inner> = Box::new(Default::default()); { let mut buf = Vec::with_capacity(256); { Hello { opt: options }.write(&inner.info, &mut buf)?; } socket.write_all(&buf[..]).await?; let stream: &mut dyn AsyncReadWrite = &mut socket; drop(buf); let mut stream = ResponseStream::with_capacity( 256, stream, &mut inner.info, options.connection_timeout, ); let (revision, timezone) = match stream.next().await? { Some(Response::Hello(_name, _major, _minor, revision, tz)) => (revision as u32, tz), _ => { socket.shutdown(Shutdown::Both)?; return Err(DriverError::ConnectionTimeout.into()); } }; drop(stream); inner.info.compression = options.compression; inner.info.revision = revision; inner.info.timezone = timezone; inner.info.readonly = options.readonly; } debug!("handshake complete"); inner.socket = Some(socket); Ok(inner) } #[inline] fn setup_stream(socket: &TcpStream, options: &Options) -> io::Result<()> { socket.set_keepalive(options.keepalive)?; socket.set_nodelay(true) } async fn cleanup(&mut self) -> Result<()> { // TODO: ensure cancel command indeed interrupt long-running process if (self.info.flag & FLAG_PENDING) == FLAG_PENDING { //TODO: simplify. There is no reason to call `split` method let wrt = if let Some((wrt, _info)) = self.split() { wrt } else { return Err(DriverError::ConnectionClosed.into()); }; debug!("cleanup connection"); CommandSink::new(wrt).cancel().await?; info!("sent cancel message"); }; Ok(()) } } pub(crate) trait ServerContext { fn info(&self) -> &ServerInfo; } /// Represent Clickhouse client active connection pub struct Connection { inner: Box<Inner>, pub(crate) pool: Option<Pool>, out: Vec<u8>, } impl fmt::Debug for Connection { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let peer = self.inner.socket.as_ref().map_or("-".to_string(), |s| { s.peer_addr().map_or("-".to_string(), |p| format!("{}", p)) }); f.debug_struct("Connection") .field("inner.pear", &peer) .finish() } } macro_rules! check_pending { ($this:ident) => { if $this.inner.info.is_pending() { return Err(DriverError::OperationInProgress.into()); } }; } impl Connection { /// Assemble connection from socket(Inner) and pool object pub(super) fn new(pool: Pool, mut conn: Box<Inner>) -> Connection { conn.info.flag = 0; Connection { pool: Some(pool), inner: conn, out: Vec::with_capacity(512), } } /// Returns Clickhouse server revision number #[inline] pub fn revision(&self) -> u32 { self.inner.info.revision } /// Check if a connection has pending status. /// Connection get pending status during query call until all data will be fetched /// or during insert call until commit #[inline] pub fn is_pending(&self) -> bool { self.inner.info.is_pending() } /// Returns Clickhouse server timezone #[inline] pub fn timezone(&self) -> Tz { self.inner.info.timezone } /// Mark connection as drain. This will recycle it on drop instead of retuning to pool #[inline] pub(super) fn set_deteriorated(&mut self) { self.inner.info.flag |= FLAG_DETERIORATED; } /// Disconnects this connection from server. pub(super) fn disconnect(mut self) -> Result<()> { if let Some(socket) = self.inner.socket.take() { debug!("disconnect method. shutdown connection"); socket.shutdown(Shutdown::Both)?; } Ok(()) } /// Get pool specific options or default ones if the connection is not established fn options(&self) -> &Options { self.pool.as_ref().map_or_else( || { let o: &Options = &*crate::DEF_OPTIONS; o }, |p| &p.inner.options, ) } /// Perform cleanum and disconnect from server. /// It would be better to drop connection instead of explicitly /// call `close`. Use `close` if you are not going to use the connection /// again or you need to interrupt server processes, /// associated with the connection pub async fn close(mut self) -> Result<()> { self.inner.cleanup().await?; self.disconnect() } /// Ping-pong connection verification pub async fn ping(&mut self) -> Result<()> { debug!("ping"); self.out.clear(); Ping.write(self.inner.info(), &mut self.out)?; let mut stream = self.write_command(self.options().ping_timeout).await?; while let Some(packet) = &mut stream.next().await? { match packet { Response::Pong => { info!("ping ok"); return Ok(()); } _ => { continue; // return Err(DriverError::PacketOutOfOrder(packet.code()).into()); } } } warn!("ping failed"); Err(DriverError::ConnectionTimeout.into()) } /// Execute DDL query statement. /// Query should not return query result. Otherwise it will return error. pub async fn execute(&mut self, ddl: impl Into<Query>) -> Result<()> { check_pending!(self); self.out.clear(); Execute { query: ddl.into() }.write(self.inner.info(), &mut self.out)?; let mut stream = self.write_command(self.options().execute_timeout).await?; if let Some(packet) = stream.next().await? { warn!("execute method returns packet {}", packet.code()); return Err(DriverError::PacketOutOfOrder(packet.code()).into()); } Ok(()) } /// Execute INSERT query sending Block of data /// Returns InsertSink that can be used to streaming next Blocks of data pub async fn insert( &mut self, data: &Block<'_>, ) -> Result<InsertSink<'_, &mut dyn AsyncReadWrite>> { check_pending!(self); let query = Query::from_block(&data); self.out.clear(); Execute { query }.write(self.inner.info(), &mut self.out)?; let mut stream = self.write_command(self.options().insert_timeout).await?; // We get first block with no rows. We can use it to define table structure. // Before call insert we will check input data against server table structure stream.skip_empty = false; //stream.set_pending(); let mut stream = if let Some(Response::Data(block)) = stream.next().await? { // log::info!("{:?}", &block); InsertSink::new(stream, block) } else { stream.set_deteriorated(); warn!("insert method. unknown packet received"); return Err(DriverError::PacketOutOfOrder(0).into()); }; stream.next(&data).await?; Ok(stream) } /// Execute SELECT statement returning sequence of ServerBlocks. /// /// # Example /// ```text /// use clickhouse_driver::prelude::*; /// /// let pool = Pool::create("tcp://localhost/"); /// let mut con = pool.connection().await.unwrap(); /// let query = con.query("SELECT id,title,message,host,ip FROM log").await.unwrap(); /// //... /// ``` pub async fn query( &mut self, sql: impl Into<Query>, ) -> Result<QueryResult<'_, &mut dyn AsyncReadWrite>> { check_pending!(self); self.out.clear(); Execute { query: sql.into() }.write(self.inner.info(), &mut self.out)?; let stream = self.write_command(self.options().query_timeout).await?; Ok(QueryResult { inner: stream }) } /// Take inner connection. Drain itself #[inline] pub(super) fn take(&mut self) -> Box<Inner> { //std::mem::replace(&mut self.inner, Box::new(Inner::default())) std::mem::take(&mut self.inner) } async fn write_command( &mut self, timeout: Duration, ) -> Result<ResponseStream<'_, &mut dyn AsyncReadWrite>> { let (rw, info) = if let Some((rw, info)) = self.inner.split() { (rw, info) } else { return Err(DriverError::ConnectionClosed.into()); }; info.set_pending(); let mut stream = ResponseStream::with_capacity(DEFAULT_QUERY_BUF_SIZE, rw, info, timeout); stream.write(self.out.as_slice()).await?; self.out.truncate(DEF_OUT_BUF_SIZE); Ok(stream) } } pub(crate) fn disconnect(mut conn: Box<Inner>) { if let Ok(handle) = tokio::runtime::Handle::try_current() { handle.spawn(async move { conn.cleanup().await }); } } impl Drop for Connection { fn drop(&mut self) { if std::thread::panicking() { return; } let conn = self.take(); if conn.is_null() { return; } if let Some(pool) = self.pool.take() { pool.inner.return_connection(conn); } else { disconnect(conn); } } }
30.814499
102
0.569402
76fe27a572dcf54503737c2f8ee59c7934354299
23,694
//! The plugin defines and implements the plugin interface, conversion boilerplate, //! internal plugins, and web plugin helpers #[macro_use] pub mod macros; pub mod catalog; pub mod external; pub mod interface; pub mod internal; use crate as cincinnati; use self::cincinnati::plugins::interface::{PluginError, PluginExchange}; use async_trait::async_trait; pub use commons::prelude_errors::*; use commons::tracing::get_tracer; use std::collections::HashMap; use std::convert::{TryFrom, TryInto}; use std::fmt::Debug; use opentelemetry::api::{trace::futures::Instrument, Tracer}; pub mod prelude { use crate as cincinnati; use self::cincinnati::plugins; pub use plugins::{BoxedPlugin, InternalPluginWrapper}; pub use plugins::catalog::PluginSettings; pub use plugins::internal::arch_filter::ArchFilterPlugin; pub use plugins::internal::channel_filter::ChannelFilterPlugin; pub use plugins::internal::cincinnati_graph_fetch::CincinnatiGraphFetchPlugin; pub use plugins::internal::edge_add_remove::EdgeAddRemovePlugin; pub use plugins::internal::github_openshift_secondary_metadata_scraper::{ GithubOpenshiftSecondaryMetadataScraperPlugin, GithubOpenshiftSecondaryMetadataScraperSettings, }; pub use plugins::internal::metadata_fetch_quay::QuayMetadataFetchPlugin; pub use plugins::internal::node_remove::NodeRemovePlugin; pub use plugins::internal::openshift_secondary_metadata_parser::{ OpenshiftSecondaryMetadataParserPlugin, OpenshiftSecondaryMetadataParserSettings, }; pub use plugins::internal::release_scrape_dockerv2::{ ReleaseScrapeDockerv2Plugin, ReleaseScrapeDockerv2Settings, }; pub use std::iter::FromIterator; pub use commons::prelude_errors::*; } pub mod prelude_plugin_impl { use self::cincinnati::plugins; use crate as cincinnati; pub use self::cincinnati::{daggy, ReleaseId}; pub use plugins::catalog::PluginSettings; pub use plugins::{BoxedPlugin, InternalIO, InternalPlugin, InternalPluginWrapper}; pub use async_trait::async_trait; pub use commons::prelude_errors::*; pub use custom_debug_derive::CustomDebug; pub use futures::TryFutureExt; pub use log::{debug, error, info, trace, warn}; pub use serde::{de::DeserializeOwned, Deserialize}; pub use smart_default::SmartDefault; pub use std::path::PathBuf; pub use std::str::FromStr; } /// Convenience type for the thread-safe storage of plugins pub type BoxedPlugin = Box<dyn Plugin<PluginIO>>; // NOTE(lucab): this abuses `Debug`, because `PartialEq` is not object-safe and // thus cannot be required on the underlying trait. It is a crude hack, but // only meant to be used by test assertions. impl PartialEq<BoxedPlugin> for BoxedPlugin { fn eq(&self, other: &Self) -> bool { format!("{:?}", self) == format!("{:?}", other) } } /// Enum for the two IO variants used by InternalPlugin and ExternalPlugin respectively #[derive(Debug)] #[cfg_attr(test, derive(Clone))] pub enum PluginIO { InternalIO(InternalIO), ExternalIO(ExternalIO), } /// Error type which corresponds to interface::PluginError #[derive(Debug, Fail)] pub enum ExternalError { #[error("PluginError: {:?}", 0)] PluginError(PluginError), } /// Enum for wrapping the interface plugin output types #[derive(Debug, PartialEq)] pub enum PluginResult { PluginExchange(interface::PluginExchange), PluginError(interface::PluginError), } /// Struct used by the ExternalPlugin trait impl's #[derive(Debug, PartialEq)] #[cfg_attr(test, derive(Clone))] pub struct InternalIO { pub graph: cincinnati::Graph, pub parameters: HashMap<String, String>, } /// Struct used by the InternalPlugin trait impl's #[derive(Debug, PartialEq)] #[cfg_attr(test, derive(Clone))] pub struct ExternalIO { pub bytes: Vec<u8>, } /// Trait which fronts InternalPlugin and ExternalPlugin, allowing their trait objects to live in the same collection #[async_trait] pub trait Plugin<T> where Self: Sync + Send + Debug, T: TryInto<PluginIO> + TryFrom<PluginIO>, T: Sync + Send, { async fn run(self: &Self, t: T) -> Fallible<T>; fn get_name(self: &Self) -> &'static str; } /// Trait to be implemented by internal plugins with their native IO type #[async_trait] pub trait InternalPlugin { const PLUGIN_NAME: &'static str; async fn run_internal(self: &Self, input: InternalIO) -> Fallible<InternalIO>; fn get_name(self: &Self) -> &'static str { Self::PLUGIN_NAME } } /// Trait to be implemented by external plugins with its native IO type /// /// There's a gotcha in that this type can't be used to access the information /// directly as it's merely bytes. #[async_trait] pub trait ExternalPlugin where Self: Debug, { const PLUGIN_NAME: &'static str; async fn run_external(self: &Self, input: ExternalIO) -> Fallible<ExternalIO>; fn get_name(self: &Self) -> &'static str { Self::PLUGIN_NAME } } /// Convert from InternalIO to PluginIO /// /// This merely wraps the struct into the enum variant. impl From<InternalIO> for PluginIO { fn from(internal_io: InternalIO) -> Self { PluginIO::InternalIO(internal_io) } } /// Convert from ExternalIO to PluginIO /// /// This merely wraps the struct into the enum variant. impl From<ExternalIO> for PluginIO { fn from(external_io: ExternalIO) -> Self { PluginIO::ExternalIO(external_io) } } /// Converts ExternalIO to PluginExchange /// /// This can fail because the ExternalIO bytes need to be deserialized into the /// PluginExchange type. impl TryFrom<ExternalIO> for PluginExchange { type Error = Error; fn try_from(external_io: ExternalIO) -> Fallible<Self> { protobuf::parse_from_bytes(&external_io.bytes) .context("could not parse ExternalIO to PluginExchange") .map_err(Into::into) } } /// Convert from ExternalIO to PluginError /// /// This can fail because the ExternalIO bytes need to be deserialized into the /// PluginError type. impl TryFrom<ExternalIO> for PluginError { type Error = Error; fn try_from(external_io: ExternalIO) -> Fallible<Self> { protobuf::parse_from_bytes(&external_io.bytes) .context("could not parse ExternalIO to PluginError") .map_err(Into::into) } } /// Convert from ExternalIO to PluginResult /// /// This can fail because the bytes of ExternalIO need to be deserialized into /// either of PluginExchange or PluginError. impl TryFrom<Fallible<ExternalIO>> for PluginResult { type Error = Error; fn try_from(external_io: Fallible<ExternalIO>) -> Fallible<Self> { match external_io { Ok(external_io) => { let exchange: interface::PluginExchange = external_io.try_into()?; Ok(PluginResult::PluginExchange(exchange)) } Err(e) => match e.downcast::<ExternalError>() { Ok(ExternalError::PluginError(error)) => Ok(PluginResult::PluginError(error)), Err(e) => Err(e), }, } } } /// Convert from interface::PluginError to a Fallible<ExternalIO> which has the PluginError embedded impl From<interface::PluginError> for Fallible<ExternalIO> { fn from(plugin_error: interface::PluginError) -> Fallible<ExternalIO> { Err(ExternalError::PluginError(plugin_error).into()) } } /// Convert from PluginExchange to ExternalIO /// /// This can fail because PluginExchange needs to be serialized into the bytes. impl TryFrom<PluginExchange> for ExternalIO { type Error = Error; fn try_from(exchange: PluginExchange) -> Fallible<Self> { use protobuf::Message; Ok(Self { bytes: exchange.write_to_bytes()?, }) } } /// Try to convert from ExternalIO to InternalIO /// /// This can fail because the ExternalIO bytes need to be deserialized into the /// InternalIO type. impl TryFrom<ExternalIO> for InternalIO { type Error = Error; fn try_from(external_io: ExternalIO) -> Fallible<Self> { let mut plugin_exchange: PluginExchange = external_io.try_into()?; Ok(Self { graph: plugin_exchange.take_graph().into(), parameters: plugin_exchange.take_parameters(), }) } } /// Convert from an InternalIO to a PluginExchange /// /// This conversion cannot fail. impl From<InternalIO> for interface::PluginExchange { fn from(internal_io: InternalIO) -> Self { let mut plugin_exchange = Self::new(); plugin_exchange.set_graph(internal_io.graph.into()); plugin_exchange.set_parameters(internal_io.parameters); plugin_exchange } } /// Convert from InternalIO to ExternalIO /// /// The serialization can apparently fail. impl TryFrom<InternalIO> for ExternalIO { type Error = Error; fn try_from(internal_io: InternalIO) -> Fallible<Self> { let exchange: PluginExchange = internal_io.into(); exchange.try_into() } } /// Try to convert from PluginIO to InternalIO /// /// In case of the variant Plugion::ExternalIO this involves deserialization /// which might fail. impl TryFrom<PluginIO> for InternalIO { type Error = Error; fn try_from(plugin_io: PluginIO) -> Fallible<Self> { match plugin_io { PluginIO::InternalIO(internal_io) => Ok(internal_io), PluginIO::ExternalIO(external_io) => external_io.try_into(), } } } /// Compatibility impl to automatically convert the unvarianted PluginIO when the /// variant struct ExternalIO is expected. /// /// This may fail due to the possible failing conversion. impl TryFrom<PluginIO> for ExternalIO { type Error = Error; fn try_from(plugin_io: PluginIO) -> Fallible<Self> { let final_io = match plugin_io { PluginIO::ExternalIO(external_io) => external_io, PluginIO::InternalIO(internal_io) => internal_io.try_into()?, }; Ok(final_io) } } /// Wrapper struct for a universal implementation of Plugin<PluginIO> for all InternalPlugin implementors #[derive(Debug)] pub struct InternalPluginWrapper<T>(pub T); /// Wrapper struct for a universal implementation of Plugin<PluginIO> for all ExternalPlugin implementors #[derive(Debug)] pub struct ExternalPluginWrapper<T>(pub T); /// This implementation allows the process function to run ipmlementors of /// InternalPlugin #[async_trait] impl<T> Plugin<PluginIO> for InternalPluginWrapper<T> where T: InternalPlugin, T: Sync + Send + Debug, { async fn run(self: &Self, plugin_io: PluginIO) -> Fallible<PluginIO> { let internal_io: InternalIO = plugin_io.try_into()?; Ok(self.0.run_internal(internal_io).await?.into()) } fn get_name(&self) -> &'static str { <T as InternalPlugin>::PLUGIN_NAME } } /// This implementation allows the process function to run ipmlementors of /// ExternalPlugin #[async_trait] impl<T> Plugin<PluginIO> for ExternalPluginWrapper<T> where T: ExternalPlugin, T: Sync + Send + Debug, { async fn run(self: &Self, plugin_io: PluginIO) -> Fallible<PluginIO> { let external_io: ExternalIO = plugin_io.try_into()?; Ok(self.0.run_external(external_io).await?.into()) } fn get_name(&self) -> &'static str { <T as ExternalPlugin>::PLUGIN_NAME } } /// Processes all given Plugins sequentially. /// /// This function automatically converts between the different IO representations /// if necessary. pub async fn process<T>(plugins: T, initial_io: PluginIO) -> Fallible<InternalIO> where T: Iterator<Item = &'static BoxedPlugin>, T: Sync + Send, T: 'static, { let mut io = initial_io; let _ = get_tracer().start("plugins", None); for next_plugin in plugins { let plugin_name = next_plugin.get_name(); log::trace!("Running next plugin '{}'", plugin_name); let plugin_span = get_tracer().start(plugin_name, None); io = next_plugin.run(io).instrument(plugin_span).await?; } io.try_into() } /// Wrapper around `process` with an optional timeout. /// /// It creates a new runtime per call which is moved to a new thread. /// This has the desired effect of timing out even if the runtime is blocked by a task. /// It has the sideeffect that these threads are unrecoverably leaked. /// /// These two strategies are used in combination to implement the timeout: /// 1. Use the runtime's internal timeout implementation which works for proper async tasks. /// 2. Spawn a separate sleeper thread to enforce a deadline of 101% of the timeout /// in case the async timeout is not effective. pub fn process_blocking<T>( plugins: T, initial_io: PluginIO, timeout: Option<std::time::Duration>, ) -> Fallible<InternalIO> where T: Iterator<Item = &'static BoxedPlugin>, T: Sync + Send, T: 'static, { let mut runtime = tokio::runtime::Runtime::new()?; let timeout = match timeout { None => return runtime.block_on(process(plugins, initial_io)), Some(timeout) => timeout, }; let deadline = timeout + (timeout / 100); let (tx, rx) = std::sync::mpsc::channel::<Fallible<InternalIO>>(); { let tx = tx.clone(); std::thread::spawn(move || { let io_future = async { tokio::time::timeout(timeout, process(plugins, initial_io)).await }; let io_result = runtime .block_on(io_future) .context(format!( "Processing all plugins with a timeout of {:?}", timeout )) .map_err(Error::from) .unwrap_or_else(Err); // This may fail if it's attempted after the timeout is exceeded. let _ = tx.send(io_result); }); }; std::thread::spawn(move || { std::thread::sleep(deadline); // This may fail if it's attempted after processing is finished. let _ = tx.send(Err(format_err!("Exceeded timeout of {:?}", &timeout))); }); rx.recv()? } #[cfg(test)] mod tests { use super::*; use crate::testing::generate_graph; use futures::lock::Mutex as FuturesMutex; use lazy_static::lazy_static; use std::collections::HashMap; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; #[test] fn convert_externalio_pluginresult() { let kind = interface::PluginError_Kind::INTERNAL_FAILURE; let value = "test succeeds on error".to_string(); let mut original_error = interface::PluginError::new(); original_error.set_kind(kind); original_error.set_value(value.clone()); let expected_result = PluginResult::PluginError(original_error.clone()); let external_io: Fallible<ExternalIO> = original_error.into(); let converted_result: PluginResult = external_io.try_into().unwrap(); assert_eq!(converted_result, expected_result); } #[test] fn convert_roundtrip_internalio_externalio() { let graph = generate_graph(); let input_internal = InternalIO { graph: graph.clone(), parameters: [("hello".to_string(), "plugin".to_string())] .iter() .cloned() .collect(), }; let output_external: ExternalIO = input_internal.clone().try_into().unwrap(); let output_internal: InternalIO = output_external.try_into().unwrap(); assert_eq!(input_internal, output_internal); } #[derive(custom_debug_derive::CustomDebug)] #[allow(clippy::type_complexity)] struct TestInternalPlugin { counter: AtomicUsize, dict: Arc<FuturesMutex<HashMap<usize, bool>>>, #[debug(skip)] inner_fn: Option<Arc<dyn Fn() -> Fallible<()> + Sync + Send>>, } #[async_trait] impl InternalPlugin for TestInternalPlugin { const PLUGIN_NAME: &'static str = "test_internal_plugin"; async fn run_internal(self: &Self, mut io: InternalIO) -> Fallible<InternalIO> { if let Some(inner_fn) = &self.inner_fn { inner_fn()?; } self.counter.fetch_add(1, Ordering::SeqCst); let counter = self.counter.load(Ordering::SeqCst); let mut dict_guard = self.dict.lock().await; (*dict_guard).insert(counter, true); io.parameters .insert("COUNTER".to_string(), format!("{}", counter)); Ok(io) } } #[derive(Debug)] struct TestExternalPlugin {} #[async_trait] impl ExternalPlugin for TestExternalPlugin { const PLUGIN_NAME: &'static str = "test_internal_plugin"; async fn run_external(self: &Self, io: ExternalIO) -> Fallible<ExternalIO> { Ok(io) } } #[test] fn process_plugins_roundtrip_external_internal() -> Fallible<()> { let mut runtime = commons::testing::init_runtime()?; lazy_static! { static ref PLUGINS: Vec<BoxedPlugin> = new_plugins!( ExternalPluginWrapper(TestExternalPlugin {}), InternalPluginWrapper(TestInternalPlugin { counter: Default::default(), dict: Arc::new(FuturesMutex::new(Default::default())), inner_fn: None, }), ExternalPluginWrapper(TestExternalPlugin {}) ); } let initial_internalio = InternalIO { graph: generate_graph(), parameters: [("hello".to_string(), "plugin".to_string())] .iter() .cloned() .collect(), }; let expected_internalio = InternalIO { graph: generate_graph(), parameters: [ ("hello".to_string(), "plugin".to_string()), ("COUNTER".to_string(), "1".to_string()), ] .iter() .cloned() .collect(), }; let plugins_future = super::process( PLUGINS.iter(), PluginIO::InternalIO(initial_internalio.clone()), ); let result_internalio: InternalIO = runtime.block_on(plugins_future)?; assert_eq!(expected_internalio, result_internalio); Ok(()) } #[test] fn process_plugins_loop() -> Fallible<()> { let mut runtime = commons::testing::init_runtime()?; lazy_static! { static ref PLUGINS: Vec<BoxedPlugin> = new_plugins!( ExternalPluginWrapper(TestExternalPlugin {}), InternalPluginWrapper(TestInternalPlugin { counter: Default::default(), dict: Arc::new(FuturesMutex::new(Default::default())), inner_fn: None, }), ExternalPluginWrapper(TestExternalPlugin {}) ); } let initial_internalio = InternalIO { graph: generate_graph(), parameters: [("hello".to_string(), "plugin".to_string())] .iter() .cloned() .collect(), }; let runs: usize = 10; for i in 0..runs { let expected_internalio = InternalIO { graph: generate_graph(), parameters: [ ("hello".to_string(), "plugin".to_string()), ("COUNTER".to_string(), format!("{}", i + 1)), ] .iter() .cloned() .collect(), }; let plugins_future = process( PLUGINS.iter(), PluginIO::InternalIO(initial_internalio.clone()), ); let result_internalio: InternalIO = runtime.block_on(plugins_future)?; assert_eq!(expected_internalio, result_internalio); } Ok(()) } #[test] fn process_blocking_succeeds() -> Fallible<()> { lazy_static! { static ref PLUGIN_DELAY: std::time::Duration = std::time::Duration::from_secs(1); static ref PLUGINS: Vec<BoxedPlugin> = new_plugins!(InternalPluginWrapper(TestInternalPlugin { counter: Default::default(), dict: Arc::new(FuturesMutex::new(Default::default())), inner_fn: Some(Arc::new(|| { std::thread::sleep(*PLUGIN_DELAY); Ok(()) })), })); } let initial_internalio = InternalIO { graph: Default::default(), parameters: Default::default(), }; let timeout = *PLUGIN_DELAY * 2; let before_process = std::time::Instant::now(); let result_internalio = super::process_blocking( PLUGINS.iter(), PluginIO::InternalIO(initial_internalio), Some(timeout), ); let process_duration = before_process.elapsed(); assert!( process_duration < timeout, "took {:?} despite timeout of {:?}", process_duration, timeout, ); assert!( result_internalio.is_ok(), "Expected Ok, got {:?}", result_internalio ); Ok(()) } #[test] fn process_blocking_times_out() -> Fallible<()> { lazy_static! { static ref PLUGIN_DELAY: std::time::Duration = std::time::Duration::from_secs(100); static ref PLUGINS: Vec<BoxedPlugin> = new_plugins!(InternalPluginWrapper(TestInternalPlugin { counter: Default::default(), dict: Arc::new(FuturesMutex::new(Default::default())), inner_fn: Some(Arc::new(|| { std::thread::sleep(*PLUGIN_DELAY); Ok(()) })), })); } let initial_internalio = InternalIO { graph: Default::default(), parameters: Default::default(), }; // timeout hit let timeout = *PLUGIN_DELAY / 100; for _ in 0..10 { let before_process = std::time::Instant::now(); let result_internalio = super::process_blocking( PLUGINS.iter(), PluginIO::InternalIO(initial_internalio.clone()), Some(timeout), ); let process_duration = before_process.elapsed(); assert!( process_duration < *PLUGIN_DELAY, "took {:?} despite timeout of {:?}", process_duration, timeout, ); assert!( result_internalio.is_err(), "Expected error, got {:?}", result_internalio ); } Ok(()) } #[test] fn plugin_names() -> Fallible<()> { lazy_static! { static ref PLUGINS: Vec<BoxedPlugin> = new_plugins!( ExternalPluginWrapper(TestExternalPlugin {}), InternalPluginWrapper(TestInternalPlugin { counter: Default::default(), dict: Arc::new(FuturesMutex::new(Default::default())), inner_fn: None, }), ExternalPluginWrapper(TestExternalPlugin {}) ); } assert_eq!(PLUGINS[0].get_name(), TestExternalPlugin::PLUGIN_NAME); assert_eq!(PLUGINS[1].get_name(), TestInternalPlugin::PLUGIN_NAME); Ok(()) } }
31.217391
117
0.617709
08b976a909634823bcc4ce7a09d11f5ed0d2a8c8
3,578
// xfail-fast // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern mod std; #[abi = "rust-intrinsic"] extern mod rusti { fn ctpop8(x: i8) -> i8; fn ctpop16(x: i16) -> i16; fn ctpop32(x: i32) -> i32; fn ctpop64(x: i64) -> i64; fn ctlz8(x: i8) -> i8; fn ctlz16(x: i16) -> i16; fn ctlz32(x: i32) -> i32; fn ctlz64(x: i64) -> i64; fn cttz8(x: i8) -> i8; fn cttz16(x: i16) -> i16; fn cttz32(x: i32) -> i32; fn cttz64(x: i64) -> i64; fn bswap16(x: i16) -> i16; fn bswap32(x: i32) -> i32; fn bswap64(x: i64) -> i64; } fn main() { unsafe { use rusti::*; assert(ctpop8(0i8) == 0i8); assert(ctpop16(0i16) == 0i16); assert(ctpop32(0i32) == 0i32); assert(ctpop64(0i64) == 0i64); assert(ctpop8(1i8) == 1i8); assert(ctpop16(1i16) == 1i16); assert(ctpop32(1i32) == 1i32); assert(ctpop64(1i64) == 1i64); assert(ctpop8(10i8) == 2i8); assert(ctpop16(10i16) == 2i16); assert(ctpop32(10i32) == 2i32); assert(ctpop64(10i64) == 2i64); assert(ctpop8(100i8) == 3i8); assert(ctpop16(100i16) == 3i16); assert(ctpop32(100i32) == 3i32); assert(ctpop64(100i64) == 3i64); assert(ctpop8(-1i8) == 8i8); assert(ctpop16(-1i16) == 16i16); assert(ctpop32(-1i32) == 32i32); assert(ctpop64(-1i64) == 64i64); assert(ctlz8(0i8) == 8i8); assert(ctlz16(0i16) == 16i16); assert(ctlz32(0i32) == 32i32); assert(ctlz64(0i64) == 64i64); assert(ctlz8(1i8) == 7i8); assert(ctlz16(1i16) == 15i16); assert(ctlz32(1i32) == 31i32); assert(ctlz64(1i64) == 63i64); assert(ctlz8(10i8) == 4i8); assert(ctlz16(10i16) == 12i16); assert(ctlz32(10i32) == 28i32); assert(ctlz64(10i64) == 60i64); assert(ctlz8(100i8) == 1i8); assert(ctlz16(100i16) == 9i16); assert(ctlz32(100i32) == 25i32); assert(ctlz64(100i64) == 57i64); assert(cttz8(-1i8) == 0i8); assert(cttz16(-1i16) == 0i16); assert(cttz32(-1i32) == 0i32); assert(cttz64(-1i64) == 0i64); assert(cttz8(0i8) == 8i8); assert(cttz16(0i16) == 16i16); assert(cttz32(0i32) == 32i32); assert(cttz64(0i64) == 64i64); assert(cttz8(1i8) == 0i8); assert(cttz16(1i16) == 0i16); assert(cttz32(1i32) == 0i32); assert(cttz64(1i64) == 0i64); assert(cttz8(10i8) == 1i8); assert(cttz16(10i16) == 1i16); assert(cttz32(10i32) == 1i32); assert(cttz64(10i64) == 1i64); assert(cttz8(100i8) == 2i8); assert(cttz16(100i16) == 2i16); assert(cttz32(100i32) == 2i32); assert(cttz64(100i64) == 2i64); assert(cttz8(-1i8) == 0i8); assert(cttz16(-1i16) == 0i16); assert(cttz32(-1i32) == 0i32); assert(cttz64(-1i64) == 0i64); assert(bswap16(0x0A0Bi16) == 0x0B0Ai16); assert(bswap32(0x0ABBCC0Di32) == 0x0DCCBB0Ai32); assert(bswap64(0x0122334455667708i64) == 0x0877665544332201i64); } }
29.570248
72
0.557574
9c5f66a6416e7b9fcd332683cee5a56427655d8d
1,540
// 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::Object; use glib::object::IsA; use glib::translate::*; use std::fmt; glib::glib_wrapper! { pub struct ObjectFactory(Object<ffi::AtkObjectFactory, ffi::AtkObjectFactoryClass>); match fn { get_type => || ffi::atk_object_factory_get_type(), } } pub const NONE_OBJECT_FACTORY: Option<&ObjectFactory> = None; pub trait ObjectFactoryExt: 'static { fn create_accessible<P: IsA<glib::Object>>(&self, obj: &P) -> Option<Object>; fn get_accessible_type(&self) -> glib::types::Type; fn invalidate(&self); } impl<O: IsA<ObjectFactory>> ObjectFactoryExt for O { fn create_accessible<P: IsA<glib::Object>>(&self, obj: &P) -> Option<Object> { unsafe { from_glib_full(ffi::atk_object_factory_create_accessible( self.as_ref().to_glib_none().0, obj.as_ref().to_glib_none().0, )) } } fn get_accessible_type(&self) -> glib::types::Type { unsafe { from_glib(ffi::atk_object_factory_get_accessible_type( self.as_ref().to_glib_none().0, )) } } fn invalidate(&self) { unsafe { ffi::atk_object_factory_invalidate(self.as_ref().to_glib_none().0); } } } impl fmt::Display for ObjectFactory { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("ObjectFactory") } }
26.551724
88
0.615584
6a32407dc0c9a94d4b38fa766cef3f34ae6fa07f
14,261
use crate::raw::{OriginalRoad, RestrictionType}; use crate::{osm, BusStopID, IntersectionID, LaneID, LaneType, Map, PathConstraints}; use abstutil::{Error, Warn}; use geom::{Distance, PolyLine, Polygon, Speed}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashSet}; use std::fmt; // TODO reconsider pub usize. maybe outside world shouldnt know. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)] pub struct RoadID(pub usize); impl fmt::Display for RoadID { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Road #{}", self.0) } } impl RoadID { pub fn forwards(self) -> DirectedRoadID { DirectedRoadID { id: self, forwards: true, } } pub fn backwards(self) -> DirectedRoadID { DirectedRoadID { id: self, forwards: false, } } } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize, Deserialize)] pub struct DirectedRoadID { pub id: RoadID, pub forwards: bool, } impl fmt::Display for DirectedRoadID { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "DirectedRoadID({}, {})", self.id.0, if self.forwards { "forwards" } else { "backwards" } ) } } impl DirectedRoadID { pub fn src_i(self, map: &Map) -> IntersectionID { let r = map.get_r(self.id); if self.forwards { r.src_i } else { r.dst_i } } pub fn dst_i(self, map: &Map) -> IntersectionID { let r = map.get_r(self.id); if self.forwards { r.dst_i } else { r.src_i } } // Strict for bikes. If there are bike lanes, not allowed to use other lanes. pub fn lanes(self, constraints: PathConstraints, map: &Map) -> Vec<LaneID> { let r = map.get_r(self.id); if self.forwards { constraints.filter_lanes(&r.children_forwards.iter().map(|(l, _)| *l).collect(), map) } else { constraints.filter_lanes(&r.children_backwards.iter().map(|(l, _)| *l).collect(), map) } } } // These're bidirectional (possibly) #[derive(Serialize, Deserialize, Debug)] pub struct Road { pub id: RoadID, // I've previously tried storing these in a compressed lookup table (since the keys and values // are often common), but the performance benefit was negligible, and the increased API // complexity was annoying. pub osm_tags: BTreeMap<String, String>, // self is 'from' pub turn_restrictions: Vec<(RestrictionType, RoadID)>, // self is 'from'. (via, to). Only BanTurns. pub complicated_turn_restrictions: Vec<(RoadID, RoadID)>, pub orig_id: OriginalRoad, pub speed_limit: Speed, pub zorder: isize, // Invariant: A road must contain at least one child // These are ordered from closest to center lane (left-most when driving on the right) to // farthest (sidewalk) pub children_forwards: Vec<(LaneID, LaneType)>, pub children_backwards: Vec<(LaneID, LaneType)>, // Unshifted original center points. Order implies road orientation. Reversing lanes doesn't // change this. pub center_pts: PolyLine, pub src_i: IntersectionID, pub dst_i: IntersectionID, } impl Road { pub fn get_lane_types(&self) -> (Vec<LaneType>, Vec<LaneType>) { ( self.children_forwards.iter().map(|pair| pair.1).collect(), self.children_backwards.iter().map(|pair| pair.1).collect(), ) } pub fn is_forwards(&self, lane: LaneID) -> bool { self.dir_and_offset(lane).0 } pub fn is_backwards(&self, lane: LaneID) -> bool { !self.dir_and_offset(lane).0 } // lane must belong to this road. Offset 0 is the centermost lane on each side of a road, then // it counts up from there. Returns true for the forwards direction, false for backwards. pub fn dir_and_offset(&self, lane: LaneID) -> (bool, usize) { if let Some(idx) = self .children_forwards .iter() .position(|pair| pair.0 == lane) { return (true, idx); } if let Some(idx) = self .children_backwards .iter() .position(|pair| pair.0 == lane) { return (false, idx); } panic!("{} doesn't contain {}", self.id, lane); } pub fn parking_to_driving(&self, parking: LaneID) -> Option<LaneID> { // TODO Crossing bike/bus lanes means higher layers of sim should know to block these off // when parking/unparking let (fwds, idx) = self.dir_and_offset(parking); if fwds { self.children_forwards[0..idx] .iter() .rev() .chain(self.children_backwards.iter()) .find(|(_, lt)| *lt == LaneType::Driving) .map(|(id, _)| *id) } else { self.children_backwards[0..idx] .iter() .rev() .chain(self.children_forwards.iter()) .find(|(_, lt)| *lt == LaneType::Driving) .map(|(id, _)| *id) } } pub fn sidewalk_to_bike(&self, sidewalk: LaneID) -> Option<LaneID> { // TODO Crossing bus lanes means higher layers of sim should know to block these off // Oneways mean we might need to consider the other side of the road. let (fwds, idx) = self.dir_and_offset(sidewalk); if fwds { self.children_forwards[0..idx] .iter() .rev() .chain(self.children_backwards.iter()) .find(|(_, lt)| *lt == LaneType::Driving || *lt == LaneType::Biking) .map(|(id, _)| *id) } else { self.children_backwards[0..idx] .iter() .rev() .chain(self.children_forwards.iter()) .find(|(_, lt)| *lt == LaneType::Driving || *lt == LaneType::Biking) .map(|(id, _)| *id) } } pub fn bike_to_sidewalk(&self, bike: LaneID) -> Option<LaneID> { // TODO Crossing bus lanes means higher layers of sim should know to block these off let (fwds, idx) = self.dir_and_offset(bike); if fwds { self.children_forwards[idx..] .iter() .find(|(_, lt)| *lt == LaneType::Sidewalk) .map(|(id, _)| *id) } else { self.children_backwards[idx..] .iter() .find(|(_, lt)| *lt == LaneType::Sidewalk) .map(|(id, _)| *id) } } pub(crate) fn speed_limit_from_osm(&self) -> Speed { if let Some(limit) = self.osm_tags.get(osm::MAXSPEED) { // TODO handle other units if limit.ends_with(" mph") { if let Ok(mph) = limit[0..limit.len() - 4].parse::<f64>() { return Speed::miles_per_hour(mph); } } } if self.osm_tags.get(osm::HIGHWAY) == Some(&"primary".to_string()) || self.osm_tags.get(osm::HIGHWAY) == Some(&"secondary".to_string()) { return Speed::miles_per_hour(40.0); } Speed::miles_per_hour(20.0) } pub fn incoming_lanes(&self, i: IntersectionID) -> &Vec<(LaneID, LaneType)> { if self.src_i == i { &self.children_backwards } else if self.dst_i == i { &self.children_forwards } else { panic!("{} doesn't have an endpoint at {}", self.id, i); } } pub fn outgoing_lanes(&self, i: IntersectionID) -> &Vec<(LaneID, LaneType)> { if self.src_i == i { &self.children_forwards } else if self.dst_i == i { &self.children_backwards } else { panic!("{} doesn't have an endpoint at {}", self.id, i); } } // If 'from' is a sidewalk, we'll also consider lanes on the other side of the road, if needed. // TODO But reusing dist_along will break loudly in that case! Really need a perpendicular // projection-and-collision method to find equivalent dist_along's. pub(crate) fn find_closest_lane( &self, from: LaneID, types: Vec<LaneType>, ) -> Result<LaneID, Error> { let lane_types: HashSet<LaneType> = types.into_iter().collect(); let (dir, from_idx) = self.dir_and_offset(from); let mut list = if dir { &self.children_forwards } else { &self.children_backwards }; // Deal with one-ways and sidewalks on both sides if list.len() == 1 && list[0].1 == LaneType::Sidewalk { list = if dir { &self.children_backwards } else { &self.children_forwards }; } if let Some((_, lane)) = list .iter() .enumerate() .filter(|(_, (lane, lt))| *lane != from && lane_types.contains(lt)) .map(|(idx, (lane, _))| (((from_idx as isize) - (idx as isize)).abs(), *lane)) .min_by_key(|(offset, _)| *offset) { Ok(lane) } else { Err(Error::new(format!( "{} isn't near a {:?} lane", from, lane_types ))) } } pub fn all_lanes(&self) -> Vec<LaneID> { self.children_forwards .iter() .map(|(id, _)| *id) .chain(self.children_backwards.iter().map(|(id, _)| *id)) .collect() } pub fn lanes_on_side(&self, dir: bool) -> Vec<LaneID> { if dir { &self.children_forwards } else { &self.children_backwards } .iter() .map(|(id, _)| *id) .collect() } pub fn get_current_center(&self, map: &Map) -> PolyLine { // The original center_pts don't account for contraflow lane edits. let lane = map.get_l(if !self.children_forwards.is_empty() { self.children_forwards[0].0 } else { self.children_backwards[0].0 }); map.left_shift(lane.lane_center_pts.clone(), lane.width / 2.0) .unwrap() } pub fn any_on_other_side(&self, l: LaneID, lt: LaneType) -> Option<LaneID> { let search = if self.is_forwards(l) { &self.children_backwards } else { &self.children_forwards }; search.iter().find(|(_, t)| lt == *t).map(|(id, _)| *id) } pub fn width_fwd(&self, map: &Map) -> Distance { self.children_forwards .iter() .map(|(l, _)| map.get_l(*l).width) .sum() } pub fn width_back(&self, map: &Map) -> Distance { self.children_backwards .iter() .map(|(l, _)| map.get_l(*l).width) .sum() } pub fn get_thick_polyline(&self, map: &Map) -> Warn<(PolyLine, Distance)> { let fwd = self.width_fwd(map); let back = self.width_back(map); if fwd >= back { map.right_shift(self.center_pts.clone(), (fwd - back) / 2.0) .map(|pl| (pl, fwd + back)) } else { map.left_shift(self.center_pts.clone(), (back - fwd) / 2.0) .map(|pl| (pl, fwd + back)) } } pub fn get_thick_polygon(&self, map: &Map) -> Warn<Polygon> { self.get_thick_polyline(map) .map(|(pl, width)| pl.make_polygons(width)) } pub fn get_name(&self) -> String { if let Some(name) = self.osm_tags.get(osm::NAME) { if name == "" { return "???".to_string(); } else { return name.to_string(); } } if let Some(name) = self.osm_tags.get("ref") { return name.to_string(); } if self .osm_tags .get(osm::HIGHWAY) .map(|hwy| hwy.ends_with("_link")) .unwrap_or(false) { if let Some(name) = self.osm_tags.get("destination:street") { return format!("Exit for {}", name); } if let Some(name) = self.osm_tags.get("destination:ref") { return format!("Exit for {}", name); } if let Some(name) = self.osm_tags.get("destination") { return format!("Exit for {}", name); } // Sometimes 'directions' is filled out, but incorrectly... } "???".to_string() } // Used to determine which roads have stop signs when roads of different types intersect. pub fn get_rank(&self) -> usize { if let Some(highway) = self.osm_tags.get(osm::HIGHWAY) { match highway.as_ref() { "motorway" => 20, "motorway_link" => 19, // TODO Probably not true in general. For the West Seattle bridge. "construction" => 18, "trunk" => 17, "trunk_link" => 16, "primary" => 15, "primary_link" => 14, "secondary" => 13, "secondary_link" => 12, "tertiary" => 10, "tertiary_link" => 9, "residential" => 5, "footway" => 1, "unclassified" => 0, "road" => 0, "crossing" => 0, // If you hit this error and the highway type doesn't represent a driveable road, // you may want to instead filter out the OSM way entirely in // convert_osm/src/osm_reader.rs's is_road(). _ => panic!("Unknown OSM highway {}", highway), } } else { 0 } } pub fn all_bus_stops(&self, map: &Map) -> Vec<BusStopID> { let mut stops = Vec::new(); for id in self.all_lanes() { stops.extend(map.get_l(id).bus_stops.iter().cloned()); } stops } }
32.783908
99
0.521142
9bb6790b07fec8e392926c96bb6cbcdc94e4d11d
205
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 mod h09; mod h3; pub mod interop; pub mod perf; pub use interop::Interop; pub use perf::Perf;
18.636364
69
0.731707
1af63bf9a2890e280ead115a2e52e9487f64835a
11,247
use settings; use connection; use api::VcxStateType; use messages::*; use messages::message_type::MessageTypes; use utils::{httpclient, error}; #[derive(Debug)] pub struct SendMessageBuilder { mtype: RemoteMessageType, to_did: String, to_vk: String, agent_did: String, agent_vk: String, payload: Vec<u8>, ref_msg_id: Option<String>, status_code: MessageStatusCode, uid: Option<String>, title: Option<String>, detail: Option<String>, } impl SendMessageBuilder { pub fn create() -> SendMessageBuilder { trace!("SendMessage::create_message >>>"); SendMessageBuilder { mtype: RemoteMessageType::Other(String::new()), to_did: String::new(), to_vk: String::new(), agent_did: String::new(), agent_vk: String::new(), payload: Vec::new(), ref_msg_id: None, status_code: MessageStatusCode::Created, uid: None, title: None, detail: None, } } pub fn msg_type(&mut self, msg: &RemoteMessageType) -> Result<&mut Self, u32> { //Todo: validate msg?? self.mtype = msg.clone(); Ok(self) } pub fn uid(&mut self, uid: Option<&str>) -> Result<&mut Self, u32> { //Todo: validate msg_uid?? self.uid = uid.map(String::from); Ok(self) } pub fn status_code(&mut self, code: &MessageStatusCode) -> Result<&mut Self, u32> { //Todo: validate that it can be parsed to number?? self.status_code = code.clone(); Ok(self) } pub fn edge_agent_payload(&mut self, my_vk: &str, their_vk: &str, data: &str, payload_type: PayloadKinds) -> Result<&mut Self, u32> { //todo: is this a json value, String?? self.payload = Payload::encrypted(my_vk, their_vk, data, payload_type)?; Ok(self) } pub fn ref_msg_id(&mut self, id: &str) -> Result<&mut Self, u32> { self.ref_msg_id = Some(String::from(id)); Ok(self) } pub fn set_title(&mut self, title: &str) -> Result<&mut Self, u32> { self.title = Some(title.to_string()); Ok(self) } pub fn set_detail(&mut self, detail: &str) -> Result<&mut Self, u32> { self.detail = Some(detail.to_string()); Ok(self) } pub fn send_secure(&mut self) -> Result<SendResponse, u32> { trace!("SendMessage::send >>>"); if settings::test_agency_mode_enabled() { return self.parse_response(::utils::constants::SEND_MESSAGE_RESPONSE.to_vec()); } let data = self.prepare_request()?; let response = httpclient::post_u8(&data).or(Err(error::POST_MSG_FAILURE.code_num))?; let result = self.parse_response(response)?; Ok(result) } fn parse_response(&self, response: Vec<u8>) -> Result<SendResponse, u32> { let mut response = parse_response_from_agency(&response)?; let index = match settings::get_protocol_type() { // TODO: THINK better settings::ProtocolTypes::V1 => { if response.len() <= 1 { return Err(error::INVALID_HTTP_RESPONSE.code_num); } 1 }, settings::ProtocolTypes::V2 => 0 }; match response.remove(index) { A2AMessage::Version1(A2AMessageV1::MessageSent(res)) => Ok(SendResponse { uid: res.uid, uids: res.uids }), A2AMessage::Version2(A2AMessageV2::SendRemoteMessageResponse(res)) => Ok(SendResponse { uid: Some(res.uid.clone()), uids: if res.sent { vec![res.uid] } else { vec![] } }), _ => return Err(error::INVALID_HTTP_RESPONSE.code_num) } } } //Todo: Every GeneralMessage extension, duplicates code impl GeneralMessage for SendMessageBuilder { type Msg = SendMessageBuilder; fn set_agent_did(&mut self, did: String) { self.agent_did = did; } fn set_agent_vk(&mut self, vk: String) { self.agent_vk = vk; } fn set_to_did(&mut self, to_did: String) { self.to_did = to_did; } fn set_to_vk(&mut self, to_vk: String) { self.to_vk = to_vk; } fn prepare_request(&mut self) -> Result<Vec<u8>, u32> { let messages = match settings::get_protocol_type() { settings::ProtocolTypes::V1 => { let create = CreateMessage { msg_type: MessageTypes::build_v1(A2AMessageKinds::CreateMessage), mtype: self.mtype.clone(), reply_to_msg_id: self.ref_msg_id.clone(), send_msg: true, uid: self.uid.clone() }; let detail = GeneralMessageDetail { msg_type: MessageTypes::build_v1(A2AMessageKinds::MessageDetail), msg: self.payload.clone(), title: self.title.clone(), detail: self.detail.clone() }; vec![A2AMessage::Version1(A2AMessageV1::CreateMessage(create)), A2AMessage::Version1(A2AMessageV1::MessageDetail(MessageDetail::General(detail)))] } settings::ProtocolTypes::V2 => { let message = SendRemoteMessage { msg_type: MessageTypes::build_v2(A2AMessageKinds::SendRemoteMessage), mtype: self.mtype.clone(), reply_to_msg_id: self.ref_msg_id.clone(), send_msg: true, uid: self.uid.clone(), msg: self.payload.clone(), title: self.title.clone(), detail: self.detail.clone(), }; vec![A2AMessage::Version2(A2AMessageV2::SendRemoteMessage(message))] } }; prepare_message_for_agent(messages, &self.to_vk, &self.agent_did, &self.agent_vk) } } #[derive(Debug, PartialEq)] pub struct SendResponse { uid: Option<String>, uids: Vec<String>, } impl SendResponse { pub fn get_msg_uid(&self) -> Result<String, u32> { self.uids .get(0) .map(|uid| uid.to_string()) .ok_or(error::INVALID_JSON.code_num) } } pub fn send_generic_message(connection_handle: u32, msg: &str, msg_type: &str, msg_title: &str) -> Result<String, u32> { if connection::get_state(connection_handle) != VcxStateType::VcxStateAccepted as u32 { return Err(error::NOT_READY.code_num); } let agent_did = connection::get_agent_did(connection_handle).or(Err(error::INVALID_CONNECTION_HANDLE.code_num))?; let agent_vk = connection::get_agent_verkey(connection_handle).or(Err(error::INVALID_CONNECTION_HANDLE.code_num))?; let did = connection::get_pw_did(connection_handle).or(Err(error::INVALID_CONNECTION_HANDLE.code_num))?; let vk = connection::get_pw_verkey(connection_handle).or(Err(error::INVALID_CONNECTION_HANDLE.code_num))?; let remote_vk = connection::get_their_pw_verkey(connection_handle).or(Err(error::INVALID_CONNECTION_HANDLE.code_num))?; let response = send_message() .to(&did)? .to_vk(&vk)? .msg_type(&RemoteMessageType::Other(msg_type.to_string()))? .edge_agent_payload(&vk, &remote_vk, &msg, PayloadKinds::Other(msg_type.to_string()))? .agent_did(&agent_did)? .agent_vk(&agent_vk)? .set_title(&msg_title)? .set_detail(&msg_title)? .status_code(&MessageStatusCode::Accepted)? .send_secure() .map_err(|err| { warn!("could not send message: {}", err); err })?; let msg_uid = response.get_msg_uid()?; return Ok(msg_uid); } #[cfg(test)] mod tests { use super::*; use utils::constants::SEND_MESSAGE_RESPONSE; #[test] fn test_msgpack() { settings::set_defaults(); settings::set_config_value(settings::CONFIG_ENABLE_TEST_MODE, "true"); let mut message = SendMessageBuilder { mtype: RemoteMessageType::CredOffer, to_did: "8XFh8yBzrpJQmNyZzgoTqB".to_string(), to_vk: "EkVTa7SCJ5SntpYyX7CSb2pcBhiVGT9kWSagA8a9T69A".to_string(), agent_did: "8XFh8yBzrpJQmNyZzgoTqB".to_string(), agent_vk: "EkVTa7SCJ5SntpYyX7CSb2pcBhiVGT9kWSagA8a9T69A".to_string(), payload: vec![1, 2, 3, 4, 5, 6, 7, 8], ref_msg_id: Some("123".to_string()), status_code: MessageStatusCode::Created, uid: Some("123".to_string()), title: Some("this is the title".to_string()), detail: Some("this is the detail".to_string()), }; /* just check that it doesn't panic */ let packed = message.prepare_request().unwrap(); } #[test] fn test_parse_send_message_response() { init!("true"); let result = SendMessageBuilder::create().parse_response(SEND_MESSAGE_RESPONSE.to_vec()).unwrap(); let expected = SendResponse { uid: None, uids: vec!["ntc2ytb".to_string()], }; assert_eq!(expected, result); } #[test] fn test_parse_send_message_bad_response() { init!("true"); let result = SendMessageBuilder::create().parse_response(::utils::constants::UPDATE_PROFILE_RESPONSE.to_vec()); assert!(result.is_err()); } #[test] fn test_parse_msg_uid() { let test_val = "devin"; let response = SendResponse { uid: None, uids: vec![test_val.to_string()], }; let uid = response.get_msg_uid().unwrap(); assert_eq!(test_val, uid); let test_val = "devin"; let response = SendResponse { uid: None, uids: vec![], }; let uid = response.get_msg_uid().unwrap_err(); assert_eq!(error::INVALID_JSON.code_num, uid); } #[cfg(feature = "agency")] #[cfg(feature = "pool_tests")] #[test] fn test_send_generic_message() { init!("agency"); let institution_did = settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(); let (faber, alice) = ::connection::tests::create_connected_connections(); match send_generic_message(alice, "this is the message", "type", "title") { Ok(x) => println!("message id: {}", x), Err(x) => panic!("paniced! {}", x), }; ::utils::devsetup::tests::set_consumer(); let all_messages = get_message::download_messages(None, None, None).unwrap(); println!("{}", serde_json::to_string(&all_messages).unwrap()); teardown!("agency"); } #[test] fn test_send_generic_message_fails_with_invalid_connection() { init!("true"); let handle = ::connection::tests::build_test_connection(); match send_generic_message(handle, "this is the message", "type", "title") { Ok(x) => panic!("test shoudl fail: {}", x), Err(x) => assert_eq!(x, error::NOT_READY.code_num), }; } }
35.932907
137
0.578732
618ff5f1f39d256561df75258298f73527f501eb
120
/*! # hypergraph System of IoT with Hypergraph Model ## Code ```rust // */ pub mod graph; pub mod value; /* ``` */
6.666667
35
0.583333
23014b4dadade42c5ad90acf0c012a28ce51c2c0
2,073
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_ses::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The name of the contact list. #[structopt(short, long)] contact_list: String, /// The AWS Region. #[structopt(short, long)] region: Option<String>, /// Whether to display additional information. #[structopt(short, long)] verbose: bool, } /// Lists the contacts in a contact list in the Region. /// # Arguments /// /// * `-c CONTACT-LIST` - The name of the contact list. /// * `[-r REGION]` - The Region in which the client is created. /// If not supplied, uses the value of the **AWS_REGION** environment variable. /// If the environment variable is not set, defaults to **us-west-2**. /// * `[-v]` - Whether to display additional information. #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); let Opt { contact_list, region, verbose, } = Opt::from_args(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); println!(); if verbose { println!("SES client version: {}", PKG_VERSION); println!( "Region: {}", region_provider.region().await.unwrap().as_ref() ); println!("Contact list: {}", &contact_list); println!(); } let shared_config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&shared_config); let resp = client .list_contacts() .contact_list_name(contact_list) .send() .await?; println!("Contacts:"); for contact in resp.contacts.unwrap_or_default() { println!(" {}", contact.email_address.as_deref().unwrap_or_default()); } Ok(()) }
27.276316
84
0.614086
3aa3a1ed8a03b5173ac486793ac16d9c4d97afd8
4,043
use super::{BindGroupDescriptor, VertexBufferDescriptor}; use crate::shader::ShaderLayout; use bevy_utils::HashMap; use std::hash::Hash; #[derive(Clone, Debug, Default)] pub struct PipelineLayout { pub bind_groups: Vec<BindGroupDescriptor>, pub vertex_buffer_descriptors: Vec<VertexBufferDescriptor>, } impl PipelineLayout { pub fn get_bind_group(&self, index: u32) -> Option<&BindGroupDescriptor> { self.bind_groups .iter() .find(|bind_group| bind_group.index == index) } pub fn from_shader_layouts(shader_layouts: &mut [ShaderLayout]) -> Self { let mut bind_groups = HashMap::<u32, BindGroupDescriptor>::default(); let mut vertex_buffer_descriptors = Vec::new(); for shader_layout in shader_layouts.iter_mut() { for shader_bind_group in shader_layout.bind_groups.iter_mut() { match bind_groups.get_mut(&shader_bind_group.index) { Some(bind_group) => { for shader_binding in shader_bind_group.bindings.iter() { if let Some(binding) = bind_group .bindings .iter_mut() .find(|binding| binding.index == shader_binding.index) { binding.shader_stage |= shader_binding.shader_stage; if binding.bind_type != shader_binding.bind_type || binding.name != shader_binding.name || binding.index != shader_binding.index { panic!("Binding {} in BindGroup {} does not match across all shader types: {:?} {:?}.", binding.index, bind_group.index, binding, shader_binding); } } else { bind_group.bindings.push(shader_binding.clone()); } } bind_group.update_id(); } None => { bind_groups.insert(shader_bind_group.index, shader_bind_group.clone()); } } } } for vertex_buffer_descriptor in shader_layouts[0].vertex_buffer_descriptors.iter() { vertex_buffer_descriptors.push(vertex_buffer_descriptor.clone()); } let mut bind_groups_result = bind_groups .drain() .map(|(_, value)| value) .collect::<Vec<BindGroupDescriptor>>(); // NOTE: for some reason bind groups need to be sorted by index. this is likely an issue with bevy and not with wgpu // TODO: try removing this bind_groups_result.sort_by(|a, b| a.index.partial_cmp(&b.index).unwrap()); PipelineLayout { bind_groups: bind_groups_result, vertex_buffer_descriptors, } } } #[derive(Hash, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] pub enum UniformProperty { UInt, Int, IVec2, Float, UVec4, Vec2, Vec3, Vec4, Mat3, Mat4, Struct(Vec<UniformProperty>), Array(Box<UniformProperty>, usize), } impl UniformProperty { pub fn get_size(&self) -> u64 { match self { UniformProperty::UInt => 4, UniformProperty::Int => 4, UniformProperty::IVec2 => 4 * 2, UniformProperty::Float => 4, UniformProperty::UVec4 => 4 * 4, UniformProperty::Vec2 => 4 * 2, UniformProperty::Vec3 => 4 * 3, UniformProperty::Vec4 => 4 * 4, UniformProperty::Mat3 => 4 * 4 * 3, UniformProperty::Mat4 => 4 * 4 * 4, UniformProperty::Struct(properties) => properties.iter().map(|p| p.get_size()).sum(), UniformProperty::Array(property, length) => property.get_size() * *length as u64, } } }
38.141509
182
0.536235