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
|
---|---|---|---|---|---|
1dfb242e71f3199c5362e54b150986a015f398b9 | 12,675 | use std::future::Future;
/// A lobste.rs request made as part of a workload.
///
/// Trawler generates requests of this type that correspond to "real" lobste.rs website requests.
///
/// Trawler does not check that the implementor correctly perform the queries corresponding to each
/// request; this must be verified with manual inspection of the Rails application or its query
/// logs.
#[non_exhaustive]
pub struct TrawlerRequest {
/// The user making the request.
pub user: Option<UserId>,
/// The specific page to be requested/rendered.
pub page: LobstersRequest,
/// `is_priming` is set to true if the request is being issued just to populate the database.
/// In this case, the backend need only issue writes and not do any other processing normally
/// associated with the given `request`.
pub is_priming: bool,
}
/// Asynchronous client shutdown.
///
/// The tokio runtime will not be shut down until the returned future resolves.
pub trait AsyncShutdown {
/// A future that will resolve once client shutdown has finished.
type Future: Future<Output = ()>;
/// Start the shutdown process.
fn shutdown(self) -> Self::Future;
}
/// A unique lobste.rs six-character story id.
pub type StoryId = [u8; 6];
/// A unique lobste.rs six-character comment id.
pub type CommentId = [u8; 6];
/// A unique lobste.rs user id.
///
/// Implementors should have a reliable mapping betwen user id and username in both directions.
/// This type is used both in the context of a username (e.g., /u/<user>) and in the context of who
/// performed an action (e.g., POST /s/ as <user>). In the former case, <user> is a username, and
/// the database will have to do a lookup based on username. In the latter, the user id is
/// associated with some session, and the backend does not need to do a lookup.
///
/// In the future, it is likely that this type will be split into two types: one for "session key" and
/// one for "username", both of which will require lookups, but on different keys.
pub type UserId = u32;
/// An up or down vote.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Vote {
/// Upvote
Up,
/// Downvote
Down,
}
/// A single lobste.rs client request.
///
/// Note that one request may end up issuing multiple backend queries. To see which queries are
/// executed by the real lobste.rs, see the [lobste.rs source
/// code](https://github.com/lobsters/lobsters).
///
/// Any request type that mentions an "acting" user is guaranteed to have the `user` argument to
/// `handle` be `Some`.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum LobstersRequest {
/// Render [the frontpage](https://lobste.rs/).
Frontpage,
/// Render [recently submitted stories](https://lobste.rs/recent).
Recent,
/// Render [recently submitted comments](https://lobste.rs/comments).
Comments,
/// Render a [user's profile](https://lobste.rs/u/jonhoo).
///
/// Note that the id here should be treated as a username.
User(UserId),
/// Render a [particular story](https://lobste.rs/s/cqnzl5/).
Story(StoryId),
/// Log in the acting user.
///
/// Note that a user need not be logged in by a `LobstersRequest::Login` in order for a
/// user-action (like `LobstersRequest::Submit`) to be issued for that user. The id here should
/// be considered *both* a username *and* an id. The user with the username derived from this
/// id should have the given id.
Login,
/// Log out the acting user.
Logout,
/// Have the acting user issue an up or down vote for the given story.
///
/// Note that the load generator does not guarantee that a given user will only issue a single
/// vote for a given story, nor that they will issue an equivalent number of upvotes and
/// downvotes for a given story.
StoryVote(StoryId, Vote),
/// Have the acting user issue an up or down vote for the given comment.
///
/// Note that the load generator does not guarantee that a given user will only issue a single
/// vote for a given comment, nor that they will issue an equivalent number of upvotes and
/// downvotes for a given comment.
CommentVote(CommentId, Vote),
/// Have the acting user submit a new story to the site.
///
/// Note that the *generator* dictates the ids of new stories so that it can more easily keep
/// track of which stories exist, and thus which stories can be voted for or commented on.
Submit {
/// The new story's id.
id: StoryId,
/// The story's title.
title: String,
},
/// Have the acting user submit a new comment to the given story.
///
/// Note that the *generator* dictates the ids of new comments so that it can more easily keep
/// track of which comments exist for the purposes of generating comment votes and deeper
/// threads.
Comment {
/// The new comment's id.
id: CommentId,
/// The story the comment is for.
story: StoryId,
/// The id of the comment's parent comment, if any.
parent: Option<CommentId>,
},
}
use std::mem;
use std::vec;
impl LobstersRequest {
/// Enumerate all possible request types in a deterministic order.
pub fn all() -> vec::IntoIter<mem::Discriminant<Self>> {
vec![
mem::discriminant(&LobstersRequest::Story([0; 6])),
mem::discriminant(&LobstersRequest::Frontpage),
mem::discriminant(&LobstersRequest::User(0)),
mem::discriminant(&LobstersRequest::Comments),
mem::discriminant(&LobstersRequest::Recent),
mem::discriminant(&LobstersRequest::CommentVote([0; 6], Vote::Up)),
mem::discriminant(&LobstersRequest::StoryVote([0; 6], Vote::Up)),
mem::discriminant(&LobstersRequest::Comment {
id: [0; 6],
story: [0; 6],
parent: None,
}),
mem::discriminant(&LobstersRequest::Login),
mem::discriminant(&LobstersRequest::Submit {
id: [0; 6],
title: String::new(),
}),
mem::discriminant(&LobstersRequest::Logout),
]
.into_iter()
}
/// Give a textual representation of the given `LobstersRequest` discriminant.
///
/// Useful for printing the keys of the maps of histograms returned by `run`.
pub fn variant_name(v: &mem::Discriminant<Self>) -> &'static str {
match *v {
d if d == mem::discriminant(&LobstersRequest::Frontpage) => "Frontpage",
d if d == mem::discriminant(&LobstersRequest::Recent) => "Recent",
d if d == mem::discriminant(&LobstersRequest::Comments) => "Comments",
d if d == mem::discriminant(&LobstersRequest::User(0)) => "User",
d if d == mem::discriminant(&LobstersRequest::Story([0; 6])) => "Story",
d if d == mem::discriminant(&LobstersRequest::Login) => "Login",
d if d == mem::discriminant(&LobstersRequest::Logout) => "Logout",
d if d == mem::discriminant(&LobstersRequest::StoryVote([0; 6], Vote::Up)) => {
"StoryVote"
}
d if d == mem::discriminant(&LobstersRequest::CommentVote([0; 6], Vote::Up)) => {
"CommentVote"
}
d if d
== mem::discriminant(&LobstersRequest::Submit {
id: [0; 6],
title: String::new(),
}) =>
{
"Submit"
}
d if d
== mem::discriminant(&LobstersRequest::Comment {
id: [0; 6],
story: [0; 6],
parent: None,
}) =>
{
"Comment"
}
_ => unreachable!(),
}
}
/// Produce a textual representation of this request.
///
/// These are on the form:
///
/// ```text
/// METHOD /path [params] <user>
/// ```
///
/// Where:
///
/// - `METHOD` is `GET` or `POST`.
/// - `/path` is the approximate lobste.rs URL endpoint for the request.
/// - `[params]` are any additional params to the request such as id to assign or associate a
/// new resource with with.
pub fn describe(&self) -> String {
match *self {
LobstersRequest::Frontpage => String::from("GET /"),
LobstersRequest::Recent => String::from("GET /recent"),
LobstersRequest::Comments => String::from("GET /comments"),
LobstersRequest::User(uid) => format!("GET /u/#{}", uid),
LobstersRequest::Story(ref slug) => {
format!("GET /s/{}", ::std::str::from_utf8(&slug[..]).unwrap())
}
LobstersRequest::Login => String::from("POST /login"),
LobstersRequest::Logout => String::from("POST /logout"),
LobstersRequest::StoryVote(ref story, v) => format!(
"POST /stories/{}/{}",
::std::str::from_utf8(&story[..]).unwrap(),
match v {
Vote::Up => "upvote",
Vote::Down => "downvote",
},
),
LobstersRequest::CommentVote(ref comment, v) => format!(
"POST /comments/{}/{}",
::std::str::from_utf8(&comment[..]).unwrap(),
match v {
Vote::Up => "upvote",
Vote::Down => "downvote",
},
),
LobstersRequest::Submit { ref id, .. } => format!(
"POST /stories [{}]",
::std::str::from_utf8(&id[..]).unwrap(),
),
LobstersRequest::Comment {
ref id,
ref story,
ref parent,
} => match *parent {
Some(ref parent) => format!(
"POST /comments/{} [{}; {}]",
::std::str::from_utf8(&parent[..]).unwrap(),
::std::str::from_utf8(&id[..]).unwrap(),
::std::str::from_utf8(&story[..]).unwrap(),
),
None => format!(
"POST /comments [{}; {}]",
::std::str::from_utf8(&id[..]).unwrap(),
::std::str::from_utf8(&story[..]).unwrap(),
),
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn textual_requests() {
assert_eq!(LobstersRequest::Frontpage.describe(), "GET /");
assert_eq!(LobstersRequest::Recent.describe(), "GET /recent");
assert_eq!(LobstersRequest::Comments.describe(), "GET /comments");
assert_eq!(LobstersRequest::User(3).describe(), "GET /u/#3");
assert_eq!(
LobstersRequest::Story([48, 48, 48, 48, 57, 97]).describe(),
"GET /s/00009a"
);
assert_eq!(LobstersRequest::Login.describe(), "POST /login");
assert_eq!(LobstersRequest::Logout.describe(), "POST /logout");
assert_eq!(
LobstersRequest::StoryVote([48, 48, 48, 98, 57, 97], Vote::Up).describe(),
"POST /stories/000b9a/upvote"
);
assert_eq!(
LobstersRequest::StoryVote([48, 48, 48, 98, 57, 97], Vote::Down).describe(),
"POST /stories/000b9a/downvote"
);
assert_eq!(
LobstersRequest::CommentVote([48, 48, 48, 98, 57, 97], Vote::Up).describe(),
"POST /comments/000b9a/upvote"
);
assert_eq!(
LobstersRequest::CommentVote([48, 48, 48, 98, 57, 97], Vote::Down).describe(),
"POST /comments/000b9a/downvote"
);
assert_eq!(
LobstersRequest::Submit {
id: [48, 48, 48, 48, 57, 97],
title: String::from("foo"),
}
.describe(),
"POST /stories [00009a]"
);
assert_eq!(
LobstersRequest::Comment {
id: [48, 48, 48, 48, 57, 97],
story: [48, 48, 48, 48, 57, 98],
parent: Some([48, 48, 48, 48, 57, 99]),
}
.describe(),
"POST /comments/00009c [00009a; 00009b]"
);
assert_eq!(
LobstersRequest::Comment {
id: [48, 48, 48, 48, 57, 97],
story: [48, 48, 48, 48, 57, 98],
parent: None,
}
.describe(),
"POST /comments [00009a; 00009b]"
);
}
}
| 38.063063 | 102 | 0.553846 |
9b4120a0a75cd70b2d375549fb7778e747ac3436 | 14,318 | use crate::key_info::{KeyInfo, X509Data};
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::Writer;
use serde::Deserialize;
use std::io::Cursor;
const NAME: &str = "ds:Signature";
const SCHEMA: (&str, &str) = ("xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct Signature {
#[serde(rename = "Id")]
pub id: Option<String>,
#[serde(rename = "SignedInfo")]
pub signed_info: SignedInfo,
#[serde(rename = "SignatureValue")]
pub signature_value: SignatureValue,
#[serde(rename = "KeyInfo")]
pub key_info: Option<Vec<KeyInfo>>,
}
impl Signature {
pub fn template(ref_id: &str, x509_cert_der: &[u8]) -> Self {
Signature {
id: None,
signed_info: SignedInfo {
id: None,
canonicalization_method: CanonicalizationMethod {
algorithm: "http://www.w3.org/2001/10/xml-exc-c14n#".to_string(),
},
signature_method: SignatureMethod {
algorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256".to_string(),
hmac_output_length: None,
},
reference: vec![Reference {
transforms: Some(Transforms {
transforms: vec![
Transform {
algorithm: "http://www.w3.org/2000/09/xmldsig#enveloped-signature"
.to_string(),
xpath: None,
},
Transform {
algorithm: "http://www.w3.org/2001/10/xml-exc-c14n#".to_string(),
xpath: None,
},
],
}),
digest_method: DigestMethod {
algorithm: "http://www.w3.org/2000/09/xmldsig#sha1".to_string(),
},
digest_value: Some(DigestValue {
base64_content: Some("".to_string()),
}),
uri: Some(format!("#{}", ref_id)),
reference_type: None,
id: None,
}],
},
signature_value: SignatureValue {
id: None,
base64_content: Some("".to_string()),
},
key_info: Some(vec![KeyInfo {
id: None,
x509_data: Some(X509Data {
certificate: Some(
crate::crypto::mime_encode_x509_cert(x509_cert_der)
),
}),
}]),
}
}
pub fn to_xml(&self) -> Result<String, Box<dyn std::error::Error>> {
let mut write_buf = Vec::new();
let mut writer = Writer::new(Cursor::new(&mut write_buf));
let mut root = BytesStart::borrowed(NAME.as_bytes(), NAME.len());
root.push_attribute(SCHEMA);
if let Some(id) = &self.id {
root.push_attribute(("Id", id.as_ref()));
}
writer.write_event(Event::Start(root))?;
writer.write(self.signed_info.to_xml()?.as_bytes())?;
writer.write(self.signature_value.to_xml()?.as_bytes())?;
if let Some(key_infos) = &self.key_info {
for key_info in key_infos {
writer.write(key_info.to_xml()?.as_bytes())?;
}
}
writer.write_event(Event::End(BytesEnd::borrowed(NAME.as_bytes())))?;
Ok(String::from_utf8(write_buf)?)
}
pub fn add_key_info(&mut self, public_cert_der: &[u8]) -> &mut Self {
self.key_info.get_or_insert(Vec::new()).push(KeyInfo {
id: None,
x509_data: Some(X509Data {
certificate: Some(base64::encode(public_cert_der)),
}),
});
self
}
}
const SIGNATURE_VALUE_NAME: &str = "ds:SignatureValue";
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct SignatureValue {
#[serde(rename = "ID")]
pub id: Option<String>,
#[serde(rename = "$value")]
pub base64_content: Option<String>,
}
impl SignatureValue {
pub fn to_xml(&self) -> Result<String, Box<dyn std::error::Error>> {
let mut write_buf = Vec::new();
let mut writer = Writer::new(Cursor::new(&mut write_buf));
let mut root =
BytesStart::borrowed(SIGNATURE_VALUE_NAME.as_bytes(), SIGNATURE_VALUE_NAME.len());
if let Some(id) = &self.id {
root.push_attribute(("Id", id.as_ref()));
}
writer.write_event(Event::Start(root))?;
if let Some(ref base64_content) = self.base64_content {
writer.write_event(Event::Text(BytesText::from_plain_str(
base64_content,
)))?;
}
writer.write_event(Event::End(BytesEnd::borrowed(
SIGNATURE_VALUE_NAME.as_bytes(),
)))?;
Ok(String::from_utf8(write_buf)?)
}
}
const SIGNED_INFO_NAME: &str = "ds:SignedInfo";
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct SignedInfo {
#[serde(rename = "ID")]
pub id: Option<String>,
#[serde(rename = "CanonicalizationMethod")]
pub canonicalization_method: CanonicalizationMethod,
#[serde(rename = "SignatureMethod")]
pub signature_method: SignatureMethod,
#[serde(rename = "Reference")]
pub reference: Vec<Reference>,
}
impl SignedInfo {
pub fn to_xml(&self) -> Result<String, Box<dyn std::error::Error>> {
let mut write_buf = Vec::new();
let mut writer = Writer::new(Cursor::new(&mut write_buf));
let mut root = BytesStart::borrowed(SIGNED_INFO_NAME.as_bytes(), SIGNED_INFO_NAME.len());
if let Some(id) = &self.id {
root.push_attribute(("Id", id.as_ref()));
}
writer.write_event(Event::Start(root))?;
writer.write(self.canonicalization_method.to_xml()?.as_bytes())?;
writer.write(self.signature_method.to_xml()?.as_bytes())?;
for reference in &self.reference {
writer.write(reference.to_xml()?.as_bytes())?;
}
writer.write_event(Event::End(BytesEnd::borrowed(SIGNED_INFO_NAME.as_bytes())))?;
Ok(String::from_utf8(write_buf)?)
}
}
const CANONICALIZATION_METHOD: &str = "ds:CanonicalizationMethod";
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct CanonicalizationMethod {
#[serde(rename = "Algorithm")]
pub algorithm: String,
}
impl CanonicalizationMethod {
pub fn to_xml(&self) -> Result<String, Box<dyn std::error::Error>> {
let mut write_buf = Vec::new();
let mut writer = Writer::new(Cursor::new(&mut write_buf));
let mut root = BytesStart::borrowed(
CANONICALIZATION_METHOD.as_bytes(),
CANONICALIZATION_METHOD.len(),
);
root.push_attribute(("Algorithm", self.algorithm.as_ref()));
writer.write_event(Event::Empty(root))?;
Ok(String::from_utf8(write_buf)?)
}
}
const SIGNATURE_METHOD_NAME: &str = "ds:SignatureMethod";
const HMAC_OUTPUT_LENGTH_NAME: &str = "ds:HMACOutputLength";
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct SignatureMethod {
#[serde(rename = "Algorithm")]
pub algorithm: String,
#[serde(rename = "ds:HMACOutputLength")]
pub hmac_output_length: Option<usize>,
}
impl SignatureMethod {
pub fn to_xml(&self) -> Result<String, Box<dyn std::error::Error>> {
let mut write_buf = Vec::new();
let mut writer = Writer::new(Cursor::new(&mut write_buf));
let mut root = BytesStart::borrowed(
SIGNATURE_METHOD_NAME.as_bytes(),
SIGNATURE_METHOD_NAME.len(),
);
root.push_attribute(("Algorithm", self.algorithm.as_ref()));
if let Some(hmac_output_length) = &self.hmac_output_length {
writer.write_event(Event::Start(root))?;
writer.write_event(Event::Start(BytesStart::borrowed(
HMAC_OUTPUT_LENGTH_NAME.as_bytes(),
HMAC_OUTPUT_LENGTH_NAME.len(),
)))?;
writer.write_event(Event::Text(BytesText::from_plain_str(
hmac_output_length.to_string().as_ref(),
)))?;
writer.write_event(Event::End(BytesEnd::borrowed(
HMAC_OUTPUT_LENGTH_NAME.as_bytes(),
)))?;
writer.write_event(Event::End(BytesEnd::borrowed(
SIGNATURE_METHOD_NAME.as_bytes(),
)))?;
} else {
writer.write_event(Event::Empty(root))?;
}
Ok(String::from_utf8(write_buf)?)
}
}
const TRANSFORMS_NAME: &str = "ds:Transforms";
const TRANSFORM_NAME: &str = "ds:Transform";
const XPATH_NAME: &str = "ds:XPath";
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct Transform {
#[serde(rename = "Algorithm")]
pub algorithm: String,
#[serde(rename = "ds:XPath")]
pub xpath: Option<String>,
}
impl Transform {
pub fn to_xml(&self) -> Result<String, Box<dyn std::error::Error>> {
let mut write_buf = Vec::new();
let mut writer = Writer::new(Cursor::new(&mut write_buf));
let mut root = BytesStart::borrowed(TRANSFORM_NAME.as_bytes(), TRANSFORM_NAME.len());
root.push_attribute(("Algorithm", self.algorithm.as_ref()));
if let Some(xpath) = &self.xpath {
writer.write_event(Event::Start(root))?;
let xpath_root = Event::Start(BytesStart::borrowed(
XPATH_NAME.as_bytes(),
XPATH_NAME.len(),
));
writer.write_event(xpath_root)?;
writer.write_event(Event::Text(BytesText::from_plain_str(xpath.as_ref())))?;
writer.write_event(Event::End(BytesEnd::borrowed(XPATH_NAME.as_bytes())))?;
writer.write_event(Event::End(BytesEnd::borrowed(TRANSFORM_NAME.as_bytes())))?;
} else {
writer.write_event(Event::Empty(root))?;
}
Ok(String::from_utf8(write_buf)?)
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct Transforms {
#[serde(rename = "Transform")]
pub transforms: Vec<Transform>,
}
impl Transforms {
pub fn to_xml(&self) -> Result<String, Box<dyn std::error::Error>> {
let mut write_buf = Vec::new();
let mut writer = Writer::new(Cursor::new(&mut write_buf));
let root = BytesStart::borrowed(TRANSFORMS_NAME.as_bytes(), TRANSFORMS_NAME.len());
writer.write_event(Event::Start(root))?;
for transform in &self.transforms {
writer.write(transform.to_xml()?.as_bytes())?;
}
writer.write_event(Event::End(BytesEnd::borrowed(TRANSFORMS_NAME.as_bytes())))?;
Ok(String::from_utf8(write_buf)?)
}
}
const DIGEST_METHOD: &str = "ds:DigestMethod";
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct DigestMethod {
#[serde(rename = "Algorithm")]
pub algorithm: String,
}
impl DigestMethod {
pub fn to_xml(&self) -> Result<String, Box<dyn std::error::Error>> {
let mut write_buf = Vec::new();
let mut writer = Writer::new(Cursor::new(&mut write_buf));
let mut root = BytesStart::borrowed(DIGEST_METHOD.as_bytes(), DIGEST_METHOD.len());
root.push_attribute(("Algorithm", self.algorithm.as_ref()));
writer.write_event(Event::Empty(root))?;
Ok(String::from_utf8(write_buf)?)
}
}
const DIGEST_VALUE_NAME: &str = "ds:DigestValue";
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct DigestValue {
#[serde(rename = "$value")]
pub base64_content: Option<String>,
}
impl DigestValue {
pub fn to_xml(&self) -> Result<String, Box<dyn std::error::Error>> {
let mut write_buf = Vec::new();
let mut writer = Writer::new(Cursor::new(&mut write_buf));
let root = BytesStart::borrowed(DIGEST_VALUE_NAME.as_bytes(), DIGEST_VALUE_NAME.len());
writer.write_event(Event::Start(root))?;
if let Some(ref base64_content) = self.base64_content {
writer.write_event(Event::Text(BytesText::from_plain_str(
base64_content,
)))?;
}
writer.write_event(Event::End(BytesEnd::borrowed(DIGEST_VALUE_NAME.as_bytes())))?;
Ok(String::from_utf8(write_buf)?)
}
}
const REFERENCE_NAME: &str = "ds:Reference";
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct Reference {
#[serde(rename = "Transforms")]
pub transforms: Option<Transforms>,
#[serde(rename = "DigestMethod")]
pub digest_method: DigestMethod,
#[serde(rename = "DigestValue")]
pub digest_value: Option<DigestValue>,
#[serde(rename = "URI")]
pub uri: Option<String>,
#[serde(rename = "Type")]
pub reference_type: Option<String>,
#[serde(rename = "Id")]
pub id: Option<String>,
}
impl Reference {
pub fn to_xml(&self) -> Result<String, Box<dyn std::error::Error>> {
let mut write_buf = Vec::new();
let mut writer = Writer::new(Cursor::new(&mut write_buf));
let mut root = BytesStart::borrowed(REFERENCE_NAME.as_bytes(), REFERENCE_NAME.len());
if let Some(id) = &self.id {
root.push_attribute(("Id", id.as_ref()));
}
if let Some(uri) = &self.uri {
root.push_attribute(("URI", uri.as_ref()));
}
if let Some(reference_type) = &self.reference_type {
root.push_attribute(("Type", reference_type.as_ref()));
}
writer.write_event(Event::Start(root))?;
if let Some(transforms) = &self.transforms {
writer.write(transforms.to_xml()?.as_bytes())?;
}
writer.write(self.digest_method.to_xml()?.as_bytes())?;
if let Some(ref digest_value) = self.digest_value {
writer.write(digest_value.to_xml()?.as_bytes())?;
}
writer.write_event(Event::End(BytesEnd::borrowed(REFERENCE_NAME.as_bytes())))?;
Ok(String::from_utf8(write_buf)?)
}
}
| 36.52551 | 98 | 0.587233 |
29bcc265652708a66ede3ef64188f3472dce0710 | 5,280 | extern crate chrono;
extern crate git2;
extern crate serde_json;
use chrono::{NaiveDateTime, DateTime, FixedOffset};
use git2::{Object, Oid, Repository, Time};
use serde_json::{map::Map, value::Value};
use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
match args.len() {
3 => match print_commits(&args[1], &args[2]) {
Ok(_) => (),
Err(err) => {
eprintln!("fatal: {}", err);
process::exit(1)
}
}
_ => {
eprintln!("{}", "Usage: git_structured_log <exclusive start of range>..<inclusive end of range> <comma-separated list of format flags>");
process::exit(1)
}
}
}
fn print_commits(revision_range: &str, formats_input: &str) -> Result<(), Box<Error>> {
let repository: &mut Repository = &mut Repository::open(".")?;
let formats = formats_input.split(',').collect::<Vec<&str>>();
let mut reference_map: HashMap<Oid, Vec<String>> = HashMap::new();
if formats.contains(&&"D") {
for reference_result in repository.references()? {
let reference = reference_result?;
let ref_shorthand = match reference.shorthand() {
Some(shorthand) => shorthand,
None => continue
};
let ref_target = reference.peel_to_commit()?.id();
reference_map.entry(ref_target).or_insert_with(Vec::new).push(ref_shorthand.to_string());
}
}
let mut revwalk = repository.revwalk()?;
revwalk.push_range(revision_range)?;
for oid in revwalk {
let commit = repository.find_commit(oid?)?;
let mut map = Map::new();
for format in &formats {
map.insert(format.to_string(), match *format {
"H" => Value::String(oid_to_hex_string(commit.id())),
"h" => Value::String(object_to_hex_string(commit.as_object())?),
"T" => Value::String(oid_to_hex_string(commit.tree_id())),
"t" => Value::String(object_to_hex_string(commit.tree()?.as_object())?),
"P" => commit.parent_ids().map(oid_to_hex_string).map(Value::String).collect::<Value>(),
"p" => commit.parents()
.map(|parent| Ok(Value::String(object_to_hex_string(parent.as_object())?)))
.collect::<Result<Value, Box<Error>>>()?,
"an" => Value::String(commit.author().name().ok_or("Author name contains invalid UTF8")?.to_string()),
"ae" => Value::String(commit.author().email().ok_or("Author email contains invalid UTF8")?.to_string()),
"aN" | "aE" => invalid_format(format, "Mailmaps not currently supported, consider using `an`/`ae` instead of `aN`/`aE`")?,
"at" => Value::Number(commit.author().when().seconds().into()),
"aI" => Value::String(git_time_to_iso8601(commit.author().when())),
"ad" | "aD" | "ar" | "ai" => invalid_format(format, "Formatted dates not supported, use `aI` and format the date yourself")?,
"ct" => Value::Number(commit.time().seconds().into()),
"cI" => Value::String(git_time_to_iso8601(commit.time())),
"cd" | "cD" | "cr" | "ci" => invalid_format(format, "Formatted dates not supported, use `cI` and format the date yourself")?,
"d" => invalid_format(format, "Formatted ref names not supported, use `D` and format the names yourself")?,
"D" => reference_map
.remove(&commit.id())
.unwrap_or_else(Vec::new)
.into_iter()
.map(Value::String)
.collect::<Value>(),
"s" => Value::String(commit.summary().ok_or("Commit header contains invalid UTF8")?.to_string()),
"b" => invalid_format(format, "Body not supported, use `B` and extract the body yourself")?,
"B" => Value::String(commit.message().ok_or("Commit message contains invalid UTF8")?.to_string()),
"N" => invalid_format(format, "Notes not currently supported")?,
"GG" | "G?" | "GS" | "GK" => invalid_format(format, "Signatures not currently supported")?,
_ => invalid_format(format, "Not found")?
});
}
println!("{}", Value::Object(map));
}
Ok(())
}
fn oid_to_hex_string(oid: Oid) -> String {
oid.as_bytes().into_iter().map(|byte| format!("{:02x}", byte)).collect::<String>()
}
fn object_to_hex_string(object: &Object) -> Result<String, Box<Error>> {
match object.short_id()?.as_str() {
Some(shorthash) => Ok(shorthash.to_string()),
None => Err("libgit returned a bad shorthash")?
}
}
fn git_time_to_iso8601(time: Time) -> String {
let time_without_zone = NaiveDateTime::from_timestamp(time.seconds(), 0);
let time_with_zone = DateTime::<FixedOffset>::from_utc(time_without_zone, FixedOffset::east(time.offset_minutes() * 60));
time_with_zone.to_rfc3339()
}
fn invalid_format(format: &str, reason: &str) -> Result<Value, Box<Error>> {
Err(format!("Invalid format `{}`: {}", format, reason))?
}
| 46.315789 | 149 | 0.575758 |
bbeb4fae562dee42975f31dc35eae48454d936a7 | 1,385 | // Copyright (c) 2018-2022 The MobileCoin Foundation
//! Watcher metrics comparing ledger height and block height
use mc_common::HashMap;
use mc_util_metrics::{IntGauge, OpMetrics};
use url::Url;
lazy_static::lazy_static! {
/// Create metric object for tracking watcher
pub static ref COLLECTOR: OpMetrics = OpMetrics::new_and_registered("watcher");
}
/// Watcher metrics tracker used to report metrics on watcher to Prometheus
pub struct WatcherMetrics {
/// Number of blocks in the ledger
ledger_block_height: IntGauge,
}
impl Default for WatcherMetrics {
fn default() -> Self {
Self::new()
}
}
impl WatcherMetrics {
/// Initialize new metrics object
pub fn new() -> Self {
let ledger_block_height = COLLECTOR.gauge("ledger_block_height");
Self {
ledger_block_height,
}
}
/// Record current ledger height
pub fn set_ledger_height(&self, ledger_height: i64) {
self.ledger_block_height.set(ledger_height);
}
/// Measure blocks synced so far for each peer
pub fn collect_peer_blocks_synced(&self, peer_sync_states: HashMap<Url, Option<u64>>) {
peer_sync_states.iter().for_each(|(url, num_blocks)| {
COLLECTOR
.peer_gauge("watcher_blocks_synced", url.as_str())
.set(num_blocks.unwrap_or(0) as i64);
});
}
}
| 28.265306 | 91 | 0.665704 |
90246a60ef8dbaa54f317542c6c809bd6e06a641 | 280 | impl Solution {
pub fn largest_perimeter(mut a: Vec<i32>) -> i32 {
a.sort_by(|a, b| b.cmp(a));
for i in 0..(a.len() - 2) {
if a[i] < a[i + 1] + a[i + 2] {
return a[i] + a[i + 1] + a[i + 2];
}
}
0
}
}
| 23.333333 | 54 | 0.353571 |
ef17b458361709b75f0637fd1c76b6eca82eb67b | 700 | use crate::registry_interface::ManifestReader;
use rocket::http::Header;
use rocket::request::Request;
use rocket::response::{self, Responder, Response};
impl<'r> Responder<'r, 'static> for ManifestReader {
fn respond_to(self, _: &Request) -> response::Result<'static> {
let ct = Header::new("Content-Type", self.content_type().to_string());
let digest = Header::new("Docker-Content-Digest", self.digest().to_string());
// Important to used sized_body in order to have content length set correctly
let mut resp = Response::build().sized_body(None, self.get_reader()).ok()?;
resp.set_header(ct);
resp.set_header(digest);
Ok(resp)
}
}
| 36.842105 | 85 | 0.665714 |
08a2c50a83c03f1d19ba7aa88f840fb36f820952 | 3,350 | #![allow(dead_code)]
use std::{any::TypeId, cmp, fmt, hash};
use crate::{
cache::load_from_source,
entry::{CacheEntry, CacheEntryInner},
source::Source,
utils, Asset, Error, SharedString,
};
pub(crate) trait AnyAsset: Send + Sync + 'static {
fn reload(self: Box<Self>, entry: CacheEntryInner);
fn create(self: Box<Self>, id: SharedString) -> CacheEntry;
}
impl<A: Asset> AnyAsset for A {
fn reload(self: Box<Self>, entry: CacheEntryInner) {
entry.handle::<A>().as_dynamic().write(*self);
}
fn create(self: Box<Self>, id: SharedString) -> CacheEntry {
CacheEntry::new::<A>(*self, id)
}
}
fn load<A: Asset>(source: &dyn Source, id: &str) -> Result<Box<dyn AnyAsset>, Error> {
let asset = load_from_source::<A, _>(source, id)?;
Ok(Box::new(asset))
}
struct Inner {
extensions: &'static [&'static str],
#[allow(clippy::type_complexity)]
load: fn(&dyn Source, id: &str) -> Result<Box<dyn AnyAsset>, Error>,
}
impl Inner {
fn of<A: Asset>() -> &'static Self {
&Inner {
extensions: A::EXTENSIONS,
load: load::<A>,
}
}
}
/// A structure to represent the type on an [`Asset`]
#[derive(Clone, Copy)]
pub struct AssetType {
// TODO: move this into `inner` when `TypeId::of` is const-stable
type_id: TypeId,
inner: &'static Inner,
}
impl AssetType {
/// Creates an `AssetType` for type `A`.
#[inline]
pub fn of<A: Asset>() -> Self {
Self {
type_id: TypeId::of::<A>(),
inner: Inner::of::<A>(),
}
}
/// The extensions associated with the reprensented asset type.
#[inline]
pub fn extensions(self) -> &'static [&'static str] {
self.inner.extensions
}
pub(crate) fn load<S: Source>(self, source: &S, id: &str) -> Result<Box<dyn AnyAsset>, Error> {
(self.inner.load)(source, id)
}
}
impl hash::Hash for AssetType {
#[inline]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.type_id.hash(state);
}
}
impl PartialEq for AssetType {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.type_id == other.type_id
}
}
impl Eq for AssetType {}
impl PartialOrd for AssetType {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.type_id.partial_cmp(&other.type_id)
}
}
impl Ord for AssetType {
#[inline]
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.type_id.cmp(&other.type_id)
}
}
impl fmt::Debug for AssetType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("AssetType")
.field("type_id", &self.type_id)
.finish()
}
}
/// An untyped representation of a stored asset.
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct AssetKey {
/// The representation of the type of the asset.
pub typ: AssetType,
/// The id of the asset.
pub id: SharedString,
}
impl AssetKey {
/// Creates a new `AssetKey` from a type and an id.
#[inline]
pub fn new<A: Asset>(id: SharedString) -> Self {
Self {
id,
typ: AssetType::of::<A>(),
}
}
pub(crate) fn into_owned_key(self) -> utils::OwnedKey {
utils::OwnedKey::new_with(self.id, self.typ.type_id)
}
}
| 24.275362 | 99 | 0.584179 |
5b1c588208b4ecdfbea2efe0b10b75accc5dc43a | 229,335 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum LicenseType {
#[allow(missing_docs)] // documentation missing in model
Aws,
#[allow(missing_docs)] // documentation missing in model
Byol,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for LicenseType {
fn from(s: &str) -> Self {
match s {
"AWS" => LicenseType::Aws,
"BYOL" => LicenseType::Byol,
other => LicenseType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for LicenseType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(LicenseType::from(s))
}
}
impl LicenseType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
LicenseType::Aws => "AWS",
LicenseType::Byol => "BYOL",
LicenseType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["AWS", "BYOL"]
}
}
impl AsRef<str> for LicenseType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Key/value pair that can be assigned to an application.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct Tag {
/// <p>The tag key.</p>
pub key: std::option::Option<std::string::String>,
/// <p>The tag value.</p>
pub value: std::option::Option<std::string::String>,
}
impl Tag {
/// <p>The tag key.</p>
pub fn key(&self) -> std::option::Option<&str> {
self.key.as_deref()
}
/// <p>The tag value.</p>
pub fn value(&self) -> std::option::Option<&str> {
self.value.as_deref()
}
}
impl std::fmt::Debug for Tag {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("Tag");
formatter.field("key", &self.key);
formatter.field("value", &self.value);
formatter.finish()
}
}
/// See [`Tag`](crate::model::Tag)
pub mod tag {
/// A builder for [`Tag`](crate::model::Tag)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) key: std::option::Option<std::string::String>,
pub(crate) value: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The tag key.</p>
pub fn key(mut self, input: impl Into<std::string::String>) -> Self {
self.key = Some(input.into());
self
}
/// <p>The tag key.</p>
pub fn set_key(mut self, input: std::option::Option<std::string::String>) -> Self {
self.key = input;
self
}
/// <p>The tag value.</p>
pub fn value(mut self, input: impl Into<std::string::String>) -> Self {
self.value = Some(input.into());
self
}
/// <p>The tag value.</p>
pub fn set_value(mut self, input: std::option::Option<std::string::String>) -> Self {
self.value = input;
self
}
/// Consumes the builder and constructs a [`Tag`](crate::model::Tag)
pub fn build(self) -> crate::model::Tag {
crate::model::Tag {
key: self.key,
value: self.value,
}
}
}
}
impl Tag {
/// Creates a new builder-style object to manufacture [`Tag`](crate::model::Tag)
pub fn builder() -> crate::model::tag::Builder {
crate::model::tag::Builder::default()
}
}
/// <p>Logical grouping of servers.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServerGroup {
/// <p>The ID of a server group.</p>
pub server_group_id: std::option::Option<std::string::String>,
/// <p>The name of a server group.</p>
pub name: std::option::Option<std::string::String>,
/// <p>The servers that belong to a server group.</p>
pub server_list: std::option::Option<std::vec::Vec<crate::model::Server>>,
}
impl ServerGroup {
/// <p>The ID of a server group.</p>
pub fn server_group_id(&self) -> std::option::Option<&str> {
self.server_group_id.as_deref()
}
/// <p>The name of a server group.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
/// <p>The servers that belong to a server group.</p>
pub fn server_list(&self) -> std::option::Option<&[crate::model::Server]> {
self.server_list.as_deref()
}
}
impl std::fmt::Debug for ServerGroup {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServerGroup");
formatter.field("server_group_id", &self.server_group_id);
formatter.field("name", &self.name);
formatter.field("server_list", &self.server_list);
formatter.finish()
}
}
/// See [`ServerGroup`](crate::model::ServerGroup)
pub mod server_group {
/// A builder for [`ServerGroup`](crate::model::ServerGroup)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) server_group_id: std::option::Option<std::string::String>,
pub(crate) name: std::option::Option<std::string::String>,
pub(crate) server_list: std::option::Option<std::vec::Vec<crate::model::Server>>,
}
impl Builder {
/// <p>The ID of a server group.</p>
pub fn server_group_id(mut self, input: impl Into<std::string::String>) -> Self {
self.server_group_id = Some(input.into());
self
}
/// <p>The ID of a server group.</p>
pub fn set_server_group_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.server_group_id = input;
self
}
/// <p>The name of a server group.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The name of a server group.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// Appends an item to `server_list`.
///
/// To override the contents of this collection use [`set_server_list`](Self::set_server_list).
///
/// <p>The servers that belong to a server group.</p>
pub fn server_list(mut self, input: impl Into<crate::model::Server>) -> Self {
let mut v = self.server_list.unwrap_or_default();
v.push(input.into());
self.server_list = Some(v);
self
}
/// <p>The servers that belong to a server group.</p>
pub fn set_server_list(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Server>>,
) -> Self {
self.server_list = input;
self
}
/// Consumes the builder and constructs a [`ServerGroup`](crate::model::ServerGroup)
pub fn build(self) -> crate::model::ServerGroup {
crate::model::ServerGroup {
server_group_id: self.server_group_id,
name: self.name,
server_list: self.server_list,
}
}
}
}
impl ServerGroup {
/// Creates a new builder-style object to manufacture [`ServerGroup`](crate::model::ServerGroup)
pub fn builder() -> crate::model::server_group::Builder {
crate::model::server_group::Builder::default()
}
}
/// <p>Represents a server.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct Server {
/// <p>The ID of the server.</p>
pub server_id: std::option::Option<std::string::String>,
/// <p>The type of server.</p>
pub server_type: std::option::Option<crate::model::ServerType>,
/// <p>Information about the VM server.</p>
pub vm_server: std::option::Option<crate::model::VmServer>,
/// <p>The ID of the replication job.</p>
pub replication_job_id: std::option::Option<std::string::String>,
/// <p>Indicates whether the replication job is deleted or failed.</p>
pub replication_job_terminated: std::option::Option<bool>,
}
impl Server {
/// <p>The ID of the server.</p>
pub fn server_id(&self) -> std::option::Option<&str> {
self.server_id.as_deref()
}
/// <p>The type of server.</p>
pub fn server_type(&self) -> std::option::Option<&crate::model::ServerType> {
self.server_type.as_ref()
}
/// <p>Information about the VM server.</p>
pub fn vm_server(&self) -> std::option::Option<&crate::model::VmServer> {
self.vm_server.as_ref()
}
/// <p>The ID of the replication job.</p>
pub fn replication_job_id(&self) -> std::option::Option<&str> {
self.replication_job_id.as_deref()
}
/// <p>Indicates whether the replication job is deleted or failed.</p>
pub fn replication_job_terminated(&self) -> std::option::Option<bool> {
self.replication_job_terminated
}
}
impl std::fmt::Debug for Server {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("Server");
formatter.field("server_id", &self.server_id);
formatter.field("server_type", &self.server_type);
formatter.field("vm_server", &self.vm_server);
formatter.field("replication_job_id", &self.replication_job_id);
formatter.field(
"replication_job_terminated",
&self.replication_job_terminated,
);
formatter.finish()
}
}
/// See [`Server`](crate::model::Server)
pub mod server {
/// A builder for [`Server`](crate::model::Server)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) server_id: std::option::Option<std::string::String>,
pub(crate) server_type: std::option::Option<crate::model::ServerType>,
pub(crate) vm_server: std::option::Option<crate::model::VmServer>,
pub(crate) replication_job_id: std::option::Option<std::string::String>,
pub(crate) replication_job_terminated: std::option::Option<bool>,
}
impl Builder {
/// <p>The ID of the server.</p>
pub fn server_id(mut self, input: impl Into<std::string::String>) -> Self {
self.server_id = Some(input.into());
self
}
/// <p>The ID of the server.</p>
pub fn set_server_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.server_id = input;
self
}
/// <p>The type of server.</p>
pub fn server_type(mut self, input: crate::model::ServerType) -> Self {
self.server_type = Some(input);
self
}
/// <p>The type of server.</p>
pub fn set_server_type(
mut self,
input: std::option::Option<crate::model::ServerType>,
) -> Self {
self.server_type = input;
self
}
/// <p>Information about the VM server.</p>
pub fn vm_server(mut self, input: crate::model::VmServer) -> Self {
self.vm_server = Some(input);
self
}
/// <p>Information about the VM server.</p>
pub fn set_vm_server(mut self, input: std::option::Option<crate::model::VmServer>) -> Self {
self.vm_server = input;
self
}
/// <p>The ID of the replication job.</p>
pub fn replication_job_id(mut self, input: impl Into<std::string::String>) -> Self {
self.replication_job_id = Some(input.into());
self
}
/// <p>The ID of the replication job.</p>
pub fn set_replication_job_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.replication_job_id = input;
self
}
/// <p>Indicates whether the replication job is deleted or failed.</p>
pub fn replication_job_terminated(mut self, input: bool) -> Self {
self.replication_job_terminated = Some(input);
self
}
/// <p>Indicates whether the replication job is deleted or failed.</p>
pub fn set_replication_job_terminated(mut self, input: std::option::Option<bool>) -> Self {
self.replication_job_terminated = input;
self
}
/// Consumes the builder and constructs a [`Server`](crate::model::Server)
pub fn build(self) -> crate::model::Server {
crate::model::Server {
server_id: self.server_id,
server_type: self.server_type,
vm_server: self.vm_server,
replication_job_id: self.replication_job_id,
replication_job_terminated: self.replication_job_terminated,
}
}
}
}
impl Server {
/// Creates a new builder-style object to manufacture [`Server`](crate::model::Server)
pub fn builder() -> crate::model::server::Builder {
crate::model::server::Builder::default()
}
}
/// <p>Represents a VM server.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct VmServer {
/// <p>The VM server location.</p>
pub vm_server_address: std::option::Option<crate::model::VmServerAddress>,
/// <p>The name of the VM.</p>
pub vm_name: std::option::Option<std::string::String>,
/// <p>The name of the VM manager.</p>
pub vm_manager_name: std::option::Option<std::string::String>,
/// <p>The type of VM management product.</p>
pub vm_manager_type: std::option::Option<crate::model::VmManagerType>,
/// <p>The VM folder path in the vCenter Server virtual machine inventory tree.</p>
pub vm_path: std::option::Option<std::string::String>,
}
impl VmServer {
/// <p>The VM server location.</p>
pub fn vm_server_address(&self) -> std::option::Option<&crate::model::VmServerAddress> {
self.vm_server_address.as_ref()
}
/// <p>The name of the VM.</p>
pub fn vm_name(&self) -> std::option::Option<&str> {
self.vm_name.as_deref()
}
/// <p>The name of the VM manager.</p>
pub fn vm_manager_name(&self) -> std::option::Option<&str> {
self.vm_manager_name.as_deref()
}
/// <p>The type of VM management product.</p>
pub fn vm_manager_type(&self) -> std::option::Option<&crate::model::VmManagerType> {
self.vm_manager_type.as_ref()
}
/// <p>The VM folder path in the vCenter Server virtual machine inventory tree.</p>
pub fn vm_path(&self) -> std::option::Option<&str> {
self.vm_path.as_deref()
}
}
impl std::fmt::Debug for VmServer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("VmServer");
formatter.field("vm_server_address", &self.vm_server_address);
formatter.field("vm_name", &self.vm_name);
formatter.field("vm_manager_name", &self.vm_manager_name);
formatter.field("vm_manager_type", &self.vm_manager_type);
formatter.field("vm_path", &self.vm_path);
formatter.finish()
}
}
/// See [`VmServer`](crate::model::VmServer)
pub mod vm_server {
/// A builder for [`VmServer`](crate::model::VmServer)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) vm_server_address: std::option::Option<crate::model::VmServerAddress>,
pub(crate) vm_name: std::option::Option<std::string::String>,
pub(crate) vm_manager_name: std::option::Option<std::string::String>,
pub(crate) vm_manager_type: std::option::Option<crate::model::VmManagerType>,
pub(crate) vm_path: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The VM server location.</p>
pub fn vm_server_address(mut self, input: crate::model::VmServerAddress) -> Self {
self.vm_server_address = Some(input);
self
}
/// <p>The VM server location.</p>
pub fn set_vm_server_address(
mut self,
input: std::option::Option<crate::model::VmServerAddress>,
) -> Self {
self.vm_server_address = input;
self
}
/// <p>The name of the VM.</p>
pub fn vm_name(mut self, input: impl Into<std::string::String>) -> Self {
self.vm_name = Some(input.into());
self
}
/// <p>The name of the VM.</p>
pub fn set_vm_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.vm_name = input;
self
}
/// <p>The name of the VM manager.</p>
pub fn vm_manager_name(mut self, input: impl Into<std::string::String>) -> Self {
self.vm_manager_name = Some(input.into());
self
}
/// <p>The name of the VM manager.</p>
pub fn set_vm_manager_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.vm_manager_name = input;
self
}
/// <p>The type of VM management product.</p>
pub fn vm_manager_type(mut self, input: crate::model::VmManagerType) -> Self {
self.vm_manager_type = Some(input);
self
}
/// <p>The type of VM management product.</p>
pub fn set_vm_manager_type(
mut self,
input: std::option::Option<crate::model::VmManagerType>,
) -> Self {
self.vm_manager_type = input;
self
}
/// <p>The VM folder path in the vCenter Server virtual machine inventory tree.</p>
pub fn vm_path(mut self, input: impl Into<std::string::String>) -> Self {
self.vm_path = Some(input.into());
self
}
/// <p>The VM folder path in the vCenter Server virtual machine inventory tree.</p>
pub fn set_vm_path(mut self, input: std::option::Option<std::string::String>) -> Self {
self.vm_path = input;
self
}
/// Consumes the builder and constructs a [`VmServer`](crate::model::VmServer)
pub fn build(self) -> crate::model::VmServer {
crate::model::VmServer {
vm_server_address: self.vm_server_address,
vm_name: self.vm_name,
vm_manager_name: self.vm_manager_name,
vm_manager_type: self.vm_manager_type,
vm_path: self.vm_path,
}
}
}
}
impl VmServer {
/// Creates a new builder-style object to manufacture [`VmServer`](crate::model::VmServer)
pub fn builder() -> crate::model::vm_server::Builder {
crate::model::vm_server::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum VmManagerType {
#[allow(missing_docs)] // documentation missing in model
HyperVManager,
#[allow(missing_docs)] // documentation missing in model
Scvmm,
#[allow(missing_docs)] // documentation missing in model
VSphere,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for VmManagerType {
fn from(s: &str) -> Self {
match s {
"HYPERV-MANAGER" => VmManagerType::HyperVManager,
"SCVMM" => VmManagerType::Scvmm,
"VSPHERE" => VmManagerType::VSphere,
other => VmManagerType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for VmManagerType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(VmManagerType::from(s))
}
}
impl VmManagerType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
VmManagerType::HyperVManager => "HYPERV-MANAGER",
VmManagerType::Scvmm => "SCVMM",
VmManagerType::VSphere => "VSPHERE",
VmManagerType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["HYPERV-MANAGER", "SCVMM", "VSPHERE"]
}
}
impl AsRef<str> for VmManagerType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Represents a VM server location.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct VmServerAddress {
/// <p>The ID of the VM manager.</p>
pub vm_manager_id: std::option::Option<std::string::String>,
/// <p>The ID of the VM.</p>
pub vm_id: std::option::Option<std::string::String>,
}
impl VmServerAddress {
/// <p>The ID of the VM manager.</p>
pub fn vm_manager_id(&self) -> std::option::Option<&str> {
self.vm_manager_id.as_deref()
}
/// <p>The ID of the VM.</p>
pub fn vm_id(&self) -> std::option::Option<&str> {
self.vm_id.as_deref()
}
}
impl std::fmt::Debug for VmServerAddress {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("VmServerAddress");
formatter.field("vm_manager_id", &self.vm_manager_id);
formatter.field("vm_id", &self.vm_id);
formatter.finish()
}
}
/// See [`VmServerAddress`](crate::model::VmServerAddress)
pub mod vm_server_address {
/// A builder for [`VmServerAddress`](crate::model::VmServerAddress)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) vm_manager_id: std::option::Option<std::string::String>,
pub(crate) vm_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The ID of the VM manager.</p>
pub fn vm_manager_id(mut self, input: impl Into<std::string::String>) -> Self {
self.vm_manager_id = Some(input.into());
self
}
/// <p>The ID of the VM manager.</p>
pub fn set_vm_manager_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.vm_manager_id = input;
self
}
/// <p>The ID of the VM.</p>
pub fn vm_id(mut self, input: impl Into<std::string::String>) -> Self {
self.vm_id = Some(input.into());
self
}
/// <p>The ID of the VM.</p>
pub fn set_vm_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.vm_id = input;
self
}
/// Consumes the builder and constructs a [`VmServerAddress`](crate::model::VmServerAddress)
pub fn build(self) -> crate::model::VmServerAddress {
crate::model::VmServerAddress {
vm_manager_id: self.vm_manager_id,
vm_id: self.vm_id,
}
}
}
}
impl VmServerAddress {
/// Creates a new builder-style object to manufacture [`VmServerAddress`](crate::model::VmServerAddress)
pub fn builder() -> crate::model::vm_server_address::Builder {
crate::model::vm_server_address::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ServerType {
#[allow(missing_docs)] // documentation missing in model
VirtualMachine,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ServerType {
fn from(s: &str) -> Self {
match s {
"VIRTUAL_MACHINE" => ServerType::VirtualMachine,
other => ServerType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ServerType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ServerType::from(s))
}
}
impl ServerType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ServerType::VirtualMachine => "VIRTUAL_MACHINE",
ServerType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["VIRTUAL_MACHINE"]
}
}
impl AsRef<str> for ServerType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Information about the application.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct AppSummary {
/// <p>The unique ID of the application.</p>
pub app_id: std::option::Option<std::string::String>,
/// <p>The ID of the application.</p>
pub imported_app_id: std::option::Option<std::string::String>,
/// <p>The name of the application.</p>
pub name: std::option::Option<std::string::String>,
/// <p>The description of the application.</p>
pub description: std::option::Option<std::string::String>,
/// <p>Status of the application.</p>
pub status: std::option::Option<crate::model::AppStatus>,
/// <p>A message related to the status of the application</p>
pub status_message: std::option::Option<std::string::String>,
/// <p>Status of the replication configuration.</p>
pub replication_configuration_status:
std::option::Option<crate::model::AppReplicationConfigurationStatus>,
/// <p>The replication status of the application.</p>
pub replication_status: std::option::Option<crate::model::AppReplicationStatus>,
/// <p>A message related to the replication status of the application.</p>
pub replication_status_message: std::option::Option<std::string::String>,
/// <p>The timestamp of the application's most recent successful replication.</p>
pub latest_replication_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>Status of the launch configuration.</p>
pub launch_configuration_status:
std::option::Option<crate::model::AppLaunchConfigurationStatus>,
/// <p>The launch status of the application.</p>
pub launch_status: std::option::Option<crate::model::AppLaunchStatus>,
/// <p>A message related to the launch status of the application.</p>
pub launch_status_message: std::option::Option<std::string::String>,
/// <p>Details about the latest launch of the application.</p>
pub launch_details: std::option::Option<crate::model::LaunchDetails>,
/// <p>The creation time of the application.</p>
pub creation_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The last modified time of the application.</p>
pub last_modified: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The name of the service role in the customer's account used by AWS SMS.</p>
pub role_name: std::option::Option<std::string::String>,
/// <p>The number of server groups present in the application.</p>
pub total_server_groups: std::option::Option<i32>,
/// <p>The number of servers present in the application.</p>
pub total_servers: std::option::Option<i32>,
}
impl AppSummary {
/// <p>The unique ID of the application.</p>
pub fn app_id(&self) -> std::option::Option<&str> {
self.app_id.as_deref()
}
/// <p>The ID of the application.</p>
pub fn imported_app_id(&self) -> std::option::Option<&str> {
self.imported_app_id.as_deref()
}
/// <p>The name of the application.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
/// <p>The description of the application.</p>
pub fn description(&self) -> std::option::Option<&str> {
self.description.as_deref()
}
/// <p>Status of the application.</p>
pub fn status(&self) -> std::option::Option<&crate::model::AppStatus> {
self.status.as_ref()
}
/// <p>A message related to the status of the application</p>
pub fn status_message(&self) -> std::option::Option<&str> {
self.status_message.as_deref()
}
/// <p>Status of the replication configuration.</p>
pub fn replication_configuration_status(
&self,
) -> std::option::Option<&crate::model::AppReplicationConfigurationStatus> {
self.replication_configuration_status.as_ref()
}
/// <p>The replication status of the application.</p>
pub fn replication_status(&self) -> std::option::Option<&crate::model::AppReplicationStatus> {
self.replication_status.as_ref()
}
/// <p>A message related to the replication status of the application.</p>
pub fn replication_status_message(&self) -> std::option::Option<&str> {
self.replication_status_message.as_deref()
}
/// <p>The timestamp of the application's most recent successful replication.</p>
pub fn latest_replication_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.latest_replication_time.as_ref()
}
/// <p>Status of the launch configuration.</p>
pub fn launch_configuration_status(
&self,
) -> std::option::Option<&crate::model::AppLaunchConfigurationStatus> {
self.launch_configuration_status.as_ref()
}
/// <p>The launch status of the application.</p>
pub fn launch_status(&self) -> std::option::Option<&crate::model::AppLaunchStatus> {
self.launch_status.as_ref()
}
/// <p>A message related to the launch status of the application.</p>
pub fn launch_status_message(&self) -> std::option::Option<&str> {
self.launch_status_message.as_deref()
}
/// <p>Details about the latest launch of the application.</p>
pub fn launch_details(&self) -> std::option::Option<&crate::model::LaunchDetails> {
self.launch_details.as_ref()
}
/// <p>The creation time of the application.</p>
pub fn creation_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.creation_time.as_ref()
}
/// <p>The last modified time of the application.</p>
pub fn last_modified(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.last_modified.as_ref()
}
/// <p>The name of the service role in the customer's account used by AWS SMS.</p>
pub fn role_name(&self) -> std::option::Option<&str> {
self.role_name.as_deref()
}
/// <p>The number of server groups present in the application.</p>
pub fn total_server_groups(&self) -> std::option::Option<i32> {
self.total_server_groups
}
/// <p>The number of servers present in the application.</p>
pub fn total_servers(&self) -> std::option::Option<i32> {
self.total_servers
}
}
impl std::fmt::Debug for AppSummary {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("AppSummary");
formatter.field("app_id", &self.app_id);
formatter.field("imported_app_id", &self.imported_app_id);
formatter.field("name", &self.name);
formatter.field("description", &self.description);
formatter.field("status", &self.status);
formatter.field("status_message", &self.status_message);
formatter.field(
"replication_configuration_status",
&self.replication_configuration_status,
);
formatter.field("replication_status", &self.replication_status);
formatter.field(
"replication_status_message",
&self.replication_status_message,
);
formatter.field("latest_replication_time", &self.latest_replication_time);
formatter.field(
"launch_configuration_status",
&self.launch_configuration_status,
);
formatter.field("launch_status", &self.launch_status);
formatter.field("launch_status_message", &self.launch_status_message);
formatter.field("launch_details", &self.launch_details);
formatter.field("creation_time", &self.creation_time);
formatter.field("last_modified", &self.last_modified);
formatter.field("role_name", &self.role_name);
formatter.field("total_server_groups", &self.total_server_groups);
formatter.field("total_servers", &self.total_servers);
formatter.finish()
}
}
/// See [`AppSummary`](crate::model::AppSummary)
pub mod app_summary {
/// A builder for [`AppSummary`](crate::model::AppSummary)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) app_id: std::option::Option<std::string::String>,
pub(crate) imported_app_id: std::option::Option<std::string::String>,
pub(crate) name: std::option::Option<std::string::String>,
pub(crate) description: std::option::Option<std::string::String>,
pub(crate) status: std::option::Option<crate::model::AppStatus>,
pub(crate) status_message: std::option::Option<std::string::String>,
pub(crate) replication_configuration_status:
std::option::Option<crate::model::AppReplicationConfigurationStatus>,
pub(crate) replication_status: std::option::Option<crate::model::AppReplicationStatus>,
pub(crate) replication_status_message: std::option::Option<std::string::String>,
pub(crate) latest_replication_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) launch_configuration_status:
std::option::Option<crate::model::AppLaunchConfigurationStatus>,
pub(crate) launch_status: std::option::Option<crate::model::AppLaunchStatus>,
pub(crate) launch_status_message: std::option::Option<std::string::String>,
pub(crate) launch_details: std::option::Option<crate::model::LaunchDetails>,
pub(crate) creation_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) last_modified: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) role_name: std::option::Option<std::string::String>,
pub(crate) total_server_groups: std::option::Option<i32>,
pub(crate) total_servers: std::option::Option<i32>,
}
impl Builder {
/// <p>The unique ID of the application.</p>
pub fn app_id(mut self, input: impl Into<std::string::String>) -> Self {
self.app_id = Some(input.into());
self
}
/// <p>The unique ID of the application.</p>
pub fn set_app_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.app_id = input;
self
}
/// <p>The ID of the application.</p>
pub fn imported_app_id(mut self, input: impl Into<std::string::String>) -> Self {
self.imported_app_id = Some(input.into());
self
}
/// <p>The ID of the application.</p>
pub fn set_imported_app_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.imported_app_id = input;
self
}
/// <p>The name of the application.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The name of the application.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// <p>The description of the application.</p>
pub fn description(mut self, input: impl Into<std::string::String>) -> Self {
self.description = Some(input.into());
self
}
/// <p>The description of the application.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.description = input;
self
}
/// <p>Status of the application.</p>
pub fn status(mut self, input: crate::model::AppStatus) -> Self {
self.status = Some(input);
self
}
/// <p>Status of the application.</p>
pub fn set_status(mut self, input: std::option::Option<crate::model::AppStatus>) -> Self {
self.status = input;
self
}
/// <p>A message related to the status of the application</p>
pub fn status_message(mut self, input: impl Into<std::string::String>) -> Self {
self.status_message = Some(input.into());
self
}
/// <p>A message related to the status of the application</p>
pub fn set_status_message(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.status_message = input;
self
}
/// <p>Status of the replication configuration.</p>
pub fn replication_configuration_status(
mut self,
input: crate::model::AppReplicationConfigurationStatus,
) -> Self {
self.replication_configuration_status = Some(input);
self
}
/// <p>Status of the replication configuration.</p>
pub fn set_replication_configuration_status(
mut self,
input: std::option::Option<crate::model::AppReplicationConfigurationStatus>,
) -> Self {
self.replication_configuration_status = input;
self
}
/// <p>The replication status of the application.</p>
pub fn replication_status(mut self, input: crate::model::AppReplicationStatus) -> Self {
self.replication_status = Some(input);
self
}
/// <p>The replication status of the application.</p>
pub fn set_replication_status(
mut self,
input: std::option::Option<crate::model::AppReplicationStatus>,
) -> Self {
self.replication_status = input;
self
}
/// <p>A message related to the replication status of the application.</p>
pub fn replication_status_message(mut self, input: impl Into<std::string::String>) -> Self {
self.replication_status_message = Some(input.into());
self
}
/// <p>A message related to the replication status of the application.</p>
pub fn set_replication_status_message(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.replication_status_message = input;
self
}
/// <p>The timestamp of the application's most recent successful replication.</p>
pub fn latest_replication_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.latest_replication_time = Some(input);
self
}
/// <p>The timestamp of the application's most recent successful replication.</p>
pub fn set_latest_replication_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.latest_replication_time = input;
self
}
/// <p>Status of the launch configuration.</p>
pub fn launch_configuration_status(
mut self,
input: crate::model::AppLaunchConfigurationStatus,
) -> Self {
self.launch_configuration_status = Some(input);
self
}
/// <p>Status of the launch configuration.</p>
pub fn set_launch_configuration_status(
mut self,
input: std::option::Option<crate::model::AppLaunchConfigurationStatus>,
) -> Self {
self.launch_configuration_status = input;
self
}
/// <p>The launch status of the application.</p>
pub fn launch_status(mut self, input: crate::model::AppLaunchStatus) -> Self {
self.launch_status = Some(input);
self
}
/// <p>The launch status of the application.</p>
pub fn set_launch_status(
mut self,
input: std::option::Option<crate::model::AppLaunchStatus>,
) -> Self {
self.launch_status = input;
self
}
/// <p>A message related to the launch status of the application.</p>
pub fn launch_status_message(mut self, input: impl Into<std::string::String>) -> Self {
self.launch_status_message = Some(input.into());
self
}
/// <p>A message related to the launch status of the application.</p>
pub fn set_launch_status_message(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.launch_status_message = input;
self
}
/// <p>Details about the latest launch of the application.</p>
pub fn launch_details(mut self, input: crate::model::LaunchDetails) -> Self {
self.launch_details = Some(input);
self
}
/// <p>Details about the latest launch of the application.</p>
pub fn set_launch_details(
mut self,
input: std::option::Option<crate::model::LaunchDetails>,
) -> Self {
self.launch_details = input;
self
}
/// <p>The creation time of the application.</p>
pub fn creation_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.creation_time = Some(input);
self
}
/// <p>The creation time of the application.</p>
pub fn set_creation_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.creation_time = input;
self
}
/// <p>The last modified time of the application.</p>
pub fn last_modified(mut self, input: aws_smithy_types::DateTime) -> Self {
self.last_modified = Some(input);
self
}
/// <p>The last modified time of the application.</p>
pub fn set_last_modified(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.last_modified = input;
self
}
/// <p>The name of the service role in the customer's account used by AWS SMS.</p>
pub fn role_name(mut self, input: impl Into<std::string::String>) -> Self {
self.role_name = Some(input.into());
self
}
/// <p>The name of the service role in the customer's account used by AWS SMS.</p>
pub fn set_role_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.role_name = input;
self
}
/// <p>The number of server groups present in the application.</p>
pub fn total_server_groups(mut self, input: i32) -> Self {
self.total_server_groups = Some(input);
self
}
/// <p>The number of server groups present in the application.</p>
pub fn set_total_server_groups(mut self, input: std::option::Option<i32>) -> Self {
self.total_server_groups = input;
self
}
/// <p>The number of servers present in the application.</p>
pub fn total_servers(mut self, input: i32) -> Self {
self.total_servers = Some(input);
self
}
/// <p>The number of servers present in the application.</p>
pub fn set_total_servers(mut self, input: std::option::Option<i32>) -> Self {
self.total_servers = input;
self
}
/// Consumes the builder and constructs a [`AppSummary`](crate::model::AppSummary)
pub fn build(self) -> crate::model::AppSummary {
crate::model::AppSummary {
app_id: self.app_id,
imported_app_id: self.imported_app_id,
name: self.name,
description: self.description,
status: self.status,
status_message: self.status_message,
replication_configuration_status: self.replication_configuration_status,
replication_status: self.replication_status,
replication_status_message: self.replication_status_message,
latest_replication_time: self.latest_replication_time,
launch_configuration_status: self.launch_configuration_status,
launch_status: self.launch_status,
launch_status_message: self.launch_status_message,
launch_details: self.launch_details,
creation_time: self.creation_time,
last_modified: self.last_modified,
role_name: self.role_name,
total_server_groups: self.total_server_groups,
total_servers: self.total_servers,
}
}
}
}
impl AppSummary {
/// Creates a new builder-style object to manufacture [`AppSummary`](crate::model::AppSummary)
pub fn builder() -> crate::model::app_summary::Builder {
crate::model::app_summary::Builder::default()
}
}
/// <p>Details about the latest launch of an application.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct LaunchDetails {
/// <p>The latest time that this application was launched successfully.</p>
pub latest_launch_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The name of the latest stack launched for this application.</p>
pub stack_name: std::option::Option<std::string::String>,
/// <p>The ID of the latest stack launched for this application.</p>
pub stack_id: std::option::Option<std::string::String>,
}
impl LaunchDetails {
/// <p>The latest time that this application was launched successfully.</p>
pub fn latest_launch_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.latest_launch_time.as_ref()
}
/// <p>The name of the latest stack launched for this application.</p>
pub fn stack_name(&self) -> std::option::Option<&str> {
self.stack_name.as_deref()
}
/// <p>The ID of the latest stack launched for this application.</p>
pub fn stack_id(&self) -> std::option::Option<&str> {
self.stack_id.as_deref()
}
}
impl std::fmt::Debug for LaunchDetails {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("LaunchDetails");
formatter.field("latest_launch_time", &self.latest_launch_time);
formatter.field("stack_name", &self.stack_name);
formatter.field("stack_id", &self.stack_id);
formatter.finish()
}
}
/// See [`LaunchDetails`](crate::model::LaunchDetails)
pub mod launch_details {
/// A builder for [`LaunchDetails`](crate::model::LaunchDetails)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) latest_launch_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) stack_name: std::option::Option<std::string::String>,
pub(crate) stack_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The latest time that this application was launched successfully.</p>
pub fn latest_launch_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.latest_launch_time = Some(input);
self
}
/// <p>The latest time that this application was launched successfully.</p>
pub fn set_latest_launch_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.latest_launch_time = input;
self
}
/// <p>The name of the latest stack launched for this application.</p>
pub fn stack_name(mut self, input: impl Into<std::string::String>) -> Self {
self.stack_name = Some(input.into());
self
}
/// <p>The name of the latest stack launched for this application.</p>
pub fn set_stack_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.stack_name = input;
self
}
/// <p>The ID of the latest stack launched for this application.</p>
pub fn stack_id(mut self, input: impl Into<std::string::String>) -> Self {
self.stack_id = Some(input.into());
self
}
/// <p>The ID of the latest stack launched for this application.</p>
pub fn set_stack_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.stack_id = input;
self
}
/// Consumes the builder and constructs a [`LaunchDetails`](crate::model::LaunchDetails)
pub fn build(self) -> crate::model::LaunchDetails {
crate::model::LaunchDetails {
latest_launch_time: self.latest_launch_time,
stack_name: self.stack_name,
stack_id: self.stack_id,
}
}
}
}
impl LaunchDetails {
/// Creates a new builder-style object to manufacture [`LaunchDetails`](crate::model::LaunchDetails)
pub fn builder() -> crate::model::launch_details::Builder {
crate::model::launch_details::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum AppLaunchStatus {
#[allow(missing_docs)] // documentation missing in model
ConfigurationInvalid,
#[allow(missing_docs)] // documentation missing in model
ConfigurationInProgress,
#[allow(missing_docs)] // documentation missing in model
DeltaLaunchFailed,
#[allow(missing_docs)] // documentation missing in model
DeltaLaunchInProgress,
#[allow(missing_docs)] // documentation missing in model
Launched,
#[allow(missing_docs)] // documentation missing in model
LaunchFailed,
#[allow(missing_docs)] // documentation missing in model
LaunchInProgress,
#[allow(missing_docs)] // documentation missing in model
LaunchPending,
#[allow(missing_docs)] // documentation missing in model
PartiallyLaunched,
#[allow(missing_docs)] // documentation missing in model
ReadyForConfiguration,
#[allow(missing_docs)] // documentation missing in model
ReadyForLaunch,
#[allow(missing_docs)] // documentation missing in model
Terminated,
#[allow(missing_docs)] // documentation missing in model
TerminateFailed,
#[allow(missing_docs)] // documentation missing in model
TerminateInProgress,
#[allow(missing_docs)] // documentation missing in model
ValidationInProgress,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for AppLaunchStatus {
fn from(s: &str) -> Self {
match s {
"CONFIGURATION_INVALID" => AppLaunchStatus::ConfigurationInvalid,
"CONFIGURATION_IN_PROGRESS" => AppLaunchStatus::ConfigurationInProgress,
"DELTA_LAUNCH_FAILED" => AppLaunchStatus::DeltaLaunchFailed,
"DELTA_LAUNCH_IN_PROGRESS" => AppLaunchStatus::DeltaLaunchInProgress,
"LAUNCHED" => AppLaunchStatus::Launched,
"LAUNCH_FAILED" => AppLaunchStatus::LaunchFailed,
"LAUNCH_IN_PROGRESS" => AppLaunchStatus::LaunchInProgress,
"LAUNCH_PENDING" => AppLaunchStatus::LaunchPending,
"PARTIALLY_LAUNCHED" => AppLaunchStatus::PartiallyLaunched,
"READY_FOR_CONFIGURATION" => AppLaunchStatus::ReadyForConfiguration,
"READY_FOR_LAUNCH" => AppLaunchStatus::ReadyForLaunch,
"TERMINATED" => AppLaunchStatus::Terminated,
"TERMINATE_FAILED" => AppLaunchStatus::TerminateFailed,
"TERMINATE_IN_PROGRESS" => AppLaunchStatus::TerminateInProgress,
"VALIDATION_IN_PROGRESS" => AppLaunchStatus::ValidationInProgress,
other => AppLaunchStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for AppLaunchStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(AppLaunchStatus::from(s))
}
}
impl AppLaunchStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
AppLaunchStatus::ConfigurationInvalid => "CONFIGURATION_INVALID",
AppLaunchStatus::ConfigurationInProgress => "CONFIGURATION_IN_PROGRESS",
AppLaunchStatus::DeltaLaunchFailed => "DELTA_LAUNCH_FAILED",
AppLaunchStatus::DeltaLaunchInProgress => "DELTA_LAUNCH_IN_PROGRESS",
AppLaunchStatus::Launched => "LAUNCHED",
AppLaunchStatus::LaunchFailed => "LAUNCH_FAILED",
AppLaunchStatus::LaunchInProgress => "LAUNCH_IN_PROGRESS",
AppLaunchStatus::LaunchPending => "LAUNCH_PENDING",
AppLaunchStatus::PartiallyLaunched => "PARTIALLY_LAUNCHED",
AppLaunchStatus::ReadyForConfiguration => "READY_FOR_CONFIGURATION",
AppLaunchStatus::ReadyForLaunch => "READY_FOR_LAUNCH",
AppLaunchStatus::Terminated => "TERMINATED",
AppLaunchStatus::TerminateFailed => "TERMINATE_FAILED",
AppLaunchStatus::TerminateInProgress => "TERMINATE_IN_PROGRESS",
AppLaunchStatus::ValidationInProgress => "VALIDATION_IN_PROGRESS",
AppLaunchStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"CONFIGURATION_INVALID",
"CONFIGURATION_IN_PROGRESS",
"DELTA_LAUNCH_FAILED",
"DELTA_LAUNCH_IN_PROGRESS",
"LAUNCHED",
"LAUNCH_FAILED",
"LAUNCH_IN_PROGRESS",
"LAUNCH_PENDING",
"PARTIALLY_LAUNCHED",
"READY_FOR_CONFIGURATION",
"READY_FOR_LAUNCH",
"TERMINATED",
"TERMINATE_FAILED",
"TERMINATE_IN_PROGRESS",
"VALIDATION_IN_PROGRESS",
]
}
}
impl AsRef<str> for AppLaunchStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum AppLaunchConfigurationStatus {
#[allow(missing_docs)] // documentation missing in model
Configured,
#[allow(missing_docs)] // documentation missing in model
NotConfigured,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for AppLaunchConfigurationStatus {
fn from(s: &str) -> Self {
match s {
"CONFIGURED" => AppLaunchConfigurationStatus::Configured,
"NOT_CONFIGURED" => AppLaunchConfigurationStatus::NotConfigured,
other => AppLaunchConfigurationStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for AppLaunchConfigurationStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(AppLaunchConfigurationStatus::from(s))
}
}
impl AppLaunchConfigurationStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
AppLaunchConfigurationStatus::Configured => "CONFIGURED",
AppLaunchConfigurationStatus::NotConfigured => "NOT_CONFIGURED",
AppLaunchConfigurationStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["CONFIGURED", "NOT_CONFIGURED"]
}
}
impl AsRef<str> for AppLaunchConfigurationStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum AppReplicationStatus {
#[allow(missing_docs)] // documentation missing in model
ConfigurationInvalid,
#[allow(missing_docs)] // documentation missing in model
ConfigurationInProgress,
#[allow(missing_docs)] // documentation missing in model
DeltaReplicated,
#[allow(missing_docs)] // documentation missing in model
DeltaReplicationFailed,
#[allow(missing_docs)] // documentation missing in model
DeltaReplicationInProgress,
#[allow(missing_docs)] // documentation missing in model
PartiallyReplicated,
#[allow(missing_docs)] // documentation missing in model
ReadyForConfiguration,
#[allow(missing_docs)] // documentation missing in model
ReadyForReplication,
#[allow(missing_docs)] // documentation missing in model
Replicated,
#[allow(missing_docs)] // documentation missing in model
ReplicationFailed,
#[allow(missing_docs)] // documentation missing in model
ReplicationInProgress,
#[allow(missing_docs)] // documentation missing in model
ReplicationPending,
#[allow(missing_docs)] // documentation missing in model
ReplicationStopped,
#[allow(missing_docs)] // documentation missing in model
ReplicationStopping,
#[allow(missing_docs)] // documentation missing in model
ReplicationStopFailed,
#[allow(missing_docs)] // documentation missing in model
ValidationInProgress,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for AppReplicationStatus {
fn from(s: &str) -> Self {
match s {
"CONFIGURATION_INVALID" => AppReplicationStatus::ConfigurationInvalid,
"CONFIGURATION_IN_PROGRESS" => AppReplicationStatus::ConfigurationInProgress,
"DELTA_REPLICATED" => AppReplicationStatus::DeltaReplicated,
"DELTA_REPLICATION_FAILED" => AppReplicationStatus::DeltaReplicationFailed,
"DELTA_REPLICATION_IN_PROGRESS" => AppReplicationStatus::DeltaReplicationInProgress,
"PARTIALLY_REPLICATED" => AppReplicationStatus::PartiallyReplicated,
"READY_FOR_CONFIGURATION" => AppReplicationStatus::ReadyForConfiguration,
"READY_FOR_REPLICATION" => AppReplicationStatus::ReadyForReplication,
"REPLICATED" => AppReplicationStatus::Replicated,
"REPLICATION_FAILED" => AppReplicationStatus::ReplicationFailed,
"REPLICATION_IN_PROGRESS" => AppReplicationStatus::ReplicationInProgress,
"REPLICATION_PENDING" => AppReplicationStatus::ReplicationPending,
"REPLICATION_STOPPED" => AppReplicationStatus::ReplicationStopped,
"REPLICATION_STOPPING" => AppReplicationStatus::ReplicationStopping,
"REPLICATION_STOP_FAILED" => AppReplicationStatus::ReplicationStopFailed,
"VALIDATION_IN_PROGRESS" => AppReplicationStatus::ValidationInProgress,
other => AppReplicationStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for AppReplicationStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(AppReplicationStatus::from(s))
}
}
impl AppReplicationStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
AppReplicationStatus::ConfigurationInvalid => "CONFIGURATION_INVALID",
AppReplicationStatus::ConfigurationInProgress => "CONFIGURATION_IN_PROGRESS",
AppReplicationStatus::DeltaReplicated => "DELTA_REPLICATED",
AppReplicationStatus::DeltaReplicationFailed => "DELTA_REPLICATION_FAILED",
AppReplicationStatus::DeltaReplicationInProgress => "DELTA_REPLICATION_IN_PROGRESS",
AppReplicationStatus::PartiallyReplicated => "PARTIALLY_REPLICATED",
AppReplicationStatus::ReadyForConfiguration => "READY_FOR_CONFIGURATION",
AppReplicationStatus::ReadyForReplication => "READY_FOR_REPLICATION",
AppReplicationStatus::Replicated => "REPLICATED",
AppReplicationStatus::ReplicationFailed => "REPLICATION_FAILED",
AppReplicationStatus::ReplicationInProgress => "REPLICATION_IN_PROGRESS",
AppReplicationStatus::ReplicationPending => "REPLICATION_PENDING",
AppReplicationStatus::ReplicationStopped => "REPLICATION_STOPPED",
AppReplicationStatus::ReplicationStopping => "REPLICATION_STOPPING",
AppReplicationStatus::ReplicationStopFailed => "REPLICATION_STOP_FAILED",
AppReplicationStatus::ValidationInProgress => "VALIDATION_IN_PROGRESS",
AppReplicationStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"CONFIGURATION_INVALID",
"CONFIGURATION_IN_PROGRESS",
"DELTA_REPLICATED",
"DELTA_REPLICATION_FAILED",
"DELTA_REPLICATION_IN_PROGRESS",
"PARTIALLY_REPLICATED",
"READY_FOR_CONFIGURATION",
"READY_FOR_REPLICATION",
"REPLICATED",
"REPLICATION_FAILED",
"REPLICATION_IN_PROGRESS",
"REPLICATION_PENDING",
"REPLICATION_STOPPED",
"REPLICATION_STOPPING",
"REPLICATION_STOP_FAILED",
"VALIDATION_IN_PROGRESS",
]
}
}
impl AsRef<str> for AppReplicationStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum AppReplicationConfigurationStatus {
#[allow(missing_docs)] // documentation missing in model
Configured,
#[allow(missing_docs)] // documentation missing in model
NotConfigured,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for AppReplicationConfigurationStatus {
fn from(s: &str) -> Self {
match s {
"CONFIGURED" => AppReplicationConfigurationStatus::Configured,
"NOT_CONFIGURED" => AppReplicationConfigurationStatus::NotConfigured,
other => AppReplicationConfigurationStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for AppReplicationConfigurationStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(AppReplicationConfigurationStatus::from(s))
}
}
impl AppReplicationConfigurationStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
AppReplicationConfigurationStatus::Configured => "CONFIGURED",
AppReplicationConfigurationStatus::NotConfigured => "NOT_CONFIGURED",
AppReplicationConfigurationStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["CONFIGURED", "NOT_CONFIGURED"]
}
}
impl AsRef<str> for AppReplicationConfigurationStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum AppStatus {
#[allow(missing_docs)] // documentation missing in model
Active,
#[allow(missing_docs)] // documentation missing in model
Creating,
#[allow(missing_docs)] // documentation missing in model
Deleted,
#[allow(missing_docs)] // documentation missing in model
DeleteFailed,
#[allow(missing_docs)] // documentation missing in model
Deleting,
#[allow(missing_docs)] // documentation missing in model
Updating,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for AppStatus {
fn from(s: &str) -> Self {
match s {
"ACTIVE" => AppStatus::Active,
"CREATING" => AppStatus::Creating,
"DELETED" => AppStatus::Deleted,
"DELETE_FAILED" => AppStatus::DeleteFailed,
"DELETING" => AppStatus::Deleting,
"UPDATING" => AppStatus::Updating,
other => AppStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for AppStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(AppStatus::from(s))
}
}
impl AppStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
AppStatus::Active => "ACTIVE",
AppStatus::Creating => "CREATING",
AppStatus::Deleted => "DELETED",
AppStatus::DeleteFailed => "DELETE_FAILED",
AppStatus::Deleting => "DELETING",
AppStatus::Updating => "UPDATING",
AppStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"ACTIVE",
"CREATING",
"DELETED",
"DELETE_FAILED",
"DELETING",
"UPDATING",
]
}
}
impl AsRef<str> for AppStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Configuration for validating an instance.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServerGroupValidationConfiguration {
/// <p>The ID of the server group.</p>
pub server_group_id: std::option::Option<std::string::String>,
/// <p>The validation configuration.</p>
pub server_validation_configurations:
std::option::Option<std::vec::Vec<crate::model::ServerValidationConfiguration>>,
}
impl ServerGroupValidationConfiguration {
/// <p>The ID of the server group.</p>
pub fn server_group_id(&self) -> std::option::Option<&str> {
self.server_group_id.as_deref()
}
/// <p>The validation configuration.</p>
pub fn server_validation_configurations(
&self,
) -> std::option::Option<&[crate::model::ServerValidationConfiguration]> {
self.server_validation_configurations.as_deref()
}
}
impl std::fmt::Debug for ServerGroupValidationConfiguration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServerGroupValidationConfiguration");
formatter.field("server_group_id", &self.server_group_id);
formatter.field(
"server_validation_configurations",
&self.server_validation_configurations,
);
formatter.finish()
}
}
/// See [`ServerGroupValidationConfiguration`](crate::model::ServerGroupValidationConfiguration)
pub mod server_group_validation_configuration {
/// A builder for [`ServerGroupValidationConfiguration`](crate::model::ServerGroupValidationConfiguration)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) server_group_id: std::option::Option<std::string::String>,
pub(crate) server_validation_configurations:
std::option::Option<std::vec::Vec<crate::model::ServerValidationConfiguration>>,
}
impl Builder {
/// <p>The ID of the server group.</p>
pub fn server_group_id(mut self, input: impl Into<std::string::String>) -> Self {
self.server_group_id = Some(input.into());
self
}
/// <p>The ID of the server group.</p>
pub fn set_server_group_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.server_group_id = input;
self
}
/// Appends an item to `server_validation_configurations`.
///
/// To override the contents of this collection use [`set_server_validation_configurations`](Self::set_server_validation_configurations).
///
/// <p>The validation configuration.</p>
pub fn server_validation_configurations(
mut self,
input: impl Into<crate::model::ServerValidationConfiguration>,
) -> Self {
let mut v = self.server_validation_configurations.unwrap_or_default();
v.push(input.into());
self.server_validation_configurations = Some(v);
self
}
/// <p>The validation configuration.</p>
pub fn set_server_validation_configurations(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ServerValidationConfiguration>>,
) -> Self {
self.server_validation_configurations = input;
self
}
/// Consumes the builder and constructs a [`ServerGroupValidationConfiguration`](crate::model::ServerGroupValidationConfiguration)
pub fn build(self) -> crate::model::ServerGroupValidationConfiguration {
crate::model::ServerGroupValidationConfiguration {
server_group_id: self.server_group_id,
server_validation_configurations: self.server_validation_configurations,
}
}
}
}
impl ServerGroupValidationConfiguration {
/// Creates a new builder-style object to manufacture [`ServerGroupValidationConfiguration`](crate::model::ServerGroupValidationConfiguration)
pub fn builder() -> crate::model::server_group_validation_configuration::Builder {
crate::model::server_group_validation_configuration::Builder::default()
}
}
/// <p>Configuration for validating an instance.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServerValidationConfiguration {
/// <p>Represents a server.</p>
pub server: std::option::Option<crate::model::Server>,
/// <p>The ID of the validation.</p>
pub validation_id: std::option::Option<std::string::String>,
/// <p>The name of the configuration.</p>
pub name: std::option::Option<std::string::String>,
/// <p>The validation strategy.</p>
pub server_validation_strategy: std::option::Option<crate::model::ServerValidationStrategy>,
/// <p>The validation parameters.</p>
pub user_data_validation_parameters:
std::option::Option<crate::model::UserDataValidationParameters>,
}
impl ServerValidationConfiguration {
/// <p>Represents a server.</p>
pub fn server(&self) -> std::option::Option<&crate::model::Server> {
self.server.as_ref()
}
/// <p>The ID of the validation.</p>
pub fn validation_id(&self) -> std::option::Option<&str> {
self.validation_id.as_deref()
}
/// <p>The name of the configuration.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
/// <p>The validation strategy.</p>
pub fn server_validation_strategy(
&self,
) -> std::option::Option<&crate::model::ServerValidationStrategy> {
self.server_validation_strategy.as_ref()
}
/// <p>The validation parameters.</p>
pub fn user_data_validation_parameters(
&self,
) -> std::option::Option<&crate::model::UserDataValidationParameters> {
self.user_data_validation_parameters.as_ref()
}
}
impl std::fmt::Debug for ServerValidationConfiguration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServerValidationConfiguration");
formatter.field("server", &self.server);
formatter.field("validation_id", &self.validation_id);
formatter.field("name", &self.name);
formatter.field(
"server_validation_strategy",
&self.server_validation_strategy,
);
formatter.field(
"user_data_validation_parameters",
&self.user_data_validation_parameters,
);
formatter.finish()
}
}
/// See [`ServerValidationConfiguration`](crate::model::ServerValidationConfiguration)
pub mod server_validation_configuration {
/// A builder for [`ServerValidationConfiguration`](crate::model::ServerValidationConfiguration)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) server: std::option::Option<crate::model::Server>,
pub(crate) validation_id: std::option::Option<std::string::String>,
pub(crate) name: std::option::Option<std::string::String>,
pub(crate) server_validation_strategy:
std::option::Option<crate::model::ServerValidationStrategy>,
pub(crate) user_data_validation_parameters:
std::option::Option<crate::model::UserDataValidationParameters>,
}
impl Builder {
/// <p>Represents a server.</p>
pub fn server(mut self, input: crate::model::Server) -> Self {
self.server = Some(input);
self
}
/// <p>Represents a server.</p>
pub fn set_server(mut self, input: std::option::Option<crate::model::Server>) -> Self {
self.server = input;
self
}
/// <p>The ID of the validation.</p>
pub fn validation_id(mut self, input: impl Into<std::string::String>) -> Self {
self.validation_id = Some(input.into());
self
}
/// <p>The ID of the validation.</p>
pub fn set_validation_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.validation_id = input;
self
}
/// <p>The name of the configuration.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The name of the configuration.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// <p>The validation strategy.</p>
pub fn server_validation_strategy(
mut self,
input: crate::model::ServerValidationStrategy,
) -> Self {
self.server_validation_strategy = Some(input);
self
}
/// <p>The validation strategy.</p>
pub fn set_server_validation_strategy(
mut self,
input: std::option::Option<crate::model::ServerValidationStrategy>,
) -> Self {
self.server_validation_strategy = input;
self
}
/// <p>The validation parameters.</p>
pub fn user_data_validation_parameters(
mut self,
input: crate::model::UserDataValidationParameters,
) -> Self {
self.user_data_validation_parameters = Some(input);
self
}
/// <p>The validation parameters.</p>
pub fn set_user_data_validation_parameters(
mut self,
input: std::option::Option<crate::model::UserDataValidationParameters>,
) -> Self {
self.user_data_validation_parameters = input;
self
}
/// Consumes the builder and constructs a [`ServerValidationConfiguration`](crate::model::ServerValidationConfiguration)
pub fn build(self) -> crate::model::ServerValidationConfiguration {
crate::model::ServerValidationConfiguration {
server: self.server,
validation_id: self.validation_id,
name: self.name,
server_validation_strategy: self.server_validation_strategy,
user_data_validation_parameters: self.user_data_validation_parameters,
}
}
}
}
impl ServerValidationConfiguration {
/// Creates a new builder-style object to manufacture [`ServerValidationConfiguration`](crate::model::ServerValidationConfiguration)
pub fn builder() -> crate::model::server_validation_configuration::Builder {
crate::model::server_validation_configuration::Builder::default()
}
}
/// <p>Contains validation parameters.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UserDataValidationParameters {
/// <p>The location of the validation script.</p>
pub source: std::option::Option<crate::model::Source>,
/// <p>The type of validation script.</p>
pub script_type: std::option::Option<crate::model::ScriptType>,
}
impl UserDataValidationParameters {
/// <p>The location of the validation script.</p>
pub fn source(&self) -> std::option::Option<&crate::model::Source> {
self.source.as_ref()
}
/// <p>The type of validation script.</p>
pub fn script_type(&self) -> std::option::Option<&crate::model::ScriptType> {
self.script_type.as_ref()
}
}
impl std::fmt::Debug for UserDataValidationParameters {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UserDataValidationParameters");
formatter.field("source", &self.source);
formatter.field("script_type", &self.script_type);
formatter.finish()
}
}
/// See [`UserDataValidationParameters`](crate::model::UserDataValidationParameters)
pub mod user_data_validation_parameters {
/// A builder for [`UserDataValidationParameters`](crate::model::UserDataValidationParameters)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) source: std::option::Option<crate::model::Source>,
pub(crate) script_type: std::option::Option<crate::model::ScriptType>,
}
impl Builder {
/// <p>The location of the validation script.</p>
pub fn source(mut self, input: crate::model::Source) -> Self {
self.source = Some(input);
self
}
/// <p>The location of the validation script.</p>
pub fn set_source(mut self, input: std::option::Option<crate::model::Source>) -> Self {
self.source = input;
self
}
/// <p>The type of validation script.</p>
pub fn script_type(mut self, input: crate::model::ScriptType) -> Self {
self.script_type = Some(input);
self
}
/// <p>The type of validation script.</p>
pub fn set_script_type(
mut self,
input: std::option::Option<crate::model::ScriptType>,
) -> Self {
self.script_type = input;
self
}
/// Consumes the builder and constructs a [`UserDataValidationParameters`](crate::model::UserDataValidationParameters)
pub fn build(self) -> crate::model::UserDataValidationParameters {
crate::model::UserDataValidationParameters {
source: self.source,
script_type: self.script_type,
}
}
}
}
impl UserDataValidationParameters {
/// Creates a new builder-style object to manufacture [`UserDataValidationParameters`](crate::model::UserDataValidationParameters)
pub fn builder() -> crate::model::user_data_validation_parameters::Builder {
crate::model::user_data_validation_parameters::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ScriptType {
#[allow(missing_docs)] // documentation missing in model
PowershellScript,
#[allow(missing_docs)] // documentation missing in model
ShellScript,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ScriptType {
fn from(s: &str) -> Self {
match s {
"POWERSHELL_SCRIPT" => ScriptType::PowershellScript,
"SHELL_SCRIPT" => ScriptType::ShellScript,
other => ScriptType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ScriptType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ScriptType::from(s))
}
}
impl ScriptType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ScriptType::PowershellScript => "POWERSHELL_SCRIPT",
ScriptType::ShellScript => "SHELL_SCRIPT",
ScriptType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["POWERSHELL_SCRIPT", "SHELL_SCRIPT"]
}
}
impl AsRef<str> for ScriptType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Contains the location of a validation script.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct Source {
/// <p>Location of an Amazon S3 object.</p>
pub s3_location: std::option::Option<crate::model::S3Location>,
}
impl Source {
/// <p>Location of an Amazon S3 object.</p>
pub fn s3_location(&self) -> std::option::Option<&crate::model::S3Location> {
self.s3_location.as_ref()
}
}
impl std::fmt::Debug for Source {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("Source");
formatter.field("s3_location", &self.s3_location);
formatter.finish()
}
}
/// See [`Source`](crate::model::Source)
pub mod source {
/// A builder for [`Source`](crate::model::Source)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) s3_location: std::option::Option<crate::model::S3Location>,
}
impl Builder {
/// <p>Location of an Amazon S3 object.</p>
pub fn s3_location(mut self, input: crate::model::S3Location) -> Self {
self.s3_location = Some(input);
self
}
/// <p>Location of an Amazon S3 object.</p>
pub fn set_s3_location(
mut self,
input: std::option::Option<crate::model::S3Location>,
) -> Self {
self.s3_location = input;
self
}
/// Consumes the builder and constructs a [`Source`](crate::model::Source)
pub fn build(self) -> crate::model::Source {
crate::model::Source {
s3_location: self.s3_location,
}
}
}
}
impl Source {
/// Creates a new builder-style object to manufacture [`Source`](crate::model::Source)
pub fn builder() -> crate::model::source::Builder {
crate::model::source::Builder::default()
}
}
/// <p>Location of an Amazon S3 object.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct S3Location {
/// <p>The Amazon S3 bucket name.</p>
pub bucket: std::option::Option<std::string::String>,
/// <p>The Amazon S3 bucket key.</p>
pub key: std::option::Option<std::string::String>,
}
impl S3Location {
/// <p>The Amazon S3 bucket name.</p>
pub fn bucket(&self) -> std::option::Option<&str> {
self.bucket.as_deref()
}
/// <p>The Amazon S3 bucket key.</p>
pub fn key(&self) -> std::option::Option<&str> {
self.key.as_deref()
}
}
impl std::fmt::Debug for S3Location {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("S3Location");
formatter.field("bucket", &self.bucket);
formatter.field("key", &self.key);
formatter.finish()
}
}
/// See [`S3Location`](crate::model::S3Location)
pub mod s3_location {
/// A builder for [`S3Location`](crate::model::S3Location)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) bucket: std::option::Option<std::string::String>,
pub(crate) key: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The Amazon S3 bucket name.</p>
pub fn bucket(mut self, input: impl Into<std::string::String>) -> Self {
self.bucket = Some(input.into());
self
}
/// <p>The Amazon S3 bucket name.</p>
pub fn set_bucket(mut self, input: std::option::Option<std::string::String>) -> Self {
self.bucket = input;
self
}
/// <p>The Amazon S3 bucket key.</p>
pub fn key(mut self, input: impl Into<std::string::String>) -> Self {
self.key = Some(input.into());
self
}
/// <p>The Amazon S3 bucket key.</p>
pub fn set_key(mut self, input: std::option::Option<std::string::String>) -> Self {
self.key = input;
self
}
/// Consumes the builder and constructs a [`S3Location`](crate::model::S3Location)
pub fn build(self) -> crate::model::S3Location {
crate::model::S3Location {
bucket: self.bucket,
key: self.key,
}
}
}
}
impl S3Location {
/// Creates a new builder-style object to manufacture [`S3Location`](crate::model::S3Location)
pub fn builder() -> crate::model::s3_location::Builder {
crate::model::s3_location::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ServerValidationStrategy {
#[allow(missing_docs)] // documentation missing in model
Userdata,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ServerValidationStrategy {
fn from(s: &str) -> Self {
match s {
"USERDATA" => ServerValidationStrategy::Userdata,
other => ServerValidationStrategy::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ServerValidationStrategy {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ServerValidationStrategy::from(s))
}
}
impl ServerValidationStrategy {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ServerValidationStrategy::Userdata => "USERDATA",
ServerValidationStrategy::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["USERDATA"]
}
}
impl AsRef<str> for ServerValidationStrategy {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Configuration for validating an application.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct AppValidationConfiguration {
/// <p>The ID of the validation.</p>
pub validation_id: std::option::Option<std::string::String>,
/// <p>The name of the configuration.</p>
pub name: std::option::Option<std::string::String>,
/// <p>The validation strategy.</p>
pub app_validation_strategy: std::option::Option<crate::model::AppValidationStrategy>,
/// <p>The validation parameters.</p>
pub ssm_validation_parameters: std::option::Option<crate::model::SsmValidationParameters>,
}
impl AppValidationConfiguration {
/// <p>The ID of the validation.</p>
pub fn validation_id(&self) -> std::option::Option<&str> {
self.validation_id.as_deref()
}
/// <p>The name of the configuration.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
/// <p>The validation strategy.</p>
pub fn app_validation_strategy(
&self,
) -> std::option::Option<&crate::model::AppValidationStrategy> {
self.app_validation_strategy.as_ref()
}
/// <p>The validation parameters.</p>
pub fn ssm_validation_parameters(
&self,
) -> std::option::Option<&crate::model::SsmValidationParameters> {
self.ssm_validation_parameters.as_ref()
}
}
impl std::fmt::Debug for AppValidationConfiguration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("AppValidationConfiguration");
formatter.field("validation_id", &self.validation_id);
formatter.field("name", &self.name);
formatter.field("app_validation_strategy", &self.app_validation_strategy);
formatter.field("ssm_validation_parameters", &self.ssm_validation_parameters);
formatter.finish()
}
}
/// See [`AppValidationConfiguration`](crate::model::AppValidationConfiguration)
pub mod app_validation_configuration {
/// A builder for [`AppValidationConfiguration`](crate::model::AppValidationConfiguration)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) validation_id: std::option::Option<std::string::String>,
pub(crate) name: std::option::Option<std::string::String>,
pub(crate) app_validation_strategy:
std::option::Option<crate::model::AppValidationStrategy>,
pub(crate) ssm_validation_parameters:
std::option::Option<crate::model::SsmValidationParameters>,
}
impl Builder {
/// <p>The ID of the validation.</p>
pub fn validation_id(mut self, input: impl Into<std::string::String>) -> Self {
self.validation_id = Some(input.into());
self
}
/// <p>The ID of the validation.</p>
pub fn set_validation_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.validation_id = input;
self
}
/// <p>The name of the configuration.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The name of the configuration.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// <p>The validation strategy.</p>
pub fn app_validation_strategy(
mut self,
input: crate::model::AppValidationStrategy,
) -> Self {
self.app_validation_strategy = Some(input);
self
}
/// <p>The validation strategy.</p>
pub fn set_app_validation_strategy(
mut self,
input: std::option::Option<crate::model::AppValidationStrategy>,
) -> Self {
self.app_validation_strategy = input;
self
}
/// <p>The validation parameters.</p>
pub fn ssm_validation_parameters(
mut self,
input: crate::model::SsmValidationParameters,
) -> Self {
self.ssm_validation_parameters = Some(input);
self
}
/// <p>The validation parameters.</p>
pub fn set_ssm_validation_parameters(
mut self,
input: std::option::Option<crate::model::SsmValidationParameters>,
) -> Self {
self.ssm_validation_parameters = input;
self
}
/// Consumes the builder and constructs a [`AppValidationConfiguration`](crate::model::AppValidationConfiguration)
pub fn build(self) -> crate::model::AppValidationConfiguration {
crate::model::AppValidationConfiguration {
validation_id: self.validation_id,
name: self.name,
app_validation_strategy: self.app_validation_strategy,
ssm_validation_parameters: self.ssm_validation_parameters,
}
}
}
}
impl AppValidationConfiguration {
/// Creates a new builder-style object to manufacture [`AppValidationConfiguration`](crate::model::AppValidationConfiguration)
pub fn builder() -> crate::model::app_validation_configuration::Builder {
crate::model::app_validation_configuration::Builder::default()
}
}
/// <p>Contains validation parameters.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct SsmValidationParameters {
/// <p>The location of the validation script.</p>
pub source: std::option::Option<crate::model::Source>,
/// <p>The ID of the instance. The instance must have the following tag: UserForSMSApplicationValidation=true.</p>
pub instance_id: std::option::Option<std::string::String>,
/// <p>The type of validation script.</p>
pub script_type: std::option::Option<crate::model::ScriptType>,
/// <p>The command to run the validation script</p>
pub command: std::option::Option<std::string::String>,
/// <p>The timeout interval, in seconds.</p>
pub execution_timeout_seconds: i32,
/// <p>The name of the S3 bucket for output.</p>
pub output_s3_bucket_name: std::option::Option<std::string::String>,
}
impl SsmValidationParameters {
/// <p>The location of the validation script.</p>
pub fn source(&self) -> std::option::Option<&crate::model::Source> {
self.source.as_ref()
}
/// <p>The ID of the instance. The instance must have the following tag: UserForSMSApplicationValidation=true.</p>
pub fn instance_id(&self) -> std::option::Option<&str> {
self.instance_id.as_deref()
}
/// <p>The type of validation script.</p>
pub fn script_type(&self) -> std::option::Option<&crate::model::ScriptType> {
self.script_type.as_ref()
}
/// <p>The command to run the validation script</p>
pub fn command(&self) -> std::option::Option<&str> {
self.command.as_deref()
}
/// <p>The timeout interval, in seconds.</p>
pub fn execution_timeout_seconds(&self) -> i32 {
self.execution_timeout_seconds
}
/// <p>The name of the S3 bucket for output.</p>
pub fn output_s3_bucket_name(&self) -> std::option::Option<&str> {
self.output_s3_bucket_name.as_deref()
}
}
impl std::fmt::Debug for SsmValidationParameters {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("SsmValidationParameters");
formatter.field("source", &self.source);
formatter.field("instance_id", &self.instance_id);
formatter.field("script_type", &self.script_type);
formatter.field("command", &self.command);
formatter.field("execution_timeout_seconds", &self.execution_timeout_seconds);
formatter.field("output_s3_bucket_name", &self.output_s3_bucket_name);
formatter.finish()
}
}
/// See [`SsmValidationParameters`](crate::model::SsmValidationParameters)
pub mod ssm_validation_parameters {
/// A builder for [`SsmValidationParameters`](crate::model::SsmValidationParameters)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) source: std::option::Option<crate::model::Source>,
pub(crate) instance_id: std::option::Option<std::string::String>,
pub(crate) script_type: std::option::Option<crate::model::ScriptType>,
pub(crate) command: std::option::Option<std::string::String>,
pub(crate) execution_timeout_seconds: std::option::Option<i32>,
pub(crate) output_s3_bucket_name: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The location of the validation script.</p>
pub fn source(mut self, input: crate::model::Source) -> Self {
self.source = Some(input);
self
}
/// <p>The location of the validation script.</p>
pub fn set_source(mut self, input: std::option::Option<crate::model::Source>) -> Self {
self.source = input;
self
}
/// <p>The ID of the instance. The instance must have the following tag: UserForSMSApplicationValidation=true.</p>
pub fn instance_id(mut self, input: impl Into<std::string::String>) -> Self {
self.instance_id = Some(input.into());
self
}
/// <p>The ID of the instance. The instance must have the following tag: UserForSMSApplicationValidation=true.</p>
pub fn set_instance_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.instance_id = input;
self
}
/// <p>The type of validation script.</p>
pub fn script_type(mut self, input: crate::model::ScriptType) -> Self {
self.script_type = Some(input);
self
}
/// <p>The type of validation script.</p>
pub fn set_script_type(
mut self,
input: std::option::Option<crate::model::ScriptType>,
) -> Self {
self.script_type = input;
self
}
/// <p>The command to run the validation script</p>
pub fn command(mut self, input: impl Into<std::string::String>) -> Self {
self.command = Some(input.into());
self
}
/// <p>The command to run the validation script</p>
pub fn set_command(mut self, input: std::option::Option<std::string::String>) -> Self {
self.command = input;
self
}
/// <p>The timeout interval, in seconds.</p>
pub fn execution_timeout_seconds(mut self, input: i32) -> Self {
self.execution_timeout_seconds = Some(input);
self
}
/// <p>The timeout interval, in seconds.</p>
pub fn set_execution_timeout_seconds(mut self, input: std::option::Option<i32>) -> Self {
self.execution_timeout_seconds = input;
self
}
/// <p>The name of the S3 bucket for output.</p>
pub fn output_s3_bucket_name(mut self, input: impl Into<std::string::String>) -> Self {
self.output_s3_bucket_name = Some(input.into());
self
}
/// <p>The name of the S3 bucket for output.</p>
pub fn set_output_s3_bucket_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.output_s3_bucket_name = input;
self
}
/// Consumes the builder and constructs a [`SsmValidationParameters`](crate::model::SsmValidationParameters)
pub fn build(self) -> crate::model::SsmValidationParameters {
crate::model::SsmValidationParameters {
source: self.source,
instance_id: self.instance_id,
script_type: self.script_type,
command: self.command,
execution_timeout_seconds: self.execution_timeout_seconds.unwrap_or_default(),
output_s3_bucket_name: self.output_s3_bucket_name,
}
}
}
}
impl SsmValidationParameters {
/// Creates a new builder-style object to manufacture [`SsmValidationParameters`](crate::model::SsmValidationParameters)
pub fn builder() -> crate::model::ssm_validation_parameters::Builder {
crate::model::ssm_validation_parameters::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum AppValidationStrategy {
#[allow(missing_docs)] // documentation missing in model
Ssm,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for AppValidationStrategy {
fn from(s: &str) -> Self {
match s {
"SSM" => AppValidationStrategy::Ssm,
other => AppValidationStrategy::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for AppValidationStrategy {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(AppValidationStrategy::from(s))
}
}
impl AppValidationStrategy {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
AppValidationStrategy::Ssm => "SSM",
AppValidationStrategy::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["SSM"]
}
}
impl AsRef<str> for AppValidationStrategy {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Replication configuration for a server group.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServerGroupReplicationConfiguration {
/// <p>The ID of the server group with which this replication configuration is
/// associated.</p>
pub server_group_id: std::option::Option<std::string::String>,
/// <p>The replication configuration for servers in the server group.</p>
pub server_replication_configurations:
std::option::Option<std::vec::Vec<crate::model::ServerReplicationConfiguration>>,
}
impl ServerGroupReplicationConfiguration {
/// <p>The ID of the server group with which this replication configuration is
/// associated.</p>
pub fn server_group_id(&self) -> std::option::Option<&str> {
self.server_group_id.as_deref()
}
/// <p>The replication configuration for servers in the server group.</p>
pub fn server_replication_configurations(
&self,
) -> std::option::Option<&[crate::model::ServerReplicationConfiguration]> {
self.server_replication_configurations.as_deref()
}
}
impl std::fmt::Debug for ServerGroupReplicationConfiguration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServerGroupReplicationConfiguration");
formatter.field("server_group_id", &self.server_group_id);
formatter.field(
"server_replication_configurations",
&self.server_replication_configurations,
);
formatter.finish()
}
}
/// See [`ServerGroupReplicationConfiguration`](crate::model::ServerGroupReplicationConfiguration)
pub mod server_group_replication_configuration {
/// A builder for [`ServerGroupReplicationConfiguration`](crate::model::ServerGroupReplicationConfiguration)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) server_group_id: std::option::Option<std::string::String>,
pub(crate) server_replication_configurations:
std::option::Option<std::vec::Vec<crate::model::ServerReplicationConfiguration>>,
}
impl Builder {
/// <p>The ID of the server group with which this replication configuration is
/// associated.</p>
pub fn server_group_id(mut self, input: impl Into<std::string::String>) -> Self {
self.server_group_id = Some(input.into());
self
}
/// <p>The ID of the server group with which this replication configuration is
/// associated.</p>
pub fn set_server_group_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.server_group_id = input;
self
}
/// Appends an item to `server_replication_configurations`.
///
/// To override the contents of this collection use [`set_server_replication_configurations`](Self::set_server_replication_configurations).
///
/// <p>The replication configuration for servers in the server group.</p>
pub fn server_replication_configurations(
mut self,
input: impl Into<crate::model::ServerReplicationConfiguration>,
) -> Self {
let mut v = self.server_replication_configurations.unwrap_or_default();
v.push(input.into());
self.server_replication_configurations = Some(v);
self
}
/// <p>The replication configuration for servers in the server group.</p>
pub fn set_server_replication_configurations(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ServerReplicationConfiguration>>,
) -> Self {
self.server_replication_configurations = input;
self
}
/// Consumes the builder and constructs a [`ServerGroupReplicationConfiguration`](crate::model::ServerGroupReplicationConfiguration)
pub fn build(self) -> crate::model::ServerGroupReplicationConfiguration {
crate::model::ServerGroupReplicationConfiguration {
server_group_id: self.server_group_id,
server_replication_configurations: self.server_replication_configurations,
}
}
}
}
impl ServerGroupReplicationConfiguration {
/// Creates a new builder-style object to manufacture [`ServerGroupReplicationConfiguration`](crate::model::ServerGroupReplicationConfiguration)
pub fn builder() -> crate::model::server_group_replication_configuration::Builder {
crate::model::server_group_replication_configuration::Builder::default()
}
}
/// <p>Replication configuration of a server.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServerReplicationConfiguration {
/// <p>The ID of the server with which this replication configuration is
/// associated.</p>
pub server: std::option::Option<crate::model::Server>,
/// <p>The parameters for replicating the server.</p>
pub server_replication_parameters:
std::option::Option<crate::model::ServerReplicationParameters>,
}
impl ServerReplicationConfiguration {
/// <p>The ID of the server with which this replication configuration is
/// associated.</p>
pub fn server(&self) -> std::option::Option<&crate::model::Server> {
self.server.as_ref()
}
/// <p>The parameters for replicating the server.</p>
pub fn server_replication_parameters(
&self,
) -> std::option::Option<&crate::model::ServerReplicationParameters> {
self.server_replication_parameters.as_ref()
}
}
impl std::fmt::Debug for ServerReplicationConfiguration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServerReplicationConfiguration");
formatter.field("server", &self.server);
formatter.field(
"server_replication_parameters",
&self.server_replication_parameters,
);
formatter.finish()
}
}
/// See [`ServerReplicationConfiguration`](crate::model::ServerReplicationConfiguration)
pub mod server_replication_configuration {
/// A builder for [`ServerReplicationConfiguration`](crate::model::ServerReplicationConfiguration)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) server: std::option::Option<crate::model::Server>,
pub(crate) server_replication_parameters:
std::option::Option<crate::model::ServerReplicationParameters>,
}
impl Builder {
/// <p>The ID of the server with which this replication configuration is
/// associated.</p>
pub fn server(mut self, input: crate::model::Server) -> Self {
self.server = Some(input);
self
}
/// <p>The ID of the server with which this replication configuration is
/// associated.</p>
pub fn set_server(mut self, input: std::option::Option<crate::model::Server>) -> Self {
self.server = input;
self
}
/// <p>The parameters for replicating the server.</p>
pub fn server_replication_parameters(
mut self,
input: crate::model::ServerReplicationParameters,
) -> Self {
self.server_replication_parameters = Some(input);
self
}
/// <p>The parameters for replicating the server.</p>
pub fn set_server_replication_parameters(
mut self,
input: std::option::Option<crate::model::ServerReplicationParameters>,
) -> Self {
self.server_replication_parameters = input;
self
}
/// Consumes the builder and constructs a [`ServerReplicationConfiguration`](crate::model::ServerReplicationConfiguration)
pub fn build(self) -> crate::model::ServerReplicationConfiguration {
crate::model::ServerReplicationConfiguration {
server: self.server,
server_replication_parameters: self.server_replication_parameters,
}
}
}
}
impl ServerReplicationConfiguration {
/// Creates a new builder-style object to manufacture [`ServerReplicationConfiguration`](crate::model::ServerReplicationConfiguration)
pub fn builder() -> crate::model::server_replication_configuration::Builder {
crate::model::server_replication_configuration::Builder::default()
}
}
/// <p>The replication parameters for replicating a server.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServerReplicationParameters {
/// <p>The seed time for creating a replication job for the server.</p>
pub seed_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The frequency of creating replication jobs for the server.</p>
pub frequency: std::option::Option<i32>,
/// <p>Indicates whether to run the replication job one time.</p>
pub run_once: std::option::Option<bool>,
/// <p>The license type for creating a replication job for the server.</p>
pub license_type: std::option::Option<crate::model::LicenseType>,
/// <p>The number of recent AMIs to keep when creating a replication job for this server.</p>
pub number_of_recent_amis_to_keep: std::option::Option<i32>,
/// <p>Indicates whether the replication job produces encrypted AMIs.</p>
pub encrypted: std::option::Option<bool>,
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following:</p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p>If encrypted is enabled but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used.</p>
pub kms_key_id: std::option::Option<std::string::String>,
}
impl ServerReplicationParameters {
/// <p>The seed time for creating a replication job for the server.</p>
pub fn seed_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.seed_time.as_ref()
}
/// <p>The frequency of creating replication jobs for the server.</p>
pub fn frequency(&self) -> std::option::Option<i32> {
self.frequency
}
/// <p>Indicates whether to run the replication job one time.</p>
pub fn run_once(&self) -> std::option::Option<bool> {
self.run_once
}
/// <p>The license type for creating a replication job for the server.</p>
pub fn license_type(&self) -> std::option::Option<&crate::model::LicenseType> {
self.license_type.as_ref()
}
/// <p>The number of recent AMIs to keep when creating a replication job for this server.</p>
pub fn number_of_recent_amis_to_keep(&self) -> std::option::Option<i32> {
self.number_of_recent_amis_to_keep
}
/// <p>Indicates whether the replication job produces encrypted AMIs.</p>
pub fn encrypted(&self) -> std::option::Option<bool> {
self.encrypted
}
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following:</p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p>If encrypted is enabled but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used.</p>
pub fn kms_key_id(&self) -> std::option::Option<&str> {
self.kms_key_id.as_deref()
}
}
impl std::fmt::Debug for ServerReplicationParameters {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServerReplicationParameters");
formatter.field("seed_time", &self.seed_time);
formatter.field("frequency", &self.frequency);
formatter.field("run_once", &self.run_once);
formatter.field("license_type", &self.license_type);
formatter.field(
"number_of_recent_amis_to_keep",
&self.number_of_recent_amis_to_keep,
);
formatter.field("encrypted", &self.encrypted);
formatter.field("kms_key_id", &self.kms_key_id);
formatter.finish()
}
}
/// See [`ServerReplicationParameters`](crate::model::ServerReplicationParameters)
pub mod server_replication_parameters {
/// A builder for [`ServerReplicationParameters`](crate::model::ServerReplicationParameters)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) seed_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) frequency: std::option::Option<i32>,
pub(crate) run_once: std::option::Option<bool>,
pub(crate) license_type: std::option::Option<crate::model::LicenseType>,
pub(crate) number_of_recent_amis_to_keep: std::option::Option<i32>,
pub(crate) encrypted: std::option::Option<bool>,
pub(crate) kms_key_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The seed time for creating a replication job for the server.</p>
pub fn seed_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.seed_time = Some(input);
self
}
/// <p>The seed time for creating a replication job for the server.</p>
pub fn set_seed_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.seed_time = input;
self
}
/// <p>The frequency of creating replication jobs for the server.</p>
pub fn frequency(mut self, input: i32) -> Self {
self.frequency = Some(input);
self
}
/// <p>The frequency of creating replication jobs for the server.</p>
pub fn set_frequency(mut self, input: std::option::Option<i32>) -> Self {
self.frequency = input;
self
}
/// <p>Indicates whether to run the replication job one time.</p>
pub fn run_once(mut self, input: bool) -> Self {
self.run_once = Some(input);
self
}
/// <p>Indicates whether to run the replication job one time.</p>
pub fn set_run_once(mut self, input: std::option::Option<bool>) -> Self {
self.run_once = input;
self
}
/// <p>The license type for creating a replication job for the server.</p>
pub fn license_type(mut self, input: crate::model::LicenseType) -> Self {
self.license_type = Some(input);
self
}
/// <p>The license type for creating a replication job for the server.</p>
pub fn set_license_type(
mut self,
input: std::option::Option<crate::model::LicenseType>,
) -> Self {
self.license_type = input;
self
}
/// <p>The number of recent AMIs to keep when creating a replication job for this server.</p>
pub fn number_of_recent_amis_to_keep(mut self, input: i32) -> Self {
self.number_of_recent_amis_to_keep = Some(input);
self
}
/// <p>The number of recent AMIs to keep when creating a replication job for this server.</p>
pub fn set_number_of_recent_amis_to_keep(
mut self,
input: std::option::Option<i32>,
) -> Self {
self.number_of_recent_amis_to_keep = input;
self
}
/// <p>Indicates whether the replication job produces encrypted AMIs.</p>
pub fn encrypted(mut self, input: bool) -> Self {
self.encrypted = Some(input);
self
}
/// <p>Indicates whether the replication job produces encrypted AMIs.</p>
pub fn set_encrypted(mut self, input: std::option::Option<bool>) -> Self {
self.encrypted = input;
self
}
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following:</p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p>If encrypted is enabled but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used.</p>
pub fn kms_key_id(mut self, input: impl Into<std::string::String>) -> Self {
self.kms_key_id = Some(input.into());
self
}
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following:</p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p>If encrypted is enabled but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used.</p>
pub fn set_kms_key_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.kms_key_id = input;
self
}
/// Consumes the builder and constructs a [`ServerReplicationParameters`](crate::model::ServerReplicationParameters)
pub fn build(self) -> crate::model::ServerReplicationParameters {
crate::model::ServerReplicationParameters {
seed_time: self.seed_time,
frequency: self.frequency,
run_once: self.run_once,
license_type: self.license_type,
number_of_recent_amis_to_keep: self.number_of_recent_amis_to_keep,
encrypted: self.encrypted,
kms_key_id: self.kms_key_id,
}
}
}
}
impl ServerReplicationParameters {
/// Creates a new builder-style object to manufacture [`ServerReplicationParameters`](crate::model::ServerReplicationParameters)
pub fn builder() -> crate::model::server_replication_parameters::Builder {
crate::model::server_replication_parameters::Builder::default()
}
}
/// <p>Launch configuration for a server group.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServerGroupLaunchConfiguration {
/// <p>The ID of the server group with which the launch configuration is
/// associated.</p>
pub server_group_id: std::option::Option<std::string::String>,
/// <p>The launch order of servers in the server group.</p>
pub launch_order: std::option::Option<i32>,
/// <p>The launch configuration for servers in the server group.</p>
pub server_launch_configurations:
std::option::Option<std::vec::Vec<crate::model::ServerLaunchConfiguration>>,
}
impl ServerGroupLaunchConfiguration {
/// <p>The ID of the server group with which the launch configuration is
/// associated.</p>
pub fn server_group_id(&self) -> std::option::Option<&str> {
self.server_group_id.as_deref()
}
/// <p>The launch order of servers in the server group.</p>
pub fn launch_order(&self) -> std::option::Option<i32> {
self.launch_order
}
/// <p>The launch configuration for servers in the server group.</p>
pub fn server_launch_configurations(
&self,
) -> std::option::Option<&[crate::model::ServerLaunchConfiguration]> {
self.server_launch_configurations.as_deref()
}
}
impl std::fmt::Debug for ServerGroupLaunchConfiguration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServerGroupLaunchConfiguration");
formatter.field("server_group_id", &self.server_group_id);
formatter.field("launch_order", &self.launch_order);
formatter.field(
"server_launch_configurations",
&self.server_launch_configurations,
);
formatter.finish()
}
}
/// See [`ServerGroupLaunchConfiguration`](crate::model::ServerGroupLaunchConfiguration)
pub mod server_group_launch_configuration {
/// A builder for [`ServerGroupLaunchConfiguration`](crate::model::ServerGroupLaunchConfiguration)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) server_group_id: std::option::Option<std::string::String>,
pub(crate) launch_order: std::option::Option<i32>,
pub(crate) server_launch_configurations:
std::option::Option<std::vec::Vec<crate::model::ServerLaunchConfiguration>>,
}
impl Builder {
/// <p>The ID of the server group with which the launch configuration is
/// associated.</p>
pub fn server_group_id(mut self, input: impl Into<std::string::String>) -> Self {
self.server_group_id = Some(input.into());
self
}
/// <p>The ID of the server group with which the launch configuration is
/// associated.</p>
pub fn set_server_group_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.server_group_id = input;
self
}
/// <p>The launch order of servers in the server group.</p>
pub fn launch_order(mut self, input: i32) -> Self {
self.launch_order = Some(input);
self
}
/// <p>The launch order of servers in the server group.</p>
pub fn set_launch_order(mut self, input: std::option::Option<i32>) -> Self {
self.launch_order = input;
self
}
/// Appends an item to `server_launch_configurations`.
///
/// To override the contents of this collection use [`set_server_launch_configurations`](Self::set_server_launch_configurations).
///
/// <p>The launch configuration for servers in the server group.</p>
pub fn server_launch_configurations(
mut self,
input: impl Into<crate::model::ServerLaunchConfiguration>,
) -> Self {
let mut v = self.server_launch_configurations.unwrap_or_default();
v.push(input.into());
self.server_launch_configurations = Some(v);
self
}
/// <p>The launch configuration for servers in the server group.</p>
pub fn set_server_launch_configurations(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ServerLaunchConfiguration>>,
) -> Self {
self.server_launch_configurations = input;
self
}
/// Consumes the builder and constructs a [`ServerGroupLaunchConfiguration`](crate::model::ServerGroupLaunchConfiguration)
pub fn build(self) -> crate::model::ServerGroupLaunchConfiguration {
crate::model::ServerGroupLaunchConfiguration {
server_group_id: self.server_group_id,
launch_order: self.launch_order,
server_launch_configurations: self.server_launch_configurations,
}
}
}
}
impl ServerGroupLaunchConfiguration {
/// Creates a new builder-style object to manufacture [`ServerGroupLaunchConfiguration`](crate::model::ServerGroupLaunchConfiguration)
pub fn builder() -> crate::model::server_group_launch_configuration::Builder {
crate::model::server_group_launch_configuration::Builder::default()
}
}
/// <p>Launch configuration for a server.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServerLaunchConfiguration {
/// <p>The ID of the server with which the launch configuration is associated.</p>
pub server: std::option::Option<crate::model::Server>,
/// <p>The logical ID of the server in the AWS CloudFormation template.</p>
pub logical_id: std::option::Option<std::string::String>,
/// <p>The ID of the VPC into which the server should be launched.</p>
pub vpc: std::option::Option<std::string::String>,
/// <p>The ID of the subnet the server should be launched into.</p>
pub subnet: std::option::Option<std::string::String>,
/// <p>The ID of the security group that applies to the launched server.</p>
pub security_group: std::option::Option<std::string::String>,
/// <p>The name of the Amazon EC2 SSH key to be used for connecting to the launched server.</p>
pub ec2_key_name: std::option::Option<std::string::String>,
/// <p>Location of the user-data script to be executed when launching the server.</p>
pub user_data: std::option::Option<crate::model::UserData>,
/// <p>The instance type to use when launching the server.</p>
pub instance_type: std::option::Option<std::string::String>,
/// <p>Indicates whether a publicly accessible IP address is created when launching the server.</p>
pub associate_public_ip_address: std::option::Option<bool>,
/// <p>The name of the IAM instance profile.</p>
pub iam_instance_profile_name: std::option::Option<std::string::String>,
/// <p>Location of an Amazon S3 object.</p>
pub configure_script: std::option::Option<crate::model::S3Location>,
/// <p>The type of configuration script.</p>
pub configure_script_type: std::option::Option<crate::model::ScriptType>,
}
impl ServerLaunchConfiguration {
/// <p>The ID of the server with which the launch configuration is associated.</p>
pub fn server(&self) -> std::option::Option<&crate::model::Server> {
self.server.as_ref()
}
/// <p>The logical ID of the server in the AWS CloudFormation template.</p>
pub fn logical_id(&self) -> std::option::Option<&str> {
self.logical_id.as_deref()
}
/// <p>The ID of the VPC into which the server should be launched.</p>
pub fn vpc(&self) -> std::option::Option<&str> {
self.vpc.as_deref()
}
/// <p>The ID of the subnet the server should be launched into.</p>
pub fn subnet(&self) -> std::option::Option<&str> {
self.subnet.as_deref()
}
/// <p>The ID of the security group that applies to the launched server.</p>
pub fn security_group(&self) -> std::option::Option<&str> {
self.security_group.as_deref()
}
/// <p>The name of the Amazon EC2 SSH key to be used for connecting to the launched server.</p>
pub fn ec2_key_name(&self) -> std::option::Option<&str> {
self.ec2_key_name.as_deref()
}
/// <p>Location of the user-data script to be executed when launching the server.</p>
pub fn user_data(&self) -> std::option::Option<&crate::model::UserData> {
self.user_data.as_ref()
}
/// <p>The instance type to use when launching the server.</p>
pub fn instance_type(&self) -> std::option::Option<&str> {
self.instance_type.as_deref()
}
/// <p>Indicates whether a publicly accessible IP address is created when launching the server.</p>
pub fn associate_public_ip_address(&self) -> std::option::Option<bool> {
self.associate_public_ip_address
}
/// <p>The name of the IAM instance profile.</p>
pub fn iam_instance_profile_name(&self) -> std::option::Option<&str> {
self.iam_instance_profile_name.as_deref()
}
/// <p>Location of an Amazon S3 object.</p>
pub fn configure_script(&self) -> std::option::Option<&crate::model::S3Location> {
self.configure_script.as_ref()
}
/// <p>The type of configuration script.</p>
pub fn configure_script_type(&self) -> std::option::Option<&crate::model::ScriptType> {
self.configure_script_type.as_ref()
}
}
impl std::fmt::Debug for ServerLaunchConfiguration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServerLaunchConfiguration");
formatter.field("server", &self.server);
formatter.field("logical_id", &self.logical_id);
formatter.field("vpc", &self.vpc);
formatter.field("subnet", &self.subnet);
formatter.field("security_group", &self.security_group);
formatter.field("ec2_key_name", &self.ec2_key_name);
formatter.field("user_data", &self.user_data);
formatter.field("instance_type", &self.instance_type);
formatter.field(
"associate_public_ip_address",
&self.associate_public_ip_address,
);
formatter.field("iam_instance_profile_name", &self.iam_instance_profile_name);
formatter.field("configure_script", &self.configure_script);
formatter.field("configure_script_type", &self.configure_script_type);
formatter.finish()
}
}
/// See [`ServerLaunchConfiguration`](crate::model::ServerLaunchConfiguration)
pub mod server_launch_configuration {
/// A builder for [`ServerLaunchConfiguration`](crate::model::ServerLaunchConfiguration)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) server: std::option::Option<crate::model::Server>,
pub(crate) logical_id: std::option::Option<std::string::String>,
pub(crate) vpc: std::option::Option<std::string::String>,
pub(crate) subnet: std::option::Option<std::string::String>,
pub(crate) security_group: std::option::Option<std::string::String>,
pub(crate) ec2_key_name: std::option::Option<std::string::String>,
pub(crate) user_data: std::option::Option<crate::model::UserData>,
pub(crate) instance_type: std::option::Option<std::string::String>,
pub(crate) associate_public_ip_address: std::option::Option<bool>,
pub(crate) iam_instance_profile_name: std::option::Option<std::string::String>,
pub(crate) configure_script: std::option::Option<crate::model::S3Location>,
pub(crate) configure_script_type: std::option::Option<crate::model::ScriptType>,
}
impl Builder {
/// <p>The ID of the server with which the launch configuration is associated.</p>
pub fn server(mut self, input: crate::model::Server) -> Self {
self.server = Some(input);
self
}
/// <p>The ID of the server with which the launch configuration is associated.</p>
pub fn set_server(mut self, input: std::option::Option<crate::model::Server>) -> Self {
self.server = input;
self
}
/// <p>The logical ID of the server in the AWS CloudFormation template.</p>
pub fn logical_id(mut self, input: impl Into<std::string::String>) -> Self {
self.logical_id = Some(input.into());
self
}
/// <p>The logical ID of the server in the AWS CloudFormation template.</p>
pub fn set_logical_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.logical_id = input;
self
}
/// <p>The ID of the VPC into which the server should be launched.</p>
pub fn vpc(mut self, input: impl Into<std::string::String>) -> Self {
self.vpc = Some(input.into());
self
}
/// <p>The ID of the VPC into which the server should be launched.</p>
pub fn set_vpc(mut self, input: std::option::Option<std::string::String>) -> Self {
self.vpc = input;
self
}
/// <p>The ID of the subnet the server should be launched into.</p>
pub fn subnet(mut self, input: impl Into<std::string::String>) -> Self {
self.subnet = Some(input.into());
self
}
/// <p>The ID of the subnet the server should be launched into.</p>
pub fn set_subnet(mut self, input: std::option::Option<std::string::String>) -> Self {
self.subnet = input;
self
}
/// <p>The ID of the security group that applies to the launched server.</p>
pub fn security_group(mut self, input: impl Into<std::string::String>) -> Self {
self.security_group = Some(input.into());
self
}
/// <p>The ID of the security group that applies to the launched server.</p>
pub fn set_security_group(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.security_group = input;
self
}
/// <p>The name of the Amazon EC2 SSH key to be used for connecting to the launched server.</p>
pub fn ec2_key_name(mut self, input: impl Into<std::string::String>) -> Self {
self.ec2_key_name = Some(input.into());
self
}
/// <p>The name of the Amazon EC2 SSH key to be used for connecting to the launched server.</p>
pub fn set_ec2_key_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.ec2_key_name = input;
self
}
/// <p>Location of the user-data script to be executed when launching the server.</p>
pub fn user_data(mut self, input: crate::model::UserData) -> Self {
self.user_data = Some(input);
self
}
/// <p>Location of the user-data script to be executed when launching the server.</p>
pub fn set_user_data(mut self, input: std::option::Option<crate::model::UserData>) -> Self {
self.user_data = input;
self
}
/// <p>The instance type to use when launching the server.</p>
pub fn instance_type(mut self, input: impl Into<std::string::String>) -> Self {
self.instance_type = Some(input.into());
self
}
/// <p>The instance type to use when launching the server.</p>
pub fn set_instance_type(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.instance_type = input;
self
}
/// <p>Indicates whether a publicly accessible IP address is created when launching the server.</p>
pub fn associate_public_ip_address(mut self, input: bool) -> Self {
self.associate_public_ip_address = Some(input);
self
}
/// <p>Indicates whether a publicly accessible IP address is created when launching the server.</p>
pub fn set_associate_public_ip_address(mut self, input: std::option::Option<bool>) -> Self {
self.associate_public_ip_address = input;
self
}
/// <p>The name of the IAM instance profile.</p>
pub fn iam_instance_profile_name(mut self, input: impl Into<std::string::String>) -> Self {
self.iam_instance_profile_name = Some(input.into());
self
}
/// <p>The name of the IAM instance profile.</p>
pub fn set_iam_instance_profile_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.iam_instance_profile_name = input;
self
}
/// <p>Location of an Amazon S3 object.</p>
pub fn configure_script(mut self, input: crate::model::S3Location) -> Self {
self.configure_script = Some(input);
self
}
/// <p>Location of an Amazon S3 object.</p>
pub fn set_configure_script(
mut self,
input: std::option::Option<crate::model::S3Location>,
) -> Self {
self.configure_script = input;
self
}
/// <p>The type of configuration script.</p>
pub fn configure_script_type(mut self, input: crate::model::ScriptType) -> Self {
self.configure_script_type = Some(input);
self
}
/// <p>The type of configuration script.</p>
pub fn set_configure_script_type(
mut self,
input: std::option::Option<crate::model::ScriptType>,
) -> Self {
self.configure_script_type = input;
self
}
/// Consumes the builder and constructs a [`ServerLaunchConfiguration`](crate::model::ServerLaunchConfiguration)
pub fn build(self) -> crate::model::ServerLaunchConfiguration {
crate::model::ServerLaunchConfiguration {
server: self.server,
logical_id: self.logical_id,
vpc: self.vpc,
subnet: self.subnet,
security_group: self.security_group,
ec2_key_name: self.ec2_key_name,
user_data: self.user_data,
instance_type: self.instance_type,
associate_public_ip_address: self.associate_public_ip_address,
iam_instance_profile_name: self.iam_instance_profile_name,
configure_script: self.configure_script,
configure_script_type: self.configure_script_type,
}
}
}
}
impl ServerLaunchConfiguration {
/// Creates a new builder-style object to manufacture [`ServerLaunchConfiguration`](crate::model::ServerLaunchConfiguration)
pub fn builder() -> crate::model::server_launch_configuration::Builder {
crate::model::server_launch_configuration::Builder::default()
}
}
/// <p>A script that runs on first launch of an Amazon EC2 instance. Used for configuring the
/// server during launch.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UserData {
/// <p>Amazon S3 location of the user-data script.</p>
pub s3_location: std::option::Option<crate::model::S3Location>,
}
impl UserData {
/// <p>Amazon S3 location of the user-data script.</p>
pub fn s3_location(&self) -> std::option::Option<&crate::model::S3Location> {
self.s3_location.as_ref()
}
}
impl std::fmt::Debug for UserData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UserData");
formatter.field("s3_location", &self.s3_location);
formatter.finish()
}
}
/// See [`UserData`](crate::model::UserData)
pub mod user_data {
/// A builder for [`UserData`](crate::model::UserData)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) s3_location: std::option::Option<crate::model::S3Location>,
}
impl Builder {
/// <p>Amazon S3 location of the user-data script.</p>
pub fn s3_location(mut self, input: crate::model::S3Location) -> Self {
self.s3_location = Some(input);
self
}
/// <p>Amazon S3 location of the user-data script.</p>
pub fn set_s3_location(
mut self,
input: std::option::Option<crate::model::S3Location>,
) -> Self {
self.s3_location = input;
self
}
/// Consumes the builder and constructs a [`UserData`](crate::model::UserData)
pub fn build(self) -> crate::model::UserData {
crate::model::UserData {
s3_location: self.s3_location,
}
}
}
}
impl UserData {
/// Creates a new builder-style object to manufacture [`UserData`](crate::model::UserData)
pub fn builder() -> crate::model::user_data::Builder {
crate::model::user_data::Builder::default()
}
}
/// <p>Contains the status of validating an application.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct NotificationContext {
/// <p>The ID of the validation.</p>
pub validation_id: std::option::Option<std::string::String>,
/// <p>The status of the validation.</p>
pub status: std::option::Option<crate::model::ValidationStatus>,
/// <p>The status message.</p>
pub status_message: std::option::Option<std::string::String>,
}
impl NotificationContext {
/// <p>The ID of the validation.</p>
pub fn validation_id(&self) -> std::option::Option<&str> {
self.validation_id.as_deref()
}
/// <p>The status of the validation.</p>
pub fn status(&self) -> std::option::Option<&crate::model::ValidationStatus> {
self.status.as_ref()
}
/// <p>The status message.</p>
pub fn status_message(&self) -> std::option::Option<&str> {
self.status_message.as_deref()
}
}
impl std::fmt::Debug for NotificationContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("NotificationContext");
formatter.field("validation_id", &self.validation_id);
formatter.field("status", &self.status);
formatter.field("status_message", &self.status_message);
formatter.finish()
}
}
/// See [`NotificationContext`](crate::model::NotificationContext)
pub mod notification_context {
/// A builder for [`NotificationContext`](crate::model::NotificationContext)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) validation_id: std::option::Option<std::string::String>,
pub(crate) status: std::option::Option<crate::model::ValidationStatus>,
pub(crate) status_message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The ID of the validation.</p>
pub fn validation_id(mut self, input: impl Into<std::string::String>) -> Self {
self.validation_id = Some(input.into());
self
}
/// <p>The ID of the validation.</p>
pub fn set_validation_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.validation_id = input;
self
}
/// <p>The status of the validation.</p>
pub fn status(mut self, input: crate::model::ValidationStatus) -> Self {
self.status = Some(input);
self
}
/// <p>The status of the validation.</p>
pub fn set_status(
mut self,
input: std::option::Option<crate::model::ValidationStatus>,
) -> Self {
self.status = input;
self
}
/// <p>The status message.</p>
pub fn status_message(mut self, input: impl Into<std::string::String>) -> Self {
self.status_message = Some(input.into());
self
}
/// <p>The status message.</p>
pub fn set_status_message(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.status_message = input;
self
}
/// Consumes the builder and constructs a [`NotificationContext`](crate::model::NotificationContext)
pub fn build(self) -> crate::model::NotificationContext {
crate::model::NotificationContext {
validation_id: self.validation_id,
status: self.status,
status_message: self.status_message,
}
}
}
}
impl NotificationContext {
/// Creates a new builder-style object to manufacture [`NotificationContext`](crate::model::NotificationContext)
pub fn builder() -> crate::model::notification_context::Builder {
crate::model::notification_context::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ValidationStatus {
#[allow(missing_docs)] // documentation missing in model
Failed,
#[allow(missing_docs)] // documentation missing in model
InProgress,
#[allow(missing_docs)] // documentation missing in model
Pending,
#[allow(missing_docs)] // documentation missing in model
ReadyForValidation,
#[allow(missing_docs)] // documentation missing in model
Succeeded,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ValidationStatus {
fn from(s: &str) -> Self {
match s {
"FAILED" => ValidationStatus::Failed,
"IN_PROGRESS" => ValidationStatus::InProgress,
"PENDING" => ValidationStatus::Pending,
"READY_FOR_VALIDATION" => ValidationStatus::ReadyForValidation,
"SUCCEEDED" => ValidationStatus::Succeeded,
other => ValidationStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ValidationStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ValidationStatus::from(s))
}
}
impl ValidationStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ValidationStatus::Failed => "FAILED",
ValidationStatus::InProgress => "IN_PROGRESS",
ValidationStatus::Pending => "PENDING",
ValidationStatus::ReadyForValidation => "READY_FOR_VALIDATION",
ValidationStatus::Succeeded => "SUCCEEDED",
ValidationStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"FAILED",
"IN_PROGRESS",
"PENDING",
"READY_FOR_VALIDATION",
"SUCCEEDED",
]
}
}
impl AsRef<str> for ValidationStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ServerCatalogStatus {
#[allow(missing_docs)] // documentation missing in model
Available,
#[allow(missing_docs)] // documentation missing in model
Deleted,
#[allow(missing_docs)] // documentation missing in model
Expired,
#[allow(missing_docs)] // documentation missing in model
Importing,
#[allow(missing_docs)] // documentation missing in model
NotImported,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ServerCatalogStatus {
fn from(s: &str) -> Self {
match s {
"AVAILABLE" => ServerCatalogStatus::Available,
"DELETED" => ServerCatalogStatus::Deleted,
"EXPIRED" => ServerCatalogStatus::Expired,
"IMPORTING" => ServerCatalogStatus::Importing,
"NOT_IMPORTED" => ServerCatalogStatus::NotImported,
other => ServerCatalogStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ServerCatalogStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ServerCatalogStatus::from(s))
}
}
impl ServerCatalogStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ServerCatalogStatus::Available => "AVAILABLE",
ServerCatalogStatus::Deleted => "DELETED",
ServerCatalogStatus::Expired => "EXPIRED",
ServerCatalogStatus::Importing => "IMPORTING",
ServerCatalogStatus::NotImported => "NOT_IMPORTED",
ServerCatalogStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"AVAILABLE",
"DELETED",
"EXPIRED",
"IMPORTING",
"NOT_IMPORTED",
]
}
}
impl AsRef<str> for ServerCatalogStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Represents a replication run.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ReplicationRun {
/// <p>The ID of the replication run.</p>
pub replication_run_id: std::option::Option<std::string::String>,
/// <p>The state of the replication run.</p>
pub state: std::option::Option<crate::model::ReplicationRunState>,
/// <p>The type of replication run.</p>
pub r#type: std::option::Option<crate::model::ReplicationRunType>,
/// <p>Details about the current stage of the replication run.</p>
pub stage_details: std::option::Option<crate::model::ReplicationRunStageDetails>,
/// <p>The description of the current status of the replication job.</p>
pub status_message: std::option::Option<std::string::String>,
/// <p>The ID of the Amazon Machine Image (AMI) from the replication
/// run.</p>
pub ami_id: std::option::Option<std::string::String>,
/// <p>The start time of the next replication run.</p>
pub scheduled_start_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The completion time of the last replication run.</p>
pub completed_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The description of the replication run.</p>
pub description: std::option::Option<std::string::String>,
/// <p>Indicates whether the replication run should produce an encrypted AMI.</p>
pub encrypted: std::option::Option<bool>,
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following:</p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p> If encrypted is <i>true</i> but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used. </p>
pub kms_key_id: std::option::Option<std::string::String>,
}
impl ReplicationRun {
/// <p>The ID of the replication run.</p>
pub fn replication_run_id(&self) -> std::option::Option<&str> {
self.replication_run_id.as_deref()
}
/// <p>The state of the replication run.</p>
pub fn state(&self) -> std::option::Option<&crate::model::ReplicationRunState> {
self.state.as_ref()
}
/// <p>The type of replication run.</p>
pub fn r#type(&self) -> std::option::Option<&crate::model::ReplicationRunType> {
self.r#type.as_ref()
}
/// <p>Details about the current stage of the replication run.</p>
pub fn stage_details(&self) -> std::option::Option<&crate::model::ReplicationRunStageDetails> {
self.stage_details.as_ref()
}
/// <p>The description of the current status of the replication job.</p>
pub fn status_message(&self) -> std::option::Option<&str> {
self.status_message.as_deref()
}
/// <p>The ID of the Amazon Machine Image (AMI) from the replication
/// run.</p>
pub fn ami_id(&self) -> std::option::Option<&str> {
self.ami_id.as_deref()
}
/// <p>The start time of the next replication run.</p>
pub fn scheduled_start_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.scheduled_start_time.as_ref()
}
/// <p>The completion time of the last replication run.</p>
pub fn completed_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.completed_time.as_ref()
}
/// <p>The description of the replication run.</p>
pub fn description(&self) -> std::option::Option<&str> {
self.description.as_deref()
}
/// <p>Indicates whether the replication run should produce an encrypted AMI.</p>
pub fn encrypted(&self) -> std::option::Option<bool> {
self.encrypted
}
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following:</p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p> If encrypted is <i>true</i> but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used. </p>
pub fn kms_key_id(&self) -> std::option::Option<&str> {
self.kms_key_id.as_deref()
}
}
impl std::fmt::Debug for ReplicationRun {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ReplicationRun");
formatter.field("replication_run_id", &self.replication_run_id);
formatter.field("state", &self.state);
formatter.field("r#type", &self.r#type);
formatter.field("stage_details", &self.stage_details);
formatter.field("status_message", &self.status_message);
formatter.field("ami_id", &self.ami_id);
formatter.field("scheduled_start_time", &self.scheduled_start_time);
formatter.field("completed_time", &self.completed_time);
formatter.field("description", &self.description);
formatter.field("encrypted", &self.encrypted);
formatter.field("kms_key_id", &self.kms_key_id);
formatter.finish()
}
}
/// See [`ReplicationRun`](crate::model::ReplicationRun)
pub mod replication_run {
/// A builder for [`ReplicationRun`](crate::model::ReplicationRun)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) replication_run_id: std::option::Option<std::string::String>,
pub(crate) state: std::option::Option<crate::model::ReplicationRunState>,
pub(crate) r#type: std::option::Option<crate::model::ReplicationRunType>,
pub(crate) stage_details: std::option::Option<crate::model::ReplicationRunStageDetails>,
pub(crate) status_message: std::option::Option<std::string::String>,
pub(crate) ami_id: std::option::Option<std::string::String>,
pub(crate) scheduled_start_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) completed_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) description: std::option::Option<std::string::String>,
pub(crate) encrypted: std::option::Option<bool>,
pub(crate) kms_key_id: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The ID of the replication run.</p>
pub fn replication_run_id(mut self, input: impl Into<std::string::String>) -> Self {
self.replication_run_id = Some(input.into());
self
}
/// <p>The ID of the replication run.</p>
pub fn set_replication_run_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.replication_run_id = input;
self
}
/// <p>The state of the replication run.</p>
pub fn state(mut self, input: crate::model::ReplicationRunState) -> Self {
self.state = Some(input);
self
}
/// <p>The state of the replication run.</p>
pub fn set_state(
mut self,
input: std::option::Option<crate::model::ReplicationRunState>,
) -> Self {
self.state = input;
self
}
/// <p>The type of replication run.</p>
pub fn r#type(mut self, input: crate::model::ReplicationRunType) -> Self {
self.r#type = Some(input);
self
}
/// <p>The type of replication run.</p>
pub fn set_type(
mut self,
input: std::option::Option<crate::model::ReplicationRunType>,
) -> Self {
self.r#type = input;
self
}
/// <p>Details about the current stage of the replication run.</p>
pub fn stage_details(mut self, input: crate::model::ReplicationRunStageDetails) -> Self {
self.stage_details = Some(input);
self
}
/// <p>Details about the current stage of the replication run.</p>
pub fn set_stage_details(
mut self,
input: std::option::Option<crate::model::ReplicationRunStageDetails>,
) -> Self {
self.stage_details = input;
self
}
/// <p>The description of the current status of the replication job.</p>
pub fn status_message(mut self, input: impl Into<std::string::String>) -> Self {
self.status_message = Some(input.into());
self
}
/// <p>The description of the current status of the replication job.</p>
pub fn set_status_message(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.status_message = input;
self
}
/// <p>The ID of the Amazon Machine Image (AMI) from the replication
/// run.</p>
pub fn ami_id(mut self, input: impl Into<std::string::String>) -> Self {
self.ami_id = Some(input.into());
self
}
/// <p>The ID of the Amazon Machine Image (AMI) from the replication
/// run.</p>
pub fn set_ami_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.ami_id = input;
self
}
/// <p>The start time of the next replication run.</p>
pub fn scheduled_start_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.scheduled_start_time = Some(input);
self
}
/// <p>The start time of the next replication run.</p>
pub fn set_scheduled_start_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.scheduled_start_time = input;
self
}
/// <p>The completion time of the last replication run.</p>
pub fn completed_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.completed_time = Some(input);
self
}
/// <p>The completion time of the last replication run.</p>
pub fn set_completed_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.completed_time = input;
self
}
/// <p>The description of the replication run.</p>
pub fn description(mut self, input: impl Into<std::string::String>) -> Self {
self.description = Some(input.into());
self
}
/// <p>The description of the replication run.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.description = input;
self
}
/// <p>Indicates whether the replication run should produce an encrypted AMI.</p>
pub fn encrypted(mut self, input: bool) -> Self {
self.encrypted = Some(input);
self
}
/// <p>Indicates whether the replication run should produce an encrypted AMI.</p>
pub fn set_encrypted(mut self, input: std::option::Option<bool>) -> Self {
self.encrypted = input;
self
}
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following:</p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p> If encrypted is <i>true</i> but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used. </p>
pub fn kms_key_id(mut self, input: impl Into<std::string::String>) -> Self {
self.kms_key_id = Some(input.into());
self
}
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following:</p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p> If encrypted is <i>true</i> but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used. </p>
pub fn set_kms_key_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.kms_key_id = input;
self
}
/// Consumes the builder and constructs a [`ReplicationRun`](crate::model::ReplicationRun)
pub fn build(self) -> crate::model::ReplicationRun {
crate::model::ReplicationRun {
replication_run_id: self.replication_run_id,
state: self.state,
r#type: self.r#type,
stage_details: self.stage_details,
status_message: self.status_message,
ami_id: self.ami_id,
scheduled_start_time: self.scheduled_start_time,
completed_time: self.completed_time,
description: self.description,
encrypted: self.encrypted,
kms_key_id: self.kms_key_id,
}
}
}
}
impl ReplicationRun {
/// Creates a new builder-style object to manufacture [`ReplicationRun`](crate::model::ReplicationRun)
pub fn builder() -> crate::model::replication_run::Builder {
crate::model::replication_run::Builder::default()
}
}
/// <p>Details of the current stage of a replication run.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ReplicationRunStageDetails {
/// <p>The current stage of a replication run.</p>
pub stage: std::option::Option<std::string::String>,
/// <p>The progress of the current stage of a replication run.</p>
pub stage_progress: std::option::Option<std::string::String>,
}
impl ReplicationRunStageDetails {
/// <p>The current stage of a replication run.</p>
pub fn stage(&self) -> std::option::Option<&str> {
self.stage.as_deref()
}
/// <p>The progress of the current stage of a replication run.</p>
pub fn stage_progress(&self) -> std::option::Option<&str> {
self.stage_progress.as_deref()
}
}
impl std::fmt::Debug for ReplicationRunStageDetails {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ReplicationRunStageDetails");
formatter.field("stage", &self.stage);
formatter.field("stage_progress", &self.stage_progress);
formatter.finish()
}
}
/// See [`ReplicationRunStageDetails`](crate::model::ReplicationRunStageDetails)
pub mod replication_run_stage_details {
/// A builder for [`ReplicationRunStageDetails`](crate::model::ReplicationRunStageDetails)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) stage: std::option::Option<std::string::String>,
pub(crate) stage_progress: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The current stage of a replication run.</p>
pub fn stage(mut self, input: impl Into<std::string::String>) -> Self {
self.stage = Some(input.into());
self
}
/// <p>The current stage of a replication run.</p>
pub fn set_stage(mut self, input: std::option::Option<std::string::String>) -> Self {
self.stage = input;
self
}
/// <p>The progress of the current stage of a replication run.</p>
pub fn stage_progress(mut self, input: impl Into<std::string::String>) -> Self {
self.stage_progress = Some(input.into());
self
}
/// <p>The progress of the current stage of a replication run.</p>
pub fn set_stage_progress(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.stage_progress = input;
self
}
/// Consumes the builder and constructs a [`ReplicationRunStageDetails`](crate::model::ReplicationRunStageDetails)
pub fn build(self) -> crate::model::ReplicationRunStageDetails {
crate::model::ReplicationRunStageDetails {
stage: self.stage,
stage_progress: self.stage_progress,
}
}
}
}
impl ReplicationRunStageDetails {
/// Creates a new builder-style object to manufacture [`ReplicationRunStageDetails`](crate::model::ReplicationRunStageDetails)
pub fn builder() -> crate::model::replication_run_stage_details::Builder {
crate::model::replication_run_stage_details::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ReplicationRunType {
#[allow(missing_docs)] // documentation missing in model
Automatic,
#[allow(missing_docs)] // documentation missing in model
OnDemand,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ReplicationRunType {
fn from(s: &str) -> Self {
match s {
"AUTOMATIC" => ReplicationRunType::Automatic,
"ON_DEMAND" => ReplicationRunType::OnDemand,
other => ReplicationRunType::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ReplicationRunType {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ReplicationRunType::from(s))
}
}
impl ReplicationRunType {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ReplicationRunType::Automatic => "AUTOMATIC",
ReplicationRunType::OnDemand => "ON_DEMAND",
ReplicationRunType::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["AUTOMATIC", "ON_DEMAND"]
}
}
impl AsRef<str> for ReplicationRunType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ReplicationRunState {
#[allow(missing_docs)] // documentation missing in model
Active,
#[allow(missing_docs)] // documentation missing in model
Completed,
#[allow(missing_docs)] // documentation missing in model
Deleted,
#[allow(missing_docs)] // documentation missing in model
Deleting,
#[allow(missing_docs)] // documentation missing in model
Failed,
#[allow(missing_docs)] // documentation missing in model
Missed,
#[allow(missing_docs)] // documentation missing in model
Pending,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ReplicationRunState {
fn from(s: &str) -> Self {
match s {
"ACTIVE" => ReplicationRunState::Active,
"COMPLETED" => ReplicationRunState::Completed,
"DELETED" => ReplicationRunState::Deleted,
"DELETING" => ReplicationRunState::Deleting,
"FAILED" => ReplicationRunState::Failed,
"MISSED" => ReplicationRunState::Missed,
"PENDING" => ReplicationRunState::Pending,
other => ReplicationRunState::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ReplicationRunState {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ReplicationRunState::from(s))
}
}
impl ReplicationRunState {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ReplicationRunState::Active => "ACTIVE",
ReplicationRunState::Completed => "COMPLETED",
ReplicationRunState::Deleted => "DELETED",
ReplicationRunState::Deleting => "DELETING",
ReplicationRunState::Failed => "FAILED",
ReplicationRunState::Missed => "MISSED",
ReplicationRunState::Pending => "PENDING",
ReplicationRunState::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"ACTIVE",
"COMPLETED",
"DELETED",
"DELETING",
"FAILED",
"MISSED",
"PENDING",
]
}
}
impl AsRef<str> for ReplicationRunState {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Represents a replication job.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ReplicationJob {
/// <p>The ID of the replication job.</p>
pub replication_job_id: std::option::Option<std::string::String>,
/// <p>The ID of the server.</p>
pub server_id: std::option::Option<std::string::String>,
/// <p>The type of server.</p>
pub server_type: std::option::Option<crate::model::ServerType>,
/// <p>Information about the VM server.</p>
pub vm_server: std::option::Option<crate::model::VmServer>,
/// <p>The seed replication time.</p>
pub seed_replication_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The time between consecutive replication runs, in hours.</p>
pub frequency: std::option::Option<i32>,
/// <p>Indicates whether to run the replication job one time.</p>
pub run_once: std::option::Option<bool>,
/// <p>The start time of the next replication run.</p>
pub next_replication_run_start_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The license type to be used for the AMI created by a successful replication
/// run.</p>
pub license_type: std::option::Option<crate::model::LicenseType>,
/// <p>The name of the IAM role to be used by AWS SMS.</p>
pub role_name: std::option::Option<std::string::String>,
/// <p>The ID of the latest Amazon Machine Image (AMI).</p>
pub latest_ami_id: std::option::Option<std::string::String>,
/// <p>The state of the replication job.</p>
pub state: std::option::Option<crate::model::ReplicationJobState>,
/// <p>The description of the current status of the replication job.</p>
pub status_message: std::option::Option<std::string::String>,
/// <p>The description of the replication job.</p>
pub description: std::option::Option<std::string::String>,
/// <p>The number of recent AMIs to keep in the customer's account for a replication job. By
/// default, the value is set to zero, meaning that all AMIs are kept.</p>
pub number_of_recent_amis_to_keep: std::option::Option<i32>,
/// <p>Indicates whether the replication job should produce encrypted AMIs.</p>
pub encrypted: std::option::Option<bool>,
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following: </p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p>If encrypted is enabled but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used.</p>
pub kms_key_id: std::option::Option<std::string::String>,
/// <p>Information about the replication runs.</p>
pub replication_run_list: std::option::Option<std::vec::Vec<crate::model::ReplicationRun>>,
}
impl ReplicationJob {
/// <p>The ID of the replication job.</p>
pub fn replication_job_id(&self) -> std::option::Option<&str> {
self.replication_job_id.as_deref()
}
/// <p>The ID of the server.</p>
pub fn server_id(&self) -> std::option::Option<&str> {
self.server_id.as_deref()
}
/// <p>The type of server.</p>
pub fn server_type(&self) -> std::option::Option<&crate::model::ServerType> {
self.server_type.as_ref()
}
/// <p>Information about the VM server.</p>
pub fn vm_server(&self) -> std::option::Option<&crate::model::VmServer> {
self.vm_server.as_ref()
}
/// <p>The seed replication time.</p>
pub fn seed_replication_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.seed_replication_time.as_ref()
}
/// <p>The time between consecutive replication runs, in hours.</p>
pub fn frequency(&self) -> std::option::Option<i32> {
self.frequency
}
/// <p>Indicates whether to run the replication job one time.</p>
pub fn run_once(&self) -> std::option::Option<bool> {
self.run_once
}
/// <p>The start time of the next replication run.</p>
pub fn next_replication_run_start_time(
&self,
) -> std::option::Option<&aws_smithy_types::DateTime> {
self.next_replication_run_start_time.as_ref()
}
/// <p>The license type to be used for the AMI created by a successful replication
/// run.</p>
pub fn license_type(&self) -> std::option::Option<&crate::model::LicenseType> {
self.license_type.as_ref()
}
/// <p>The name of the IAM role to be used by AWS SMS.</p>
pub fn role_name(&self) -> std::option::Option<&str> {
self.role_name.as_deref()
}
/// <p>The ID of the latest Amazon Machine Image (AMI).</p>
pub fn latest_ami_id(&self) -> std::option::Option<&str> {
self.latest_ami_id.as_deref()
}
/// <p>The state of the replication job.</p>
pub fn state(&self) -> std::option::Option<&crate::model::ReplicationJobState> {
self.state.as_ref()
}
/// <p>The description of the current status of the replication job.</p>
pub fn status_message(&self) -> std::option::Option<&str> {
self.status_message.as_deref()
}
/// <p>The description of the replication job.</p>
pub fn description(&self) -> std::option::Option<&str> {
self.description.as_deref()
}
/// <p>The number of recent AMIs to keep in the customer's account for a replication job. By
/// default, the value is set to zero, meaning that all AMIs are kept.</p>
pub fn number_of_recent_amis_to_keep(&self) -> std::option::Option<i32> {
self.number_of_recent_amis_to_keep
}
/// <p>Indicates whether the replication job should produce encrypted AMIs.</p>
pub fn encrypted(&self) -> std::option::Option<bool> {
self.encrypted
}
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following: </p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p>If encrypted is enabled but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used.</p>
pub fn kms_key_id(&self) -> std::option::Option<&str> {
self.kms_key_id.as_deref()
}
/// <p>Information about the replication runs.</p>
pub fn replication_run_list(&self) -> std::option::Option<&[crate::model::ReplicationRun]> {
self.replication_run_list.as_deref()
}
}
impl std::fmt::Debug for ReplicationJob {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ReplicationJob");
formatter.field("replication_job_id", &self.replication_job_id);
formatter.field("server_id", &self.server_id);
formatter.field("server_type", &self.server_type);
formatter.field("vm_server", &self.vm_server);
formatter.field("seed_replication_time", &self.seed_replication_time);
formatter.field("frequency", &self.frequency);
formatter.field("run_once", &self.run_once);
formatter.field(
"next_replication_run_start_time",
&self.next_replication_run_start_time,
);
formatter.field("license_type", &self.license_type);
formatter.field("role_name", &self.role_name);
formatter.field("latest_ami_id", &self.latest_ami_id);
formatter.field("state", &self.state);
formatter.field("status_message", &self.status_message);
formatter.field("description", &self.description);
formatter.field(
"number_of_recent_amis_to_keep",
&self.number_of_recent_amis_to_keep,
);
formatter.field("encrypted", &self.encrypted);
formatter.field("kms_key_id", &self.kms_key_id);
formatter.field("replication_run_list", &self.replication_run_list);
formatter.finish()
}
}
/// See [`ReplicationJob`](crate::model::ReplicationJob)
pub mod replication_job {
/// A builder for [`ReplicationJob`](crate::model::ReplicationJob)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) replication_job_id: std::option::Option<std::string::String>,
pub(crate) server_id: std::option::Option<std::string::String>,
pub(crate) server_type: std::option::Option<crate::model::ServerType>,
pub(crate) vm_server: std::option::Option<crate::model::VmServer>,
pub(crate) seed_replication_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) frequency: std::option::Option<i32>,
pub(crate) run_once: std::option::Option<bool>,
pub(crate) next_replication_run_start_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) license_type: std::option::Option<crate::model::LicenseType>,
pub(crate) role_name: std::option::Option<std::string::String>,
pub(crate) latest_ami_id: std::option::Option<std::string::String>,
pub(crate) state: std::option::Option<crate::model::ReplicationJobState>,
pub(crate) status_message: std::option::Option<std::string::String>,
pub(crate) description: std::option::Option<std::string::String>,
pub(crate) number_of_recent_amis_to_keep: std::option::Option<i32>,
pub(crate) encrypted: std::option::Option<bool>,
pub(crate) kms_key_id: std::option::Option<std::string::String>,
pub(crate) replication_run_list:
std::option::Option<std::vec::Vec<crate::model::ReplicationRun>>,
}
impl Builder {
/// <p>The ID of the replication job.</p>
pub fn replication_job_id(mut self, input: impl Into<std::string::String>) -> Self {
self.replication_job_id = Some(input.into());
self
}
/// <p>The ID of the replication job.</p>
pub fn set_replication_job_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.replication_job_id = input;
self
}
/// <p>The ID of the server.</p>
pub fn server_id(mut self, input: impl Into<std::string::String>) -> Self {
self.server_id = Some(input.into());
self
}
/// <p>The ID of the server.</p>
pub fn set_server_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.server_id = input;
self
}
/// <p>The type of server.</p>
pub fn server_type(mut self, input: crate::model::ServerType) -> Self {
self.server_type = Some(input);
self
}
/// <p>The type of server.</p>
pub fn set_server_type(
mut self,
input: std::option::Option<crate::model::ServerType>,
) -> Self {
self.server_type = input;
self
}
/// <p>Information about the VM server.</p>
pub fn vm_server(mut self, input: crate::model::VmServer) -> Self {
self.vm_server = Some(input);
self
}
/// <p>Information about the VM server.</p>
pub fn set_vm_server(mut self, input: std::option::Option<crate::model::VmServer>) -> Self {
self.vm_server = input;
self
}
/// <p>The seed replication time.</p>
pub fn seed_replication_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.seed_replication_time = Some(input);
self
}
/// <p>The seed replication time.</p>
pub fn set_seed_replication_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.seed_replication_time = input;
self
}
/// <p>The time between consecutive replication runs, in hours.</p>
pub fn frequency(mut self, input: i32) -> Self {
self.frequency = Some(input);
self
}
/// <p>The time between consecutive replication runs, in hours.</p>
pub fn set_frequency(mut self, input: std::option::Option<i32>) -> Self {
self.frequency = input;
self
}
/// <p>Indicates whether to run the replication job one time.</p>
pub fn run_once(mut self, input: bool) -> Self {
self.run_once = Some(input);
self
}
/// <p>Indicates whether to run the replication job one time.</p>
pub fn set_run_once(mut self, input: std::option::Option<bool>) -> Self {
self.run_once = input;
self
}
/// <p>The start time of the next replication run.</p>
pub fn next_replication_run_start_time(
mut self,
input: aws_smithy_types::DateTime,
) -> Self {
self.next_replication_run_start_time = Some(input);
self
}
/// <p>The start time of the next replication run.</p>
pub fn set_next_replication_run_start_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.next_replication_run_start_time = input;
self
}
/// <p>The license type to be used for the AMI created by a successful replication
/// run.</p>
pub fn license_type(mut self, input: crate::model::LicenseType) -> Self {
self.license_type = Some(input);
self
}
/// <p>The license type to be used for the AMI created by a successful replication
/// run.</p>
pub fn set_license_type(
mut self,
input: std::option::Option<crate::model::LicenseType>,
) -> Self {
self.license_type = input;
self
}
/// <p>The name of the IAM role to be used by AWS SMS.</p>
pub fn role_name(mut self, input: impl Into<std::string::String>) -> Self {
self.role_name = Some(input.into());
self
}
/// <p>The name of the IAM role to be used by AWS SMS.</p>
pub fn set_role_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.role_name = input;
self
}
/// <p>The ID of the latest Amazon Machine Image (AMI).</p>
pub fn latest_ami_id(mut self, input: impl Into<std::string::String>) -> Self {
self.latest_ami_id = Some(input.into());
self
}
/// <p>The ID of the latest Amazon Machine Image (AMI).</p>
pub fn set_latest_ami_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.latest_ami_id = input;
self
}
/// <p>The state of the replication job.</p>
pub fn state(mut self, input: crate::model::ReplicationJobState) -> Self {
self.state = Some(input);
self
}
/// <p>The state of the replication job.</p>
pub fn set_state(
mut self,
input: std::option::Option<crate::model::ReplicationJobState>,
) -> Self {
self.state = input;
self
}
/// <p>The description of the current status of the replication job.</p>
pub fn status_message(mut self, input: impl Into<std::string::String>) -> Self {
self.status_message = Some(input.into());
self
}
/// <p>The description of the current status of the replication job.</p>
pub fn set_status_message(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.status_message = input;
self
}
/// <p>The description of the replication job.</p>
pub fn description(mut self, input: impl Into<std::string::String>) -> Self {
self.description = Some(input.into());
self
}
/// <p>The description of the replication job.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.description = input;
self
}
/// <p>The number of recent AMIs to keep in the customer's account for a replication job. By
/// default, the value is set to zero, meaning that all AMIs are kept.</p>
pub fn number_of_recent_amis_to_keep(mut self, input: i32) -> Self {
self.number_of_recent_amis_to_keep = Some(input);
self
}
/// <p>The number of recent AMIs to keep in the customer's account for a replication job. By
/// default, the value is set to zero, meaning that all AMIs are kept.</p>
pub fn set_number_of_recent_amis_to_keep(
mut self,
input: std::option::Option<i32>,
) -> Self {
self.number_of_recent_amis_to_keep = input;
self
}
/// <p>Indicates whether the replication job should produce encrypted AMIs.</p>
pub fn encrypted(mut self, input: bool) -> Self {
self.encrypted = Some(input);
self
}
/// <p>Indicates whether the replication job should produce encrypted AMIs.</p>
pub fn set_encrypted(mut self, input: std::option::Option<bool>) -> Self {
self.encrypted = input;
self
}
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following: </p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p>If encrypted is enabled but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used.</p>
pub fn kms_key_id(mut self, input: impl Into<std::string::String>) -> Self {
self.kms_key_id = Some(input.into());
self
}
/// <p>The ID of the KMS key for replication jobs that produce encrypted AMIs.
/// This value can be any of the following: </p>
/// <ul>
/// <li>
/// <p>KMS key ID</p>
/// </li>
/// <li>
/// <p>KMS key alias</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key ID</p>
/// </li>
/// <li>
/// <p>ARN referring to the KMS key alias</p>
/// </li>
/// </ul>
/// <p>If encrypted is enabled but a KMS key ID is not specified, the
/// customer's default KMS key for Amazon EBS is used.</p>
pub fn set_kms_key_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.kms_key_id = input;
self
}
/// Appends an item to `replication_run_list`.
///
/// To override the contents of this collection use [`set_replication_run_list`](Self::set_replication_run_list).
///
/// <p>Information about the replication runs.</p>
pub fn replication_run_list(
mut self,
input: impl Into<crate::model::ReplicationRun>,
) -> Self {
let mut v = self.replication_run_list.unwrap_or_default();
v.push(input.into());
self.replication_run_list = Some(v);
self
}
/// <p>Information about the replication runs.</p>
pub fn set_replication_run_list(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ReplicationRun>>,
) -> Self {
self.replication_run_list = input;
self
}
/// Consumes the builder and constructs a [`ReplicationJob`](crate::model::ReplicationJob)
pub fn build(self) -> crate::model::ReplicationJob {
crate::model::ReplicationJob {
replication_job_id: self.replication_job_id,
server_id: self.server_id,
server_type: self.server_type,
vm_server: self.vm_server,
seed_replication_time: self.seed_replication_time,
frequency: self.frequency,
run_once: self.run_once,
next_replication_run_start_time: self.next_replication_run_start_time,
license_type: self.license_type,
role_name: self.role_name,
latest_ami_id: self.latest_ami_id,
state: self.state,
status_message: self.status_message,
description: self.description,
number_of_recent_amis_to_keep: self.number_of_recent_amis_to_keep,
encrypted: self.encrypted,
kms_key_id: self.kms_key_id,
replication_run_list: self.replication_run_list,
}
}
}
}
impl ReplicationJob {
/// Creates a new builder-style object to manufacture [`ReplicationJob`](crate::model::ReplicationJob)
pub fn builder() -> crate::model::replication_job::Builder {
crate::model::replication_job::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ReplicationJobState {
#[allow(missing_docs)] // documentation missing in model
Active,
#[allow(missing_docs)] // documentation missing in model
Completed,
#[allow(missing_docs)] // documentation missing in model
Deleted,
#[allow(missing_docs)] // documentation missing in model
Deleting,
#[allow(missing_docs)] // documentation missing in model
Failed,
#[allow(missing_docs)] // documentation missing in model
Failing,
#[allow(missing_docs)] // documentation missing in model
PausedOnFailure,
#[allow(missing_docs)] // documentation missing in model
Pending,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ReplicationJobState {
fn from(s: &str) -> Self {
match s {
"ACTIVE" => ReplicationJobState::Active,
"COMPLETED" => ReplicationJobState::Completed,
"DELETED" => ReplicationJobState::Deleted,
"DELETING" => ReplicationJobState::Deleting,
"FAILED" => ReplicationJobState::Failed,
"FAILING" => ReplicationJobState::Failing,
"PAUSED_ON_FAILURE" => ReplicationJobState::PausedOnFailure,
"PENDING" => ReplicationJobState::Pending,
other => ReplicationJobState::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ReplicationJobState {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ReplicationJobState::from(s))
}
}
impl ReplicationJobState {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ReplicationJobState::Active => "ACTIVE",
ReplicationJobState::Completed => "COMPLETED",
ReplicationJobState::Deleted => "DELETED",
ReplicationJobState::Deleting => "DELETING",
ReplicationJobState::Failed => "FAILED",
ReplicationJobState::Failing => "FAILING",
ReplicationJobState::PausedOnFailure => "PAUSED_ON_FAILURE",
ReplicationJobState::Pending => "PENDING",
ReplicationJobState::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"ACTIVE",
"COMPLETED",
"DELETED",
"DELETING",
"FAILED",
"FAILING",
"PAUSED_ON_FAILURE",
"PENDING",
]
}
}
impl AsRef<str> for ReplicationJobState {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Represents a connector.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct Connector {
/// <p>The ID of the connector.</p>
pub connector_id: std::option::Option<std::string::String>,
/// <p>The connector version.</p>
pub version: std::option::Option<std::string::String>,
/// <p>The status of the connector.</p>
pub status: std::option::Option<crate::model::ConnectorStatus>,
/// <p>The capabilities of the connector.</p>
pub capability_list: std::option::Option<std::vec::Vec<crate::model::ConnectorCapability>>,
/// <p>The name of the VM manager.</p>
pub vm_manager_name: std::option::Option<std::string::String>,
/// <p>The VM management product.</p>
pub vm_manager_type: std::option::Option<crate::model::VmManagerType>,
/// <p>The ID of the VM manager.</p>
pub vm_manager_id: std::option::Option<std::string::String>,
/// <p>The IP address of the connector.</p>
pub ip_address: std::option::Option<std::string::String>,
/// <p>The MAC address of the connector.</p>
pub mac_address: std::option::Option<std::string::String>,
/// <p>The time the connector was associated.</p>
pub associated_on: std::option::Option<aws_smithy_types::DateTime>,
}
impl Connector {
/// <p>The ID of the connector.</p>
pub fn connector_id(&self) -> std::option::Option<&str> {
self.connector_id.as_deref()
}
/// <p>The connector version.</p>
pub fn version(&self) -> std::option::Option<&str> {
self.version.as_deref()
}
/// <p>The status of the connector.</p>
pub fn status(&self) -> std::option::Option<&crate::model::ConnectorStatus> {
self.status.as_ref()
}
/// <p>The capabilities of the connector.</p>
pub fn capability_list(&self) -> std::option::Option<&[crate::model::ConnectorCapability]> {
self.capability_list.as_deref()
}
/// <p>The name of the VM manager.</p>
pub fn vm_manager_name(&self) -> std::option::Option<&str> {
self.vm_manager_name.as_deref()
}
/// <p>The VM management product.</p>
pub fn vm_manager_type(&self) -> std::option::Option<&crate::model::VmManagerType> {
self.vm_manager_type.as_ref()
}
/// <p>The ID of the VM manager.</p>
pub fn vm_manager_id(&self) -> std::option::Option<&str> {
self.vm_manager_id.as_deref()
}
/// <p>The IP address of the connector.</p>
pub fn ip_address(&self) -> std::option::Option<&str> {
self.ip_address.as_deref()
}
/// <p>The MAC address of the connector.</p>
pub fn mac_address(&self) -> std::option::Option<&str> {
self.mac_address.as_deref()
}
/// <p>The time the connector was associated.</p>
pub fn associated_on(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.associated_on.as_ref()
}
}
impl std::fmt::Debug for Connector {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("Connector");
formatter.field("connector_id", &self.connector_id);
formatter.field("version", &self.version);
formatter.field("status", &self.status);
formatter.field("capability_list", &self.capability_list);
formatter.field("vm_manager_name", &self.vm_manager_name);
formatter.field("vm_manager_type", &self.vm_manager_type);
formatter.field("vm_manager_id", &self.vm_manager_id);
formatter.field("ip_address", &self.ip_address);
formatter.field("mac_address", &self.mac_address);
formatter.field("associated_on", &self.associated_on);
formatter.finish()
}
}
/// See [`Connector`](crate::model::Connector)
pub mod connector {
/// A builder for [`Connector`](crate::model::Connector)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) connector_id: std::option::Option<std::string::String>,
pub(crate) version: std::option::Option<std::string::String>,
pub(crate) status: std::option::Option<crate::model::ConnectorStatus>,
pub(crate) capability_list:
std::option::Option<std::vec::Vec<crate::model::ConnectorCapability>>,
pub(crate) vm_manager_name: std::option::Option<std::string::String>,
pub(crate) vm_manager_type: std::option::Option<crate::model::VmManagerType>,
pub(crate) vm_manager_id: std::option::Option<std::string::String>,
pub(crate) ip_address: std::option::Option<std::string::String>,
pub(crate) mac_address: std::option::Option<std::string::String>,
pub(crate) associated_on: std::option::Option<aws_smithy_types::DateTime>,
}
impl Builder {
/// <p>The ID of the connector.</p>
pub fn connector_id(mut self, input: impl Into<std::string::String>) -> Self {
self.connector_id = Some(input.into());
self
}
/// <p>The ID of the connector.</p>
pub fn set_connector_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.connector_id = input;
self
}
/// <p>The connector version.</p>
pub fn version(mut self, input: impl Into<std::string::String>) -> Self {
self.version = Some(input.into());
self
}
/// <p>The connector version.</p>
pub fn set_version(mut self, input: std::option::Option<std::string::String>) -> Self {
self.version = input;
self
}
/// <p>The status of the connector.</p>
pub fn status(mut self, input: crate::model::ConnectorStatus) -> Self {
self.status = Some(input);
self
}
/// <p>The status of the connector.</p>
pub fn set_status(
mut self,
input: std::option::Option<crate::model::ConnectorStatus>,
) -> Self {
self.status = input;
self
}
/// Appends an item to `capability_list`.
///
/// To override the contents of this collection use [`set_capability_list`](Self::set_capability_list).
///
/// <p>The capabilities of the connector.</p>
pub fn capability_list(
mut self,
input: impl Into<crate::model::ConnectorCapability>,
) -> Self {
let mut v = self.capability_list.unwrap_or_default();
v.push(input.into());
self.capability_list = Some(v);
self
}
/// <p>The capabilities of the connector.</p>
pub fn set_capability_list(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ConnectorCapability>>,
) -> Self {
self.capability_list = input;
self
}
/// <p>The name of the VM manager.</p>
pub fn vm_manager_name(mut self, input: impl Into<std::string::String>) -> Self {
self.vm_manager_name = Some(input.into());
self
}
/// <p>The name of the VM manager.</p>
pub fn set_vm_manager_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.vm_manager_name = input;
self
}
/// <p>The VM management product.</p>
pub fn vm_manager_type(mut self, input: crate::model::VmManagerType) -> Self {
self.vm_manager_type = Some(input);
self
}
/// <p>The VM management product.</p>
pub fn set_vm_manager_type(
mut self,
input: std::option::Option<crate::model::VmManagerType>,
) -> Self {
self.vm_manager_type = input;
self
}
/// <p>The ID of the VM manager.</p>
pub fn vm_manager_id(mut self, input: impl Into<std::string::String>) -> Self {
self.vm_manager_id = Some(input.into());
self
}
/// <p>The ID of the VM manager.</p>
pub fn set_vm_manager_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.vm_manager_id = input;
self
}
/// <p>The IP address of the connector.</p>
pub fn ip_address(mut self, input: impl Into<std::string::String>) -> Self {
self.ip_address = Some(input.into());
self
}
/// <p>The IP address of the connector.</p>
pub fn set_ip_address(mut self, input: std::option::Option<std::string::String>) -> Self {
self.ip_address = input;
self
}
/// <p>The MAC address of the connector.</p>
pub fn mac_address(mut self, input: impl Into<std::string::String>) -> Self {
self.mac_address = Some(input.into());
self
}
/// <p>The MAC address of the connector.</p>
pub fn set_mac_address(mut self, input: std::option::Option<std::string::String>) -> Self {
self.mac_address = input;
self
}
/// <p>The time the connector was associated.</p>
pub fn associated_on(mut self, input: aws_smithy_types::DateTime) -> Self {
self.associated_on = Some(input);
self
}
/// <p>The time the connector was associated.</p>
pub fn set_associated_on(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.associated_on = input;
self
}
/// Consumes the builder and constructs a [`Connector`](crate::model::Connector)
pub fn build(self) -> crate::model::Connector {
crate::model::Connector {
connector_id: self.connector_id,
version: self.version,
status: self.status,
capability_list: self.capability_list,
vm_manager_name: self.vm_manager_name,
vm_manager_type: self.vm_manager_type,
vm_manager_id: self.vm_manager_id,
ip_address: self.ip_address,
mac_address: self.mac_address,
associated_on: self.associated_on,
}
}
}
}
impl Connector {
/// Creates a new builder-style object to manufacture [`Connector`](crate::model::Connector)
pub fn builder() -> crate::model::connector::Builder {
crate::model::connector::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ConnectorCapability {
#[allow(missing_docs)] // documentation missing in model
HyperVManager,
#[allow(missing_docs)] // documentation missing in model
Scvmm,
#[allow(missing_docs)] // documentation missing in model
SmsOptimized,
#[allow(missing_docs)] // documentation missing in model
SnapshotBatching,
#[allow(missing_docs)] // documentation missing in model
VSphere,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ConnectorCapability {
fn from(s: &str) -> Self {
match s {
"HYPERV-MANAGER" => ConnectorCapability::HyperVManager,
"SCVMM" => ConnectorCapability::Scvmm,
"SMS_OPTIMIZED" => ConnectorCapability::SmsOptimized,
"SNAPSHOT_BATCHING" => ConnectorCapability::SnapshotBatching,
"VSPHERE" => ConnectorCapability::VSphere,
other => ConnectorCapability::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ConnectorCapability {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ConnectorCapability::from(s))
}
}
impl ConnectorCapability {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ConnectorCapability::HyperVManager => "HYPERV-MANAGER",
ConnectorCapability::Scvmm => "SCVMM",
ConnectorCapability::SmsOptimized => "SMS_OPTIMIZED",
ConnectorCapability::SnapshotBatching => "SNAPSHOT_BATCHING",
ConnectorCapability::VSphere => "VSPHERE",
ConnectorCapability::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&[
"HYPERV-MANAGER",
"SCVMM",
"SMS_OPTIMIZED",
"SNAPSHOT_BATCHING",
"VSPHERE",
]
}
}
impl AsRef<str> for ConnectorCapability {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum ConnectorStatus {
#[allow(missing_docs)] // documentation missing in model
Healthy,
#[allow(missing_docs)] // documentation missing in model
Unhealthy,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for ConnectorStatus {
fn from(s: &str) -> Self {
match s {
"HEALTHY" => ConnectorStatus::Healthy,
"UNHEALTHY" => ConnectorStatus::Unhealthy,
other => ConnectorStatus::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for ConnectorStatus {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(ConnectorStatus::from(s))
}
}
impl ConnectorStatus {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
ConnectorStatus::Healthy => "HEALTHY",
ConnectorStatus::Unhealthy => "UNHEALTHY",
ConnectorStatus::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["HEALTHY", "UNHEALTHY"]
}
}
impl AsRef<str> for ConnectorStatus {
fn as_ref(&self) -> &str {
self.as_str()
}
}
/// <p>Contains validation output.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ValidationOutput {
/// <p>The ID of the validation.</p>
pub validation_id: std::option::Option<std::string::String>,
/// <p>The name of the validation.</p>
pub name: std::option::Option<std::string::String>,
/// <p>The status of the validation.</p>
pub status: std::option::Option<crate::model::ValidationStatus>,
/// <p>The status message.</p>
pub status_message: std::option::Option<std::string::String>,
/// <p>The latest time that the validation was performed.</p>
pub latest_validation_time: std::option::Option<aws_smithy_types::DateTime>,
/// <p>The output from validating an application.</p>
pub app_validation_output: std::option::Option<crate::model::AppValidationOutput>,
/// <p>The output from validation an instance.</p>
pub server_validation_output: std::option::Option<crate::model::ServerValidationOutput>,
}
impl ValidationOutput {
/// <p>The ID of the validation.</p>
pub fn validation_id(&self) -> std::option::Option<&str> {
self.validation_id.as_deref()
}
/// <p>The name of the validation.</p>
pub fn name(&self) -> std::option::Option<&str> {
self.name.as_deref()
}
/// <p>The status of the validation.</p>
pub fn status(&self) -> std::option::Option<&crate::model::ValidationStatus> {
self.status.as_ref()
}
/// <p>The status message.</p>
pub fn status_message(&self) -> std::option::Option<&str> {
self.status_message.as_deref()
}
/// <p>The latest time that the validation was performed.</p>
pub fn latest_validation_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.latest_validation_time.as_ref()
}
/// <p>The output from validating an application.</p>
pub fn app_validation_output(&self) -> std::option::Option<&crate::model::AppValidationOutput> {
self.app_validation_output.as_ref()
}
/// <p>The output from validation an instance.</p>
pub fn server_validation_output(
&self,
) -> std::option::Option<&crate::model::ServerValidationOutput> {
self.server_validation_output.as_ref()
}
}
impl std::fmt::Debug for ValidationOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ValidationOutput");
formatter.field("validation_id", &self.validation_id);
formatter.field("name", &self.name);
formatter.field("status", &self.status);
formatter.field("status_message", &self.status_message);
formatter.field("latest_validation_time", &self.latest_validation_time);
formatter.field("app_validation_output", &self.app_validation_output);
formatter.field("server_validation_output", &self.server_validation_output);
formatter.finish()
}
}
/// See [`ValidationOutput`](crate::model::ValidationOutput)
pub mod validation_output {
/// A builder for [`ValidationOutput`](crate::model::ValidationOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) validation_id: std::option::Option<std::string::String>,
pub(crate) name: std::option::Option<std::string::String>,
pub(crate) status: std::option::Option<crate::model::ValidationStatus>,
pub(crate) status_message: std::option::Option<std::string::String>,
pub(crate) latest_validation_time: std::option::Option<aws_smithy_types::DateTime>,
pub(crate) app_validation_output: std::option::Option<crate::model::AppValidationOutput>,
pub(crate) server_validation_output:
std::option::Option<crate::model::ServerValidationOutput>,
}
impl Builder {
/// <p>The ID of the validation.</p>
pub fn validation_id(mut self, input: impl Into<std::string::String>) -> Self {
self.validation_id = Some(input.into());
self
}
/// <p>The ID of the validation.</p>
pub fn set_validation_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.validation_id = input;
self
}
/// <p>The name of the validation.</p>
pub fn name(mut self, input: impl Into<std::string::String>) -> Self {
self.name = Some(input.into());
self
}
/// <p>The name of the validation.</p>
pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.name = input;
self
}
/// <p>The status of the validation.</p>
pub fn status(mut self, input: crate::model::ValidationStatus) -> Self {
self.status = Some(input);
self
}
/// <p>The status of the validation.</p>
pub fn set_status(
mut self,
input: std::option::Option<crate::model::ValidationStatus>,
) -> Self {
self.status = input;
self
}
/// <p>The status message.</p>
pub fn status_message(mut self, input: impl Into<std::string::String>) -> Self {
self.status_message = Some(input.into());
self
}
/// <p>The status message.</p>
pub fn set_status_message(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.status_message = input;
self
}
/// <p>The latest time that the validation was performed.</p>
pub fn latest_validation_time(mut self, input: aws_smithy_types::DateTime) -> Self {
self.latest_validation_time = Some(input);
self
}
/// <p>The latest time that the validation was performed.</p>
pub fn set_latest_validation_time(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.latest_validation_time = input;
self
}
/// <p>The output from validating an application.</p>
pub fn app_validation_output(mut self, input: crate::model::AppValidationOutput) -> Self {
self.app_validation_output = Some(input);
self
}
/// <p>The output from validating an application.</p>
pub fn set_app_validation_output(
mut self,
input: std::option::Option<crate::model::AppValidationOutput>,
) -> Self {
self.app_validation_output = input;
self
}
/// <p>The output from validation an instance.</p>
pub fn server_validation_output(
mut self,
input: crate::model::ServerValidationOutput,
) -> Self {
self.server_validation_output = Some(input);
self
}
/// <p>The output from validation an instance.</p>
pub fn set_server_validation_output(
mut self,
input: std::option::Option<crate::model::ServerValidationOutput>,
) -> Self {
self.server_validation_output = input;
self
}
/// Consumes the builder and constructs a [`ValidationOutput`](crate::model::ValidationOutput)
pub fn build(self) -> crate::model::ValidationOutput {
crate::model::ValidationOutput {
validation_id: self.validation_id,
name: self.name,
status: self.status,
status_message: self.status_message,
latest_validation_time: self.latest_validation_time,
app_validation_output: self.app_validation_output,
server_validation_output: self.server_validation_output,
}
}
}
}
impl ValidationOutput {
/// Creates a new builder-style object to manufacture [`ValidationOutput`](crate::model::ValidationOutput)
pub fn builder() -> crate::model::validation_output::Builder {
crate::model::validation_output::Builder::default()
}
}
/// <p>Contains output from validating an instance.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServerValidationOutput {
/// <p>Represents a server.</p>
pub server: std::option::Option<crate::model::Server>,
}
impl ServerValidationOutput {
/// <p>Represents a server.</p>
pub fn server(&self) -> std::option::Option<&crate::model::Server> {
self.server.as_ref()
}
}
impl std::fmt::Debug for ServerValidationOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServerValidationOutput");
formatter.field("server", &self.server);
formatter.finish()
}
}
/// See [`ServerValidationOutput`](crate::model::ServerValidationOutput)
pub mod server_validation_output {
/// A builder for [`ServerValidationOutput`](crate::model::ServerValidationOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) server: std::option::Option<crate::model::Server>,
}
impl Builder {
/// <p>Represents a server.</p>
pub fn server(mut self, input: crate::model::Server) -> Self {
self.server = Some(input);
self
}
/// <p>Represents a server.</p>
pub fn set_server(mut self, input: std::option::Option<crate::model::Server>) -> Self {
self.server = input;
self
}
/// Consumes the builder and constructs a [`ServerValidationOutput`](crate::model::ServerValidationOutput)
pub fn build(self) -> crate::model::ServerValidationOutput {
crate::model::ServerValidationOutput {
server: self.server,
}
}
}
}
impl ServerValidationOutput {
/// Creates a new builder-style object to manufacture [`ServerValidationOutput`](crate::model::ServerValidationOutput)
pub fn builder() -> crate::model::server_validation_output::Builder {
crate::model::server_validation_output::Builder::default()
}
}
/// <p>Output from validating an application.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct AppValidationOutput {
/// <p>Output from using SSM to validate the application.</p>
pub ssm_output: std::option::Option<crate::model::SsmOutput>,
}
impl AppValidationOutput {
/// <p>Output from using SSM to validate the application.</p>
pub fn ssm_output(&self) -> std::option::Option<&crate::model::SsmOutput> {
self.ssm_output.as_ref()
}
}
impl std::fmt::Debug for AppValidationOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("AppValidationOutput");
formatter.field("ssm_output", &self.ssm_output);
formatter.finish()
}
}
/// See [`AppValidationOutput`](crate::model::AppValidationOutput)
pub mod app_validation_output {
/// A builder for [`AppValidationOutput`](crate::model::AppValidationOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) ssm_output: std::option::Option<crate::model::SsmOutput>,
}
impl Builder {
/// <p>Output from using SSM to validate the application.</p>
pub fn ssm_output(mut self, input: crate::model::SsmOutput) -> Self {
self.ssm_output = Some(input);
self
}
/// <p>Output from using SSM to validate the application.</p>
pub fn set_ssm_output(
mut self,
input: std::option::Option<crate::model::SsmOutput>,
) -> Self {
self.ssm_output = input;
self
}
/// Consumes the builder and constructs a [`AppValidationOutput`](crate::model::AppValidationOutput)
pub fn build(self) -> crate::model::AppValidationOutput {
crate::model::AppValidationOutput {
ssm_output: self.ssm_output,
}
}
}
}
impl AppValidationOutput {
/// Creates a new builder-style object to manufacture [`AppValidationOutput`](crate::model::AppValidationOutput)
pub fn builder() -> crate::model::app_validation_output::Builder {
crate::model::app_validation_output::Builder::default()
}
}
/// <p>Contains the location of validation output.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct SsmOutput {
/// <p>Location of an Amazon S3 object.</p>
pub s3_location: std::option::Option<crate::model::S3Location>,
}
impl SsmOutput {
/// <p>Location of an Amazon S3 object.</p>
pub fn s3_location(&self) -> std::option::Option<&crate::model::S3Location> {
self.s3_location.as_ref()
}
}
impl std::fmt::Debug for SsmOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("SsmOutput");
formatter.field("s3_location", &self.s3_location);
formatter.finish()
}
}
/// See [`SsmOutput`](crate::model::SsmOutput)
pub mod ssm_output {
/// A builder for [`SsmOutput`](crate::model::SsmOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) s3_location: std::option::Option<crate::model::S3Location>,
}
impl Builder {
/// <p>Location of an Amazon S3 object.</p>
pub fn s3_location(mut self, input: crate::model::S3Location) -> Self {
self.s3_location = Some(input);
self
}
/// <p>Location of an Amazon S3 object.</p>
pub fn set_s3_location(
mut self,
input: std::option::Option<crate::model::S3Location>,
) -> Self {
self.s3_location = input;
self
}
/// Consumes the builder and constructs a [`SsmOutput`](crate::model::SsmOutput)
pub fn build(self) -> crate::model::SsmOutput {
crate::model::SsmOutput {
s3_location: self.s3_location,
}
}
}
}
impl SsmOutput {
/// Creates a new builder-style object to manufacture [`SsmOutput`](crate::model::SsmOutput)
pub fn builder() -> crate::model::ssm_output::Builder {
crate::model::ssm_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(
std::clone::Clone,
std::cmp::Eq,
std::cmp::Ord,
std::cmp::PartialEq,
std::cmp::PartialOrd,
std::fmt::Debug,
std::hash::Hash,
)]
pub enum OutputFormat {
#[allow(missing_docs)] // documentation missing in model
Json,
#[allow(missing_docs)] // documentation missing in model
Yaml,
/// Unknown contains new variants that have been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for OutputFormat {
fn from(s: &str) -> Self {
match s {
"JSON" => OutputFormat::Json,
"YAML" => OutputFormat::Yaml,
other => OutputFormat::Unknown(other.to_owned()),
}
}
}
impl std::str::FromStr for OutputFormat {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
Ok(OutputFormat::from(s))
}
}
impl OutputFormat {
/// Returns the `&str` value of the enum member.
pub fn as_str(&self) -> &str {
match self {
OutputFormat::Json => "JSON",
OutputFormat::Yaml => "YAML",
OutputFormat::Unknown(s) => s.as_ref(),
}
}
/// Returns all the `&str` values of the enum members.
pub fn values() -> &'static [&'static str] {
&["JSON", "YAML"]
}
}
impl AsRef<str> for OutputFormat {
fn as_ref(&self) -> &str {
self.as_str()
}
}
| 40.454225 | 148 | 0.609305 |
0afd6b1756870bb7e4bcc291d59659cc997793f9 | 17,746 | use std::borrow::Cow;
use std::cmp;
use std::cmp::Ordering::{self, Less, Greater, Equal};
use std::iter::repeat;
use std::mem;
use traits;
use traits::{Zero, One};
use biguint::BigUint;
use bigint::Sign;
use bigint::Sign::{Minus, NoSign, Plus};
#[allow(non_snake_case)]
pub mod big_digit {
/// A `BigDigit` is a `BigUint`'s composing element.
pub type BigDigit = u32;
/// A `DoubleBigDigit` is the internal type used to do the computations. Its
/// size is the double of the size of `BigDigit`.
pub type DoubleBigDigit = u64;
pub const ZERO_BIG_DIGIT: BigDigit = 0;
// `DoubleBigDigit` size dependent
pub const BITS: usize = 32;
pub const BASE: DoubleBigDigit = 1 << BITS;
const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS;
#[inline]
fn get_hi(n: DoubleBigDigit) -> BigDigit {
(n >> BITS) as BigDigit
}
#[inline]
fn get_lo(n: DoubleBigDigit) -> BigDigit {
(n & LO_MASK) as BigDigit
}
/// Split one `DoubleBigDigit` into two `BigDigit`s.
#[inline]
pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) {
(get_hi(n), get_lo(n))
}
/// Join two `BigDigit`s into one `DoubleBigDigit`
#[inline]
pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit {
(lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << BITS)
}
}
use big_digit::{BigDigit, DoubleBigDigit};
// Generic functions for add/subtract/multiply with carry/borrow:
// Add with carry:
#[inline]
fn adc(a: BigDigit, b: BigDigit, carry: &mut BigDigit) -> BigDigit {
let (hi, lo) = big_digit::from_doublebigdigit((a as DoubleBigDigit) + (b as DoubleBigDigit) +
(*carry as DoubleBigDigit));
*carry = hi;
lo
}
// Subtract with borrow:
#[inline]
fn sbb(a: BigDigit, b: BigDigit, borrow: &mut BigDigit) -> BigDigit {
let (hi, lo) = big_digit::from_doublebigdigit(big_digit::BASE + (a as DoubleBigDigit) -
(b as DoubleBigDigit) -
(*borrow as DoubleBigDigit));
// hi * (base) + lo == 1*(base) + ai - bi - borrow
// => ai - bi - borrow < 0 <=> hi == 0
*borrow = (hi == 0) as BigDigit;
lo
}
#[inline]
pub fn mac_with_carry(a: BigDigit, b: BigDigit, c: BigDigit, carry: &mut BigDigit) -> BigDigit {
let (hi, lo) = big_digit::from_doublebigdigit((a as DoubleBigDigit) +
(b as DoubleBigDigit) * (c as DoubleBigDigit) +
(*carry as DoubleBigDigit));
*carry = hi;
lo
}
/// Divide a two digit numerator by a one digit divisor, returns quotient and remainder:
///
/// Note: the caller must ensure that both the quotient and remainder will fit into a single digit.
/// This is _not_ true for an arbitrary numerator/denominator.
///
/// (This function also matches what the x86 divide instruction does).
#[inline]
fn div_wide(hi: BigDigit, lo: BigDigit, divisor: BigDigit) -> (BigDigit, BigDigit) {
debug_assert!(hi < divisor);
let lhs = big_digit::to_doublebigdigit(hi, lo);
let rhs = divisor as DoubleBigDigit;
((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit)
}
pub fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) {
let mut rem = 0;
for d in a.data.iter_mut().rev() {
let (q, r) = div_wide(rem, *d, b);
*d = q;
rem = r;
}
(a.normalize(), rem)
}
// Only for the Add impl:
#[must_use]
#[inline]
pub fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit {
debug_assert!(a.len() >= b.len());
let mut carry = 0;
let (a_lo, a_hi) = a.split_at_mut(b.len());
for (a, b) in a_lo.iter_mut().zip(b) {
*a = adc(*a, *b, &mut carry);
}
if carry != 0 {
for a in a_hi {
*a = adc(*a, 0, &mut carry);
if carry == 0 { break }
}
}
carry
}
/// /Two argument addition of raw slices:
/// a += b
///
/// The caller _must_ ensure that a is big enough to store the result - typically this means
/// resizing a to max(a.len(), b.len()) + 1, to fit a possible carry.
pub fn add2(a: &mut [BigDigit], b: &[BigDigit]) {
let carry = __add2(a, b);
debug_assert!(carry == 0);
}
pub fn sub2(a: &mut [BigDigit], b: &[BigDigit]) {
let mut borrow = 0;
let len = cmp::min(a.len(), b.len());
let (a_lo, a_hi) = a.split_at_mut(len);
let (b_lo, b_hi) = b.split_at(len);
for (a, b) in a_lo.iter_mut().zip(b_lo) {
*a = sbb(*a, *b, &mut borrow);
}
if borrow != 0 {
for a in a_hi {
*a = sbb(*a, 0, &mut borrow);
if borrow == 0 { break }
}
}
// note: we're _required_ to fail on underflow
assert!(borrow == 0 && b_hi.iter().all(|x| *x == 0),
"Cannot subtract b from a because b is larger than a.");
}
pub fn sub2rev(a: &[BigDigit], b: &mut [BigDigit]) {
debug_assert!(b.len() >= a.len());
let mut borrow = 0;
let len = cmp::min(a.len(), b.len());
let (a_lo, a_hi) = a.split_at(len);
let (b_lo, b_hi) = b.split_at_mut(len);
for (a, b) in a_lo.iter().zip(b_lo) {
*b = sbb(*a, *b, &mut borrow);
}
assert!(a_hi.is_empty());
// note: we're _required_ to fail on underflow
assert!(borrow == 0 && b_hi.iter().all(|x| *x == 0),
"Cannot subtract b from a because b is larger than a.");
}
pub fn sub_sign(a: &[BigDigit], b: &[BigDigit]) -> (Sign, BigUint) {
// Normalize:
let a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
let b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
match cmp_slice(a, b) {
Greater => {
let mut a = a.to_vec();
sub2(&mut a, b);
(Plus, BigUint::new(a))
}
Less => {
let mut b = b.to_vec();
sub2(&mut b, a);
(Minus, BigUint::new(b))
}
_ => (NoSign, Zero::zero()),
}
}
/// Three argument multiply accumulate:
/// acc += b * c
fn mac_digit(acc: &mut [BigDigit], b: &[BigDigit], c: BigDigit) {
if c == 0 {
return;
}
let mut b_iter = b.iter();
let mut carry = 0;
for ai in acc.iter_mut() {
if let Some(bi) = b_iter.next() {
*ai = mac_with_carry(*ai, *bi, c, &mut carry);
} else if carry != 0 {
*ai = mac_with_carry(*ai, 0, c, &mut carry);
} else {
break;
}
}
assert!(carry == 0);
}
/// Three argument multiply accumulate:
/// acc += b * c
fn mac3(acc: &mut [BigDigit], b: &[BigDigit], c: &[BigDigit]) {
let (x, y) = if b.len() < c.len() {
(b, c)
} else {
(c, b)
};
// Karatsuba multiplication is slower than long multiplication for small x and y:
//
if x.len() <= 4 {
for (i, xi) in x.iter().enumerate() {
mac_digit(&mut acc[i..], y, *xi);
}
} else {
/*
* Karatsuba multiplication:
*
* The idea is that we break x and y up into two smaller numbers that each have about half
* as many digits, like so (note that multiplying by b is just a shift):
*
* x = x0 + x1 * b
* y = y0 + y1 * b
*
* With some algebra, we can compute x * y with three smaller products, where the inputs to
* each of the smaller products have only about half as many digits as x and y:
*
* x * y = (x0 + x1 * b) * (y0 + y1 * b)
*
* x * y = x0 * y0
* + x0 * y1 * b
* + x1 * y0 * b
* + x1 * y1 * b^2
*
* Let p0 = x0 * y0 and p2 = x1 * y1:
*
* x * y = p0
* + (x0 * y1 + x1 * y0) * b
* + p2 * b^2
*
* The real trick is that middle term:
*
* x0 * y1 + x1 * y0
*
* = x0 * y1 + x1 * y0 - p0 + p0 - p2 + p2
*
* = x0 * y1 + x1 * y0 - x0 * y0 - x1 * y1 + p0 + p2
*
* Now we complete the square:
*
* = -(x0 * y0 - x0 * y1 - x1 * y0 + x1 * y1) + p0 + p2
*
* = -((x1 - x0) * (y1 - y0)) + p0 + p2
*
* Let p1 = (x1 - x0) * (y1 - y0), and substitute back into our original formula:
*
* x * y = p0
* + (p0 + p2 - p1) * b
* + p2 * b^2
*
* Where the three intermediate products are:
*
* p0 = x0 * y0
* p1 = (x1 - x0) * (y1 - y0)
* p2 = x1 * y1
*
* In doing the computation, we take great care to avoid unnecessary temporary variables
* (since creating a BigUint requires a heap allocation): thus, we rearrange the formula a
* bit so we can use the same temporary variable for all the intermediate products:
*
* x * y = p2 * b^2 + p2 * b
* + p0 * b + p0
* - p1 * b
*
* The other trick we use is instead of doing explicit shifts, we slice acc at the
* appropriate offset when doing the add.
*/
/*
* When x is smaller than y, it's significantly faster to pick b such that x is split in
* half, not y:
*/
let b = x.len() / 2;
let (x0, x1) = x.split_at(b);
let (y0, y1) = y.split_at(b);
/*
* We reuse the same BigUint for all the intermediate multiplies and have to size p
* appropriately here: x1.len() >= x0.len and y1.len() >= y0.len():
*/
let len = x1.len() + y1.len() + 1;
let mut p = BigUint { data: vec![0; len] };
// p2 = x1 * y1
mac3(&mut p.data[..], x1, y1);
// Not required, but the adds go faster if we drop any unneeded 0s from the end:
p = p.normalize();
add2(&mut acc[b..], &p.data[..]);
add2(&mut acc[b * 2..], &p.data[..]);
// Zero out p before the next multiply:
p.data.truncate(0);
p.data.extend(repeat(0).take(len));
// p0 = x0 * y0
mac3(&mut p.data[..], x0, y0);
p = p.normalize();
add2(&mut acc[..], &p.data[..]);
add2(&mut acc[b..], &p.data[..]);
// p1 = (x1 - x0) * (y1 - y0)
// We do this one last, since it may be negative and acc can't ever be negative:
let (j0_sign, j0) = sub_sign(x1, x0);
let (j1_sign, j1) = sub_sign(y1, y0);
match j0_sign * j1_sign {
Plus => {
p.data.truncate(0);
p.data.extend(repeat(0).take(len));
mac3(&mut p.data[..], &j0.data[..], &j1.data[..]);
p = p.normalize();
sub2(&mut acc[b..], &p.data[..]);
},
Minus => {
mac3(&mut acc[b..], &j0.data[..], &j1.data[..]);
},
NoSign => (),
}
}
}
pub fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint {
let len = x.len() + y.len() + 1;
let mut prod = BigUint { data: vec![0; len] };
mac3(&mut prod.data[..], x, y);
prod.normalize()
}
pub fn div_rem(u: &BigUint, d: &BigUint) -> (BigUint, BigUint) {
if d.is_zero() {
panic!()
}
if u.is_zero() {
return (Zero::zero(), Zero::zero());
}
if *d == One::one() {
return (u.clone(), Zero::zero());
}
// Required or the q_len calculation below can underflow:
match u.cmp(d) {
Less => return (Zero::zero(), u.clone()),
Equal => return (One::one(), Zero::zero()),
Greater => {} // Do nothing
}
// This algorithm is from Knuth, TAOCP vol 2 section 4.3, algorithm D:
//
// First, normalize the arguments so the highest bit in the highest digit of the divisor is
// set: the main loop uses the highest digit of the divisor for generating guesses, so we
// want it to be the largest number we can efficiently divide by.
//
let shift = d.data.last().unwrap().leading_zeros() as usize;
let mut a = u << shift;
let b = d << shift;
// The algorithm works by incrementally calculating "guesses", q0, for part of the
// remainder. Once we have any number q0 such that q0 * b <= a, we can set
//
// q += q0
// a -= q0 * b
//
// and then iterate until a < b. Then, (q, a) will be our desired quotient and remainder.
//
// q0, our guess, is calculated by dividing the last few digits of a by the last digit of b
// - this should give us a guess that is "close" to the actual quotient, but is possibly
// greater than the actual quotient. If q0 * b > a, we simply use iterated subtraction
// until we have a guess such that q0 & b <= a.
//
let bn = *b.data.last().unwrap();
let q_len = a.data.len() - b.data.len() + 1;
let mut q = BigUint { data: vec![0; q_len] };
// We reuse the same temporary to avoid hitting the allocator in our inner loop - this is
// sized to hold a0 (in the common case; if a particular digit of the quotient is zero a0
// can be bigger).
//
let mut tmp = BigUint { data: Vec::with_capacity(2) };
for j in (0..q_len).rev() {
/*
* When calculating our next guess q0, we don't need to consider the digits below j
* + b.data.len() - 1: we're guessing digit j of the quotient (i.e. q0 << j) from
* digit bn of the divisor (i.e. bn << (b.data.len() - 1) - so the product of those
* two numbers will be zero in all digits up to (j + b.data.len() - 1).
*/
let offset = j + b.data.len() - 1;
if offset >= a.data.len() {
continue;
}
/* just avoiding a heap allocation: */
let mut a0 = tmp;
a0.data.truncate(0);
a0.data.extend(a.data[offset..].iter().cloned());
/*
* q0 << j * big_digit::BITS is our actual quotient estimate - we do the shifts
* implicitly at the end, when adding and subtracting to a and q. Not only do we
* save the cost of the shifts, the rest of the arithmetic gets to work with
* smaller numbers.
*/
let (mut q0, _) = div_rem_digit(a0, bn);
let mut prod = &b * &q0;
while cmp_slice(&prod.data[..], &a.data[j..]) == Greater {
let one: BigUint = One::one();
q0 = q0 - one;
prod = prod - &b;
}
add2(&mut q.data[j..], &q0.data[..]);
sub2(&mut a.data[j..], &prod.data[..]);
a = a.normalize();
tmp = q0;
}
debug_assert!(a < b);
(q.normalize(), a >> shift)
}
/// Find last set bit
/// fls(0) == 0, fls(u32::MAX) == 32
pub fn fls<T: traits::PrimInt>(v: T) -> usize {
mem::size_of::<T>() * 8 - v.leading_zeros() as usize
}
pub fn ilog2<T: traits::PrimInt>(v: T) -> usize {
fls(v) - 1
}
#[inline]
pub fn biguint_shl(n: Cow<BigUint>, bits: usize) -> BigUint {
let n_unit = bits / big_digit::BITS;
let mut data = match n_unit {
0 => n.into_owned().data,
_ => {
let len = n_unit + n.data.len() + 1;
let mut data = Vec::with_capacity(len);
data.extend(repeat(0).take(n_unit));
data.extend(n.data.iter().cloned());
data
}
};
let n_bits = bits % big_digit::BITS;
if n_bits > 0 {
let mut carry = 0;
for elem in data[n_unit..].iter_mut() {
let new_carry = *elem >> (big_digit::BITS - n_bits);
*elem = (*elem << n_bits) | carry;
carry = new_carry;
}
if carry != 0 {
data.push(carry);
}
}
BigUint::new(data)
}
#[inline]
pub fn biguint_shr(n: Cow<BigUint>, bits: usize) -> BigUint {
let n_unit = bits / big_digit::BITS;
if n_unit >= n.data.len() {
return Zero::zero();
}
let mut data = match n_unit {
0 => n.into_owned().data,
_ => n.data[n_unit..].to_vec(),
};
let n_bits = bits % big_digit::BITS;
if n_bits > 0 {
let mut borrow = 0;
for elem in data.iter_mut().rev() {
let new_borrow = *elem << (big_digit::BITS - n_bits);
*elem = (*elem >> n_bits) | borrow;
borrow = new_borrow;
}
}
BigUint::new(data)
}
pub fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering {
debug_assert!(a.last() != Some(&0));
debug_assert!(b.last() != Some(&0));
let (a_len, b_len) = (a.len(), b.len());
if a_len < b_len {
return Less;
}
if a_len > b_len {
return Greater;
}
for (&ai, &bi) in a.iter().rev().zip(b.iter().rev()) {
if ai < bi {
return Less;
}
if ai > bi {
return Greater;
}
}
return Equal;
}
#[cfg(test)]
mod algorithm_tests {
use {BigDigit, BigUint, BigInt};
use Sign::Plus;
use traits::Num;
#[test]
fn test_sub_sign() {
use super::sub_sign;
fn sub_sign_i(a: &[BigDigit], b: &[BigDigit]) -> BigInt {
let (sign, val) = sub_sign(a, b);
BigInt::from_biguint(sign, val)
}
let a = BigUint::from_str_radix("265252859812191058636308480000000", 10).unwrap();
let b = BigUint::from_str_radix("26525285981219105863630848000000", 10).unwrap();
let a_i = BigInt::from_biguint(Plus, a.clone());
let b_i = BigInt::from_biguint(Plus, b.clone());
assert_eq!(sub_sign_i(&a.data[..], &b.data[..]), &a_i - &b_i);
assert_eq!(sub_sign_i(&b.data[..], &a.data[..]), &b_i - &a_i);
}
}
| 30.231687 | 99 | 0.514989 |
e8df3ee96c9903286192a8ece42055cf0bb80857 | 9,344 | // Non-camel case types are used for Stomp Protocol version enum variants
#![macro_use]
#![allow(non_camel_case_types)]
use std::slice::Iter;
use unicode_segmentation::UnicodeSegmentation;
// Ideally this would be a simple typedef. However:
// See Rust bug #11047: https://github.com/mozilla/rust/issues/11047
// Cannot call static methods (`with_capacity`) on type aliases (`HeaderList`)
#[derive(Clone, Debug)]
pub struct HeaderList {
pub headers: Vec<Header>,
}
impl HeaderList {
pub fn new() -> HeaderList {
HeaderList::with_capacity(0)
}
pub fn with_capacity(capacity: usize) -> HeaderList {
HeaderList {
headers: Vec::with_capacity(capacity),
}
}
pub fn push(&mut self, header: Header) {
self.headers.push(header);
}
pub fn pop(&mut self) -> Option<Header> {
self.headers.pop()
}
pub fn iter<'a>(&'a self) -> Iter<'a, Header> {
self.headers.iter()
}
pub fn drain<F>(&mut self, mut sink: F)
where
F: FnMut(Header),
{
while let Some(header) = self.headers.pop() {
sink(header);
}
}
pub fn concat(&mut self, other_list: &mut HeaderList) {
other_list.headers.reverse();
while let Some(header) = other_list.pop() {
self.headers.push(header);
}
}
pub fn retain<F>(&mut self, test: F)
where
F: Fn(&Header) -> bool,
{
self.headers.retain(test)
}
}
pub struct SuppressedHeader<'a>(pub &'a str);
pub struct ContentType<'a>(pub &'a str);
#[derive(Clone, Debug)]
pub struct Header(pub String, pub String);
impl Header {
pub fn new(key: &str, value: &str) -> Header {
Header(Self::encode_value(key), Self::encode_value(value))
}
pub fn new_raw<T: Into<String>, U: Into<String>>(key: T, value: U) -> Header {
Header(key.into(), value.into())
}
pub fn get_raw(&self) -> String {
format!("{}:{}", self.0, self.1)
}
pub fn encode_value(value: &str) -> String {
let mut encoded = String::new(); //self.strings.detached();
for grapheme in UnicodeSegmentation::graphemes(value, true) {
match grapheme {
"\\" => encoded.push_str(r"\\"), // Order is significant
"\r" => encoded.push_str(r"\r"),
"\n" => encoded.push_str(r"\n"),
":" => encoded.push_str(r"\c"),
g => encoded.push_str(g),
}
}
encoded
}
pub fn get_key<'a>(&'a self) -> &'a str {
&self.0
}
pub fn get_value<'a>(&'a self) -> &'a str {
&self.1
}
}
// Headers in the Spec
#[derive(Clone)]
pub struct AcceptVersion(pub Vec<StompVersion>);
pub struct Ack<'a>(pub &'a str);
#[derive(Clone, Copy)]
pub struct ContentLength(pub u32);
pub struct Custom(pub Header);
pub struct Destination<'a>(pub &'a str);
#[derive(Clone, Copy)]
pub struct HeartBeat(pub u32, pub u32);
pub struct Host<'a>(pub &'a str);
pub struct Id<'a>(pub &'a str);
pub struct Login<'a>(pub &'a str);
pub struct MessageId<'a>(pub &'a str);
pub struct Passcode<'a>(pub &'a str);
pub struct Receipt<'a>(pub &'a str);
pub struct ReceiptId<'a>(pub &'a str);
pub struct Server<'a>(pub &'a str);
pub struct Session<'a>(pub &'a str);
pub struct Subscription<'a>(pub &'a str);
pub struct Transaction<'a>(pub &'a str);
#[derive(Clone, Copy)]
pub struct Version(pub StompVersion);
#[derive(Clone, Copy)]
pub enum StompVersion {
Stomp_v1_0,
Stomp_v1_1,
Stomp_v1_2,
}
impl HeaderList {
pub fn get_header<'a>(&'a self, key: &str) -> Option<&'a Header> {
self.headers.iter().find(|header| match **header {
ref h if h.get_key() == key => true,
_ => false,
})
}
pub fn get_accept_version(&self) -> Option<Vec<StompVersion>> {
let versions: &str = match self.get_header("accept-version") {
Some(h) => h.get_value(),
None => return None,
};
let versions: Vec<StompVersion> = versions
.split(',')
.filter_map(|v| match v.trim() {
"1.0" => Some(StompVersion::Stomp_v1_0),
"1.1" => Some(StompVersion::Stomp_v1_1),
"1.2" => Some(StompVersion::Stomp_v1_2),
_ => None,
})
.collect();
Some(versions)
}
pub fn get_ack<'a>(&'a self) -> Option<Ack<'a>> {
match self.get_header("ack") {
Some(h) => Some(Ack(h.get_value())),
None => None,
}
}
pub fn get_destination<'a>(&'a self) -> Option<Destination<'a>> {
match self.get_header("destination") {
Some(h) => Some(Destination(h.get_value())),
None => return None,
}
}
pub fn get_heart_beat(&self) -> Option<HeartBeat> {
let spec = match self.get_header("heart-beat") {
Some(h) => h.get_value(),
None => return None,
};
let spec_list: Vec<u32> = spec
.split(',')
.filter_map(|str_val| str_val.parse::<u32>().ok())
.collect();
if spec_list.len() != 2 {
return None;
}
Some(HeartBeat(spec_list[0], spec_list[1]))
}
pub fn get_host<'a>(&'a self) -> Option<Host<'a>> {
match self.get_header("host") {
Some(h) => Some(Host(h.get_value())),
None => None,
}
}
pub fn get_id<'a>(&'a self) -> Option<Id<'a>> {
match self.get_header("id") {
Some(h) => Some(Id(h.get_value())),
None => None,
}
}
pub fn get_login<'a>(&'a self) -> Option<Login<'a>> {
match self.get_header("login") {
Some(h) => Some(Login(h.get_value())),
None => None,
}
}
pub fn get_message_id<'a>(&'a self) -> Option<MessageId<'a>> {
match self.get_header("message-id") {
Some(h) => Some(MessageId(h.get_value())),
None => None,
}
}
pub fn get_passcode<'a>(&'a self) -> Option<Passcode<'a>> {
match self.get_header("passcode") {
Some(h) => Some(Passcode(h.get_value())),
None => None,
}
}
pub fn get_receipt<'a>(&'a self) -> Option<Receipt<'a>> {
match self.get_header("receipt") {
Some(h) => Some(Receipt(h.get_value())),
None => None,
}
}
pub fn get_receipt_id<'a>(&'a self) -> Option<ReceiptId<'a>> {
match self.get_header("receipt-id") {
Some(h) => Some(ReceiptId(h.get_value())),
None => None,
}
}
pub fn get_server<'a>(&'a self) -> Option<Server<'a>> {
match self.get_header("server") {
Some(h) => Some(Server(h.get_value())),
None => None,
}
}
pub fn get_session<'a>(&'a self) -> Option<Session<'a>> {
match self.get_header("session") {
Some(h) => Some(Session(h.get_value())),
None => None,
}
}
pub fn get_subscription<'a>(&'a self) -> Option<Subscription<'a>> {
match self.get_header("subscription") {
Some(h) => Some(Subscription(h.get_value())),
None => None,
}
}
pub fn get_transaction<'a>(&'a self) -> Option<Transaction<'a>> {
match self.get_header("transaction") {
Some(h) => Some(Transaction(h.get_value())),
None => None,
}
}
pub fn get_version(&self) -> Option<Version> {
let version = match self.get_header("version") {
Some(h) => h.get_value(),
None => return None,
};
match (version).as_ref() {
"1.0" => Some(Version(StompVersion::Stomp_v1_0)), // TODO: Impl FromStr for StompVersion
"1.1" => Some(Version(StompVersion::Stomp_v1_1)),
"1.2" => Some(Version(StompVersion::Stomp_v1_2)),
_ => None,
}
}
pub fn get_content_length(&self) -> Option<ContentLength> {
let length = match self.get_header("content-length") {
Some(h) => h.get_value(),
None => return None,
};
match length.parse::<u32>().ok() {
Some(l) => Some(ContentLength(l)),
None => None,
}
}
}
#[macro_export]
macro_rules! header_list [
($($header: expr), *) => ({
let header_list = HeaderList::new();
$(header_list.push($header);)*
header_list
});
($($key:expr => $value: expr), *) => ({
let mut header_list = HeaderList::new();
$(header_list.push(Header::new($key, $value));)*
header_list
})
];
#[test]
fn encode_return_carriage() {
let unencoded = "Hello\rWorld";
let encoded = r"Hello\rWorld";
assert!(encoded == Header::encode_value(unencoded));
}
#[test]
fn encode_newline() {
let unencoded = "Hello\nWorld";
let encoded = r"Hello\nWorld";
assert!(encoded == Header::encode_value(unencoded));
}
#[test]
fn encode_colon() {
let unencoded = "Hello:World";
let encoded = r"Hello\cWorld";
assert!(encoded == Header::encode_value(unencoded));
}
#[test]
fn encode_slash() {
let unencoded = r"Hello\World";
let encoded = r"Hello\\World";
assert!(encoded == Header::encode_value(unencoded));
}
| 26.470255 | 100 | 0.539277 |
f864df31fa3093c7aea2766fd03905b467e038ee | 2,333 | /*
* Copyright (C) 2019-2021 TON Labs. All Rights Reserved.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* 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 TON DEV software governing permissions and
* limitations under the License.
*/
use crate::{error::TvmError, types::{Exception, Status}};
use ton_types::{error, types::ExceptionCode};
pub trait OperationBehavior {
fn quiet() -> bool;
fn name_prefix() -> Option<&'static str>;
fn on_nan_parameter(file: &'static str, line: u32) -> Status;
fn on_integer_overflow(file: &'static str, line: u32) -> Status;
fn on_range_check_error(file: &'static str, line: u32) -> Status;
}
pub struct Signaling {}
pub struct Quiet {}
#[macro_export]
macro_rules! on_integer_overflow {
($T: ident) => {{
$T::on_integer_overflow(file!(), line!())
}}
}
#[macro_export]
macro_rules! on_nan_parameter {
($T: ident) => {{
$T::on_nan_parameter(file!(), line!())
}}
}
#[macro_export]
macro_rules! on_range_check_error {
($T: ident) => {{
$T::on_range_check_error(file!(), line!())
}}
}
impl OperationBehavior for Signaling {
fn quiet() -> bool {
false
}
fn name_prefix() -> Option<&'static str> {
None
}
fn on_integer_overflow(file: &'static str, line: u32) -> Status {
err!(ExceptionCode::IntegerOverflow, file, line)
}
fn on_nan_parameter(file: &'static str, line: u32) -> Status {
err!(ExceptionCode::IntegerOverflow, file, line)
}
fn on_range_check_error(file: &'static str, line: u32) -> Status {
err!(ExceptionCode::RangeCheckError, file, line)
}
}
impl OperationBehavior for Quiet {
fn quiet() -> bool {
true
}
fn name_prefix() -> Option<&'static str> {
Some("Q")
}
fn on_integer_overflow(_: &'static str, _: u32) -> Status {
Ok(())
}
fn on_nan_parameter(_: &'static str, _: u32) -> Status {
Ok(())
}
fn on_range_check_error(_: &'static str, _: u32) -> Status {
Ok(())
}
}
| 27.77381 | 81 | 0.633948 |
f4e7147e97e61b2367bda0ba83df2f7c0235706a | 5,607 | use std::{fs::File, path::PathBuf};
use kagamijxl::{decode_memory, Decoder};
use libjxl_sys::JXL_ORIENT_IDENTITY;
const MANIFEST_DIR: &str = env!("CARGO_MANIFEST_DIR");
fn sample_image_path() -> PathBuf {
// Resolve path manually or it will fail when running each test
PathBuf::from(MANIFEST_DIR).join("tests/resources/sample.jxl")
}
fn get_sample_image() -> Vec<u8> {
std::fs::read(sample_image_path()).expect("Failed to read the sample image")
}
fn get_sample_image_file() -> File {
File::open(sample_image_path()).expect("Failed to read the sample image")
}
fn get_sample_animation() -> Vec<u8> {
// Resolve path manually or it will fail when running each test
let sample_path = PathBuf::from(MANIFEST_DIR).join("tests/resources/spinfox.jxl");
std::fs::read(sample_path).expect("Failed to read the sample image")
}
#[test]
fn test_decode_memory() {
let data = get_sample_image();
let result = decode_memory(&data).expect("Failed to decode the sample image");
let basic_info = &result.basic_info;
assert_eq!(basic_info.xsize, 1404);
assert_eq!(basic_info.ysize, 936);
assert_eq!(basic_info.have_container, 0);
assert_eq!(basic_info.orientation, JXL_ORIENT_IDENTITY);
assert_eq!(result.preview.len(), 0);
assert_eq!(result.color_profile.len(), 0);
assert_eq!(result.frames.len(), 1);
assert_eq!(result.frames[0].name, "");
assert_ne!(result.frames[0].data.len(), 0);
assert_eq!(result.frames[0].dc.len(), 0);
}
#[test]
fn test_decode_default() {
let data = get_sample_image();
let result = Decoder::default()
.decode(&data)
.expect("Failed to decode the sample image");
let basic_info = &result.basic_info;
assert_eq!(basic_info.xsize, 1404);
assert_eq!(basic_info.ysize, 936);
}
#[test]
fn test_decode_new() {
let data = get_sample_image();
let result = Decoder::new()
.decode(&data)
.expect("Failed to decode the sample image");
let basic_info = &result.basic_info;
assert_eq!(basic_info.xsize, 1404);
assert_eq!(basic_info.ysize, 936);
}
#[test]
fn test_decode_no_frame() {
let data = get_sample_image();
let mut decoder = Decoder::default();
decoder.no_full_frame = true;
let result = decoder
.decode(&data)
.expect("Failed to decode the sample image");
assert_eq!(result.frames.len(), 0);
}
// https://gitlab.com/wg1/jpeg-xl/-/issues/194
// #[test]
// fn test_decode_dc_frame() {
// let data = get_sample_image();
// let mut decoder = Decoder::default();
// decoder.need_optional_dc_frame = true;
// let result = decoder
// .decode(&data)
// .expect("Failed to decode the sample image");
// assert_eq!(result.frames.len(), 1);
// assert_ne!(result.frames[0].dc.len(), 0);
// }
#[test]
fn test_decode_dc_frame_animation() {
let data = get_sample_animation();
let mut decoder = Decoder::default();
decoder.need_optional_dc_frame = true;
let result = decoder
.decode(&data)
.expect("Failed to decode the sample image");
assert_eq!(result.frames.len(), 25);
assert_eq!(result.frames[0].dc.len(), 0); // Probably because it's small enough
}
#[test]
fn test_decode_color_profile() {
let data = get_sample_image();
let mut decoder = Decoder::default();
decoder.need_color_profile = true;
let result = decoder
.decode(&data)
.expect("Failed to decode the sample image");
assert_ne!(result.color_profile.len(), 0);
}
#[test]
fn test_decode_file() {
let file = get_sample_image_file();
let result = Decoder::default()
.decode_file(&file)
.expect("Failed to decode the sample image");
let basic_info = &result.basic_info;
assert_eq!(basic_info.xsize, 1404);
assert_eq!(basic_info.ysize, 936);
}
#[test]
fn test_decode_need_more_input() {
let path = PathBuf::from(MANIFEST_DIR).join("tests/resources/needmoreinput.jxl");
let file = File::open(path).expect("Failed to open the sample image");
let result = Decoder::default()
.decode_file(&file)
.expect("Failed to decode the sample image");
let basic_info = &result.basic_info;
assert_eq!(basic_info.xsize, 3264);
assert_eq!(basic_info.ysize, 1836);
}
#[test]
fn test_decode_animation() {
let data = get_sample_animation();
let result = decode_memory(&data).expect("Failed to decode the sample image");
assert_eq!(result.frames.len(), 25);
for frame in result.frames {
assert_ne!(frame.data.len(), 0);
}
}
#[test]
fn test_decode_animation_first() {
let data = get_sample_animation();
let mut decoder = Decoder::default();
decoder.max_frames = Some(1);
let result = decoder
.decode(&data)
.expect("Failed to decode the sample image");
assert_eq!(result.frames.len(), 1);
assert_ne!(result.frames[0].data.len(), 0);
}
#[test]
fn test_decode_partial() {
let data = get_sample_image();
let mut decoder = Decoder::default();
decoder.allow_partial = true;
let result = decoder
.decode(&data[..40960])
.expect("Failed to decode the sample image");
assert_eq!(result.frames.len(), 1);
assert_ne!(result.frames[0].data.len(), 0);
}
#[test]
#[should_panic]
fn test_decode_partial_fail() {
let data = get_sample_image();
decode_memory(&data[..40960]).expect("Failed to decode the sample image");
}
#[test]
#[should_panic]
fn test_decode_partial_fail_buffer() {
decode_memory(&[0xff, 0x0a]).expect("Failed to decode the data");
}
| 26.956731 | 86 | 0.661138 |
90b3733821622a9f249d6bb9402325dd51e7fcef | 30,203 | use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::ffi::OsStr;
use std::fmt;
use std::path::PathBuf;
use std::str::FromStr;
use rustc_data_structures::fx::FxHashMap;
use rustc_session::config::{
self, parse_crate_types_from_list, parse_externs, parse_target_triple, CrateType,
};
use rustc_session::config::{get_cmd_lint_options, nightly_options};
use rustc_session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs};
use rustc_session::getopts;
use rustc_session::lint::Level;
use rustc_session::search_paths::SearchPath;
use rustc_span::edition::Edition;
use rustc_target::spec::TargetTriple;
use crate::core::new_handler;
use crate::externalfiles::ExternalHtml;
use crate::html;
use crate::html::markdown::IdMap;
use crate::html::render::StylePath;
use crate::html::static_files;
use crate::opts;
use crate::passes::{self, Condition, DefaultPassOption};
use crate::theme;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
crate enum OutputFormat {
Json,
Html,
}
impl Default for OutputFormat {
fn default() -> OutputFormat {
OutputFormat::Html
}
}
impl OutputFormat {
crate fn is_json(&self) -> bool {
matches!(self, OutputFormat::Json)
}
}
impl TryFrom<&str> for OutputFormat {
type Error = String;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"json" => Ok(OutputFormat::Json),
"html" => Ok(OutputFormat::Html),
_ => Err(format!("unknown output format `{}`", value)),
}
}
}
/// Configuration options for rustdoc.
#[derive(Clone)]
crate struct Options {
// Basic options / Options passed directly to rustc
/// The crate root or Markdown file to load.
crate input: PathBuf,
/// The name of the crate being documented.
crate crate_name: Option<String>,
/// Whether or not this is a proc-macro crate
crate proc_macro_crate: bool,
/// How to format errors and warnings.
crate error_format: ErrorOutputType,
/// Library search paths to hand to the compiler.
crate libs: Vec<SearchPath>,
/// Library search paths strings to hand to the compiler.
crate lib_strs: Vec<String>,
/// The list of external crates to link against.
crate externs: Externs,
/// The list of external crates strings to link against.
crate extern_strs: Vec<String>,
/// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`.
crate cfgs: Vec<String>,
/// Codegen options to hand to the compiler.
crate codegen_options: CodegenOptions,
/// Codegen options strings to hand to the compiler.
crate codegen_options_strs: Vec<String>,
/// Debugging (`-Z`) options to pass to the compiler.
crate debugging_opts: DebuggingOptions,
/// Debugging (`-Z`) options strings to pass to the compiler.
crate debugging_opts_strs: Vec<String>,
/// The target used to compile the crate against.
crate target: TargetTriple,
/// Edition used when reading the crate. Defaults to "2015". Also used by default when
/// compiling doctests from the crate.
crate edition: Edition,
/// The path to the sysroot. Used during the compilation process.
crate maybe_sysroot: Option<PathBuf>,
/// Lint information passed over the command-line.
crate lint_opts: Vec<(String, Level)>,
/// Whether to ask rustc to describe the lints it knows.
crate describe_lints: bool,
/// What level to cap lints at.
crate lint_cap: Option<Level>,
// Options specific to running doctests
/// Whether we should run doctests instead of generating docs.
crate should_test: bool,
/// List of arguments to pass to the test harness, if running tests.
crate test_args: Vec<String>,
/// The working directory in which to run tests.
crate test_run_directory: Option<PathBuf>,
/// Optional path to persist the doctest executables to, defaults to a
/// temporary directory if not set.
crate persist_doctests: Option<PathBuf>,
/// Runtool to run doctests with
crate runtool: Option<String>,
/// Arguments to pass to the runtool
crate runtool_args: Vec<String>,
/// Whether to allow ignoring doctests on a per-target basis
/// For example, using ignore-foo to ignore running the doctest on any target that
/// contains "foo" as a substring
crate enable_per_target_ignores: bool,
/// Do not run doctests, compile them if should_test is active.
crate no_run: bool,
/// The path to a rustc-like binary to build tests with. If not set, we
/// default to loading from `$sysroot/bin/rustc`.
crate test_builder: Option<PathBuf>,
// Options that affect the documentation process
/// The selected default set of passes to use.
///
/// Be aware: This option can come both from the CLI and from crate attributes!
crate default_passes: DefaultPassOption,
/// Any passes manually selected by the user.
///
/// Be aware: This option can come both from the CLI and from crate attributes!
crate manual_passes: Vec<String>,
/// Whether to display warnings during doc generation or while gathering doctests. By default,
/// all non-rustdoc-specific lints are allowed when generating docs.
crate display_warnings: bool,
/// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
/// with and without documentation.
crate show_coverage: bool,
// Options that alter generated documentation pages
/// Crate version to note on the sidebar of generated docs.
crate crate_version: Option<String>,
/// Collected options specific to outputting final pages.
crate render_options: RenderOptions,
/// The format that we output when rendering.
///
/// Currently used only for the `--show-coverage` option.
crate output_format: OutputFormat,
/// If this option is set to `true`, rustdoc will only run checks and not generate
/// documentation.
crate run_check: bool,
/// Whether doctests should emit unused externs
crate json_unused_externs: bool,
}
impl fmt::Debug for Options {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct FmtExterns<'a>(&'a Externs);
impl<'a> fmt::Debug for FmtExterns<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.0.iter()).finish()
}
}
f.debug_struct("Options")
.field("input", &self.input)
.field("crate_name", &self.crate_name)
.field("proc_macro_crate", &self.proc_macro_crate)
.field("error_format", &self.error_format)
.field("libs", &self.libs)
.field("externs", &FmtExterns(&self.externs))
.field("cfgs", &self.cfgs)
.field("codegen_options", &"...")
.field("debugging_options", &"...")
.field("target", &self.target)
.field("edition", &self.edition)
.field("maybe_sysroot", &self.maybe_sysroot)
.field("lint_opts", &self.lint_opts)
.field("describe_lints", &self.describe_lints)
.field("lint_cap", &self.lint_cap)
.field("should_test", &self.should_test)
.field("test_args", &self.test_args)
.field("test_run_directory", &self.test_run_directory)
.field("persist_doctests", &self.persist_doctests)
.field("default_passes", &self.default_passes)
.field("manual_passes", &self.manual_passes)
.field("display_warnings", &self.display_warnings)
.field("show_coverage", &self.show_coverage)
.field("crate_version", &self.crate_version)
.field("render_options", &self.render_options)
.field("runtool", &self.runtool)
.field("runtool_args", &self.runtool_args)
.field("enable-per-target-ignores", &self.enable_per_target_ignores)
.field("run_check", &self.run_check)
.field("no_run", &self.no_run)
.finish()
}
}
/// Configuration options for the HTML page-creation process.
#[derive(Clone, Debug)]
crate struct RenderOptions {
/// Output directory to generate docs into. Defaults to `doc`.
crate output: PathBuf,
/// External files to insert into generated pages.
crate external_html: ExternalHtml,
/// A pre-populated `IdMap` with the default headings and any headings added by Markdown files
/// processed by `external_html`.
crate id_map: IdMap,
/// If present, playground URL to use in the "Run" button added to code samples.
///
/// Be aware: This option can come both from the CLI and from crate attributes!
crate playground_url: Option<String>,
/// Whether to sort modules alphabetically on a module page instead of using declaration order.
/// `true` by default.
//
// FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is
// inverted once read.
crate sort_modules_alphabetically: bool,
/// List of themes to extend the docs with. Original argument name is included to assist in
/// displaying errors if it fails a theme check.
crate themes: Vec<StylePath>,
/// If present, CSS file that contains rules to add to the default CSS.
crate extension_css: Option<PathBuf>,
/// A map of crate names to the URL to use instead of querying the crate's `html_root_url`.
crate extern_html_root_urls: BTreeMap<String, String>,
/// A map of the default settings (values are as for DOM storage API). Keys should lack the
/// `rustdoc-` prefix.
crate default_settings: FxHashMap<String, String>,
/// If present, suffix added to CSS/JavaScript files when referencing them in generated pages.
crate resource_suffix: String,
/// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by
/// default.
//
// FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted
// once read.
crate enable_minification: bool,
/// Whether to create an index page in the root of the output directory. If this is true but
/// `enable_index_page` is None, generate a static listing of crates instead.
crate enable_index_page: bool,
/// A file to use as the index page at the root of the output directory. Overrides
/// `enable_index_page` to be true if set.
crate index_page: Option<PathBuf>,
/// An optional path to use as the location of static files. If not set, uses combinations of
/// `../` to reach the documentation root.
crate static_root_path: Option<String>,
// Options specific to reading standalone Markdown files
/// Whether to generate a table of contents on the output file when reading a standalone
/// Markdown file.
crate markdown_no_toc: bool,
/// Additional CSS files to link in pages generated from standalone Markdown files.
crate markdown_css: Vec<String>,
/// If present, playground URL to use in the "Run" button added to code samples generated from
/// standalone Markdown files. If not present, `playground_url` is used.
crate markdown_playground_url: Option<String>,
/// If false, the `select` element to have search filtering by crates on rendered docs
/// won't be generated.
crate generate_search_filter: bool,
/// Document items that have lower than `pub` visibility.
crate document_private: bool,
/// Document items that have `doc(hidden)`.
crate document_hidden: bool,
/// If `true`, generate a JSON file in the crate folder instead of HTML redirection files.
crate generate_redirect_map: bool,
/// Show the memory layout of types in the docs.
crate show_type_layout: bool,
crate unstable_features: rustc_feature::UnstableFeatures,
crate emit: Vec<EmitType>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
crate enum EmitType {
Unversioned,
Toolchain,
InvocationSpecific,
}
impl FromStr for EmitType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
use EmitType::*;
match s {
"unversioned-shared-resources" => Ok(Unversioned),
"toolchain-shared-resources" => Ok(Toolchain),
"invocation-specific" => Ok(InvocationSpecific),
_ => Err(()),
}
}
}
impl RenderOptions {
crate fn should_emit_crate(&self) -> bool {
self.emit.is_empty() || self.emit.contains(&EmitType::InvocationSpecific)
}
}
impl Options {
/// Parses the given command-line for options. If an error message or other early-return has
/// been printed, returns `Err` with the exit code.
crate fn from_matches(matches: &getopts::Matches) -> Result<Options, i32> {
// Check for unstable options.
nightly_options::check_nightly_options(&matches, &opts());
if matches.opt_present("h") || matches.opt_present("help") {
crate::usage("rustdoc");
return Err(0);
} else if matches.opt_present("version") {
rustc_driver::version("rustdoc", &matches);
return Err(0);
}
if matches.opt_strs("passes") == ["list"] {
println!("Available passes for running rustdoc:");
for pass in passes::PASSES {
println!("{:>20} - {}", pass.name, pass.description);
}
println!("\nDefault passes for rustdoc:");
for p in passes::DEFAULT_PASSES {
print!("{:>20}", p.pass.name);
println_condition(p.condition);
}
if nightly_options::match_is_nightly_build(matches) {
println!("\nPasses run with `--show-coverage`:");
for p in passes::COVERAGE_PASSES {
print!("{:>20}", p.pass.name);
println_condition(p.condition);
}
}
fn println_condition(condition: Condition) {
use Condition::*;
match condition {
Always => println!(),
WhenDocumentPrivate => println!(" (when --document-private-items)"),
WhenNotDocumentPrivate => println!(" (when not --document-private-items)"),
WhenNotDocumentHidden => println!(" (when not --document-hidden-items)"),
}
}
return Err(0);
}
let color = config::parse_color(&matches);
let config::JsonConfig { json_rendered, json_unused_externs, .. } =
config::parse_json(&matches);
let error_format = config::parse_error_format(&matches, color, json_rendered);
let codegen_options = CodegenOptions::build(matches, error_format);
let debugging_opts = DebuggingOptions::build(matches, error_format);
let diag = new_handler(error_format, None, &debugging_opts);
// check for deprecated options
check_deprecated_options(&matches, &diag);
let mut emit = Vec::new();
for list in matches.opt_strs("emit") {
for kind in list.split(',') {
match kind.parse() {
Ok(kind) => emit.push(kind),
Err(()) => {
diag.err(&format!("unrecognized emission type: {}", kind));
return Err(1);
}
}
}
}
// check for `--output-format=json`
if !matches!(matches.opt_str("output-format").as_deref(), None | Some("html"))
&& !matches.opt_present("show-coverage")
&& !nightly_options::is_unstable_enabled(matches)
{
rustc_session::early_error(
error_format,
"the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
);
}
let to_check = matches.opt_strs("check-theme");
if !to_check.is_empty() {
let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
let mut errors = 0;
println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
for theme_file in to_check.iter() {
print!(" - Checking \"{}\"...", theme_file);
let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
if !differences.is_empty() || !success {
println!(" FAILED");
errors += 1;
if !differences.is_empty() {
println!("{}", differences.join("\n"));
}
} else {
println!(" OK");
}
}
if errors != 0 {
return Err(1);
}
return Err(0);
}
if matches.free.is_empty() {
diag.struct_err("missing file operand").emit();
return Err(1);
}
if matches.free.len() > 1 {
diag.struct_err("too many file operands").emit();
return Err(1);
}
let input = PathBuf::from(&matches.free[0]);
let libs = matches
.opt_strs("L")
.iter()
.map(|s| SearchPath::from_cli_opt(s, error_format))
.collect();
let externs = parse_externs(&matches, &debugging_opts, error_format);
let extern_html_root_urls = match parse_extern_html_roots(&matches) {
Ok(ex) => ex,
Err(err) => {
diag.struct_err(err).emit();
return Err(1);
}
};
let default_settings: Vec<Vec<(String, String)>> = vec![
matches
.opt_str("default-theme")
.iter()
.map(|theme| {
vec![
("use-system-theme".to_string(), "false".to_string()),
("theme".to_string(), theme.to_string()),
]
})
.flatten()
.collect(),
matches
.opt_strs("default-setting")
.iter()
.map(|s| match s.split_once('=') {
None => (s.clone(), "true".to_string()),
Some((k, v)) => (k.to_string(), v.to_string()),
})
.collect(),
];
let default_settings = default_settings.into_iter().flatten().collect();
let test_args = matches.opt_strs("test-args");
let test_args: Vec<String> =
test_args.iter().flat_map(|s| s.split_whitespace()).map(|s| s.to_string()).collect();
let should_test = matches.opt_present("test");
let no_run = matches.opt_present("no-run");
if !should_test && no_run {
diag.err("the `--test` flag must be passed to enable `--no-run`");
return Err(1);
}
let output =
matches.opt_str("o").map(|s| PathBuf::from(&s)).unwrap_or_else(|| PathBuf::from("doc"));
let cfgs = matches.opt_strs("cfg");
let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));
if let Some(ref p) = extension_css {
if !p.is_file() {
diag.struct_err("option --extend-css argument must be a file").emit();
return Err(1);
}
}
let mut themes = Vec::new();
if matches.opt_present("theme") {
let paths = theme::load_css_paths(static_files::themes::LIGHT.as_bytes());
for (theme_file, theme_s) in
matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
{
if !theme_file.is_file() {
diag.struct_err(&format!("invalid argument: \"{}\"", theme_s))
.help("arguments to --theme must be files")
.emit();
return Err(1);
}
if theme_file.extension() != Some(OsStr::new("css")) {
diag.struct_err(&format!("invalid argument: \"{}\"", theme_s))
.help("arguments to --theme must have a .css extension")
.emit();
return Err(1);
}
let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
if !success {
diag.struct_err(&format!("error loading theme file: \"{}\"", theme_s)).emit();
return Err(1);
} else if !ret.is_empty() {
diag.struct_warn(&format!(
"theme file \"{}\" is missing CSS rules from the default theme",
theme_s
))
.warn("the theme may appear incorrect when loaded")
.help(&format!(
"to see what rules are missing, call `rustdoc --check-theme \"{}\"`",
theme_s
))
.emit();
}
themes.push(StylePath { path: theme_file, disabled: true });
}
}
let edition = config::parse_crate_edition(&matches);
let mut id_map = html::markdown::IdMap::new();
let external_html = match ExternalHtml::load(
&matches.opt_strs("html-in-header"),
&matches.opt_strs("html-before-content"),
&matches.opt_strs("html-after-content"),
&matches.opt_strs("markdown-before-content"),
&matches.opt_strs("markdown-after-content"),
nightly_options::match_is_nightly_build(&matches),
&diag,
&mut id_map,
edition,
&None,
) {
Some(eh) => eh,
None => return Err(3),
};
match matches.opt_str("r").as_deref() {
Some("rust") | None => {}
Some(s) => {
diag.struct_err(&format!("unknown input format: {}", s)).emit();
return Err(1);
}
}
let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
if let Some(ref index_page) = index_page {
if !index_page.is_file() {
diag.struct_err("option `--index-page` argument must be a file").emit();
return Err(1);
}
}
let target = parse_target_triple(matches, error_format);
let show_coverage = matches.opt_present("show-coverage");
let default_passes = if matches.opt_present("no-defaults") {
passes::DefaultPassOption::None
} else if show_coverage {
passes::DefaultPassOption::Coverage
} else {
passes::DefaultPassOption::Default
};
let manual_passes = matches.opt_strs("passes");
let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
Ok(types) => types,
Err(e) => {
diag.struct_err(&format!("unknown crate type: {}", e)).emit();
return Err(1);
}
};
let output_format = match matches.opt_str("output-format") {
Some(s) => match OutputFormat::try_from(s.as_str()) {
Ok(out_fmt) => {
if !out_fmt.is_json() && show_coverage {
diag.struct_err(
"html output format isn't supported for the --show-coverage option",
)
.emit();
return Err(1);
}
out_fmt
}
Err(e) => {
diag.struct_err(&e).emit();
return Err(1);
}
},
None => OutputFormat::default(),
};
let crate_name = matches.opt_str("crate-name");
let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
let playground_url = matches.opt_str("playground-url");
let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
let display_warnings = matches.opt_present("display-warnings");
let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
let enable_minification = !matches.opt_present("disable-minification");
let markdown_no_toc = matches.opt_present("markdown-no-toc");
let markdown_css = matches.opt_strs("markdown-css");
let markdown_playground_url = matches.opt_str("markdown-playground-url");
let crate_version = matches.opt_str("crate-version");
let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some();
let static_root_path = matches.opt_str("static-root-path");
let generate_search_filter = !matches.opt_present("disable-per-crate-search");
let test_run_directory = matches.opt_str("test-run-directory").map(PathBuf::from);
let persist_doctests = matches.opt_str("persist-doctests").map(PathBuf::from);
let test_builder = matches.opt_str("test-builder").map(PathBuf::from);
let codegen_options_strs = matches.opt_strs("C");
let debugging_opts_strs = matches.opt_strs("Z");
let lib_strs = matches.opt_strs("L");
let extern_strs = matches.opt_strs("extern");
let runtool = matches.opt_str("runtool");
let runtool_args = matches.opt_strs("runtool-arg");
let enable_per_target_ignores = matches.opt_present("enable-per-target-ignores");
let document_private = matches.opt_present("document-private-items");
let document_hidden = matches.opt_present("document-hidden-items");
let run_check = matches.opt_present("check");
let generate_redirect_map = matches.opt_present("generate-redirect-map");
let show_type_layout = matches.opt_present("show-type-layout");
let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
Ok(Options {
input,
proc_macro_crate,
error_format,
libs,
lib_strs,
externs,
extern_strs,
cfgs,
codegen_options,
codegen_options_strs,
debugging_opts,
debugging_opts_strs,
target,
edition,
maybe_sysroot,
lint_opts,
describe_lints,
lint_cap,
should_test,
test_args,
default_passes,
manual_passes,
display_warnings,
show_coverage,
crate_version,
test_run_directory,
persist_doctests,
runtool,
runtool_args,
enable_per_target_ignores,
test_builder,
run_check,
no_run,
render_options: RenderOptions {
output,
external_html,
id_map,
playground_url,
sort_modules_alphabetically,
themes,
extension_css,
extern_html_root_urls,
default_settings,
resource_suffix,
enable_minification,
enable_index_page,
index_page,
static_root_path,
markdown_no_toc,
markdown_css,
markdown_playground_url,
generate_search_filter,
document_private,
document_hidden,
generate_redirect_map,
show_type_layout,
unstable_features: rustc_feature::UnstableFeatures::from_environment(
crate_name.as_deref(),
),
emit,
},
crate_name,
output_format,
json_unused_externs,
})
}
/// Returns `true` if the file given as `self.input` is a Markdown file.
crate fn markdown_input(&self) -> bool {
self.input.extension().map_or(false, |e| e == "md" || e == "markdown")
}
}
/// Prints deprecation warnings for deprecated options
fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Handler) {
let deprecated_flags = ["input-format", "no-defaults", "passes"];
for flag in deprecated_flags.iter() {
if matches.opt_present(flag) {
let mut err = diag.struct_warn(&format!("the `{}` flag is deprecated", flag));
err.note(
"see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
for more information",
);
if *flag == "no-defaults" {
err.help("you may want to use --document-private-items");
}
err.emit();
}
}
let removed_flags = ["plugins", "plugin-path"];
for &flag in removed_flags.iter() {
if matches.opt_present(flag) {
diag.struct_warn(&format!("the '{}' flag no longer functions", flag))
.warn("see CVE-2018-1000622")
.emit();
}
}
}
/// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
/// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
/// describing the issue.
fn parse_extern_html_roots(
matches: &getopts::Matches,
) -> Result<BTreeMap<String, String>, &'static str> {
let mut externs = BTreeMap::new();
for arg in &matches.opt_strs("extern-html-root-url") {
let (name, url) =
arg.split_once('=').ok_or("--extern-html-root-url must be of the form name=url")?;
externs.insert(name.to_string(), url.to_string());
}
Ok(externs)
}
| 40.163564 | 170 | 0.585372 |
abe22c0a70018e04660bed0f8d9b02db9b6964df | 2,474 | use super::conn::Connection;
use r2d2::{ManageConnection, Pool, PooledConnection};
use crate::{OrientError, OrientResult};
use std::net::SocketAddr;
use std::sync::Arc;
pub type SyncConnection = PooledConnection<ServerConnectionManager>;
pub struct Cluster {
servers: Vec<Arc<Server>>,
}
impl Cluster {
pub(crate) fn builder() -> ClusterBuilder {
ClusterBuilder::default()
}
pub(crate) fn connection(&self) -> OrientResult<(SyncConnection, Arc<Server>)> {
let conn = self.servers[0].connection()?;
Ok((conn, self.servers[0].clone()))
}
pub(crate) fn select(&self) -> Arc<Server> {
self.servers[0].clone()
}
}
pub struct ClusterBuilder {
pool_max: u32,
servers: Vec<SocketAddr>,
}
impl ClusterBuilder {
pub fn build(self) -> Cluster {
let pool_max = self.pool_max;
let servers = self
.servers
.into_iter()
.map(|s| {
// handle unreachable servers
Arc::new(Server::new(s, pool_max).unwrap())
})
.collect();
Cluster { servers }
}
pub fn pool_max(mut self, pool_max: u32) -> Self {
self.pool_max = pool_max;
self
}
pub fn add_server<T: Into<SocketAddr>>(mut self, address: T) -> Self {
self.servers.push(address.into());
self
}
}
impl Default for ClusterBuilder {
fn default() -> ClusterBuilder {
ClusterBuilder {
pool_max: 20,
servers: vec![],
}
}
}
pub struct Server {
pool: Pool<ServerConnectionManager>,
}
impl Server {
fn new(address: SocketAddr, pool_max: u32) -> OrientResult<Server> {
let manager = ServerConnectionManager { address };
let pool = Pool::builder().max_size(pool_max).build(manager)?;
Ok(Server { pool })
}
pub(crate) fn connection(&self) -> OrientResult<PooledConnection<ServerConnectionManager>> {
self.pool.get().map_err(OrientError::from)
}
}
pub struct ServerConnectionManager {
address: SocketAddr,
}
impl ManageConnection for ServerConnectionManager {
type Connection = Connection;
type Error = OrientError;
fn connect(&self) -> OrientResult<Connection> {
Connection::connect(&self.address)
}
fn is_valid(&self, _conn: &mut Connection) -> OrientResult<()> {
Ok(())
}
fn has_broken(&self, _conn: &mut Connection) -> bool {
false
}
}
| 24.254902 | 96 | 0.604285 |
185371875acbd84205f3de615a7305f27fc2e3d9 | 580 | use bebop::{bebop, Bebop};
bebop!("tests/a.bop");
#[test]
fn media_message() {
let data = MediaMessage {
codec: Some(VideoCodec::H264),
data: Some(VideoData {
time: 1.0,
width: 100,
height: 300,
fragment: vec![1, 2, 3],
}),
};
let bytes = data.encode();
assert_eq!(
bytes,
b"\x1e\0\0\0\x01\0\0\0\0\x02\0\0\0\0\0\0\xf0\x3f\
\x64\0\0\0\x2c\x01\0\0\x03\0\0\0\x01\x02\x03\0"
);
let data2 = MediaMessage::decode(&bytes).unwrap();
assert_eq!(data, data2);
}
| 21.481481 | 57 | 0.505172 |
1823f4efa60666cfa5a91704cad3b0a0df72783a | 246 | pub mod config;
pub mod dict_data;
pub mod dict_type;
pub mod gen_config_template;
pub mod gen_table;
pub mod gen_table_column;
pub mod login_log;
pub mod menu;
pub mod middleware;
pub mod oper_log;
pub mod role;
pub mod user;
pub mod user_role;
| 17.571429 | 28 | 0.788618 |
281ff6bcdac38e055e40bb1152677abdc895adbd | 133 | #![deny(missing_debug_implementations, missing_docs)] // kcov-ignore
//! Logic to control dispatcher frame rate.
pub mod strategy;
| 22.166667 | 68 | 0.766917 |
62f86ac8e2bc97c4aabc798af2c61ce63d08e6b7 | 3,253 | use parity_codec::Encode;
use support::{decl_storage, decl_module, StorageValue, StorageMap,
dispatch::Result, ensure, decl_event};
use system::ensure_signed;
use runtime_primitives::traits::{As, Hash};
#[derive(Encode, Decode, Default, Clone, PartialEq)]
pub struct Kitty<Hash, Balance> {
id: Hash,
dna: Hash,
price: Balance,
gen: u64,
}
pub trait Trait: balances::Trait {
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
}
decl_event!(
pub enum Event<T>
where
<T as system::Trait>::AccountId,
<T as system::Trait>::Hash
{
Created(AccountId, Hash),
}
);
decl_storage! {
trait Store for Module<T: Trait> as KittyStorage {
Kitties get(kitty): map T::Hash => Kitty<T::Hash, T::Balance>;
KittyOwner get(owner_of): map T::Hash => Option<T::AccountId>;
AllKittiesArray get(kitty_by_index): map u64 => T::Hash;
AllKittiesCount get(all_kitties_count): u64;
AllKittiesIndex: map T::Hash => u64;
OwnedKittiesArray get(kitty_of_owner_by_index): map (T::AccountId, u64) => T::Hash;
OwnedKittiesCount get(owned_kitty_count): map T::AccountId => u64;
OwnedKittiesIndex: map T::Hash => u64;
Nonce: u64;
}
}
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
fn deposit_event<T>() = default;
fn create_kitty(origin) -> Result {
let sender = ensure_signed(origin)?;
let nonce = <Nonce<T>>::get();
let random_hash = (<system::Module<T>>::random_seed(), &sender, nonce)
.using_encoded(<T as system::Trait>::Hashing::hash);
let new_kitty = Kitty {
id: random_hash,
dna: random_hash,
price: <T::Balance as As<u64>>::sa(0),
gen: 0,
};
Self::_mint(sender, random_hash, new_kitty)?;
<Nonce<T>>::mutate(|n| *n += 1);
Ok(())
}
}
}
impl<T: Trait> Module<T> {
fn _mint(to: T::AccountId, kitty_id: T::Hash, new_kitty: Kitty<T::Hash, T::Balance>) -> Result {
ensure!(!<KittyOwner<T>>::exists(kitty_id), "Kitty already exists");
let owned_kitty_count = Self::owned_kitty_count(&to);
let new_owned_kitty_count = owned_kitty_count.checked_add(1)
.ok_or("Overflow adding a new kitty to account balance")?;
let all_kitties_count = Self::all_kitties_count();
let new_all_kitties_count = all_kitties_count.checked_add(1)
.ok_or("Overflow adding a new kitty to total supply")?;
<Kitties<T>>::insert(kitty_id, new_kitty);
<KittyOwner<T>>::insert(kitty_id, &to);
<AllKittiesArray<T>>::insert(all_kitties_count, kitty_id);
<AllKittiesCount<T>>::put(new_all_kitties_count);
<AllKittiesIndex<T>>::insert(kitty_id, all_kitties_count);
<OwnedKittiesArray<T>>::insert((to.clone(), owned_kitty_count), kitty_id);
<OwnedKittiesCount<T>>::insert(&to, new_owned_kitty_count);
<OwnedKittiesIndex<T>>::insert(kitty_id, owned_kitty_count);
Self::deposit_event(RawEvent::Created(to, kitty_id));
Ok(())
}
} | 31.892157 | 100 | 0.607132 |
79ac22efccae4f51d32a672d907e89cf2a37c42e | 3,742 | extern crate clap;
extern crate serde_json;
extern crate jmespath;
use std::rc::Rc;
use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::process::exit;
use clap::{Arg, App};
use jmespath::Rcvar;
use jmespath::{Variable, compile};
macro_rules! die(
($msg:expr) => (
match writeln!(&mut ::std::io::stderr(), "{}", $msg) {
Ok(_) => exit(1),
Err(x) => panic!("Unable to write to stderr: {}", x),
}
)
);
fn main() {
let matches = App::new("jp")
.version("0.0.1")
.about("JMESPath command line interface")
.arg(Arg::with_name("filename")
.help("Read input JSON from a file instead of stdin.")
.short("f")
.takes_value(true)
.long("filename"))
.arg(Arg::with_name("unquoted")
.help("If the final result is a string, it will be printed without quotes.")
.short("u")
.long("unquoted")
.multiple(false))
.arg(Arg::with_name("ast")
.help("Only print the AST of the parsed expression. Do not rely on this output, \
only useful for debugging purposes.")
.long("ast")
.multiple(false))
.arg(Arg::with_name("expr-file")
.help("Read JMESPath expression from the specified file.")
.short("e")
.takes_value(true)
.long("expr-file")
.conflicts_with("expression")
.required(true))
.arg(Arg::with_name("expression")
.help("JMESPath expression to evaluate")
.index(1)
.conflicts_with("expr-file")
.required(true))
.get_matches();
let file_expression = matches.value_of("expr-file")
.map(|f| read_file("expression", f));
let expr = if let Some(ref e) = file_expression {
compile(e)
} else {
compile(matches.value_of("expression").unwrap())
}
.map_err(|e| die!(e.to_string()))
.unwrap();
if matches.is_present("ast") {
println!("{:#?}", expr.as_ast());
exit(0);
}
let json = Rc::new(get_json(matches.value_of("filename")));
match expr.search(&json) {
Err(e) => die!(e.to_string()),
Ok(result) => show_result(result, matches.is_present("unquoted")),
}
}
fn show_result(result: Rcvar, unquoted: bool) {
if unquoted && result.is_string() {
println!("{}", result.as_string().unwrap());
} else {
let mut out = io::stdout();
serde_json::to_writer_pretty(&mut out, &result)
.map(|_| out.write(&['\n' as u8]))
.map_err(|e| die!(format!("Error converting result to string: {}", e)))
.ok();
}
}
fn read_file(label: &str, filename: &str) -> String {
match File::open(filename) {
Err(e) => die!(format!("Error opening {} file at {}: {}", label, filename, e)),
Ok(mut file) => {
let mut buffer = String::new();
file.read_to_string(&mut buffer)
.map_err(|e| die!(format!("Error reading {} from {}: {}", label, filename, e)))
.map(|_| buffer)
.unwrap()
}
}
}
fn get_json(filename: Option<&str>) -> Variable {
let buffer = match filename {
Some(f) => read_file("JSON", f),
None => {
let mut buffer = String::new();
match io::stdin().read_to_string(&mut buffer) {
Ok(_) => buffer,
Err(e) => die!(format!("Error reading JSON from stdin: {}", e)),
}
}
};
Variable::from_json(&buffer)
.map_err(|e| die!(format!("Error parsing JSON: {}", e)))
.unwrap()
}
| 30.92562 | 95 | 0.519241 |
03180946b8d60c91d963f913cdceeae6de07687f | 838 | use colored::Colorize;
use std::fmt;
pub enum Response<T: fmt::Display> {
Wrong(T),
Weird(T),
Note(T),
}
use self::Response::*;
#[macro_export]
macro_rules! response {
( $( $r:expr ),+ ) => {{
$(
print!("{}", $r);
)*
println!();
}};
}
impl<T: fmt::Display> fmt::Display for Response<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (color, message_type, message) = match *self {
Wrong(ref m) => ("red", "wrong", m),
Weird(ref m) => ("yellow", "weird", m),
Note(ref m) => ("cyan", "note", m),
};
let message_type = format!("\n{}", message_type).color(color).bold();
let message = format!("{}", message);
let message = format!("{}: {}", message_type, message);
write!(f, "{}", message)
}
}
| 22.052632 | 77 | 0.49642 |
75125c12085a68166d253f08d030f1762187beb3 | 24,644 | #[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::C1SC {
#[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 = "Possible values of the field `DMA`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DMAR {
#[doc = "Disable DMA transfers."]
_0,
#[doc = "Enable DMA transfers."]
_1,
}
impl DMAR {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
DMAR::_0 => false,
DMAR::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> DMAR {
match value {
false => DMAR::_0,
true => DMAR::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == DMAR::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == DMAR::_1
}
}
#[doc = "Possible values of the field `ICRST`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ICRSTR {
#[doc = "FTM counter is not reset when the selected channel (n) input event is detected."]
_0,
#[doc = "FTM counter is reset when the selected channel (n) input event is detected."]
_1,
}
impl ICRSTR {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
ICRSTR::_0 => false,
ICRSTR::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> ICRSTR {
match value {
false => ICRSTR::_0,
true => ICRSTR::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == ICRSTR::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == ICRSTR::_1
}
}
#[doc = r" Value of the field"]
pub struct ELSAR {
bits: bool,
}
impl ELSAR {
#[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 ELSBR {
bits: bool,
}
impl ELSBR {
#[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 MSAR {
bits: bool,
}
impl MSAR {
#[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 MSBR {
bits: bool,
}
impl MSBR {
#[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 = "Possible values of the field `CHIE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CHIER {
#[doc = "Disable channel (n) interrupt. Use software polling."]
_0,
#[doc = "Enable channel (n) interrupt."]
_1,
}
impl CHIER {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
CHIER::_0 => false,
CHIER::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> CHIER {
match value {
false => CHIER::_0,
true => CHIER::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == CHIER::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == CHIER::_1
}
}
#[doc = "Possible values of the field `CHF`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CHFR {
#[doc = "No channel (n) event has occurred."]
_0,
#[doc = "A channel (n) event has occurred."]
_1,
}
impl CHFR {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
CHFR::_0 => false,
CHFR::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> CHFR {
match value {
false => CHFR::_0,
true => CHFR::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == CHFR::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == CHFR::_1
}
}
#[doc = "Possible values of the field `TRIGMODE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TRIGMODER {
#[doc = "Channel outputs will generate the normal PWM outputs without generating a pulse."]
_0,
#[doc = "If a match in the channel occurs, a trigger generation on channel output will happen. The trigger pulse width has one FTM clock cycle."]
_1,
}
impl TRIGMODER {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
TRIGMODER::_0 => false,
TRIGMODER::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> TRIGMODER {
match value {
false => TRIGMODER::_0,
true => TRIGMODER::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == TRIGMODER::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == TRIGMODER::_1
}
}
#[doc = "Possible values of the field `CHIS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CHISR {
#[doc = "The channel (n) input is zero."]
_0,
#[doc = "The channel (n) input is one."]
_1,
}
impl CHISR {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
CHISR::_0 => false,
CHISR::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> CHISR {
match value {
false => CHISR::_0,
true => CHISR::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == CHISR::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == CHISR::_1
}
}
#[doc = "Possible values of the field `CHOV`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CHOVR {
#[doc = "The channel (n) output is zero."]
_0,
#[doc = "The channel (n) output is one."]
_1,
}
impl CHOVR {
#[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 as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
CHOVR::_0 => false,
CHOVR::_1 => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> CHOVR {
match value {
false => CHOVR::_0,
true => CHOVR::_1,
}
}
#[doc = "Checks if the value of the field is `_0`"]
#[inline]
pub fn is_0(&self) -> bool {
*self == CHOVR::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline]
pub fn is_1(&self) -> bool {
*self == CHOVR::_1
}
}
#[doc = "Values that can be written to the field `DMA`"]
pub enum DMAW {
#[doc = "Disable DMA transfers."]
_0,
#[doc = "Enable DMA transfers."]
_1,
}
impl DMAW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
DMAW::_0 => false,
DMAW::_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _DMAW<'a> {
w: &'a mut W,
}
impl<'a> _DMAW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: DMAW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable DMA transfers."]
#[inline]
pub fn _0(self) -> &'a mut W {
self.variant(DMAW::_0)
}
#[doc = "Enable DMA transfers."]
#[inline]
pub fn _1(self) -> &'a mut W {
self.variant(DMAW::_1)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `ICRST`"]
pub enum ICRSTW {
#[doc = "FTM counter is not reset when the selected channel (n) input event is detected."]
_0,
#[doc = "FTM counter is reset when the selected channel (n) input event is detected."]
_1,
}
impl ICRSTW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
ICRSTW::_0 => false,
ICRSTW::_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _ICRSTW<'a> {
w: &'a mut W,
}
impl<'a> _ICRSTW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: ICRSTW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "FTM counter is not reset when the selected channel (n) input event is detected."]
#[inline]
pub fn _0(self) -> &'a mut W {
self.variant(ICRSTW::_0)
}
#[doc = "FTM counter is reset when the selected channel (n) input event is detected."]
#[inline]
pub fn _1(self) -> &'a mut W {
self.variant(ICRSTW::_1)
}
#[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 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _ELSAW<'a> {
w: &'a mut W,
}
impl<'a> _ELSAW<'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 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _ELSBW<'a> {
w: &'a mut W,
}
impl<'a> _ELSBW<'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 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _MSAW<'a> {
w: &'a mut W,
}
impl<'a> _MSAW<'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 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _MSBW<'a> {
w: &'a mut W,
}
impl<'a> _MSBW<'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 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `CHIE`"]
pub enum CHIEW {
#[doc = "Disable channel (n) interrupt. Use software polling."]
_0,
#[doc = "Enable channel (n) interrupt."]
_1,
}
impl CHIEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
CHIEW::_0 => false,
CHIEW::_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _CHIEW<'a> {
w: &'a mut W,
}
impl<'a> _CHIEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CHIEW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Disable channel (n) interrupt. Use software polling."]
#[inline]
pub fn _0(self) -> &'a mut W {
self.variant(CHIEW::_0)
}
#[doc = "Enable channel (n) interrupt."]
#[inline]
pub fn _1(self) -> &'a mut W {
self.variant(CHIEW::_1)
}
#[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 = "Values that can be written to the field `TRIGMODE`"]
pub enum TRIGMODEW {
#[doc = "Channel outputs will generate the normal PWM outputs without generating a pulse."]
_0,
#[doc = "If a match in the channel occurs, a trigger generation on channel output will happen. The trigger pulse width has one FTM clock cycle."]
_1,
}
impl TRIGMODEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
TRIGMODEW::_0 => false,
TRIGMODEW::_1 => true,
}
}
}
#[doc = r" Proxy"]
pub struct _TRIGMODEW<'a> {
w: &'a mut W,
}
impl<'a> _TRIGMODEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: TRIGMODEW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Channel outputs will generate the normal PWM outputs without generating a pulse."]
#[inline]
pub fn _0(self) -> &'a mut W {
self.variant(TRIGMODEW::_0)
}
#[doc = "If a match in the channel occurs, a trigger generation on channel output will happen. The trigger pulse width has one FTM clock cycle."]
#[inline]
pub fn _1(self) -> &'a mut W {
self.variant(TRIGMODEW::_1)
}
#[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 = 8;
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 = "Bit 0 - DMA Enable"]
#[inline]
pub fn dma(&self) -> DMAR {
DMAR::_from({
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 1 - FTM counter reset by the selected input capture event."]
#[inline]
pub fn icrst(&self) -> ICRSTR {
ICRSTR::_from({
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 2 - Channel (n) Edge or Level Select"]
#[inline]
pub fn elsa(&self) -> ELSAR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
};
ELSAR { bits }
}
#[doc = "Bit 3 - Channel (n) Edge or Level Select"]
#[inline]
pub fn elsb(&self) -> ELSBR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
};
ELSBR { bits }
}
#[doc = "Bit 4 - Channel (n) Mode Select"]
#[inline]
pub fn msa(&self) -> MSAR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
};
MSAR { bits }
}
#[doc = "Bit 5 - Channel (n) Mode Select"]
#[inline]
pub fn msb(&self) -> MSBR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
};
MSBR { bits }
}
#[doc = "Bit 6 - Channel (n) Interrupt Enable"]
#[inline]
pub fn chie(&self) -> CHIER {
CHIER::_from({
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 7 - Channel (n) Flag"]
#[inline]
pub fn chf(&self) -> CHFR {
CHFR::_from({
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 8 - Trigger mode control"]
#[inline]
pub fn trigmode(&self) -> TRIGMODER {
TRIGMODER::_from({
const MASK: bool = true;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 9 - Channel (n) Input State"]
#[inline]
pub fn chis(&self) -> CHISR {
CHISR::_from({
const MASK: bool = true;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 10 - Channel (n) Output Value"]
#[inline]
pub fn chov(&self) -> CHOVR {
CHOVR::_from({
const MASK: bool = true;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 0 - DMA Enable"]
#[inline]
pub fn dma(&mut self) -> _DMAW {
_DMAW { w: self }
}
#[doc = "Bit 1 - FTM counter reset by the selected input capture event."]
#[inline]
pub fn icrst(&mut self) -> _ICRSTW {
_ICRSTW { w: self }
}
#[doc = "Bit 2 - Channel (n) Edge or Level Select"]
#[inline]
pub fn elsa(&mut self) -> _ELSAW {
_ELSAW { w: self }
}
#[doc = "Bit 3 - Channel (n) Edge or Level Select"]
#[inline]
pub fn elsb(&mut self) -> _ELSBW {
_ELSBW { w: self }
}
#[doc = "Bit 4 - Channel (n) Mode Select"]
#[inline]
pub fn msa(&mut self) -> _MSAW {
_MSAW { w: self }
}
#[doc = "Bit 5 - Channel (n) Mode Select"]
#[inline]
pub fn msb(&mut self) -> _MSBW {
_MSBW { w: self }
}
#[doc = "Bit 6 - Channel (n) Interrupt Enable"]
#[inline]
pub fn chie(&mut self) -> _CHIEW {
_CHIEW { w: self }
}
#[doc = "Bit 8 - Trigger mode control"]
#[inline]
pub fn trigmode(&mut self) -> _TRIGMODEW {
_TRIGMODEW { w: self }
}
}
| 26.133616 | 149 | 0.501583 |
21a6d1712d0b36c781022682e68b8a7c4171e88b | 12,384 | // Copyright 2022 Cargill Incorporated
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::BatchTrackingStoreOperations;
use crate::error::InternalError;
use crate::batch_tracking::store::diesel::{
models::{
BatchModel, BatchStatusModel, SubmissionModel, TransactionModel, TransactionReceiptModel,
},
schema::{batch_statuses, batches, submissions, transaction_receipts, transactions},
BatchStatus, InvalidTransaction, SubmissionError, TrackingBatch, TrackingTransaction,
TransactionReceipt, ValidTransaction,
};
use crate::batch_tracking::store::BatchTrackingStoreError;
use diesel::prelude::*;
use std::convert::TryFrom;
pub(in crate::batch_tracking::store::diesel) trait BatchTrackingStoreGetBatchOperation {
fn get_batch(
&self,
id: &str,
service_id: &str,
) -> Result<Option<TrackingBatch>, BatchTrackingStoreError>;
}
#[cfg(feature = "postgres")]
impl<'a> BatchTrackingStoreGetBatchOperation
for BatchTrackingStoreOperations<'a, diesel::pg::PgConnection>
{
fn get_batch(
&self,
id: &str,
service_id: &str,
) -> Result<Option<TrackingBatch>, BatchTrackingStoreError> {
self.conn.transaction::<_, BatchTrackingStoreError, _>(|| {
// This performs a query to select all columns from the batches,
// batch_statuses, and submissions tables joined on the batch_id
// column. These rows are then filtered on the batch_id.
let query = batches::table
.into_boxed()
.left_join(
batch_statuses::table.on(batches::batch_id
.eq(batch_statuses::batch_id)
.and(batches::service_id.eq(batch_statuses::service_id))),
)
.left_join(
submissions::table.on(batches::batch_id
.eq(submissions::batch_id)
.and(batches::service_id.eq(submissions::service_id))),
)
.filter(
batches::batch_id
.eq(&id)
.and(batches::service_id.eq(&service_id)),
)
.select((
batches::all_columns,
batch_statuses::all_columns.nullable(),
submissions::all_columns.nullable(),
));
// Diesel will deserialize the joined results into the respective
// models for the tables in the join.
let batch_result: Option<(
BatchModel,
Option<BatchStatusModel>,
Option<SubmissionModel>,
)> = query
.first::<(
BatchModel,
Option<BatchStatusModel>,
Option<SubmissionModel>,
)>(self.conn)
.optional()
.map_err(|err| {
BatchTrackingStoreError::InternalError(InternalError::from_source(Box::new(
err,
)))
})?;
// This query is used to fetch the transactions for a given batch
// ID. These will be used to construct the `TrackingBatch` struct
// that is returned to the user and to fetch transaction receipts.
let query = transactions::table
.into_boxed()
.select(transactions::all_columns)
.filter(
transactions::batch_id
.eq(&id)
.and(transactions::service_id.eq(&service_id)),
);
let txn_models: Vec<TransactionModel> =
query.load::<TransactionModel>(self.conn).map_err(|err| {
BatchTrackingStoreError::InternalError(InternalError::from_source(Box::new(
err,
)))
})?;
let mut txns = Vec::new();
let mut txn_ids = Vec::new();
let mut valid_txns = Vec::new();
let mut invalid_txns = Vec::new();
for t in txn_models {
txns.push(TrackingTransaction::from(&t));
txn_ids.push(t.transaction_id.to_string());
}
// This query fetches the transaction receipts for the transactions
// in the batch. These are used to build the valid and invalid
// transaction structs that are used to build the batch status.
let query = transaction_receipts::table
.into_boxed()
.filter(transaction_receipts::transaction_id.eq_any(txn_ids));
let receipt_results: Vec<TransactionReceiptModel> = query
.load::<TransactionReceiptModel>(self.conn)
.map_err(|err| {
BatchTrackingStoreError::InternalError(InternalError::from_source(Box::new(
err,
)))
})?;
for rcpt in receipt_results {
if rcpt.result_valid {
valid_txns.push(ValidTransaction::try_from(TransactionReceipt::from(rcpt))?);
} else {
invalid_txns.push(InvalidTransaction::try_from(TransactionReceipt::from(
rcpt,
))?);
}
}
if let Some(res) = batch_result {
let (b, stat, sub) = res;
{
let sub_err: Option<SubmissionError> = if let Some(sub) = sub {
if sub.error_type.is_some() && sub.error_message.is_some() {
Some(SubmissionError::try_from(&sub)?)
} else {
None
}
} else {
None
};
let status = if let Some(s) = stat {
let grid_status = BatchStatus::try_from((s, invalid_txns, valid_txns))?;
Some(grid_status)
} else {
None
};
return Ok(Some(TrackingBatch::from((b, txns, status, sub_err))));
}
}
Ok(None)
})
}
}
#[cfg(feature = "sqlite")]
impl<'a> BatchTrackingStoreGetBatchOperation
for BatchTrackingStoreOperations<'a, diesel::sqlite::SqliteConnection>
{
fn get_batch(
&self,
id: &str,
service_id: &str,
) -> Result<Option<TrackingBatch>, BatchTrackingStoreError> {
self.conn.transaction::<_, BatchTrackingStoreError, _>(|| {
// This performs a query to select all columns from the batches,
// batch_statuses, and submissions tables joined on the batch_id
// column. These rows are then filtered on the batch_id.
let query = batches::table
.into_boxed()
.left_join(
batch_statuses::table.on(batches::batch_id
.eq(batch_statuses::batch_id)
.and(batches::service_id.eq(batch_statuses::service_id))),
)
.left_join(
submissions::table.on(batches::batch_id
.eq(submissions::batch_id)
.and(batches::service_id.eq(submissions::service_id))),
)
.filter(
batches::batch_id
.eq(&id)
.and(batches::service_id.eq(&service_id)),
)
.select((
batches::all_columns,
batch_statuses::all_columns.nullable(),
submissions::all_columns.nullable(),
));
// Diesel will deserialize the joined results into the respective
// models for the tables in the join.
let batch_result: Option<(
BatchModel,
Option<BatchStatusModel>,
Option<SubmissionModel>,
)> = query
.first::<(
BatchModel,
Option<BatchStatusModel>,
Option<SubmissionModel>,
)>(self.conn)
.optional()
.map_err(|err| {
BatchTrackingStoreError::InternalError(InternalError::from_source(Box::new(
err,
)))
})?;
// This query is used to fetch the transactions for a given batch
// ID. These will be used to construct the `TrackingBatch` struct
// that is returned to the user and to fetch transaction receipts.
let query = transactions::table
.into_boxed()
.select(transactions::all_columns)
.filter(
transactions::batch_id
.eq(&id)
.and(transactions::service_id.eq(&service_id)),
);
let txn_models: Vec<TransactionModel> =
query.load::<TransactionModel>(self.conn).map_err(|err| {
BatchTrackingStoreError::InternalError(InternalError::from_source(Box::new(
err,
)))
})?;
let mut txns = Vec::new();
let mut txn_ids = Vec::new();
let mut valid_txns = Vec::new();
let mut invalid_txns = Vec::new();
for t in txn_models {
txns.push(TrackingTransaction::from(&t));
txn_ids.push(t.transaction_id.to_string());
}
// This query fetches the transaction receipts for the transactions
// in the batch. These are used to build the valid and invalid
// transaction structs that are used to build the batch status.
let query = transaction_receipts::table
.into_boxed()
.filter(transaction_receipts::transaction_id.eq_any(txn_ids));
let receipt_results: Vec<TransactionReceiptModel> = query
.load::<TransactionReceiptModel>(self.conn)
.map_err(|err| {
BatchTrackingStoreError::InternalError(InternalError::from_source(Box::new(
err,
)))
})?;
for rcpt in receipt_results {
if rcpt.result_valid {
valid_txns.push(ValidTransaction::try_from(TransactionReceipt::from(rcpt))?);
} else {
invalid_txns.push(InvalidTransaction::try_from(TransactionReceipt::from(
rcpt,
))?);
}
}
if let Some(res) = batch_result {
let (b, stat, sub) = res;
{
let sub_err: Option<SubmissionError> = if let Some(sub) = sub {
if sub.error_type.is_some() && sub.error_message.is_some() {
Some(SubmissionError::try_from(&sub)?)
} else {
None
}
} else {
None
};
let status = if let Some(s) = stat {
let grid_status = BatchStatus::try_from((s, invalid_txns, valid_txns))?;
Some(grid_status)
} else {
None
};
return Ok(Some(TrackingBatch::from((b, txns, status, sub_err))));
}
}
Ok(None)
})
}
}
| 39.43949 | 97 | 0.50541 |
ddd0bc306101fff1f5c1b3f1e0ca38e63838800e | 1,176 | use std::prelude::v1::*;
use {
super::{error::ValueError, Value},
crate::{
executor::GroupKey,
result::{Error, Result},
},
std::convert::TryInto,
};
impl TryInto<GroupKey> for Value {
type Error = Error;
fn try_into(self) -> Result<GroupKey> {
use Value::*;
match self {
Bool(v) => Ok(GroupKey::Bool(v)),
I64(v) => Ok(GroupKey::I64(v)),
Str(v) => Ok(GroupKey::Str(v)),
Date(v) => Ok(GroupKey::Date(v)),
Timestamp(v) => Ok(GroupKey::Timestamp(v)),
Time(v) => Ok(GroupKey::Time(v)),
Interval(v) => Ok(GroupKey::Interval(v)),
Uuid(v) => Ok(GroupKey::Uuid(v)),
Null => Ok(GroupKey::None),
F64(_) => Err(ValueError::GroupByNotSupported("FLOAT".to_owned()).into()),
Map(_) => Err(ValueError::GroupByNotSupported("MAP".to_owned()).into()),
List(_) => Err(ValueError::GroupByNotSupported("LIST".to_owned()).into()),
}
}
}
impl TryInto<GroupKey> for &Value {
type Error = Error;
fn try_into(self) -> Result<GroupKey> {
self.clone().try_into()
}
}
| 28 | 86 | 0.526361 |
b9afc2311a299f95d8e93791b5ee3e00c8933fda | 32,206 | //! A library for generating a message from a sequence of instructions
use crate::sanitize::{Sanitize, SanitizeError};
use crate::serialize_utils::{
append_slice, append_u16, append_u8, read_pubkey, read_slice, read_u16, read_u8,
};
use crate::{
hash::Hash,
instruction::{AccountMeta, CompiledInstruction, Instruction},
pubkey::Pubkey,
short_vec, system_instruction,
};
use itertools::Itertools;
use std::convert::TryFrom;
fn position(keys: &[Pubkey], key: &Pubkey) -> u8 {
keys.iter().position(|k| k == key).unwrap() as u8
}
fn compile_instruction(ix: &Instruction, keys: &[Pubkey]) -> CompiledInstruction {
let accounts: Vec<_> = ix
.accounts
.iter()
.map(|account_meta| position(keys, &account_meta.pubkey))
.collect();
CompiledInstruction {
program_id_index: position(keys, &ix.program_id),
data: ix.data.clone(),
accounts,
}
}
fn compile_instructions(ixs: &[Instruction], keys: &[Pubkey]) -> Vec<CompiledInstruction> {
ixs.iter().map(|ix| compile_instruction(ix, keys)).collect()
}
/// A helper struct to collect pubkeys referenced by a set of instructions and read-only counts
#[derive(Debug, PartialEq, Eq)]
struct InstructionKeys {
pub signed_keys: Vec<Pubkey>,
pub unsigned_keys: Vec<Pubkey>,
pub num_readonly_signed_accounts: u8,
pub num_readonly_unsigned_accounts: u8,
}
impl InstructionKeys {
fn new(
signed_keys: Vec<Pubkey>,
unsigned_keys: Vec<Pubkey>,
num_readonly_signed_accounts: u8,
num_readonly_unsigned_accounts: u8,
) -> Self {
Self {
signed_keys,
unsigned_keys,
num_readonly_signed_accounts,
num_readonly_unsigned_accounts,
}
}
}
/// Return pubkeys referenced by all instructions, with the ones needing signatures first. If the
/// payer key is provided, it is always placed first in the list of signed keys. Read-only signed
/// accounts are placed last in the set of signed accounts. Read-only unsigned accounts,
/// including program ids, are placed last in the set. No duplicates and order is preserved.
fn get_keys(instructions: &[Instruction], payer: Option<&Pubkey>) -> InstructionKeys {
let programs: Vec<_> = get_program_ids(instructions)
.iter()
.map(|program_id| AccountMeta {
pubkey: *program_id,
is_signer: false,
is_writable: false,
})
.collect();
let mut keys_and_signed: Vec<_> = instructions
.iter()
.flat_map(|ix| ix.accounts.iter())
.collect();
keys_and_signed.extend(&programs);
keys_and_signed.sort_by(|x, y| {
y.is_signer
.cmp(&x.is_signer)
.then(y.is_writable.cmp(&x.is_writable))
});
let payer_account_meta;
if let Some(payer) = payer {
payer_account_meta = AccountMeta {
pubkey: *payer,
is_signer: true,
is_writable: true,
};
keys_and_signed.insert(0, &payer_account_meta);
}
let mut unique_metas: Vec<AccountMeta> = vec![];
for account_meta in keys_and_signed {
// Promote to writable if a later AccountMeta requires it
if let Some(x) = unique_metas
.iter_mut()
.find(|x| x.pubkey == account_meta.pubkey)
{
x.is_writable |= account_meta.is_writable;
continue;
}
unique_metas.push(account_meta.clone());
}
let mut signed_keys = vec![];
let mut unsigned_keys = vec![];
let mut num_readonly_signed_accounts = 0;
let mut num_readonly_unsigned_accounts = 0;
for account_meta in unique_metas {
if account_meta.is_signer {
signed_keys.push(account_meta.pubkey);
if !account_meta.is_writable {
num_readonly_signed_accounts += 1;
}
} else {
unsigned_keys.push(account_meta.pubkey);
if !account_meta.is_writable {
num_readonly_unsigned_accounts += 1;
}
}
}
InstructionKeys::new(
signed_keys,
unsigned_keys,
num_readonly_signed_accounts,
num_readonly_unsigned_accounts,
)
}
/// Return program ids referenced by all instructions. No duplicates and order is preserved.
fn get_program_ids(instructions: &[Instruction]) -> Vec<Pubkey> {
instructions
.iter()
.map(|ix| ix.program_id)
.unique()
.collect()
}
#[frozen_abi(digest = "BVC5RhetsNpheGipt5rUrkR6RDDUHtD5sCLK1UjymL4S")]
#[derive(Serialize, Deserialize, Default, Debug, PartialEq, Eq, Clone, AbiExample)]
#[serde(rename_all = "camelCase")]
pub struct MessageHeader {
/// The number of signatures required for this message to be considered valid. The
/// signatures must match the first `num_required_signatures` of `account_keys`.
/// NOTE: Serialization-related changes must be paired with the direct read at sigverify.
pub num_required_signatures: u8,
/// The last num_readonly_signed_accounts of the signed keys are read-only accounts. Programs
/// may process multiple transactions that load read-only accounts within a single PoH entry,
/// but are not permitted to credit or debit lamports or modify account data. Transactions
/// targeting the same read-write account are evaluated sequentially.
pub num_readonly_signed_accounts: u8,
/// The last num_readonly_unsigned_accounts of the unsigned keys are read-only accounts.
pub num_readonly_unsigned_accounts: u8,
}
#[frozen_abi(digest = "BPBJZxpRQ4JS7LGJtsgoyctg4BXyBbbY4uc7FjowtxLV")]
#[derive(Serialize, Deserialize, Default, Debug, PartialEq, Eq, Clone, AbiExample)]
#[serde(rename_all = "camelCase")]
pub struct Message {
/// The message header, identifying signed and read-only `account_keys`
/// NOTE: Serialization-related changes must be paired with the direct read at sigverify.
pub header: MessageHeader,
/// All the account keys used by this transaction
#[serde(with = "short_vec")]
pub account_keys: Vec<Pubkey>,
/// The id of a recent ledger entry.
pub recent_blockhash: Hash,
/// Programs that will be executed in sequence and committed in one atomic transaction if all
/// succeed.
#[serde(with = "short_vec")]
pub instructions: Vec<CompiledInstruction>,
}
impl Sanitize for Message {
fn sanitize(&self) -> std::result::Result<(), SanitizeError> {
// signing area and read-only non-signing area should not overlap
if self.header.num_required_signatures as usize
+ self.header.num_readonly_unsigned_accounts as usize
> self.account_keys.len()
{
return Err(SanitizeError::IndexOutOfBounds);
}
// there should be at least 1 RW fee-payer account.
if self.header.num_readonly_signed_accounts >= self.header.num_required_signatures {
return Err(SanitizeError::IndexOutOfBounds);
}
for ci in &self.instructions {
if ci.program_id_index as usize >= self.account_keys.len() {
return Err(SanitizeError::IndexOutOfBounds);
}
// A program cannot be a payer.
if ci.program_id_index == 0 {
return Err(SanitizeError::IndexOutOfBounds);
}
for ai in &ci.accounts {
if *ai as usize >= self.account_keys.len() {
return Err(SanitizeError::IndexOutOfBounds);
}
}
}
self.account_keys.sanitize()?;
self.recent_blockhash.sanitize()?;
self.instructions.sanitize()?;
Ok(())
}
}
impl Message {
pub fn new_with_compiled_instructions(
num_required_signatures: u8,
num_readonly_signed_accounts: u8,
num_readonly_unsigned_accounts: u8,
account_keys: Vec<Pubkey>,
recent_blockhash: Hash,
instructions: Vec<CompiledInstruction>,
) -> Self {
Self {
header: MessageHeader {
num_required_signatures,
num_readonly_signed_accounts,
num_readonly_unsigned_accounts,
},
account_keys,
recent_blockhash,
instructions,
}
}
pub fn new(instructions: &[Instruction], payer: Option<&Pubkey>) -> Self {
let InstructionKeys {
mut signed_keys,
unsigned_keys,
num_readonly_signed_accounts,
num_readonly_unsigned_accounts,
} = get_keys(instructions, payer);
let num_required_signatures = signed_keys.len() as u8;
signed_keys.extend(&unsigned_keys);
let instructions = compile_instructions(instructions, &signed_keys);
Self::new_with_compiled_instructions(
num_required_signatures,
num_readonly_signed_accounts,
num_readonly_unsigned_accounts,
signed_keys,
Hash::default(),
instructions,
)
}
pub fn new_with_nonce(
mut instructions: Vec<Instruction>,
payer: Option<&Pubkey>,
nonce_account_pubkey: &Pubkey,
nonce_authority_pubkey: &Pubkey,
) -> Self {
let nonce_ix = system_instruction::advance_nonce_account(
&nonce_account_pubkey,
&nonce_authority_pubkey,
);
instructions.insert(0, nonce_ix);
Self::new(&instructions, payer)
}
pub fn compile_instruction(&self, ix: &Instruction) -> CompiledInstruction {
compile_instruction(ix, &self.account_keys)
}
pub fn serialize(&self) -> Vec<u8> {
bincode::serialize(self).unwrap()
}
pub fn program_id(&self, instruction_index: usize) -> Option<&Pubkey> {
Some(
&self.account_keys[self.instructions.get(instruction_index)?.program_id_index as usize],
)
}
pub fn program_index(&self, instruction_index: usize) -> Option<usize> {
Some(self.instructions.get(instruction_index)?.program_id_index as usize)
}
pub fn program_ids(&self) -> Vec<&Pubkey> {
self.instructions
.iter()
.map(|ix| &self.account_keys[ix.program_id_index as usize])
.collect()
}
pub fn is_key_passed_to_program(&self, index: usize) -> bool {
if let Ok(index) = u8::try_from(index) {
for ix in self.instructions.iter() {
if ix.accounts.contains(&index) {
return true;
}
}
}
false
}
pub fn is_non_loader_key(&self, key: &Pubkey, key_index: usize) -> bool {
!self.program_ids().contains(&key) || self.is_key_passed_to_program(key_index)
}
pub fn program_position(&self, index: usize) -> Option<usize> {
let program_ids = self.program_ids();
program_ids
.iter()
.position(|&&pubkey| pubkey == self.account_keys[index])
}
pub fn is_writable(&self, i: usize) -> bool {
i < (self.header.num_required_signatures - self.header.num_readonly_signed_accounts)
as usize
|| (i >= self.header.num_required_signatures as usize
&& i < self.account_keys.len()
- self.header.num_readonly_unsigned_accounts as usize)
}
pub fn is_signer(&self, i: usize) -> bool {
i < self.header.num_required_signatures as usize
}
pub fn get_account_keys_by_lock_type(&self) -> (Vec<&Pubkey>, Vec<&Pubkey>) {
let mut writable_keys = vec![];
let mut readonly_keys = vec![];
for (i, key) in self.account_keys.iter().enumerate() {
if self.is_writable(i) {
writable_keys.push(key);
} else {
readonly_keys.push(key);
}
}
(writable_keys, readonly_keys)
}
// First encode the number of instructions:
// [0..2 - num_instructions
//
// Then a table of offsets of where to find them in the data
// 3..2*num_instructions table of instruction offsets
//
// Each instruction is then encoded as:
// 0..2 - num_accounts
// 3 - meta_byte -> (bit 0 signer, bit 1 is_writable)
// 4..36 - pubkey - 32 bytes
// 36..64 - program_id
// 33..34 - data len - u16
// 35..data_len - data
pub fn serialize_instructions(&self) -> Vec<u8> {
// 64 bytes is a reasonable guess, calculating exactly is slower in benchmarks
let mut data = Vec::with_capacity(self.instructions.len() * (32 * 2));
append_u16(&mut data, self.instructions.len() as u16);
for _ in 0..self.instructions.len() {
append_u16(&mut data, 0);
}
for (i, instruction) in self.instructions.iter().enumerate() {
let start_instruction_offset = data.len() as u16;
let start = 2 + (2 * i);
data[start..start + 2].copy_from_slice(&start_instruction_offset.to_le_bytes());
append_u16(&mut data, instruction.accounts.len() as u16);
for account_index in &instruction.accounts {
let account_index = *account_index as usize;
let is_signer = self.is_signer(account_index);
let is_writable = self.is_writable(account_index);
let mut meta_byte = 0;
if is_signer {
meta_byte |= 1 << Self::IS_SIGNER_BIT;
}
if is_writable {
meta_byte |= 1 << Self::IS_WRITABLE_BIT;
}
append_u8(&mut data, meta_byte);
append_slice(&mut data, self.account_keys[account_index].as_ref());
}
let program_id = &self.account_keys[instruction.program_id_index as usize];
append_slice(&mut data, program_id.as_ref());
append_u16(&mut data, instruction.data.len() as u16);
append_slice(&mut data, &instruction.data);
}
data
}
const IS_SIGNER_BIT: usize = 0;
const IS_WRITABLE_BIT: usize = 1;
pub fn deserialize_instruction(
index: usize,
data: &[u8],
) -> Result<Instruction, SanitizeError> {
let mut current = 0;
let _num_instructions = read_u16(&mut current, &data)?;
// index into the instruction byte-offset table.
current += index * 2;
let start = read_u16(&mut current, &data)?;
current = start as usize;
let num_accounts = read_u16(&mut current, &data)?;
let mut accounts = Vec::with_capacity(num_accounts as usize);
for _ in 0..num_accounts {
let meta_byte = read_u8(&mut current, &data)?;
let mut is_signer = false;
let mut is_writable = false;
if meta_byte & (1 << Self::IS_SIGNER_BIT) != 0 {
is_signer = true;
}
if meta_byte & (1 << Self::IS_WRITABLE_BIT) != 0 {
is_writable = true;
}
let pubkey = read_pubkey(&mut current, &data)?;
accounts.push(AccountMeta {
pubkey,
is_signer,
is_writable,
});
}
let program_id = read_pubkey(&mut current, &data)?;
let data_len = read_u16(&mut current, &data)?;
let data = read_slice(&mut current, &data, data_len as usize)?;
Ok(Instruction {
program_id,
data,
accounts,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::instruction::AccountMeta;
#[test]
fn test_message_unique_program_ids() {
let program_id0 = Pubkey::default();
let program_ids = get_program_ids(&[
Instruction::new_with_bincode(program_id0, &0, vec![]),
Instruction::new_with_bincode(program_id0, &0, vec![]),
]);
assert_eq!(program_ids, vec![program_id0]);
}
#[test]
fn test_message_unique_program_ids_not_adjacent() {
let program_id0 = Pubkey::default();
let program_id1 = Pubkey::new_unique();
let program_ids = get_program_ids(&[
Instruction::new_with_bincode(program_id0, &0, vec![]),
Instruction::new_with_bincode(program_id1, &0, vec![]),
Instruction::new_with_bincode(program_id0, &0, vec![]),
]);
assert_eq!(program_ids, vec![program_id0, program_id1]);
}
#[test]
fn test_message_unique_program_ids_order_preserved() {
let program_id0 = Pubkey::new_unique();
let program_id1 = Pubkey::default(); // Key less than program_id0
let program_ids = get_program_ids(&[
Instruction::new_with_bincode(program_id0, &0, vec![]),
Instruction::new_with_bincode(program_id1, &0, vec![]),
Instruction::new_with_bincode(program_id0, &0, vec![]),
]);
assert_eq!(program_ids, vec![program_id0, program_id1]);
}
#[test]
fn test_message_unique_keys_both_signed() {
let program_id = Pubkey::default();
let id0 = Pubkey::default();
let keys = get_keys(
&[
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, true)]),
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, true)]),
],
None,
);
assert_eq!(keys, InstructionKeys::new(vec![id0], vec![], 0, 0));
}
#[test]
fn test_message_unique_keys_signed_and_payer() {
let program_id = Pubkey::default();
let id0 = Pubkey::default();
let keys = get_keys(
&[Instruction::new_with_bincode(
program_id,
&0,
vec![AccountMeta::new(id0, true)],
)],
Some(&id0),
);
assert_eq!(keys, InstructionKeys::new(vec![id0], vec![], 0, 0));
}
#[test]
fn test_message_unique_keys_unsigned_and_payer() {
let program_id = Pubkey::default();
let id0 = Pubkey::default();
let keys = get_keys(
&[Instruction::new_with_bincode(
program_id,
&0,
vec![AccountMeta::new(id0, false)],
)],
Some(&id0),
);
assert_eq!(keys, InstructionKeys::new(vec![id0], vec![], 0, 0));
}
#[test]
fn test_message_unique_keys_one_signed() {
let program_id = Pubkey::default();
let id0 = Pubkey::default();
let keys = get_keys(
&[
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, false)]),
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, true)]),
],
None,
);
assert_eq!(keys, InstructionKeys::new(vec![id0], vec![], 0, 0));
}
#[test]
fn test_message_unique_keys_one_readonly_signed() {
let program_id = Pubkey::default();
let id0 = Pubkey::default();
let keys = get_keys(
&[
Instruction::new_with_bincode(
program_id,
&0,
vec![AccountMeta::new_readonly(id0, true)],
),
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, true)]),
],
None,
);
// Ensure the key is no longer readonly
assert_eq!(keys, InstructionKeys::new(vec![id0], vec![], 0, 0));
}
#[test]
fn test_message_unique_keys_one_readonly_unsigned() {
let program_id = Pubkey::default();
let id0 = Pubkey::default();
let keys = get_keys(
&[
Instruction::new_with_bincode(
program_id,
&0,
vec![AccountMeta::new_readonly(id0, false)],
),
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, false)]),
],
None,
);
// Ensure the key is no longer readonly
assert_eq!(keys, InstructionKeys::new(vec![], vec![id0], 0, 0));
}
#[test]
fn test_message_unique_keys_order_preserved() {
let program_id = Pubkey::default();
let id0 = Pubkey::new_unique();
let id1 = Pubkey::default(); // Key less than id0
let keys = get_keys(
&[
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, false)]),
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id1, false)]),
],
None,
);
assert_eq!(keys, InstructionKeys::new(vec![], vec![id0, id1], 0, 0));
}
#[test]
fn test_message_unique_keys_not_adjacent() {
let program_id = Pubkey::default();
let id0 = Pubkey::default();
let id1 = Pubkey::new_unique();
let keys = get_keys(
&[
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, false)]),
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id1, false)]),
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, true)]),
],
None,
);
assert_eq!(keys, InstructionKeys::new(vec![id0], vec![id1], 0, 0));
}
#[test]
fn test_message_signed_keys_first() {
let program_id = Pubkey::default();
let id0 = Pubkey::default();
let id1 = Pubkey::new_unique();
let keys = get_keys(
&[
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, false)]),
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id1, true)]),
],
None,
);
assert_eq!(keys, InstructionKeys::new(vec![id1], vec![id0], 0, 0));
}
#[test]
// Ensure there's a way to calculate the number of required signatures.
fn test_message_signed_keys_len() {
let program_id = Pubkey::default();
let id0 = Pubkey::default();
let ix = Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, false)]);
let message = Message::new(&[ix], None);
assert_eq!(message.header.num_required_signatures, 0);
let ix = Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, true)]);
let message = Message::new(&[ix], Some(&id0));
assert_eq!(message.header.num_required_signatures, 1);
}
#[test]
fn test_message_readonly_keys_last() {
let program_id = Pubkey::default();
let id0 = Pubkey::default(); // Identical key/program_id should be de-duped
let id1 = Pubkey::new_unique();
let id2 = Pubkey::new_unique();
let id3 = Pubkey::new_unique();
let keys = get_keys(
&[
Instruction::new_with_bincode(
program_id,
&0,
vec![AccountMeta::new_readonly(id0, false)],
),
Instruction::new_with_bincode(
program_id,
&0,
vec![AccountMeta::new_readonly(id1, true)],
),
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id2, false)]),
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id3, true)]),
],
None,
);
assert_eq!(
keys,
InstructionKeys::new(vec![id3, id1], vec![id2, id0], 1, 1)
);
}
#[test]
fn test_message_kitchen_sink() {
let program_id0 = Pubkey::new_unique();
let program_id1 = Pubkey::new_unique();
let id0 = Pubkey::default();
let id1 = Pubkey::new_unique();
let message = Message::new(
&[
Instruction::new_with_bincode(program_id0, &0, vec![AccountMeta::new(id0, false)]),
Instruction::new_with_bincode(program_id1, &0, vec![AccountMeta::new(id1, true)]),
Instruction::new_with_bincode(program_id0, &0, vec![AccountMeta::new(id1, false)]),
],
Some(&id1),
);
assert_eq!(
message.instructions[0],
CompiledInstruction::new(2, &0, vec![1])
);
assert_eq!(
message.instructions[1],
CompiledInstruction::new(3, &0, vec![0])
);
assert_eq!(
message.instructions[2],
CompiledInstruction::new(2, &0, vec![0])
);
}
#[test]
fn test_message_payer_first() {
let program_id = Pubkey::default();
let payer = Pubkey::new_unique();
let id0 = Pubkey::default();
let ix = Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, false)]);
let message = Message::new(&[ix], Some(&payer));
assert_eq!(message.header.num_required_signatures, 1);
let ix = Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, true)]);
let message = Message::new(&[ix], Some(&payer));
assert_eq!(message.header.num_required_signatures, 2);
let ix = Instruction::new_with_bincode(
program_id,
&0,
vec![AccountMeta::new(payer, true), AccountMeta::new(id0, true)],
);
let message = Message::new(&[ix], Some(&payer));
assert_eq!(message.header.num_required_signatures, 2);
}
#[test]
fn test_message_program_last() {
let program_id = Pubkey::default();
let id0 = Pubkey::new_unique();
let id1 = Pubkey::new_unique();
let keys = get_keys(
&[
Instruction::new_with_bincode(
program_id,
&0,
vec![AccountMeta::new_readonly(id0, false)],
),
Instruction::new_with_bincode(
program_id,
&0,
vec![AccountMeta::new_readonly(id1, true)],
),
],
None,
);
assert_eq!(
keys,
InstructionKeys::new(vec![id1], vec![id0, program_id], 1, 2)
);
}
#[test]
fn test_program_position() {
let program_id0 = Pubkey::default();
let program_id1 = Pubkey::new_unique();
let id = Pubkey::new_unique();
let message = Message::new(
&[
Instruction::new_with_bincode(program_id0, &0, vec![AccountMeta::new(id, false)]),
Instruction::new_with_bincode(program_id1, &0, vec![AccountMeta::new(id, true)]),
],
Some(&id),
);
assert_eq!(message.program_position(0), None);
assert_eq!(message.program_position(1), Some(0));
assert_eq!(message.program_position(2), Some(1));
}
#[test]
fn test_is_writable() {
let key0 = Pubkey::new_unique();
let key1 = Pubkey::new_unique();
let key2 = Pubkey::new_unique();
let key3 = Pubkey::new_unique();
let key4 = Pubkey::new_unique();
let key5 = Pubkey::new_unique();
let message = Message {
header: MessageHeader {
num_required_signatures: 3,
num_readonly_signed_accounts: 2,
num_readonly_unsigned_accounts: 1,
},
account_keys: vec![key0, key1, key2, key3, key4, key5],
recent_blockhash: Hash::default(),
instructions: vec![],
};
assert_eq!(message.is_writable(0), true);
assert_eq!(message.is_writable(1), false);
assert_eq!(message.is_writable(2), false);
assert_eq!(message.is_writable(3), true);
assert_eq!(message.is_writable(4), true);
assert_eq!(message.is_writable(5), false);
}
#[test]
fn test_get_account_keys_by_lock_type() {
let program_id = Pubkey::default();
let id0 = Pubkey::new_unique();
let id1 = Pubkey::new_unique();
let id2 = Pubkey::new_unique();
let id3 = Pubkey::new_unique();
let message = Message::new(
&[
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, false)]),
Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id1, true)]),
Instruction::new_with_bincode(
program_id,
&0,
vec![AccountMeta::new_readonly(id2, false)],
),
Instruction::new_with_bincode(
program_id,
&0,
vec![AccountMeta::new_readonly(id3, true)],
),
],
Some(&id1),
);
assert_eq!(
message.get_account_keys_by_lock_type(),
(vec![&id1, &id0], vec![&id3, &id2, &program_id])
);
}
#[test]
fn test_decompile_instructions() {
solana_logger::setup();
let program_id0 = Pubkey::new_unique();
let program_id1 = Pubkey::new_unique();
let id0 = Pubkey::new_unique();
let id1 = Pubkey::new_unique();
let id2 = Pubkey::new_unique();
let id3 = Pubkey::new_unique();
let instructions = vec![
Instruction::new_with_bincode(program_id0, &0, vec![AccountMeta::new(id0, false)]),
Instruction::new_with_bincode(program_id0, &0, vec![AccountMeta::new(id1, true)]),
Instruction::new_with_bincode(
program_id1,
&0,
vec![AccountMeta::new_readonly(id2, false)],
),
Instruction::new_with_bincode(
program_id1,
&0,
vec![AccountMeta::new_readonly(id3, true)],
),
];
let message = Message::new(&instructions, Some(&id1));
let serialized = message.serialize_instructions();
for (i, instruction) in instructions.iter().enumerate() {
assert_eq!(
Message::deserialize_instruction(i, &serialized).unwrap(),
*instruction
);
}
}
#[test]
fn test_program_ids() {
let key0 = Pubkey::new_unique();
let key1 = Pubkey::new_unique();
let loader2 = Pubkey::new_unique();
let instructions = vec![CompiledInstruction::new(2, &(), vec![0, 1])];
let message = Message::new_with_compiled_instructions(
1,
0,
2,
vec![key0, key1, loader2],
Hash::default(),
instructions,
);
assert_eq!(message.program_ids(), vec![&loader2]);
}
#[test]
fn test_is_key_passed_to_program() {
let key0 = Pubkey::new_unique();
let key1 = Pubkey::new_unique();
let loader2 = Pubkey::new_unique();
let instructions = vec![CompiledInstruction::new(2, &(), vec![0, 1])];
let message = Message::new_with_compiled_instructions(
1,
0,
2,
vec![key0, key1, loader2],
Hash::default(),
instructions,
);
assert!(message.is_key_passed_to_program(0));
assert!(message.is_key_passed_to_program(1));
assert!(!message.is_key_passed_to_program(2));
}
#[test]
fn test_is_non_loader_key() {
let key0 = Pubkey::new_unique();
let key1 = Pubkey::new_unique();
let loader2 = Pubkey::new_unique();
let instructions = vec![CompiledInstruction::new(2, &(), vec![0, 1])];
let message = Message::new_with_compiled_instructions(
1,
0,
2,
vec![key0, key1, loader2],
Hash::default(),
instructions,
);
assert!(message.is_non_loader_key(&key0, 0));
assert!(message.is_non_loader_key(&key1, 1));
assert!(!message.is_non_loader_key(&loader2, 2));
}
}
| 35.430143 | 100 | 0.572254 |
f97d499efd353d5f36f89c9f2fcfdc0828406850 | 13,146 | use std::borrow::Cow;
use chrono::{
DateTime,
Utc,
};
use derive_into_owned::IntoOwned;
use super::{
EventData,
UTC_TIME_FORMAT,
};
use crate::{
error::{
Error,
Result,
},
util,
};
/// The process creation event provides extended information about a newly created process. The
/// full command line provides context on the process execution. The ProcessGUID field is a unique
/// value for this process across a domain to make event correlation easier. The hash is a full
/// hash of the file with the algorithms in the HashType field.
///
/// <event name="SYSMONEVENT_CREATE_PROCESS" value="1" level="Informational" template="Process Create" rulename="ProcessCreate" ruledefault="include" version="5" target="all">
///
/// <https://docs.microsoft.com/en-us/sysinternals/downloads/sysmon#event-id-1-process-creation>
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Hash, IntoOwned)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ProcessCreateEventData<'a> {
/// <data name="RuleName" inType="win:UnicodeString" outType="xs:string" />
pub rule_name: Option<Cow<'a, str>>,
/// <data name="SequenceNumber" inType="win:UInt64" />
pub sequence_number: Option<u64>,
/// <data name="UtcTime" inType="win:UnicodeString" outType="xs:string" />
pub utc_time: DateTime<Utc>,
/// <data name="ProcessGuid" inType="win:GUID" />
pub process_guid: uuid::Uuid,
/// <data name="ProcessId" inType="win:UInt32" outType="win:PID" />
pub process_id: u32,
/// <data name="Image" inType="win:UnicodeString" outType="xs:string" />
pub image: Cow<'a, str>,
/// <data name="FileVersion" inType="win:UnicodeString" outType="xs:string" />
pub file_version: Option<Cow<'a, str>>,
/// <data name="Description" inType="win:UnicodeString" outType="xs:string" />
pub description: Option<Cow<'a, str>>,
/// <data name="Product" inType="win:UnicodeString" outType="xs:string" />
pub product: Option<Cow<'a, str>>,
/// <data name="Company" inType="win:UnicodeString" outType="xs:string" />
pub company: Option<Cow<'a, str>>,
/// <data name="OriginalFileName" inType="win:UnicodeString" outType="xs:string" />
pub original_file_name: Option<Cow<'a, str>>,
/// <data name="CommandLine" inType="win:UnicodeString" outType="xs:string" />
pub command_line: Cow<'a, str>,
/// <data name="CurrentDirectory" inType="win:UnicodeString" outType="xs:string" />
pub current_directory: Cow<'a, str>,
/// <data name="User" inType="win:UnicodeString" outType="xs:string" />
pub user: Cow<'a, str>,
/// <data name="LogonGuid" inType="win:GUID" />
pub logon_guid: uuid::Uuid,
/// <data name="LogonId" inType="win:HexInt64" />
pub logon_id: u64,
/// <data name="TerminalSessionId" inType="win:UInt32" />
pub terminal_session_id: u32,
/// <data name="IntegrityLevel" inType="win:UnicodeString" outType="xs:string" />
pub integrity_level: Cow<'a, str>,
/// <data name="Hashes" inType="win:UnicodeString" outType="xs:string" />
pub hashes: Cow<'a, str>,
/// <data name="ParentProcessGuid" inType="win:GUID" />
pub parent_process_guid: uuid::Uuid,
/// <data name="ParentProcessId" inType="win:UInt32" outType="win:PID" />
pub parent_process_id: u32,
/// <data name="ParentImage" inType="win:UnicodeString" outType="xs:string" />
pub parent_image: Cow<'a, str>,
/// <data name="ParentCommandLine" inType="win:UnicodeString" outType="xs:string" />
pub parent_command_line: Cow<'a, str>,
/// <data name="ParentUser" inType="win:UnicodeString" outType="xs:string" />
pub parent_user: Option<Cow<'a, str>>,
}
impl<'a> ProcessCreateEventData<'a> {
pub(crate) fn try_from(tokenizer: &mut xmlparser::Tokenizer<'a>) -> Result<Self> {
let mut rule_name = None;
let mut utc_time = None;
let mut process_guid = None;
let mut process_id = None;
let mut image = None;
let mut file_version = None;
let mut description = None;
let mut product = None;
let mut company = None;
let mut original_file_name = None;
let mut command_line = None;
let mut current_directory = None;
let mut user = None;
let mut logon_guid = None;
let mut logon_id = None;
let mut terminal_session_id = None;
let mut integrity_level = None;
let mut hashes = None;
let mut parent_process_guid = None;
let mut parent_process_id = None;
let mut parent_image = None;
let mut parent_command_line = None;
let mut parent_user = None;
let mut sequence_number = None;
for result in util::EventDataIterator::new(tokenizer)? {
let (name, ref value) = result?;
match name {
"RuleName" => rule_name = Some(util::unescape_xml(value)?),
"SequenceNumber" => sequence_number = Some(util::parse_int::<u64>(value)?),
"UtcTime" => utc_time = Some(util::parse_utc_from_str(value, UTC_TIME_FORMAT)?),
"ProcessGuid" => process_guid = Some(util::parse_win_guid_str(value)?),
"ProcessId" => process_id = Some(util::parse_int::<u32>(value)?),
"Image" => image = Some(util::unescape_xml(value)?),
"FileVersion" => file_version = Some(util::unescape_xml(value)?),
"Description" => description = Some(util::unescape_xml(value)?),
"Product" => product = Some(util::unescape_xml(value)?),
"Company" => company = Some(util::unescape_xml(value)?),
"OriginalFileName" => original_file_name = Some(util::unescape_xml(value)?),
"CommandLine" => command_line = Some(util::unescape_xml(value)?),
"CurrentDirectory" => current_directory = Some(util::unescape_xml(value)?),
"User" => user = Some(util::unescape_xml(value)?),
"LogonGuid" => logon_guid = Some(util::parse_win_guid_str(value)?),
"LogonId" => logon_id = Some(util::from_zero_or_hex_str(value)?),
"TerminalSessionId" => terminal_session_id = Some(util::parse_int::<u32>(value)?),
"IntegrityLevel" => integrity_level = Some(util::unescape_xml(value)?),
"Hashes" => hashes = Some(util::unescape_xml(value)?),
"ParentProcessGuid" => parent_process_guid = Some(util::parse_win_guid_str(value)?),
"ParentProcessId" => parent_process_id = Some(util::parse_int::<u32>(value)?),
"ParentImage" => parent_image = Some(util::unescape_xml(value)?),
"ParentCommandLine" => parent_command_line = Some(util::unescape_xml(value)?),
"ParentUser" => parent_user = Some(util::unescape_xml(value)?),
_ => {}
}
}
// expected fields - present in all observed schema versions
let utc_time = utc_time.ok_or(Error::MissingField("UtcTime"))?;
let process_guid = process_guid.ok_or(Error::MissingField("ProcessGuid"))?;
let process_id = process_id.ok_or(Error::MissingField("ProcessId"))?;
let image = image.ok_or(Error::MissingField("Image"))?;
let command_line = command_line.ok_or(Error::MissingField("CommandLine"))?;
let current_directory = current_directory.ok_or(Error::MissingField("CurrentDirectory"))?;
let user = user.ok_or(Error::MissingField("User"))?;
let logon_guid = logon_guid.ok_or(Error::MissingField("LogonGuid"))?;
let logon_id = logon_id.ok_or(Error::MissingField("LogonId"))?;
let terminal_session_id =
terminal_session_id.ok_or(Error::MissingField("TerminalSessionId"))?;
let integrity_level = integrity_level.ok_or(Error::MissingField("IntegrityLevel"))?;
let hashes = hashes.ok_or(Error::MissingField("Hashes"))?;
let parent_process_guid =
parent_process_guid.ok_or(Error::MissingField("ParentProcessGuid"))?;
let parent_process_id = parent_process_id.ok_or(Error::MissingField("ParentProcessId"))?;
let parent_image = parent_image.ok_or(Error::MissingField("ParentImage"))?;
let parent_command_line =
parent_command_line.ok_or(Error::MissingField("ParentCommandLine"))?;
Ok(ProcessCreateEventData {
rule_name,
utc_time,
process_guid,
process_id,
image,
file_version,
description,
product,
company,
original_file_name,
command_line,
current_directory,
user,
logon_guid,
logon_id,
terminal_session_id,
integrity_level,
hashes,
parent_process_guid,
parent_process_id,
parent_image,
parent_command_line,
parent_user,
sequence_number,
})
}
}
impl<'a> TryFrom<EventData<'a>> for ProcessCreateEventData<'a> {
type Error = Error;
fn try_from(event_data: EventData<'a>) -> Result<Self> {
match event_data {
EventData::ProcessCreate(event_data) => Ok(event_data),
_ => Err(Error::ExpectEventType("ProcessCreate")),
}
}
}
impl<'a, 'b: 'a> TryFrom<&'b EventData<'a>> for &ProcessCreateEventData<'a> {
type Error = Error;
fn try_from(event_data: &'b EventData<'a>) -> Result<Self> {
match event_data {
EventData::ProcessCreate(event_data) => Ok(event_data),
_ => Err(Error::ExpectEventType("ProcessCreate")),
}
}
}
#[cfg(test)]
mod tests {
use chrono::TimeZone;
use xmlparser::StrSpan;
use super::*;
#[test]
fn parse_process_creation_event() -> std::result::Result<(), Box<dyn std::error::Error>> {
let xml = r#"
<EventData>
<Data Name="RuleName">rule_name</Data>
<Data Name="UtcTime">2022-01-04 19:54:15.661</Data>
<Data Name="ProcessGuid">{49e2a5f6-a5e7-61d4-119e-dc77a5550000}</Data>
<Data Name="ProcessId">49570</Data>
<Data Name="Image">/usr/bin/tr</Data>
<Data Name="FileVersion">-</Data>
<Data Name="Description">-</Data>
<Data Name="Product">-</Data>
<Data Name="Company">-</Data>
<Data Name="OriginalFileName">-</Data>
<Data Name="CommandLine">tr [:upper:][:lower:]</Data>
<Data Name="CurrentDirectory">/root</Data>
<Data Name="User">root</Data>
<Data Name="LogonGuid">{49e2a5f6-0000-0000-0000-000000000000}</Data>
<Data Name="LogonId">0</Data>
<Data Name="TerminalSessionId">3</Data>
<Data Name="IntegrityLevel">no level</Data>
<Data Name="Hashes">-</Data>
<Data Name="ParentProcessGuid">{00000000-0000-0000-0000-000000000000}</Data>
<Data Name="ParentProcessId">49568</Data>
<Data Name="ParentImage">-</Data>
<Data Name="ParentCommandLine">-</Data>
<Data Name="ParentUser">-</Data>
</EventData>"#;
let mut tokenizer = xmlparser::Tokenizer::from(xml);
let process_creation_event = ProcessCreateEventData::try_from(&mut tokenizer)?;
assert_eq!(
process_creation_event,
ProcessCreateEventData {
rule_name: Some(Cow::Borrowed("rule_name")),
utc_time: Utc.datetime_from_str("2022-01-04 19:54:15.661", UTC_TIME_FORMAT)?,
process_guid: util::parse_win_guid_str(&StrSpan::from(
"49e2a5f6-a5e7-61d4-119e-dc77a5550000"
))?,
process_id: 49570,
image: Cow::Borrowed("/usr/bin/tr"),
file_version: Some(Cow::Borrowed("-")),
description: Some(Cow::Borrowed("-")),
product: Some(Cow::Borrowed("-")),
company: Some(Cow::Borrowed("-")),
original_file_name: Some(Cow::Borrowed("-")),
command_line: Cow::Borrowed("tr [:upper:][:lower:]"),
current_directory: Cow::Borrowed("/root"),
user: Cow::Borrowed("root"),
logon_guid: util::parse_win_guid_str(&StrSpan::from(
"49e2a5f6-0000-0000-0000-000000000000"
))?,
logon_id: 0,
terminal_session_id: 3,
integrity_level: Cow::Borrowed("no level"),
hashes: Cow::Borrowed("-"),
parent_process_guid: util::parse_win_guid_str(&StrSpan::from(
"00000000-0000-0000-0000-000000000000"
))?,
parent_process_id: 49568,
parent_image: Cow::Borrowed("-"),
parent_command_line: Cow::Borrowed("-"),
parent_user: Some(Cow::Borrowed("-")),
sequence_number: None,
}
);
Ok(())
}
}
| 41.866242 | 175 | 0.59927 |
29d7f2629a8bb2d2ed7ea19d2debb723f64b4090 | 16,253 | //! A Parser for Proguard Mapping Files.
//!
//! The mapping file format is described
//! [here](https://www.guardsquare.com/en/products/proguard/manual/retrace).
use std::fmt;
use std::str;
#[cfg(feature = "uuid")]
use uuid_::Uuid;
/// Error when parsing a proguard mapping line.
///
/// Since the mapping parses proguard line-by-line, an error will also contain
/// the offending line.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ParseError<'s> {
line: &'s [u8],
kind: ParseErrorKind,
}
impl<'s> ParseError<'s> {
/// The offending line that caused the error.
pub fn line(&self) -> &[u8] {
self.line
}
/// The specific parse Error.
pub fn kind(&self) -> ParseErrorKind {
self.kind
}
}
impl fmt::Display for ParseError<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind {
ParseErrorKind::Utf8Error(e) => e.fmt(f),
ParseErrorKind::ParseError(d) => d.fmt(f),
}
}
}
impl std::error::Error for ParseError<'_> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self.kind {
ParseErrorKind::Utf8Error(ref e) => Some(e),
ParseErrorKind::ParseError(_) => None,
}
}
}
/// The specific parse Error.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ParseErrorKind {
/// The line failed utf-8 conversion.
Utf8Error(str::Utf8Error),
/// The line failed parsing.
ParseError(&'static str),
}
/// Summary of a mapping file.
pub struct MappingSummary<'s> {
compiler: Option<&'s str>,
compiler_version: Option<&'s str>,
min_api: Option<u32>,
class_count: usize,
method_count: usize,
}
impl<'s> MappingSummary<'s> {
fn new(mapping: &'s ProguardMapping<'s>) -> MappingSummary<'s> {
let mut compiler = None;
let mut compiler_version = None;
let mut min_api = None;
let mut class_count = 0;
let mut method_count = 0;
for record in mapping.iter() {
match record {
Ok(ProguardRecord::Header { key, value }) => match key {
"compiler" => {
compiler = value;
}
"compiler_version" => {
compiler_version = value;
}
"min_api" => {
min_api = value.and_then(|x| x.parse().ok());
}
_ => {}
},
Ok(ProguardRecord::Class { .. }) => class_count += 1,
Ok(ProguardRecord::Method { .. }) => method_count += 1,
_ => {}
}
}
MappingSummary {
compiler,
compiler_version,
min_api,
class_count,
method_count,
}
}
/// Returns the name of the compiler that created the proguard mapping.
pub fn compiler(&self) -> Option<&str> {
self.compiler
}
/// Returns the version of the compiler.
pub fn compiler_version(&self) -> Option<&str> {
self.compiler_version
}
/// Returns the min-api value.
pub fn min_api(&self) -> Option<u32> {
self.min_api
}
/// Returns the number of classes in the mapping file.
pub fn class_count(&self) -> usize {
self.class_count
}
/// Returns the number of methods in the mapping file.
pub fn method_count(&self) -> usize {
self.method_count
}
}
/// A Proguard Mapping file.
#[derive(Clone, Default)]
pub struct ProguardMapping<'s> {
source: &'s [u8],
}
impl<'s> fmt::Debug for ProguardMapping<'s> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProguardMapping").finish()
}
}
impl<'s> ProguardMapping<'s> {
/// Create a new Proguard Mapping.
pub fn new(source: &'s [u8]) -> Self {
Self { source }
}
/// Whether the mapping file is indeed valid.
///
/// # Examples
///
/// ```
/// use proguard::ProguardMapping;
///
/// let valid = ProguardMapping::new(b"a -> b:\n void method() -> b");
/// assert_eq!(valid.is_valid(), true);
///
/// let invalid = ProguardMapping::new(
/// br#"
/// # looks: like
/// a -> proguard:
/// mapping but(is) -> not
/// "#,
/// );
/// assert_eq!(invalid.is_valid(), false);
/// ```
pub fn is_valid(&self) -> bool {
// In order to not parse the whole file, we look for a class followed by
// a member in the first 50 lines, which is a good heuristic.
let mut has_class_line = false;
for record in self.iter().take(50) {
match record {
Ok(ProguardRecord::Class { .. }) => {
has_class_line = true;
}
Ok(ProguardRecord::Field { .. }) | Ok(ProguardRecord::Method { .. })
if has_class_line =>
{
return true;
}
_ => {}
}
}
false
}
/// Returns a summary of the file.
pub fn summary(&self) -> MappingSummary<'_> {
MappingSummary::new(self)
}
/// Whether the mapping file contains line info.
///
/// # Examples
///
/// ```
/// use proguard::ProguardMapping;
///
/// let with = ProguardMapping::new(b"a -> b:\n 1:1:void method() -> a");
/// assert_eq!(with.has_line_info(), true);
///
/// let without = ProguardMapping::new(b"a -> b:\n void method() -> b");
/// assert_eq!(without.has_line_info(), false);
/// ```
pub fn has_line_info(&self) -> bool {
// Similarly to `is_valid` above, we only scan the first 100 lines, and
// are looking for a method record with a valid line_mapping.
for record in self.iter().take(100) {
if let Ok(ProguardRecord::Method { line_mapping, .. }) = record {
if line_mapping.is_some() {
return true;
}
}
}
false
}
/// Calculates the UUID of the mapping file.
///
/// The UUID is generated from a file checksum.
#[cfg(feature = "uuid")]
pub fn uuid(&self) -> Uuid {
lazy_static::lazy_static! {
static ref NAMESPACE: Uuid = Uuid::new_v5(&Uuid::NAMESPACE_DNS, b"guardsquare.com");
}
// this internally only operates on bytes, so this is safe to do
Uuid::new_v5(&NAMESPACE, self.source)
}
/// Create an Iterator over [`ProguardRecord`]s.
///
/// [`ProguardRecord`]: enum.ProguardRecord.html
pub fn iter(&self) -> ProguardRecordIter<'s> {
ProguardRecordIter { slice: self.source }
}
}
/// Split the input `slice` on line terminators.
///
/// This is basically [`str::lines`], except it works on a byte slice.
/// Also NOTE that it does not treat `\r\n` as a single line ending.
fn split_line(slice: &[u8]) -> (&[u8], &[u8]) {
let pos = slice.iter().position(|c| *c == b'\n' || *c == b'\r');
match pos {
Some(pos) => (&slice[0..pos], &slice[pos + 1..]),
None => (slice, &[]),
}
}
/// An Iterator yielding [`ProguardRecord`]s, created by [`ProguardMapping::iter`].
///
/// [`ProguardRecord`]: enum.ProguardRecord.html
/// [`ProguardMapping::iter`]: struct.ProguardMapping.html#method.iter
#[derive(Clone, Default)]
pub struct ProguardRecordIter<'s> {
slice: &'s [u8],
}
impl<'s> fmt::Debug for ProguardRecordIter<'s> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProguardRecordIter").finish()
}
}
impl<'s> Iterator for ProguardRecordIter<'s> {
type Item = Result<ProguardRecord<'s>, ParseError<'s>>;
fn next(&mut self) -> Option<Self::Item> {
// We loop here, ignoring empty lines, which is important also because
// `split_line` above would output an empty line for each `\r\n`.
loop {
let (line, rest) = split_line(self.slice);
self.slice = rest;
if !line.is_empty() {
return Some(ProguardRecord::try_parse(line));
}
if rest.is_empty() {
return None;
};
}
}
}
/// A proguard line mapping.
///
/// Maps start/end lines of a minified file to original start/end lines.
///
/// All line mappings are 1-based and inclusive.
#[derive(Clone, Debug, PartialEq)]
pub struct LineMapping {
/// Start Line, 1-based.
pub startline: usize,
/// End Line, inclusive.
pub endline: usize,
/// The original Start Line.
pub original_startline: Option<usize>,
/// The original End Line.
pub original_endline: Option<usize>,
}
/// A Proguard Mapping Record.
#[derive(Clone, Debug, PartialEq)]
pub enum ProguardRecord<'s> {
/// A Proguard Header.
Header {
/// The Key of the Header.
key: &'s str,
/// Optional value if the Header is a KV pair.
value: Option<&'s str>,
},
/// A Class Mapping.
Class {
/// Original name of the class.
original: &'s str,
/// Obfuscated name of the class.
obfuscated: &'s str,
},
/// A Field Mapping.
Field {
/// Type of the field
ty: &'s str,
/// Original name of the field.
original: &'s str,
/// Obfuscated name of the field.
obfuscated: &'s str,
},
/// A Method Mapping.
Method {
/// Return Type of the method.
ty: &'s str,
/// Original name of the method.
original: &'s str,
/// Obfuscated name of the method.
obfuscated: &'s str,
/// Arguments of the method as raw string.
arguments: &'s str,
/// Original class of a foreign inlined method.
original_class: Option<&'s str>,
/// Optional line mapping of the method.
line_mapping: Option<LineMapping>,
},
}
impl<'s> ProguardRecord<'s> {
/// Parses a line from a proguard mapping file.
///
/// # Examples
///
/// ```
/// use proguard::ProguardRecord;
///
/// // Headers
/// let parsed = ProguardRecord::try_parse(b"# compiler: R8");
/// assert_eq!(
/// parsed,
/// Ok(ProguardRecord::Header {
/// key: "compiler",
/// value: Some("R8")
/// })
/// );
///
/// // Class Mappings
/// let parsed =
/// ProguardRecord::try_parse(b"android.arch.core.executor.ArchTaskExecutor -> a.a.a.a.c:");
/// assert_eq!(
/// parsed,
/// Ok(ProguardRecord::Class {
/// original: "android.arch.core.executor.ArchTaskExecutor",
/// obfuscated: "a.a.a.a.c"
/// })
/// );
///
/// // Field
/// let parsed =
/// ProguardRecord::try_parse(b" android.arch.core.executor.ArchTaskExecutor sInstance -> a");
/// assert_eq!(
/// parsed,
/// Ok(ProguardRecord::Field {
/// ty: "android.arch.core.executor.ArchTaskExecutor",
/// original: "sInstance",
/// obfuscated: "a",
/// })
/// );
///
/// // Method without line mappings
/// let parsed = ProguardRecord::try_parse(
/// b" java.lang.Object putIfAbsent(java.lang.Object,java.lang.Object) -> b",
/// );
/// assert_eq!(
/// parsed,
/// Ok(ProguardRecord::Method {
/// ty: "java.lang.Object",
/// original: "putIfAbsent",
/// obfuscated: "b",
/// arguments: "java.lang.Object,java.lang.Object",
/// original_class: None,
/// line_mapping: None,
/// })
/// );
///
/// // Inlined method from foreign class
/// let parsed = ProguardRecord::try_parse(
/// b" 1016:1016:void com.example1.domain.MyBean.doWork():16:16 -> buttonClicked",
/// );
/// assert_eq!(
/// parsed,
/// Ok(ProguardRecord::Method {
/// ty: "void",
/// original: "doWork",
/// obfuscated: "buttonClicked",
/// arguments: "",
/// original_class: Some("com.example1.domain.MyBean"),
/// line_mapping: Some(proguard::LineMapping {
/// startline: 1016,
/// endline: 1016,
/// original_startline: Some(16),
/// original_endline: Some(16),
/// }),
/// })
/// );
/// ```
pub fn try_parse(line: &'s [u8]) -> Result<Self, ParseError<'s>> {
let line = std::str::from_utf8(line).map_err(|e| ParseError {
line,
kind: ParseErrorKind::Utf8Error(e),
})?;
parse_mapping(line).ok_or_else(|| ParseError {
line: line.as_ref(),
kind: ParseErrorKind::ParseError("line is not a valid proguard record"),
})
}
}
/// Parses a single line from a Proguard File.
///
/// Returns `None` if the line could not be parsed.
// TODO: this function is private here, but in the future it would be nice to
// better elaborate parse errors.
fn parse_mapping(mut line: &str) -> Option<ProguardRecord> {
if line.starts_with('#') {
let mut split = line[1..].splitn(2, ':');
let key = split.next()?.trim();
let value = split.next().map(|s| s.trim());
return Some(ProguardRecord::Header { key, value });
}
if !line.starts_with(" ") {
// class line: `originalclassname -> obfuscatedclassname:`
let mut split = line.splitn(3, ' ');
let original = split.next()?;
if split.next()? != "->" || !line.ends_with(':') {
return None;
}
let mut obfuscated = split.next()?;
obfuscated = &obfuscated[..obfuscated.len() - 1];
return Some(ProguardRecord::Class {
original,
obfuscated,
});
}
// field line or method line:
// `originalfieldtype originalfieldname -> obfuscatedfieldname`
// `[startline:endline:]originalreturntype [originalclassname.]originalmethodname(originalargumenttype,...)[:originalstartline[:originalendline]] -> obfuscatedmethodname`
line = &line[4..];
let mut line_mapping = LineMapping {
startline: 0,
endline: 0,
original_startline: None,
original_endline: None,
};
// leading line mapping
if line.starts_with(char::is_numeric) {
let mut nums = line.splitn(3, ':');
line_mapping.startline = nums.next()?.parse().ok()?;
line_mapping.endline = nums.next()?.parse().ok()?;
line = nums.next()?;
}
// split the type, name and obfuscated name
let mut split = line.splitn(4, ' ');
let ty = split.next()?;
let mut original = split.next()?;
if split.next()? != "->" {
return None;
}
let obfuscated = split.next()?;
// split off trailing line mappings
let mut nums = original.splitn(3, ':');
original = nums.next()?;
line_mapping.original_startline = match nums.next() {
Some(n) => Some(n.parse().ok()?),
_ => None,
};
line_mapping.original_endline = match nums.next() {
Some(n) => Some(n.parse().ok()?),
_ => None,
};
// split off the arguments
let mut args = original.splitn(2, '(');
original = args.next()?;
Some(match args.next() {
None => ProguardRecord::Field {
ty,
original,
obfuscated,
},
Some(args) => {
if !args.ends_with(')') {
return None;
}
let arguments = &args[..args.len() - 1];
let mut split_class = original.rsplitn(2, '.');
original = split_class.next()?;
let original_class = split_class.next();
ProguardRecord::Method {
ty,
original,
obfuscated,
arguments,
original_class,
line_mapping: if line_mapping.startline > 0 {
Some(line_mapping)
} else {
None
},
}
}
})
}
| 30.210037 | 174 | 0.530487 |
3a653e1c5e5a9a7dcebd0410e0260a09a8338ef1 | 6,516 | use crate::actions::Action;
use crate::Role;
use mcts::{statistics, SearchSettings};
use rand::Rng;
use search_graph;
use std::{cmp, mem};
#[derive(Clone, Debug)]
pub struct Game {}
impl statistics::two_player::PlayerMapping for Role {
fn player_one() -> Self {
Role::Dwarf
}
fn player_two() -> Self {
Role::Troll
}
fn resolve_player(&self) -> statistics::two_player::Player {
match *self {
Role::Dwarf => statistics::two_player::Player::One,
Role::Troll => statistics::two_player::Player::Two,
}
}
}
impl mcts::game::State for crate::state::State {
type Action = Action;
type PlayerId = Role;
fn active_player(&self) -> &Role {
&self.active_role()
}
fn actions<'s>(&'s self) -> Box<dyn Iterator<Item = Action> + 's> {
Box::new(self.actions())
}
fn do_action(&mut self, action: &Action) {
self.do_action(action);
}
}
impl mcts::game::Game for Game {
type Action = Action;
type PlayerId = Role;
type Payoff = statistics::two_player::ScoredPayoff;
type State = crate::state::State;
type Statistics = statistics::two_player::ScoredStatistics<Role>;
fn payoff_of(state: &Self::State) -> Option<Self::Payoff> {
if state.terminated() {
Some(statistics::two_player::ScoredPayoff {
visits: 1,
score_one: state.score(Role::Dwarf) as u32,
score_two: state.score(Role::Troll) as u32,
})
} else {
None
}
}
}
/// Controls how a game action is selected by the [MCTS
/// agent](struct.Agent.html) after MCTS search has terminated and all
/// statistics have been gathered.
#[derive(Debug, Clone, Copy)]
pub enum ActionSelect {
/// Select the action that was visited the most times.
VisitCount,
/// Select the action with the best UCB score.
Ucb,
}
/// Controls how graph compaction is done by the [MCTS agent](struct.Agent.html)
/// before each round of MCTS search.
#[derive(Debug, Clone, Copy)]
pub enum GraphCompact {
/// Prune the search graph so that the current game state and all its
/// descendants are retained, but game states that are not reachable from the
/// current game state are removed.
Prune,
/// Clear the entire search graph.
Clear,
/// Retain the entire contents of the search graph.
Retain,
}
type SearchGraph =
search_graph::Graph<crate::state::State, mcts::graph::VertexData, mcts::graph::EdgeData<Game>>;
pub struct Agent<R: Rng> {
settings: SearchSettings,
iterations: u32,
rng: R,
action_select: ActionSelect,
graph_compact: GraphCompact,
graph: SearchGraph,
}
impl<R: Rng> Agent<R> {
pub fn new(
settings: SearchSettings,
iterations: u32,
rng: R,
action_select: ActionSelect,
graph_compact: GraphCompact,
) -> Self {
Agent {
settings,
iterations,
rng,
action_select,
graph_compact,
graph: SearchGraph::new(),
}
}
}
fn find_most_visited_child<'a, 'id, R: Rng>(
view: &search_graph::view::View<
'a,
'id,
crate::state::State,
mcts::graph::VertexData,
mcts::graph::EdgeData<Game>,
>,
root: search_graph::view::NodeRef<'id>,
mut rng: R,
) -> search_graph::view::EdgeRef<'id> {
let mut children = view.children(root);
let mut best_child = children.next().unwrap();
let mut best_child_visits = view[best_child].statistics.visits();
let mut reservoir_count = 1u32;
for child in children {
let visits = view[child].statistics.visits();
match visits.cmp(&best_child_visits) {
cmp::Ordering::Less => continue,
cmp::Ordering::Equal => {
reservoir_count += 1;
if !rng.gen_bool(1.0f64 / (reservoir_count as f64)) {
continue;
}
}
cmp::Ordering::Greater => reservoir_count = 1,
}
best_child = child;
best_child_visits = visits;
}
best_child
}
impl<R: Rng + Send> crate::agent::Agent for Agent<R> {
fn propose_action(&mut self, state: &crate::state::State) -> crate::agent::Result {
match self.graph_compact {
GraphCompact::Prune => {
if let Some(node) = self.graph.find_node_mut(state) {
search_graph::view::of_node(node, |view, node| {
view.retain_reachable_from(Some(node).into_iter());
});
} else {
mem::swap(&mut self.graph, &mut SearchGraph::new());
}
}
GraphCompact::Clear => mem::swap(&mut self.graph, &mut SearchGraph::new()),
GraphCompact::Retain => (),
}
// Borrow/copy stuff out of self because the closure passed to of_graph
// can't borrow self.
let (rng, graph, settings, iterations, action_select) = (
&mut self.rng,
&mut self.graph,
self.settings.clone(),
self.iterations,
self.action_select,
);
search_graph::view::of_graph(graph, |view| -> crate::agent::Result {
let mut rollout = mcts::RolloutPhase::initialize(rng, settings, state.clone(), view);
for _ in 0..iterations {
let scoring = match rollout.rollout::<mcts::ucb::Rollout>() {
Ok(s) => s,
Err(e) => return Err(Box::new(e)),
};
let backprop = match scoring.score::<mcts::simulation::RandomSimulator>() {
Ok(b) => b,
Err(e) => return Err(Box::new(e)),
};
rollout = backprop
.backprop::<mcts::ucb::BestParentBackprop>()
.expand();
}
let (rng, view) = rollout.recover_components();
let root = view.find_node(state).unwrap();
let child_edge = match action_select {
ActionSelect::Ucb => {
match mcts::ucb::find_best_child(&view, root, settings.explore_bias, rng) {
Ok(child) => child,
Err(e) => return Err(Box::new(e)),
}
}
ActionSelect::VisitCount => find_most_visited_child(&view, root, rng),
};
// Because search graph de-duplication maps each set of equivalent game
// states to a single "canonical" game state, the state in the search graph
// that corresponds to `state` may not actually be the game state at `root`. As
// a result, actions on the root game state need to be mapped back into the
// set of actions on `state`.
let transposed_to_state = view.node_state(view.edge_target(child_edge));
for action in state.actions() {
let mut actual_to_state = state.clone();
actual_to_state.do_action(&action);
if actual_to_state == *transposed_to_state {
return Ok(action);
}
}
unreachable!()
})
}
}
| 29.484163 | 97 | 0.626151 |
9be8714933f49c1175601a3874f78ec02e8cbd92 | 119 | #![feature(test)]
extern crate test;
use test::Bencher;
#[bench]
fn example2(b: &mut Bencher) {
b.iter(|| 1);
}
| 10.818182 | 30 | 0.605042 |
d5142dbe8a3976ae5d698ca536fd9ced69091a9f | 9,480 | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// 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.
//
//! Alacritty - The GPU Enhanced Terminal
#![deny(clippy::all, clippy::if_not_else, clippy::enum_glob_use, clippy::wrong_pub_self_convention)]
#![cfg_attr(feature = "nightly", feature(core_intrinsics))]
#![cfg_attr(all(test, feature = "bench"), feature(test))]
// With the default subsystem, 'console', windows creates an additional console
// window for the program.
// This is silently ignored on non-windows systems.
// See https://msdn.microsoft.com/en-us/library/4cc7ya5b.aspx for more details.
#![windows_subsystem = "windows"]
#[cfg(target_os = "macos")]
use dirs;
#[cfg(windows)]
use winapi::um::wincon::{AttachConsole, FreeConsole, ATTACH_PARENT_PROCESS};
use log::{info, error};
use std::error::Error;
use std::sync::Arc;
use std::io::{self, Write};
use std::fs;
#[cfg(target_os = "macos")]
use std::env;
#[cfg(not(windows))]
use std::os::unix::io::AsRawFd;
#[cfg(target_os = "macos")]
use alacritty::locale;
use alacritty::{cli, event, die};
use alacritty::config::{self, Config, Monitor};
use alacritty::display::Display;
use alacritty::event_loop::{self, EventLoop, Msg};
use alacritty::logging;
use alacritty::panic;
use alacritty::sync::FairMutex;
use alacritty::term::Term;
use alacritty::tty;
use alacritty::util::fmt::Red;
use alacritty::message_bar::MessageBuffer;
fn main() {
panic::attach_handler();
// When linked with the windows subsystem windows won't automatically attach
// to the console of the parent process, so we do it explicitly. This fails
// silently if the parent has no console.
#[cfg(windows)]
unsafe { AttachConsole(ATTACH_PARENT_PROCESS); }
// Load command line options
let options = cli::Options::load();
// Setup storage for message UI
let message_buffer = MessageBuffer::new();
// Initialize the logger as soon as possible as to capture output from other subsystems
let log_file =
logging::initialize(&options, message_buffer.tx()).expect("Unable to initialize logger");
// Load configuration file
// If the file is a command line argument, we won't write a generated default file
let config_path = options.config_path()
.or_else(Config::installed_config)
.or_else(|| Config::write_defaults().ok())
.map(|path| path.to_path_buf());
let config = if let Some(path) = config_path {
Config::load_from(path).update_dynamic_title(&options)
} else {
error!("Unable to write the default config");
Config::default()
};
// Switch to home directory
#[cfg(target_os = "macos")]
env::set_current_dir(dirs::home_dir().unwrap()).unwrap();
// Set locale
#[cfg(target_os = "macos")]
locale::set_locale_environment();
// Store if log file should be deleted before moving config
let persistent_logging = options.persistent_logging || config.persistent_logging();
// Run alacritty
if let Err(err) = run(config, &options, message_buffer) {
die!("Alacritty encountered an unrecoverable error:\n\n\t{}\n", Red(err));
}
// Clean up logfile
if let Some(log_file) = log_file {
if !persistent_logging && fs::remove_file(&log_file).is_ok() {
let _ = writeln!(io::stdout(), "Deleted log file at {:?}", log_file);
}
}
}
/// Run Alacritty
///
/// Creates a window, the terminal state, pty, I/O event loop, input processor,
/// config change monitor, and runs the main display loop.
fn run(
mut config: Config,
options: &cli::Options,
message_buffer: MessageBuffer,
) -> Result<(), Box<dyn Error>> {
info!("Welcome to Alacritty");
if let Some(config_path) = config.path() {
info!("Configuration loaded from {:?}", config_path.display());
};
// Set environment variables
tty::setup_env(&config);
// Create a display.
//
// The display manages a window and can draw the terminal
let mut display = Display::new(&config, options)?;
info!(
"PTY Dimensions: {:?} x {:?}",
display.size().lines(),
display.size().cols()
);
// Create the terminal
//
// This object contains all of the state about what's being displayed. It's
// wrapped in a clonable mutex since both the I/O loop and display need to
// access it.
let terminal = Term::new(&config, display.size().to_owned(), message_buffer);
let terminal = Arc::new(FairMutex::new(terminal));
// Find the window ID for setting $WINDOWID
let window_id = display.get_window_id();
// Create the pty
//
// The pty forks a process to run the shell on the slave side of the
// pseudoterminal. A file descriptor for the master side is retained for
// reading/writing to the shell.
let pty = tty::new(&config, options, &display.size(), window_id);
// Get a reference to something that we can resize
//
// This exists because rust doesn't know the interface is thread-safe
// and we need to be able to resize the PTY from the main thread while the IO
// thread owns the EventedRW object.
#[cfg(windows)]
let mut resize_handle = pty.resize_handle();
#[cfg(not(windows))]
let mut resize_handle = pty.fd.as_raw_fd();
// Create the pseudoterminal I/O loop
//
// pty I/O is ran on another thread as to not occupy cycles used by the
// renderer and input processing. Note that access to the terminal state is
// synchronized since the I/O loop updates the state, and the display
// consumes it periodically.
let event_loop = EventLoop::new(
Arc::clone(&terminal),
display.notifier(),
pty,
options.ref_test,
);
// The event loop channel allows write requests from the event processor
// to be sent to the loop and ultimately written to the pty.
let loop_tx = event_loop.channel();
// Event processor
//
// Need the Rc<RefCell<_>> here since a ref is shared in the resize callback
let mut processor = event::Processor::new(
event_loop::Notifier(event_loop.channel()),
display.resize_channel(),
options,
&config,
options.ref_test,
display.size().to_owned(),
);
// Create a config monitor when config was loaded from path
//
// The monitor watches the config file for changes and reloads it. Pending
// config changes are processed in the main loop.
let config_monitor = match (options.live_config_reload, config.live_config_reload()) {
// Start monitor if CLI flag says yes
(Some(true), _) |
// Or if no CLI flag was passed and the config says yes
(None, true) => config.path()
.map(|path| config::Monitor::new(path, display.notifier())),
// Otherwise, don't start the monitor
_ => None,
};
// Kick off the I/O thread
let _io_thread = event_loop.spawn(None);
info!("Initialisation complete");
// Main display loop
loop {
// Process input and window events
let mut terminal_lock = processor.process_events(&terminal, display.window());
// Handle config reloads
if let Some(ref path) = config_monitor.as_ref().and_then(Monitor::pending) {
// Clear old config messages from bar
terminal_lock.message_buffer_mut().remove_topic(config::SOURCE_FILE_PATH);
if let Ok(new_config) = Config::reload_from(path) {
config = new_config.update_dynamic_title(options);
display.update_config(&config);
processor.update_config(&config);
terminal_lock.update_config(&config);
}
terminal_lock.dirty = true;
}
// Begin shutdown if the flag was raised
if terminal_lock.should_exit() || tty::process_should_exit() {
break;
}
// Maybe draw the terminal
if terminal_lock.needs_draw() {
// Try to update the position of the input method editor
#[cfg(not(windows))]
display.update_ime_position(&terminal_lock);
// Handle pending resize events
//
// The second argument is a list of types that want to be notified
// of display size changes.
display.handle_resize(&mut terminal_lock, &config, &mut resize_handle, &mut processor);
drop(terminal_lock);
// Draw the current state of the terminal
display.draw(&terminal, &config);
}
}
loop_tx
.send(Msg::Shutdown)
.expect("Error sending shutdown to event loop");
// FIXME patch notify library to have a shutdown method
// config_reloader.join().ok();
// Without explicitly detaching the console cmd won't redraw it's prompt
#[cfg(windows)]
unsafe { FreeConsole(); }
info!("Goodbye");
Ok(())
}
| 34.223827 | 100 | 0.651793 |
222788ec6dbc8fa8166c86fe5734a92db9fac6c8 | 1,362 | // This node creates an end-to-end encrypted secure channel over two tcp transport hops.
// It then routes a message, to a worker on a different node, through this encrypted channel.
use ockam::{
route, Address, Context, Entity, NoOpTrustPolicy, Result, SecureChannels, TcpTransport, TCP,
};
#[ockam::node]
async fn main(mut ctx: Context) -> Result<()> {
// Initialize the TCP Transport.
let tcp = TcpTransport::create(&ctx).await?;
// Create a TCP connection.
tcp.connect("127.0.0.1:3000").await?;
let mut alice = Entity::create(&ctx)?;
let middle: Address = (TCP, "127.0.0.1:3000").into();
let responder: Address = (TCP, "127.0.0.1:4000").into();
let route = route![middle, responder, "bob_secure_channel_listener"];
// Connect to a secure channel listener and perform a handshake.
let channel = alice.create_secure_channel(route, NoOpTrustPolicy)?;
// Send a message to the echoer worker via the channel.
let echoer_route = route![channel, "echoer"];
ctx.send(echoer_route, "Hello Ockam!".to_string()).await?;
// Wait to receive a reply and print it.
let reply = ctx.receive::<String>().await?;
println!("App Received: {}", reply); // should print "Hello Ockam!"
// Stop all workers, stop the node, cleanup and return.
ctx.stop().await
}
| 38.914286 | 96 | 0.657856 |
23e96110c066568dd1e32f341f3501d15a5bf7f2 | 12,598 | // 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.
// Type encoding
use std::cell::RefCell;
use std::hashmap::HashMap;
use std::io;
use std::io::MemWriter;
use std::str;
use std::fmt;
use middle::ty::param_ty;
use middle::ty;
use syntax::abi::AbiSet;
use syntax::ast;
use syntax::ast::*;
use syntax::diagnostic::SpanHandler;
use syntax::print::pprust::*;
macro_rules! mywrite( ($wr:expr, $($arg:tt)*) => (
format_args!(|a| { mywrite($wr, a) }, $($arg)*)
) )
pub struct ctxt {
diag: @SpanHandler,
// Def -> str Callback:
ds: extern "Rust" fn(DefId) -> ~str,
// The type context.
tcx: ty::ctxt,
abbrevs: abbrev_ctxt
}
// Compact string representation for ty.t values. API ty_str & parse_from_str.
// Extra parameters are for converting to/from def_ids in the string rep.
// Whatever format you choose should not contain pipe characters.
pub struct ty_abbrev {
pos: uint,
len: uint,
s: @str
}
pub enum abbrev_ctxt {
ac_no_abbrevs,
ac_use_abbrevs(@RefCell<HashMap<ty::t, ty_abbrev>>),
}
fn mywrite(w: &mut MemWriter, fmt: &fmt::Arguments) {
fmt::write(&mut *w as &mut io::Writer, fmt);
}
pub fn enc_ty(w: &mut MemWriter, cx: @ctxt, t: ty::t) {
match cx.abbrevs {
ac_no_abbrevs => {
let result_str_opt;
{
let short_names_cache = cx.tcx.short_names_cache.borrow();
result_str_opt = short_names_cache.get()
.find(&t)
.map(|result| *result);
}
let result_str = match result_str_opt {
Some(s) => s,
None => {
let wr = &mut MemWriter::new();
enc_sty(wr, cx, &ty::get(t).sty);
let s = str::from_utf8(wr.get_ref()).unwrap().to_managed();
let mut short_names_cache = cx.tcx
.short_names_cache
.borrow_mut();
short_names_cache.get().insert(t, s);
s
}
};
w.write(result_str.as_bytes());
}
ac_use_abbrevs(abbrevs) => {
{
let mut abbrevs = abbrevs.borrow_mut();
match abbrevs.get().find(&t) {
Some(a) => { w.write(a.s.as_bytes()); return; }
None => {}
}
}
let pos = w.tell();
enc_sty(w, cx, &ty::get(t).sty);
let end = w.tell();
let len = end - pos;
fn estimate_sz(u: u64) -> u64 {
let mut n = u;
let mut len = 0;
while n != 0 { len += 1; n = n >> 4; }
return len;
}
let abbrev_len = 3 + estimate_sz(pos) + estimate_sz(len);
if abbrev_len < len {
// I.e. it's actually an abbreviation.
let s = format!("\\#{:x}:{:x}\\#", pos, len).to_managed();
let a = ty_abbrev { pos: pos as uint,
len: len as uint,
s: s };
{
let mut abbrevs = abbrevs.borrow_mut();
abbrevs.get().insert(t, a);
}
}
return;
}
}
}
fn enc_mutability(w: &mut MemWriter, mt: ast::Mutability) {
match mt {
MutImmutable => (),
MutMutable => mywrite!(w, "m"),
}
}
fn enc_mt(w: &mut MemWriter, cx: @ctxt, mt: ty::mt) {
enc_mutability(w, mt.mutbl);
enc_ty(w, cx, mt.ty);
}
fn enc_opt<T>(w: &mut MemWriter, t: Option<T>, enc_f: |&mut MemWriter, T|) {
match t {
None => mywrite!(w, "n"),
Some(v) => {
mywrite!(w, "s");
enc_f(w, v);
}
}
}
pub fn enc_substs(w: &mut MemWriter, cx: @ctxt, substs: &ty::substs) {
enc_region_substs(w, cx, &substs.regions);
enc_opt(w, substs.self_ty, |w, t| enc_ty(w, cx, t));
mywrite!(w, "[");
for t in substs.tps.iter() { enc_ty(w, cx, *t); }
mywrite!(w, "]");
}
fn enc_region_substs(w: &mut MemWriter, cx: @ctxt, substs: &ty::RegionSubsts) {
match *substs {
ty::ErasedRegions => {
mywrite!(w, "e");
}
ty::NonerasedRegions(ref regions) => {
mywrite!(w, "n");
for &r in regions.iter() {
enc_region(w, cx, r);
}
mywrite!(w, ".");
}
}
}
fn enc_region(w: &mut MemWriter, cx: @ctxt, r: ty::Region) {
match r {
ty::ReLateBound(id, br) => {
mywrite!(w, "b[{}|", id);
enc_bound_region(w, cx, br);
mywrite!(w, "]");
}
ty::ReEarlyBound(node_id, index, ident) => {
mywrite!(w, "B[{}|{}|{}]",
node_id,
index,
cx.tcx.sess.str_of(ident));
}
ty::ReFree(ref fr) => {
mywrite!(w, "f[{}|", fr.scope_id);
enc_bound_region(w, cx, fr.bound_region);
mywrite!(w, "]");
}
ty::ReScope(nid) => {
mywrite!(w, "s{}|", nid);
}
ty::ReStatic => {
mywrite!(w, "t");
}
ty::ReEmpty => {
mywrite!(w, "e");
}
ty::ReInfer(_) => {
// these should not crop up after typeck
cx.diag.handler().bug("Cannot encode region variables");
}
}
}
fn enc_bound_region(w: &mut MemWriter, cx: @ctxt, br: ty::BoundRegion) {
match br {
ty::BrAnon(idx) => {
mywrite!(w, "a{}|", idx);
}
ty::BrNamed(d, s) => {
mywrite!(w, "[{}|{}]",
(cx.ds)(d),
cx.tcx.sess.str_of(s));
}
ty::BrFresh(id) => {
mywrite!(w, "f{}|", id);
}
}
}
pub fn enc_vstore(w: &mut MemWriter, cx: @ctxt, v: ty::vstore) {
mywrite!(w, "/");
match v {
ty::vstore_fixed(u) => mywrite!(w, "{}|", u),
ty::vstore_uniq => mywrite!(w, "~"),
ty::vstore_box => mywrite!(w, "@"),
ty::vstore_slice(r) => {
mywrite!(w, "&");
enc_region(w, cx, r);
}
}
}
pub fn enc_trait_ref(w: &mut MemWriter, cx: @ctxt, s: &ty::TraitRef) {
mywrite!(w, "{}|", (cx.ds)(s.def_id));
enc_substs(w, cx, &s.substs);
}
pub fn enc_trait_store(w: &mut MemWriter, cx: @ctxt, s: ty::TraitStore) {
match s {
ty::UniqTraitStore => mywrite!(w, "~"),
ty::BoxTraitStore => mywrite!(w, "@"),
ty::RegionTraitStore(re) => {
mywrite!(w, "&");
enc_region(w, cx, re);
}
}
}
fn enc_sty(w: &mut MemWriter, cx: @ctxt, st: &ty::sty) {
match *st {
ty::ty_nil => mywrite!(w, "n"),
ty::ty_bot => mywrite!(w, "z"),
ty::ty_bool => mywrite!(w, "b"),
ty::ty_char => mywrite!(w, "c"),
ty::ty_int(t) => {
match t {
TyI => mywrite!(w, "i"),
TyI8 => mywrite!(w, "MB"),
TyI16 => mywrite!(w, "MW"),
TyI32 => mywrite!(w, "ML"),
TyI64 => mywrite!(w, "MD")
}
}
ty::ty_uint(t) => {
match t {
TyU => mywrite!(w, "u"),
TyU8 => mywrite!(w, "Mb"),
TyU16 => mywrite!(w, "Mw"),
TyU32 => mywrite!(w, "Ml"),
TyU64 => mywrite!(w, "Md")
}
}
ty::ty_float(t) => {
match t {
TyF32 => mywrite!(w, "Mf"),
TyF64 => mywrite!(w, "MF"),
}
}
ty::ty_enum(def, ref substs) => {
mywrite!(w, "t[{}|", (cx.ds)(def));
enc_substs(w, cx, substs);
mywrite!(w, "]");
}
ty::ty_trait(def, ref substs, store, mt, bounds) => {
mywrite!(w, "x[{}|", (cx.ds)(def));
enc_substs(w, cx, substs);
enc_trait_store(w, cx, store);
enc_mutability(w, mt);
let bounds = ty::ParamBounds {builtin_bounds: bounds,
trait_bounds: ~[]};
enc_bounds(w, cx, &bounds);
mywrite!(w, "]");
}
ty::ty_tup(ref ts) => {
mywrite!(w, "T[");
for t in ts.iter() { enc_ty(w, cx, *t); }
mywrite!(w, "]");
}
ty::ty_box(typ) => { mywrite!(w, "@"); enc_ty(w, cx, typ); }
ty::ty_uniq(typ) => { mywrite!(w, "~"); enc_ty(w, cx, typ); }
ty::ty_ptr(mt) => { mywrite!(w, "*"); enc_mt(w, cx, mt); }
ty::ty_rptr(r, mt) => {
mywrite!(w, "&");
enc_region(w, cx, r);
enc_mt(w, cx, mt);
}
ty::ty_vec(mt, v) => {
mywrite!(w, "V");
enc_mt(w, cx, mt);
enc_vstore(w, cx, v);
}
ty::ty_str(v) => {
mywrite!(w, "v");
enc_vstore(w, cx, v);
}
ty::ty_unboxed_vec(mt) => { mywrite!(w, "U"); enc_mt(w, cx, mt); }
ty::ty_closure(ref f) => {
mywrite!(w, "f");
enc_closure_ty(w, cx, f);
}
ty::ty_bare_fn(ref f) => {
mywrite!(w, "F");
enc_bare_fn_ty(w, cx, f);
}
ty::ty_infer(_) => {
cx.diag.handler().bug("Cannot encode inference variable types");
}
ty::ty_param(param_ty {idx: id, def_id: did}) => {
mywrite!(w, "p{}|{}", (cx.ds)(did), id);
}
ty::ty_self(did) => {
mywrite!(w, "s{}|", (cx.ds)(did));
}
ty::ty_type => mywrite!(w, "Y"),
ty::ty_struct(def, ref substs) => {
mywrite!(w, "a[{}|", (cx.ds)(def));
enc_substs(w, cx, substs);
mywrite!(w, "]");
}
ty::ty_err => fail!("Shouldn't encode error type")
}
}
fn enc_sigil(w: &mut MemWriter, sigil: Sigil) {
match sigil {
ManagedSigil => mywrite!(w, "@"),
OwnedSigil => mywrite!(w, "~"),
BorrowedSigil => mywrite!(w, "&"),
}
}
fn enc_purity(w: &mut MemWriter, p: Purity) {
match p {
ImpureFn => mywrite!(w, "i"),
UnsafeFn => mywrite!(w, "u"),
ExternFn => mywrite!(w, "c")
}
}
fn enc_abi_set(w: &mut MemWriter, abis: AbiSet) {
mywrite!(w, "[");
abis.each(|abi| {
mywrite!(w, "{},", abi.name());
true
});
mywrite!(w, "]")
}
fn enc_onceness(w: &mut MemWriter, o: Onceness) {
match o {
Once => mywrite!(w, "o"),
Many => mywrite!(w, "m")
}
}
pub fn enc_bare_fn_ty(w: &mut MemWriter, cx: @ctxt, ft: &ty::BareFnTy) {
enc_purity(w, ft.purity);
enc_abi_set(w, ft.abis);
enc_fn_sig(w, cx, &ft.sig);
}
fn enc_closure_ty(w: &mut MemWriter, cx: @ctxt, ft: &ty::ClosureTy) {
enc_sigil(w, ft.sigil);
enc_purity(w, ft.purity);
enc_onceness(w, ft.onceness);
enc_region(w, cx, ft.region);
let bounds = ty::ParamBounds {builtin_bounds: ft.bounds,
trait_bounds: ~[]};
enc_bounds(w, cx, &bounds);
enc_fn_sig(w, cx, &ft.sig);
}
fn enc_fn_sig(w: &mut MemWriter, cx: @ctxt, fsig: &ty::FnSig) {
mywrite!(w, "[{}|", fsig.binder_id);
for ty in fsig.inputs.iter() {
enc_ty(w, cx, *ty);
}
mywrite!(w, "]");
if fsig.variadic {
mywrite!(w, "V");
} else {
mywrite!(w, "N");
}
enc_ty(w, cx, fsig.output);
}
fn enc_bounds(w: &mut MemWriter, cx: @ctxt, bs: &ty::ParamBounds) {
for bound in bs.builtin_bounds.iter() {
match bound {
ty::BoundSend => mywrite!(w, "S"),
ty::BoundFreeze => mywrite!(w, "K"),
ty::BoundStatic => mywrite!(w, "O"),
ty::BoundSized => mywrite!(w, "Z"),
ty::BoundPod => mywrite!(w, "P"),
}
}
for &tp in bs.trait_bounds.iter() {
mywrite!(w, "I");
enc_trait_ref(w, cx, tp);
}
mywrite!(w, ".");
}
pub fn enc_type_param_def(w: &mut MemWriter, cx: @ctxt, v: &ty::TypeParameterDef) {
mywrite!(w, "{}:{}|", cx.tcx.sess.str_of(v.ident), (cx.ds)(v.def_id));
enc_bounds(w, cx, v.bounds);
}
| 29.642353 | 83 | 0.462613 |
56acc4d92c6318c5bb3cc78e6d48c22c93f50e0a | 11,966 | mod auth;
mod error;
mod helpers;
mod responders;
mod routes;
mod snapshot;
mod state;
#[macro_use]
extern crate tracing;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{anyhow, Context, Result};
use bincode::Options;
use clap::Parser;
use engine::structures::{IndexDeclaration, ROOT_PATH};
use engine::Engine;
use hyper::Server;
use mimalloc::MiMalloc;
use routerify::RouterService;
use tracing::Level;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::filter::EnvFilter;
use tracing_subscriber::fmt::writer::MakeWriterExt;
#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;
use crate::auth::AuthManager;
use crate::snapshot::{create_snapshot, load_snapshot};
use crate::state::State;
pub static STORAGE_SUB_ROOT_PATH: &str = "engine-storage";
static INDEX_KEYSPACE: &str = "persistent_indexes";
#[derive(Debug, Parser)]
#[clap(name = "lnx", about, version)]
struct Settings {
/// The log level filter, any logs that are above this level won't
/// be displayed.
///
/// For more detailed control you can use the `RUST_LOG` env var.
#[clap(long, default_value = "info", env)]
log_level: Level,
/// An optional bool to disable ASNI colours and pretty formatting for logs.
/// You probably want to disable this if using file-based logging.
#[clap(long, env)]
disable_asni_logs: bool,
/// An optional bool to enable verbose logging, this includes additional metadata
/// like span targets, thread-names, ids, etc... as well as the existing info.
///
/// Generally you probably dont need this unless you're debugging.
#[clap(long, env)]
verbose_logs: bool,
/// An optional bool to enable pretty formatting logging.
///
/// This for most people, this is probably too much pretty formatting however, it
/// can make reading the logs easier especially when trying to debug and / or test.
#[clap(long, env)]
pretty_logs: bool,
/// An optional bool to enable json formatting logging.
///
/// This formats the resulting log data into line-by-line JSON objects.
/// This can be useful for log files or automatic log ingestion systems however,
/// this can come at the cost for performance at very high loads.
#[clap(long, env)]
json_logs: bool,
/// A optional directory to send persistent logs.
///
/// Logs are split into hourly chunks.
#[clap(long, env)]
log_directory: Option<String>,
/// If enabled each search request wont be logged.
#[clap(long, env)]
silent_search: bool,
/// The host to bind to (normally: '127.0.0.1' or '0.0.0.0'.)
#[clap(long, short, default_value = "127.0.0.1", env)]
host: String,
/// The port to bind the server to.
#[clap(long, short, default_value = "8000", env)]
port: u16,
/// The super user key.
///
/// If specified this will enable auth mode and require a token
/// bearer on every endpoint.
///
/// The super user key is used to make tokens with given permissions.
#[clap(long, env, hide_env_values = true)]
super_user_key: Option<String>,
/// The number of threads to use for the tokio runtime.
///
/// If this is not set, the number of logical cores on the machine is used.
#[clap(long, short = 't', env)]
runtime_threads: Option<usize>,
/// Load a past snapshot and use it's data.
///
/// This expects `./index` not to have any existing data or exist.
///
/// This is technically a separate sub command.
#[clap(long)]
load_snapshot: Option<String>,
/// The interval time in hours to take an automatic snapshot.
///
/// The limits are between 1 and 255 hours.
///
/// This is quite a heavy process at larger index sizes so anything less
/// than 24 hours is generally recommended against.
///
/// The extracted snapshot will be saved in the directory provided by `--snapshot-directory`.
#[clap(long, env)]
snapshot_interval: Option<u8>,
/// Generates a snapshot of the current server setup.
///
/// The extracted snapshot will be saved in the directory provided by `--snapshot-directory`.
#[clap(long)]
snapshot: bool,
/// The output directory where snapshots should be extracted to.
#[clap(long, default_value = "./snapshots", env)]
snapshot_directory: String,
}
fn main() {
let settings = match setup() {
Ok(s) => s,
Err(e) => {
eprintln!("error during server config parsing: {:?}", e);
return;
},
};
let _guard = setup_logger(
settings.log_level,
&settings.log_directory,
!settings.disable_asni_logs,
settings.pretty_logs,
settings.json_logs,
settings.verbose_logs,
);
if let Some(snapshot) = settings.load_snapshot {
if let Err(e) = load_snapshot(Path::new(&snapshot)) {
error!("error during snapshot extraction: {}", e);
} else {
info!(
"snapshot successfully extracted, restart the server without \
the `--load-snapshot` flag to start normally."
);
}
return;
}
let threads = settings.runtime_threads.unwrap_or_else(num_cpus::get);
info!("starting runtime with {} threads", threads);
let maybe_runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(threads)
.enable_all()
.build();
let result = match maybe_runtime {
Ok(runtime) => runtime.block_on(start(settings)),
Err(e) => {
error!("error during runtime creation: {:?}", e);
return;
},
};
if let Err(e) = result {
error!("error during lnx runtime: {:?}", e);
}
}
fn setup_logger(
level: Level,
log_dir: &Option<String>,
asni_colours: bool,
pretty: bool,
json: bool,
verbose: bool,
) -> Option<WorkerGuard> {
if std::env::var_os("RUST_LOG").is_none() {
std::env::set_var("RUST_LOG", format!("{},compress=off,tantivy=info", level));
}
let fmt = tracing_subscriber::fmt()
.with_target(verbose)
.with_thread_names(verbose)
.with_thread_ids(verbose)
.with_ansi(asni_colours)
.with_env_filter(EnvFilter::from_default_env());
if let Some(dir) = log_dir {
let file_appender = tracing_appender::rolling::hourly(dir, "lnx.log");
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
let fmt = fmt.with_writer(std::io::stdout.and(non_blocking));
if pretty {
fmt.pretty().init();
} else if json {
fmt.json().init();
} else {
fmt.compact().init();
}
Some(guard)
} else {
if pretty {
fmt.pretty().init();
} else if json {
fmt.json().init();
} else {
fmt.compact().init();
}
None
}
}
/// Parses the config and sets up logging
fn setup() -> Result<Settings> {
let config: Settings = Settings::parse();
Ok(config)
}
async fn start(settings: Settings) -> Result<()> {
tokio::fs::create_dir_all(Path::new(ROOT_PATH).join(STORAGE_SUB_ROOT_PATH)).await?;
if settings.snapshot {
info!("beginning snapshot process, this may take a while...");
create_snapshot(Path::new(&settings.snapshot_directory)).await?;
info!("snapshot process completed!");
return Ok(());
}
if let Some(hours) = settings.snapshot_interval {
if hours >= 1 {
let output_dir = PathBuf::from(settings.snapshot_directory.clone());
let interval_period = Duration::from_secs(hours as u64 * 60 * 60);
tokio::spawn(
async move { snapshot_loop(interval_period, output_dir).await },
);
}
}
let state = create_state(&settings).await?;
let router = routes::get_router(state.clone());
let service = RouterService::new(router).unwrap();
let address: SocketAddr = format!("{}:{}", &settings.host, settings.port).parse()?;
let server = Server::bind(&address).serve(service);
let (major_minor_version, _) = env!("CARGO_PKG_VERSION")
.rsplit_once('.')
.unwrap_or(("0.0", ""));
info!("Lnx has started!");
info!(
"serving requests @ http://{}:{}",
&settings.host, settings.port
);
info!("GitHub: https://github.com/lnx-search/lnx");
info!("To ask questions visit: https://github.com/lnx-search/lnx/discussions");
info!(
"To get started you can check out the documentation @ https://docs.lnx.rs?version={}",
major_minor_version
);
tokio::select! {
_r = wait_for_signal() => {
info!("got shutdown signal, preparing shutdown");
},
r = server => {
if let Err(e) = r {
error!("server error: {:?}", e)
};
}
}
info!("shutting down engine...");
state.engine.shutdown().await?;
Ok(())
}
async fn wait_for_signal() -> Result<()> {
#[cfg(not(unix))]
{
tokio::signal::ctrl_c().await?;
}
#[cfg(unix)]
{
use tokio::signal::unix::{signal, SignalKind};
let mut stream_quit = signal(SignalKind::quit())?;
let mut stream_interupt = signal(SignalKind::interrupt())?;
let mut stream_term = signal(SignalKind::terminate())?;
tokio::select! {
_ = stream_quit.recv() => {},
_ = stream_interupt.recv() => {},
_ = stream_term.recv() => {},
}
}
Ok(())
}
async fn create_state(settings: &Settings) -> Result<State> {
let db = sled::Config::new()
.path(Path::new(ROOT_PATH).join(STORAGE_SUB_ROOT_PATH))
.mode(sled::Mode::HighThroughput)
.use_compression(true)
.open()
.map_err(|e| anyhow!("failed to open database due to error {}", e))?;
let engine = load_existing_indexes(&db)
.await
.map_err(|e| anyhow!("failed to load existing indexes due to error {}", e))?;
let auth = setup_authentication(&db, settings)
.map_err(|e| anyhow!("failed to load authentication data due to error {}", e))?;
Ok(State::new(engine, db, auth, !settings.silent_search))
}
#[instrument(name = "setup-existing-indexes", level = "info", skip(db))]
async fn load_existing_indexes(db: &sled::Db) -> Result<Engine> {
info!("loading existing indexes...");
let existing_indexes: Vec<IndexDeclaration> =
if let Some(buff) = db.get(INDEX_KEYSPACE)? {
let buff: Vec<u8> = bincode::options()
.with_big_endian()
.deserialize(&buff)
.context("failed to deserialize index payload from persisted values.")?;
serde_json::from_slice(&buff)?
} else {
vec![]
};
info!(
" {} existing indexes discovered, recreating state...",
existing_indexes.len()
);
let engine = Engine::default();
for index in existing_indexes {
engine.add_index(index, true).await?;
}
Ok(engine)
}
#[instrument(name = "setup-authentication", level = "info", skip(db, settings))]
fn setup_authentication(db: &sled::Db, settings: &Settings) -> Result<AuthManager> {
let (enabled, key) = if let Some(ref key) = settings.super_user_key {
(true, key.to_string())
} else {
(false, String::new())
};
let auth = AuthManager::new(enabled, key, db)?;
Ok(auth)
}
#[instrument(name = "snapshot-loop")]
async fn snapshot_loop(interval_time: Duration, output: PathBuf) {
let mut interval = tokio::time::interval(interval_time);
loop {
interval.tick().await;
if let Err(e) = create_snapshot(&output).await {
error!("failed to create snapshot due to error: {}", e);
}
}
}
| 30.141058 | 97 | 0.607053 |
61e0677ca8c9bc29df5f02e92ededc7b0d173dbc | 5,456 | use serde::de::DeserializeOwned;
use serde_json::from_reader;
use std::fs::File;
use std::path::PathBuf;
use std::process::{Command, Output};
use std::str::from_utf8;
use tempfile::TempDir;
use types::{ChainSpec, Config, EthSpec};
pub trait CommandLineTestExec {
type Config: DeserializeOwned;
fn cmd_mut(&mut self) -> &mut Command;
/// Adds a flag with optional value to the command.
fn flag(&mut self, flag: &str, value: Option<&str>) -> &mut Self {
self.cmd_mut().arg(format!("--{}", flag));
if let Some(value) = value {
self.cmd_mut().arg(value);
}
self
}
/// Executes the `Command` returned by `Self::cmd_mut` with temporary data directory, dumps
/// the configuration and shuts down immediately.
///
/// Options `--datadir`, `--dump-config`, `--dump-chain-config` and `--immediate-shutdown` must
/// not be set on the command.
fn run(&mut self) -> CompletedTest<Self::Config> {
// Setup temp directory.
let tmp_dir = TempDir::new().expect("Unable to create temporary directory");
let tmp_config_path: PathBuf = tmp_dir.path().join("config.json");
let tmp_chain_config_path: PathBuf = tmp_dir.path().join("chain_spec.yaml");
// Add args --datadir <tmp_dir> --dump-config <tmp_config_path> --dump-chain-config <tmp_chain_config_path> --immediate-shutdown
let cmd = self.cmd_mut();
cmd.arg("--datadir")
.arg(tmp_dir.path().as_os_str())
.arg(format!("--{}", "dump-config"))
.arg(tmp_config_path.as_os_str())
.arg(format!("--{}", "dump-chain-config"))
.arg(tmp_chain_config_path.as_os_str())
.arg("--immediate-shutdown");
// Run the command.
let output = output_result(cmd);
if let Err(e) = output {
panic!("{:?}", e);
}
// Grab the config.
let config_file = File::open(tmp_config_path).expect("Unable to open dumped config");
let config: Self::Config = from_reader(config_file).expect("Unable to deserialize config");
// Grab the chain config.
let spec_file =
File::open(tmp_chain_config_path).expect("Unable to open dumped chain spec");
let chain_config: Config =
serde_yaml::from_reader(spec_file).expect("Unable to deserialize config");
CompletedTest::new(config, chain_config, tmp_dir)
}
/// Executes the `Command` returned by `Self::cmd_mut` dumps the configuration and
/// shuts down immediately.
///
/// Options `--dump-config`, `--dump-chain-config` and `--immediate-shutdown` must not be set on
/// the command.
fn run_with_no_datadir(&mut self) -> CompletedTest<Self::Config> {
// Setup temp directory.
let tmp_dir = TempDir::new().expect("Unable to create temporary directory");
let tmp_config_path: PathBuf = tmp_dir.path().join("config.json");
let tmp_chain_config_path: PathBuf = tmp_dir.path().join("chain_spec.yaml");
// Add args --datadir <tmp_dir> --dump-config <tmp_config_path> --dump-chain-config <tmp_chain_config_path> --immediate-shutdown
let cmd = self.cmd_mut();
cmd.arg(format!("--{}", "dump-config"))
.arg(tmp_config_path.as_os_str())
.arg(format!("--{}", "dump-chain-config"))
.arg(tmp_chain_config_path.as_os_str())
.arg("--immediate-shutdown");
// Run the command.
let output = output_result(cmd);
if let Err(e) = output {
panic!("{:?}", e);
}
// Grab the config.
let config_file = File::open(tmp_config_path).expect("Unable to open dumped config");
let config: Self::Config = from_reader(config_file).expect("Unable to deserialize config");
// Grab the chain config.
let spec_file =
File::open(tmp_chain_config_path).expect("Unable to open dumped chain spec");
let chain_config: Config =
serde_yaml::from_reader(spec_file).expect("Unable to deserialize config");
CompletedTest::new(config, chain_config, tmp_dir)
}
}
/// Executes a `Command`, returning a `Result` based upon the success exit code of the command.
fn output_result(cmd: &mut Command) -> Result<Output, String> {
let output = cmd.output().expect("should run command");
if output.status.success() {
Ok(output)
} else {
Err(from_utf8(&output.stderr)
.expect("stderr is not utf8")
.to_string())
}
}
pub struct CompletedTest<C> {
config: C,
chain_config: Config,
dir: TempDir,
}
impl<C> CompletedTest<C> {
fn new(config: C, chain_config: Config, dir: TempDir) -> Self {
CompletedTest {
config,
chain_config,
dir,
}
}
pub fn with_config<F: Fn(&C)>(self, func: F) {
func(&self.config);
}
pub fn with_spec<E: EthSpec, F: Fn(ChainSpec)>(self, func: F) {
let spec = ChainSpec::from_config::<E>(&self.chain_config).unwrap();
func(spec);
}
pub fn with_config_and_dir<F: Fn(&C, &TempDir)>(self, func: F) {
func(&self.config, &self.dir);
}
#[allow(dead_code)]
pub fn with_config_and_spec<E: EthSpec, F: Fn(&C, ChainSpec)>(self, func: F) {
let spec = ChainSpec::from_config::<E>(&self.chain_config).unwrap();
func(&self.config, spec);
}
}
| 36.864865 | 136 | 0.608138 |
f5e93c3971fb0fb3777ce7e18c46e5f88c8434c2 | 35,080 | // Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Implements a `AvailabilityStoreSubsystem`.
#![recursion_limit = "256"]
#![warn(missing_docs)]
use std::{
collections::{BTreeSet, HashMap, HashSet},
io,
sync::Arc,
time::{Duration, SystemTime, SystemTimeError, UNIX_EPOCH},
};
use futures::{channel::oneshot, future, select, FutureExt};
use futures_timer::Delay;
use kvdb::{DBTransaction, KeyValueDB};
use parity_scale_codec::{Decode, Encode, Error as CodecError, Input};
use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec};
use elexeum_node_primitives::{AvailableData, ErasureChunk};
use elexeum_node_subsystem_util as util;
use elexeum_primitives::v1::{
BlockNumber, CandidateEvent, CandidateHash, CandidateReceipt, Hash, Header, ValidatorIndex,
};
use elexeum_subsystem::{
errors::{ChainApiError, RuntimeApiError},
messages::{AvailabilityStoreMessage, ChainApiMessage},
overseer, ActiveLeavesUpdate, FromOverseer, OverseerSignal, SpawnedSubsystem, SubsystemContext,
SubsystemError,
};
mod metrics;
pub use self::metrics::*;
#[cfg(test)]
mod tests;
const LOG_TARGET: &str = "parachain::availability";
/// The following constants are used under normal conditions:
const AVAILABLE_PREFIX: &[u8; 9] = b"available";
const CHUNK_PREFIX: &[u8; 5] = b"chunk";
const META_PREFIX: &[u8; 4] = b"meta";
const UNFINALIZED_PREFIX: &[u8; 11] = b"unfinalized";
const PRUNE_BY_TIME_PREFIX: &[u8; 13] = b"prune_by_time";
// We have some keys we want to map to empty values because existence of the key is enough. We use this because
// rocksdb doesn't support empty values.
const TOMBSTONE_VALUE: &[u8] = &*b" ";
/// Unavailable blocks are kept for 1 hour.
const KEEP_UNAVAILABLE_FOR: Duration = Duration::from_secs(60 * 60);
/// Finalized data is kept for 25 hours.
const KEEP_FINALIZED_FOR: Duration = Duration::from_secs(25 * 60 * 60);
/// The pruning interval.
const PRUNING_INTERVAL: Duration = Duration::from_secs(60 * 5);
/// Unix time wrapper with big-endian encoding.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
struct BETimestamp(u64);
impl Encode for BETimestamp {
fn size_hint(&self) -> usize {
std::mem::size_of::<u64>()
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
f(&self.0.to_be_bytes())
}
}
impl Decode for BETimestamp {
fn decode<I: Input>(value: &mut I) -> Result<Self, CodecError> {
<[u8; 8]>::decode(value).map(u64::from_be_bytes).map(Self)
}
}
impl From<Duration> for BETimestamp {
fn from(d: Duration) -> Self {
BETimestamp(d.as_secs())
}
}
impl Into<Duration> for BETimestamp {
fn into(self) -> Duration {
Duration::from_secs(self.0)
}
}
/// [`BlockNumber`] wrapper with big-endian encoding.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord)]
struct BEBlockNumber(BlockNumber);
impl Encode for BEBlockNumber {
fn size_hint(&self) -> usize {
std::mem::size_of::<BlockNumber>()
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
f(&self.0.to_be_bytes())
}
}
impl Decode for BEBlockNumber {
fn decode<I: Input>(value: &mut I) -> Result<Self, CodecError> {
<[u8; std::mem::size_of::<BlockNumber>()]>::decode(value)
.map(BlockNumber::from_be_bytes)
.map(Self)
}
}
#[derive(Debug, Encode, Decode)]
enum State {
/// Candidate data was first observed at the given time but is not available in any block.
#[codec(index = 0)]
Unavailable(BETimestamp),
/// The candidate was first observed at the given time and was included in the given list of unfinalized blocks, which may be
/// empty. The timestamp here is not used for pruning. Either one of these blocks will be finalized or the state will regress to
/// `State::Unavailable`, in which case the same timestamp will be reused. Blocks are sorted ascending first by block number and
/// then hash.
#[codec(index = 1)]
Unfinalized(BETimestamp, Vec<(BEBlockNumber, Hash)>),
/// Candidate data has appeared in a finalized block and did so at the given time.
#[codec(index = 2)]
Finalized(BETimestamp),
}
// Meta information about a candidate.
#[derive(Debug, Encode, Decode)]
struct CandidateMeta {
state: State,
data_available: bool,
chunks_stored: BitVec<BitOrderLsb0, u8>,
}
fn query_inner<D: Decode>(
db: &Arc<dyn KeyValueDB>,
column: u32,
key: &[u8],
) -> Result<Option<D>, Error> {
match db.get(column, key) {
Ok(Some(raw)) => {
let res = D::decode(&mut &raw[..])?;
Ok(Some(res))
},
Ok(None) => Ok(None),
Err(err) => {
tracing::warn!(target: LOG_TARGET, ?err, "Error reading from the availability store");
Err(err.into())
},
}
}
fn write_available_data(
tx: &mut DBTransaction,
config: &Config,
hash: &CandidateHash,
available_data: &AvailableData,
) {
let key = (AVAILABLE_PREFIX, hash).encode();
tx.put_vec(config.col_data, &key[..], available_data.encode());
}
fn load_available_data(
db: &Arc<dyn KeyValueDB>,
config: &Config,
hash: &CandidateHash,
) -> Result<Option<AvailableData>, Error> {
let key = (AVAILABLE_PREFIX, hash).encode();
query_inner(db, config.col_data, &key)
}
fn delete_available_data(tx: &mut DBTransaction, config: &Config, hash: &CandidateHash) {
let key = (AVAILABLE_PREFIX, hash).encode();
tx.delete(config.col_data, &key[..])
}
fn load_chunk(
db: &Arc<dyn KeyValueDB>,
config: &Config,
candidate_hash: &CandidateHash,
chunk_index: ValidatorIndex,
) -> Result<Option<ErasureChunk>, Error> {
let key = (CHUNK_PREFIX, candidate_hash, chunk_index).encode();
query_inner(db, config.col_data, &key)
}
fn write_chunk(
tx: &mut DBTransaction,
config: &Config,
candidate_hash: &CandidateHash,
chunk_index: ValidatorIndex,
erasure_chunk: &ErasureChunk,
) {
let key = (CHUNK_PREFIX, candidate_hash, chunk_index).encode();
tx.put_vec(config.col_data, &key, erasure_chunk.encode());
}
fn delete_chunk(
tx: &mut DBTransaction,
config: &Config,
candidate_hash: &CandidateHash,
chunk_index: ValidatorIndex,
) {
let key = (CHUNK_PREFIX, candidate_hash, chunk_index).encode();
tx.delete(config.col_data, &key[..]);
}
fn load_meta(
db: &Arc<dyn KeyValueDB>,
config: &Config,
hash: &CandidateHash,
) -> Result<Option<CandidateMeta>, Error> {
let key = (META_PREFIX, hash).encode();
query_inner(db, config.col_meta, &key)
}
fn write_meta(tx: &mut DBTransaction, config: &Config, hash: &CandidateHash, meta: &CandidateMeta) {
let key = (META_PREFIX, hash).encode();
tx.put_vec(config.col_meta, &key, meta.encode());
}
fn delete_meta(tx: &mut DBTransaction, config: &Config, hash: &CandidateHash) {
let key = (META_PREFIX, hash).encode();
tx.delete(config.col_meta, &key[..])
}
fn delete_unfinalized_height(tx: &mut DBTransaction, config: &Config, block_number: BlockNumber) {
let prefix = (UNFINALIZED_PREFIX, BEBlockNumber(block_number)).encode();
tx.delete_prefix(config.col_meta, &prefix);
}
fn delete_unfinalized_inclusion(
tx: &mut DBTransaction,
config: &Config,
block_number: BlockNumber,
block_hash: &Hash,
candidate_hash: &CandidateHash,
) {
let key =
(UNFINALIZED_PREFIX, BEBlockNumber(block_number), block_hash, candidate_hash).encode();
tx.delete(config.col_meta, &key[..]);
}
fn delete_pruning_key(
tx: &mut DBTransaction,
config: &Config,
t: impl Into<BETimestamp>,
h: &CandidateHash,
) {
let key = (PRUNE_BY_TIME_PREFIX, t.into(), h).encode();
tx.delete(config.col_meta, &key);
}
fn write_pruning_key(
tx: &mut DBTransaction,
config: &Config,
t: impl Into<BETimestamp>,
h: &CandidateHash,
) {
let t = t.into();
let key = (PRUNE_BY_TIME_PREFIX, t, h).encode();
tx.put(config.col_meta, &key, TOMBSTONE_VALUE);
}
fn finalized_block_range(finalized: BlockNumber) -> (Vec<u8>, Vec<u8>) {
// We use big-endian encoding to iterate in ascending order.
let start = UNFINALIZED_PREFIX.encode();
let end = (UNFINALIZED_PREFIX, BEBlockNumber(finalized + 1)).encode();
(start, end)
}
fn write_unfinalized_block_contains(
tx: &mut DBTransaction,
config: &Config,
n: BlockNumber,
h: &Hash,
ch: &CandidateHash,
) {
let key = (UNFINALIZED_PREFIX, BEBlockNumber(n), h, ch).encode();
tx.put(config.col_meta, &key, TOMBSTONE_VALUE);
}
fn pruning_range(now: impl Into<BETimestamp>) -> (Vec<u8>, Vec<u8>) {
let start = PRUNE_BY_TIME_PREFIX.encode();
let end = (PRUNE_BY_TIME_PREFIX, BETimestamp(now.into().0 + 1)).encode();
(start, end)
}
fn decode_unfinalized_key(s: &[u8]) -> Result<(BlockNumber, Hash, CandidateHash), CodecError> {
if !s.starts_with(UNFINALIZED_PREFIX) {
return Err("missing magic string".into())
}
<(BEBlockNumber, Hash, CandidateHash)>::decode(&mut &s[UNFINALIZED_PREFIX.len()..])
.map(|(b, h, ch)| (b.0, h, ch))
}
fn decode_pruning_key(s: &[u8]) -> Result<(Duration, CandidateHash), CodecError> {
if !s.starts_with(PRUNE_BY_TIME_PREFIX) {
return Err("missing magic string".into())
}
<(BETimestamp, CandidateHash)>::decode(&mut &s[PRUNE_BY_TIME_PREFIX.len()..])
.map(|(t, ch)| (t.into(), ch))
}
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum Error {
#[error(transparent)]
RuntimeApi(#[from] RuntimeApiError),
#[error(transparent)]
ChainApi(#[from] ChainApiError),
#[error(transparent)]
Erasure(#[from] erasure::Error),
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Oneshot(#[from] oneshot::Canceled),
#[error(transparent)]
Subsystem(#[from] SubsystemError),
#[error(transparent)]
Time(#[from] SystemTimeError),
#[error(transparent)]
Codec(#[from] CodecError),
#[error("Custom databases are not supported")]
CustomDatabase,
}
impl Error {
/// Determine if the error is irrecoverable
/// or notifying the user via means of logging
/// is sufficient.
fn is_fatal(&self) -> bool {
match self {
Self::Io(_) => true,
Self::Oneshot(_) => true,
Self::CustomDatabase => true,
_ => false,
}
}
}
impl Error {
fn trace(&self) {
match self {
// don't spam the log with spurious errors
Self::RuntimeApi(_) | Self::Oneshot(_) => {
tracing::debug!(target: LOG_TARGET, err = ?self)
},
// it's worth reporting otherwise
_ => tracing::warn!(target: LOG_TARGET, err = ?self),
}
}
}
/// Struct holding pruning timing configuration.
/// The only purpose of this structure is to use different timing
/// configurations in production and in testing.
#[derive(Clone)]
struct PruningConfig {
/// How long unavailable data should be kept.
keep_unavailable_for: Duration,
/// How long finalized data should be kept.
keep_finalized_for: Duration,
/// How often to perform data pruning.
pruning_interval: Duration,
}
impl Default for PruningConfig {
fn default() -> Self {
Self {
keep_unavailable_for: KEEP_UNAVAILABLE_FOR,
keep_finalized_for: KEEP_FINALIZED_FOR,
pruning_interval: PRUNING_INTERVAL,
}
}
}
/// Configuration for the availability store.
#[derive(Debug, Clone, Copy)]
pub struct Config {
/// The column family for availability data and chunks.
pub col_data: u32,
/// The column family for availability store meta information.
pub col_meta: u32,
}
trait Clock: Send + Sync {
// Returns time since unix epoch.
fn now(&self) -> Result<Duration, Error>;
}
struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> Result<Duration, Error> {
SystemTime::now().duration_since(UNIX_EPOCH).map_err(Into::into)
}
}
/// An implementation of the Availability Store subsystem.
pub struct AvailabilityStoreSubsystem {
pruning_config: PruningConfig,
config: Config,
db: Arc<dyn KeyValueDB>,
known_blocks: KnownUnfinalizedBlocks,
finalized_number: Option<BlockNumber>,
metrics: Metrics,
clock: Box<dyn Clock>,
}
impl AvailabilityStoreSubsystem {
/// Create a new `AvailabilityStoreSubsystem` with a given config on disk.
pub fn new(db: Arc<dyn KeyValueDB>, config: Config, metrics: Metrics) -> Self {
Self::with_pruning_config_and_clock(
db,
config,
PruningConfig::default(),
Box::new(SystemClock),
metrics,
)
}
/// Create a new `AvailabilityStoreSubsystem` with a given config on disk.
fn with_pruning_config_and_clock(
db: Arc<dyn KeyValueDB>,
config: Config,
pruning_config: PruningConfig,
clock: Box<dyn Clock>,
metrics: Metrics,
) -> Self {
Self {
pruning_config,
config,
db,
metrics,
clock,
known_blocks: KnownUnfinalizedBlocks::default(),
finalized_number: None,
}
}
}
/// We keep the hashes and numbers of all unfinalized
/// processed blocks in memory.
#[derive(Default, Debug)]
struct KnownUnfinalizedBlocks {
by_hash: HashSet<Hash>,
by_number: BTreeSet<(BlockNumber, Hash)>,
}
impl KnownUnfinalizedBlocks {
/// Check whether the block has been already processed.
fn is_known(&self, hash: &Hash) -> bool {
self.by_hash.contains(hash)
}
/// Insert a new block into the known set.
fn insert(&mut self, hash: Hash, number: BlockNumber) {
self.by_hash.insert(hash);
self.by_number.insert((number, hash));
}
/// Prune all finalized blocks.
fn prune_finalized(&mut self, finalized: BlockNumber) {
// split_off returns everything after the given key, including the key
let split_point = finalized.saturating_add(1);
let mut finalized = self.by_number.split_off(&(split_point, Hash::zero()));
// after split_off `finalized` actually contains unfinalized blocks, we need to swap
std::mem::swap(&mut self.by_number, &mut finalized);
for (_, block) in finalized {
self.by_hash.remove(&block);
}
}
}
impl<Context> overseer::Subsystem<Context, SubsystemError> for AvailabilityStoreSubsystem
where
Context: SubsystemContext<Message = AvailabilityStoreMessage>,
Context: overseer::SubsystemContext<Message = AvailabilityStoreMessage>,
{
fn start(self, ctx: Context) -> SpawnedSubsystem {
let future = run(self, ctx).map(|_| Ok(())).boxed();
SpawnedSubsystem { name: "availability-store-subsystem", future }
}
}
async fn run<Context>(mut subsystem: AvailabilityStoreSubsystem, mut ctx: Context)
where
Context: SubsystemContext<Message = AvailabilityStoreMessage>,
Context: overseer::SubsystemContext<Message = AvailabilityStoreMessage>,
{
let mut next_pruning = Delay::new(subsystem.pruning_config.pruning_interval).fuse();
loop {
let res = run_iteration(&mut ctx, &mut subsystem, &mut next_pruning).await;
match res {
Err(e) => {
e.trace();
if e.is_fatal() {
break
}
},
Ok(true) => {
tracing::info!(target: LOG_TARGET, "received `Conclude` signal, exiting");
break
},
Ok(false) => continue,
}
}
}
async fn run_iteration<Context>(
ctx: &mut Context,
subsystem: &mut AvailabilityStoreSubsystem,
mut next_pruning: &mut future::Fuse<Delay>,
) -> Result<bool, Error>
where
Context: SubsystemContext<Message = AvailabilityStoreMessage>,
Context: overseer::SubsystemContext<Message = AvailabilityStoreMessage>,
{
select! {
incoming = ctx.recv().fuse() => {
match incoming? {
FromOverseer::Signal(OverseerSignal::Conclude) => return Ok(true),
FromOverseer::Signal(OverseerSignal::ActiveLeaves(
ActiveLeavesUpdate { activated, .. })
) => {
for activated in activated.into_iter() {
let _timer = subsystem.metrics.time_block_activated();
process_block_activated(ctx, subsystem, activated.hash).await?;
}
}
FromOverseer::Signal(OverseerSignal::BlockFinalized(hash, number)) => {
let _timer = subsystem.metrics.time_process_block_finalized();
subsystem.finalized_number = Some(number);
subsystem.known_blocks.prune_finalized(number);
process_block_finalized(
ctx,
&subsystem,
hash,
number,
).await?;
}
FromOverseer::Communication { msg } => {
let _timer = subsystem.metrics.time_process_message();
process_message(subsystem, msg)?;
}
}
}
_ = next_pruning => {
// It's important to set the delay before calling `prune_all` because an error in `prune_all`
// could lead to the delay not being set again. Then we would never prune anything anymore.
*next_pruning = Delay::new(subsystem.pruning_config.pruning_interval).fuse();
let _timer = subsystem.metrics.time_pruning();
prune_all(&subsystem.db, &subsystem.config, &*subsystem.clock)?;
}
}
Ok(false)
}
async fn process_block_activated<Context>(
ctx: &mut Context,
subsystem: &mut AvailabilityStoreSubsystem,
activated: Hash,
) -> Result<(), Error>
where
Context: SubsystemContext<Message = AvailabilityStoreMessage>,
Context: overseer::SubsystemContext<Message = AvailabilityStoreMessage>,
{
let now = subsystem.clock.now()?;
let block_header = {
let (tx, rx) = oneshot::channel();
ctx.send_message(ChainApiMessage::BlockHeader(activated, tx)).await;
match rx.await?? {
None => return Ok(()),
Some(n) => n,
}
};
let block_number = block_header.number;
let new_blocks = util::determine_new_blocks(
ctx.sender(),
|hash| -> Result<bool, Error> { Ok(subsystem.known_blocks.is_known(hash)) },
activated,
&block_header,
subsystem.finalized_number.unwrap_or(block_number.saturating_sub(1)),
)
.await?;
// determine_new_blocks is descending in block height
for (hash, header) in new_blocks.into_iter().rev() {
// it's important to commit the db transactions for a head before the next one is processed
// alternatively, we could utilize the OverlayBackend from approval-voting
let mut tx = DBTransaction::new();
process_new_head(
ctx,
&subsystem.db,
&mut tx,
&subsystem.config,
&subsystem.pruning_config,
now,
hash,
header,
)
.await?;
subsystem.known_blocks.insert(hash, block_number);
subsystem.db.write(tx)?;
}
Ok(())
}
async fn process_new_head<Context>(
ctx: &mut Context,
db: &Arc<dyn KeyValueDB>,
db_transaction: &mut DBTransaction,
config: &Config,
pruning_config: &PruningConfig,
now: Duration,
hash: Hash,
header: Header,
) -> Result<(), Error>
where
Context: SubsystemContext<Message = AvailabilityStoreMessage>,
Context: overseer::SubsystemContext<Message = AvailabilityStoreMessage>,
{
let candidate_events = util::request_candidate_events(hash, ctx.sender()).await.await??;
// We need to request the number of validators based on the parent state,
// as that is the number of validators used to create this block.
let n_validators =
util::request_validators(header.parent_hash, ctx.sender()).await.await??.len();
for event in candidate_events {
match event {
CandidateEvent::CandidateBacked(receipt, _head, _core_index, _group_index) => {
note_block_backed(
db,
db_transaction,
config,
pruning_config,
now,
n_validators,
receipt,
)?;
},
CandidateEvent::CandidateIncluded(receipt, _head, _core_index, _group_index) => {
note_block_included(
db,
db_transaction,
config,
pruning_config,
(header.number, hash),
receipt,
)?;
},
_ => {},
}
}
Ok(())
}
fn note_block_backed(
db: &Arc<dyn KeyValueDB>,
db_transaction: &mut DBTransaction,
config: &Config,
pruning_config: &PruningConfig,
now: Duration,
n_validators: usize,
candidate: CandidateReceipt,
) -> Result<(), Error> {
let candidate_hash = candidate.hash();
tracing::debug!(target: LOG_TARGET, ?candidate_hash, "Candidate backed");
if load_meta(db, config, &candidate_hash)?.is_none() {
let meta = CandidateMeta {
state: State::Unavailable(now.into()),
data_available: false,
chunks_stored: bitvec::bitvec![BitOrderLsb0, u8; 0; n_validators],
};
let prune_at = now + pruning_config.keep_unavailable_for;
write_pruning_key(db_transaction, config, prune_at, &candidate_hash);
write_meta(db_transaction, config, &candidate_hash, &meta);
}
Ok(())
}
fn note_block_included(
db: &Arc<dyn KeyValueDB>,
db_transaction: &mut DBTransaction,
config: &Config,
pruning_config: &PruningConfig,
block: (BlockNumber, Hash),
candidate: CandidateReceipt,
) -> Result<(), Error> {
let candidate_hash = candidate.hash();
match load_meta(db, config, &candidate_hash)? {
None => {
// This is alarming. We've observed a block being included without ever seeing it backed.
// Warn and ignore.
tracing::warn!(
target: LOG_TARGET,
?candidate_hash,
"Candidate included without being backed?",
);
},
Some(mut meta) => {
let be_block = (BEBlockNumber(block.0), block.1);
tracing::debug!(target: LOG_TARGET, ?candidate_hash, "Candidate included");
meta.state = match meta.state {
State::Unavailable(at) => {
let at_d: Duration = at.into();
let prune_at = at_d + pruning_config.keep_unavailable_for;
delete_pruning_key(db_transaction, config, prune_at, &candidate_hash);
State::Unfinalized(at, vec![be_block])
},
State::Unfinalized(at, mut within) => {
if let Err(i) = within.binary_search(&be_block) {
within.insert(i, be_block);
State::Unfinalized(at, within)
} else {
return Ok(())
}
},
State::Finalized(_at) => {
// This should never happen as a candidate would have to be included after
// finality.
return Ok(())
},
};
write_unfinalized_block_contains(
db_transaction,
config,
block.0,
&block.1,
&candidate_hash,
);
write_meta(db_transaction, config, &candidate_hash, &meta);
},
}
Ok(())
}
macro_rules! peek_num {
($iter:ident) => {
match $iter.peek() {
Some((k, _)) => decode_unfinalized_key(&k[..]).ok().map(|(b, _, _)| b),
None => None,
}
};
}
async fn process_block_finalized<Context>(
ctx: &mut Context,
subsystem: &AvailabilityStoreSubsystem,
finalized_hash: Hash,
finalized_number: BlockNumber,
) -> Result<(), Error>
where
Context: SubsystemContext<Message = AvailabilityStoreMessage>,
Context: overseer::SubsystemContext<Message = AvailabilityStoreMessage>,
{
let now = subsystem.clock.now()?;
let mut next_possible_batch = 0;
loop {
let mut db_transaction = DBTransaction::new();
let (start_prefix, end_prefix) = finalized_block_range(finalized_number);
// We have to do some juggling here of the `iter` to make sure it doesn't cross the `.await` boundary
// as it is not `Send`. That is why we create the iterator once within this loop, drop it,
// do an asynchronous request, and then instantiate the exact same iterator again.
let batch_num = {
let mut iter = subsystem
.db
.iter_with_prefix(subsystem.config.col_meta, &start_prefix)
.take_while(|(k, _)| &k[..] < &end_prefix[..])
.peekable();
match peek_num!(iter) {
None => break, // end of iterator.
Some(n) => n,
}
};
if batch_num < next_possible_batch {
continue
} // sanity.
next_possible_batch = batch_num + 1;
let batch_finalized_hash = if batch_num == finalized_number {
finalized_hash
} else {
let (tx, rx) = oneshot::channel();
ctx.send_message(ChainApiMessage::FinalizedBlockHash(batch_num, tx)).await;
match rx.await? {
Err(err) => {
tracing::warn!(
target: LOG_TARGET,
batch_num,
?err,
"Failed to retrieve finalized block number.",
);
break
},
Ok(None) => {
tracing::warn!(
target: LOG_TARGET,
"Availability store was informed that block #{} is finalized, \
but chain API has no finalized hash.",
batch_num,
);
break
},
Ok(Some(h)) => h,
}
};
let iter = subsystem
.db
.iter_with_prefix(subsystem.config.col_meta, &start_prefix)
.take_while(|(k, _)| &k[..] < &end_prefix[..])
.peekable();
let batch = load_all_at_finalized_height(iter, batch_num, batch_finalized_hash);
// Now that we've iterated over the entire batch at this finalized height,
// update the meta.
delete_unfinalized_height(&mut db_transaction, &subsystem.config, batch_num);
update_blocks_at_finalized_height(&subsystem, &mut db_transaction, batch, batch_num, now)?;
// We need to write at the end of the loop so the prefix iterator doesn't pick up the same values again
// in the next iteration. Another unfortunate effect of having to re-initialize the iterator.
subsystem.db.write(db_transaction)?;
}
Ok(())
}
// loads all candidates at the finalized height and maps them to `true` if finalized
// and `false` if unfinalized.
fn load_all_at_finalized_height(
mut iter: std::iter::Peekable<impl Iterator<Item = (Box<[u8]>, Box<[u8]>)>>,
block_number: BlockNumber,
finalized_hash: Hash,
) -> impl IntoIterator<Item = (CandidateHash, bool)> {
// maps candidate hashes to true if finalized, false otherwise.
let mut candidates = HashMap::new();
// Load all candidates that were included at this height.
loop {
match peek_num!(iter) {
None => break, // end of iterator.
Some(n) if n != block_number => break, // end of batch.
_ => {},
}
let (k, _v) = iter.next().expect("`peek` used to check non-empty; qed");
let (_, block_hash, candidate_hash) =
decode_unfinalized_key(&k[..]).expect("`peek_num` checks validity of key; qed");
if block_hash == finalized_hash {
candidates.insert(candidate_hash, true);
} else {
candidates.entry(candidate_hash).or_insert(false);
}
}
candidates
}
fn update_blocks_at_finalized_height(
subsystem: &AvailabilityStoreSubsystem,
db_transaction: &mut DBTransaction,
candidates: impl IntoIterator<Item = (CandidateHash, bool)>,
block_number: BlockNumber,
now: Duration,
) -> Result<(), Error> {
for (candidate_hash, is_finalized) in candidates {
let mut meta = match load_meta(&subsystem.db, &subsystem.config, &candidate_hash)? {
None => {
tracing::warn!(
target: LOG_TARGET,
"Dangling candidate metadata for {}",
candidate_hash,
);
continue
},
Some(c) => c,
};
if is_finalized {
// Clear everything else related to this block. We're finalized now!
match meta.state {
State::Finalized(_) => continue, // sanity
State::Unavailable(at) => {
// This is also not going to happen; the very fact that we are
// iterating over the candidate here indicates that `State` should
// be `Unfinalized`.
delete_pruning_key(db_transaction, &subsystem.config, at, &candidate_hash);
},
State::Unfinalized(_, blocks) => {
for (block_num, block_hash) in blocks.iter().cloned() {
// this exact height is all getting cleared out anyway.
if block_num.0 != block_number {
delete_unfinalized_inclusion(
db_transaction,
&subsystem.config,
block_num.0,
&block_hash,
&candidate_hash,
);
}
}
},
}
meta.state = State::Finalized(now.into());
// Write the meta and a pruning record.
write_meta(db_transaction, &subsystem.config, &candidate_hash, &meta);
write_pruning_key(
db_transaction,
&subsystem.config,
now + subsystem.pruning_config.keep_finalized_for,
&candidate_hash,
);
} else {
meta.state = match meta.state {
State::Finalized(_) => continue, // sanity.
State::Unavailable(_) => continue, // sanity.
State::Unfinalized(at, mut blocks) => {
// Clear out everything at this height.
blocks.retain(|(n, _)| n.0 != block_number);
// If empty, we need to go back to being unavailable as we aren't
// aware of any blocks this is included in.
if blocks.is_empty() {
let at_d: Duration = at.into();
let prune_at = at_d + subsystem.pruning_config.keep_unavailable_for;
write_pruning_key(
db_transaction,
&subsystem.config,
prune_at,
&candidate_hash,
);
State::Unavailable(at)
} else {
State::Unfinalized(at, blocks)
}
},
};
// Update the meta entry.
write_meta(db_transaction, &subsystem.config, &candidate_hash, &meta)
}
}
Ok(())
}
fn process_message(
subsystem: &mut AvailabilityStoreSubsystem,
msg: AvailabilityStoreMessage,
) -> Result<(), Error> {
match msg {
AvailabilityStoreMessage::QueryAvailableData(candidate, tx) => {
let _ = tx.send(load_available_data(&subsystem.db, &subsystem.config, &candidate)?);
},
AvailabilityStoreMessage::QueryDataAvailability(candidate, tx) => {
let a = load_meta(&subsystem.db, &subsystem.config, &candidate)?
.map_or(false, |m| m.data_available);
let _ = tx.send(a);
},
AvailabilityStoreMessage::QueryChunk(candidate, validator_index, tx) => {
let _timer = subsystem.metrics.time_get_chunk();
let _ =
tx.send(load_chunk(&subsystem.db, &subsystem.config, &candidate, validator_index)?);
},
AvailabilityStoreMessage::QueryAllChunks(candidate, tx) => {
match load_meta(&subsystem.db, &subsystem.config, &candidate)? {
None => {
let _ = tx.send(Vec::new());
},
Some(meta) => {
let mut chunks = Vec::new();
for (index, _) in meta.chunks_stored.iter().enumerate().filter(|(_, b)| **b) {
let _timer = subsystem.metrics.time_get_chunk();
match load_chunk(
&subsystem.db,
&subsystem.config,
&candidate,
ValidatorIndex(index as _),
)? {
Some(c) => chunks.push(c),
None => {
tracing::warn!(
target: LOG_TARGET,
?candidate,
index,
"No chunk found for set bit in meta"
);
},
}
}
let _ = tx.send(chunks);
},
}
},
AvailabilityStoreMessage::QueryChunkAvailability(candidate, validator_index, tx) => {
let a = load_meta(&subsystem.db, &subsystem.config, &candidate)?.map_or(false, |m| {
*m.chunks_stored.get(validator_index.0 as usize).as_deref().unwrap_or(&false)
});
let _ = tx.send(a);
},
AvailabilityStoreMessage::StoreChunk { candidate_hash, chunk, tx } => {
subsystem.metrics.on_chunks_received(1);
let _timer = subsystem.metrics.time_store_chunk();
match store_chunk(&subsystem.db, &subsystem.config, candidate_hash, chunk) {
Ok(true) => {
let _ = tx.send(Ok(()));
},
Ok(false) => {
let _ = tx.send(Err(()));
},
Err(e) => {
let _ = tx.send(Err(()));
return Err(e)
},
}
},
AvailabilityStoreMessage::StoreAvailableData {
candidate_hash,
n_validators,
available_data,
tx,
} => {
subsystem.metrics.on_chunks_received(n_validators as _);
let _timer = subsystem.metrics.time_store_available_data();
let res =
store_available_data(&subsystem, candidate_hash, n_validators as _, available_data);
match res {
Ok(()) => {
let _ = tx.send(Ok(()));
},
Err(e) => {
let _ = tx.send(Err(()));
return Err(e.into())
},
}
},
}
Ok(())
}
// Ok(true) on success, Ok(false) on failure, and Err on internal error.
fn store_chunk(
db: &Arc<dyn KeyValueDB>,
config: &Config,
candidate_hash: CandidateHash,
chunk: ErasureChunk,
) -> Result<bool, Error> {
let mut tx = DBTransaction::new();
let mut meta = match load_meta(db, config, &candidate_hash)? {
Some(m) => m,
None => return Ok(false), // we weren't informed of this candidate by import events.
};
match meta.chunks_stored.get(chunk.index.0 as usize).map(|b| *b) {
Some(true) => return Ok(true), // already stored.
Some(false) => {
meta.chunks_stored.set(chunk.index.0 as usize, true);
write_chunk(&mut tx, config, &candidate_hash, chunk.index, &chunk);
write_meta(&mut tx, config, &candidate_hash, &meta);
},
None => return Ok(false), // out of bounds.
}
tracing::debug!(
target: LOG_TARGET,
?candidate_hash,
chunk_index = %chunk.index.0,
"Stored chunk index for candidate.",
);
db.write(tx)?;
Ok(true)
}
// Ok(true) on success, Ok(false) on failure, and Err on internal error.
fn store_available_data(
subsystem: &AvailabilityStoreSubsystem,
candidate_hash: CandidateHash,
n_validators: usize,
available_data: AvailableData,
) -> Result<(), Error> {
let mut tx = DBTransaction::new();
let mut meta = match load_meta(&subsystem.db, &subsystem.config, &candidate_hash)? {
Some(m) => {
if m.data_available {
return Ok(()) // already stored.
}
m
},
None => {
let now = subsystem.clock.now()?;
// Write a pruning record.
let prune_at = now + subsystem.pruning_config.keep_unavailable_for;
write_pruning_key(&mut tx, &subsystem.config, prune_at, &candidate_hash);
CandidateMeta {
state: State::Unavailable(now.into()),
data_available: false,
chunks_stored: BitVec::new(),
}
},
};
let chunks = erasure::obtain_chunks_v1(n_validators, &available_data)?;
let branches = erasure::branches(chunks.as_ref());
let erasure_chunks = chunks.iter().zip(branches.map(|(proof, _)| proof)).enumerate().map(
|(index, (chunk, proof))| ErasureChunk {
chunk: chunk.clone(),
proof,
index: ValidatorIndex(index as u32),
},
);
for chunk in erasure_chunks {
write_chunk(&mut tx, &subsystem.config, &candidate_hash, chunk.index, &chunk);
}
meta.data_available = true;
meta.chunks_stored = bitvec::bitvec![BitOrderLsb0, u8; 1; n_validators];
write_meta(&mut tx, &subsystem.config, &candidate_hash, &meta);
write_available_data(&mut tx, &subsystem.config, &candidate_hash, &available_data);
subsystem.db.write(tx)?;
tracing::debug!(target: LOG_TARGET, ?candidate_hash, "Stored data and chunks");
Ok(())
}
fn prune_all(db: &Arc<dyn KeyValueDB>, config: &Config, clock: &dyn Clock) -> Result<(), Error> {
let now = clock.now()?;
let (range_start, range_end) = pruning_range(now);
let mut tx = DBTransaction::new();
let iter = db
.iter_with_prefix(config.col_meta, &range_start[..])
.take_while(|(k, _)| &k[..] < &range_end[..]);
for (k, _v) in iter {
tx.delete(config.col_meta, &k[..]);
let (_, candidate_hash) = match decode_pruning_key(&k[..]) {
Ok(m) => m,
Err(_) => continue, // sanity
};
delete_meta(&mut tx, config, &candidate_hash);
// Clean up all attached data of the candidate.
if let Some(meta) = load_meta(db, config, &candidate_hash)? {
// delete available data.
if meta.data_available {
delete_available_data(&mut tx, config, &candidate_hash)
}
// delete chunks.
for (i, b) in meta.chunks_stored.iter().enumerate() {
if *b {
delete_chunk(&mut tx, config, &candidate_hash, ValidatorIndex(i as _));
}
}
// delete unfinalized block references. Pruning references don't need to be
// manually taken care of as we are deleting them as we go in the outer loop.
if let State::Unfinalized(_, blocks) = meta.state {
for (block_number, block_hash) in blocks {
delete_unfinalized_inclusion(
&mut tx,
config,
block_number.0,
&block_hash,
&candidate_hash,
);
}
}
}
}
db.write(tx)?;
Ok(())
}
| 27.470634 | 129 | 0.684692 |
2fe929dd42b3b0b7a3357d57d0037bdd45f77d8e | 585 | //! Available methods.
use hyper::Method;
use serde::{de::DeserializeOwned, Serialize};
pub mod builders;
mod close;
mod forward_message;
mod get_chat;
mod get_me;
mod get_updates;
mod log_out;
mod send_chat_action;
mod send_dice;
mod send_message;
pub use close::*;
pub use forward_message::*;
pub use get_chat::*;
pub use get_me::*;
pub use get_updates::*;
pub use log_out::*;
pub use send_chat_action::*;
pub use send_dice::*;
pub use send_message::*;
pub trait Request: Serialize {
const NAME: &'static str;
const METHOD: Method;
type Response: DeserializeOwned;
}
| 18.28125 | 45 | 0.726496 |
e4fcbb117a5057c0dd55eb757713496102a08bad | 668 | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:derive-unstable-2.rs
#![allow(warnings)]
#[macro_use]
extern crate derive_unstable_2;
#[derive(Unstable)]
//~^ ERROR: reserved for internal compiler
struct A;
fn main() {
foo();
}
| 26.72 | 68 | 0.726048 |
8760345409c8e9dfa1d1bf6ef6e1c556fa298fc7 | 304 | // error-pattern: pointer at offset 32 is out-of-bounds
fn main() {
let x = Box::into_raw(Box::new(0u32));
let x = x.wrapping_offset(8); // ok, this has no inbounds tag
let _x = unsafe { x.offset(0) }; // UB despite offset 0, the pointer is not inbounds of the only object it can point to
}
| 38 | 123 | 0.661184 |
64b63c01eafe3aa201949e707c8d35a1f1c31f87 | 1,502 | use std::collections::HashSet;
use std::hash::Hash;
use std::time::Instant;
use unique_id::random::RandomGenerator;
use unique_id::sequence::SequenceGenerator;
use unique_id::string::StringGenerator;
use unique_id::{Generator, GeneratorWithInvalid};
#[test]
fn test_random_uniqueness() {
let generator = RandomGenerator::default();
test_generator(generator, Some(RandomGenerator::invalid_id()), "random");
}
#[test]
fn test_sequence_uniqueness() {
let generator = SequenceGenerator::default();
test_generator(generator, Some(SequenceGenerator::invalid_id()), "sequence");
}
#[test]
fn test_string_uniqueness() {
let generator = StringGenerator::default();
test_generator(generator, Some(StringGenerator::invalid_id()), "string");
}
const ITERATIONS: usize = 1_000_000;
fn test_generator<T: PartialEq + Eq + Hash>(
generator: impl Generator<T>,
illegal: Option<T>,
label: &str,
) {
let mut generated = HashSet::new();
let now = Instant::now();
for _ in 0..ITERATIONS {
let value = generator.next_id();
if let Some(illegal) = &illegal {
assert!(&value != illegal);
}
generated.insert(value);
}
// Anything other than equality here implies that non-unique
// values were inserted into the set and therefore de-duped.
assert_eq!(generated.len(), ITERATIONS);
println!(
"Generated {} {} values in {}ms",
ITERATIONS,
label,
now.elapsed().as_millis()
);
}
| 28.339623 | 81 | 0.667776 |
efa8e29c4946af94538a55d1ef9c735abe7f80df | 9,149 | use std::{os::unix::io::RawFd, sync::Arc};
use adw::prelude::*;
use ashpd::{
desktop::{
screencast::{CursorMode, PersistMode, ScreenCastProxy, SourceType, Stream},
SessionProxy,
},
enumflags2::BitFlags,
zbus, WindowIdentifier,
};
use futures::lock::Mutex;
use gtk::{
glib::{self, clone},
subclass::prelude::*,
};
use crate::widgets::{
CameraPaintable, NotificationKind, PortalPage, PortalPageExt, PortalPageImpl,
};
mod imp {
use adw::subclass::prelude::*;
use super::*;
#[derive(Debug, Default, gtk::CompositeTemplate)]
#[template(resource = "/com/belmoussaoui/ashpd/demo/screencast.ui")]
pub struct ScreenCastPage {
#[template_child]
pub streams_carousel: TemplateChild<adw::Carousel>,
#[template_child]
pub response_group: TemplateChild<adw::PreferencesGroup>,
#[template_child]
pub multiple_switch: TemplateChild<gtk::Switch>,
pub session: Arc<Mutex<Option<SessionProxy<'static>>>>,
#[template_child]
pub monitor_check: TemplateChild<gtk::CheckButton>,
#[template_child]
pub window_check: TemplateChild<gtk::CheckButton>,
#[template_child]
pub virtual_check: TemplateChild<gtk::CheckButton>,
#[template_child]
pub cursor_mode_combo: TemplateChild<adw::ComboRow>,
#[template_child]
pub persist_mode_combo: TemplateChild<adw::ComboRow>,
pub session_token: Arc<Mutex<Option<String>>>,
}
#[glib::object_subclass]
impl ObjectSubclass for ScreenCastPage {
const NAME: &'static str = "ScreenCastPage";
type Type = super::ScreenCastPage;
type ParentType = PortalPage;
fn class_init(klass: &mut Self::Class) {
Self::bind_template(klass);
klass.install_action("screencast.start", None, move |page, _action, _target| {
let ctx = glib::MainContext::default();
ctx.spawn_local(clone!(@weak page => async move {
page.start_session().await;
}));
});
klass.install_action("screencast.stop", None, move |page, _action, _target| {
let ctx = glib::MainContext::default();
ctx.spawn_local(clone!(@weak page => async move {
page.stop_session().await;
page.send_notification("Screen cast session stopped", NotificationKind::Info);
}));
});
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for ScreenCastPage {
fn constructed(&self, obj: &Self::Type) {
obj.action_set_enabled("screencast.stop", false);
self.parent_constructed(obj);
}
}
impl WidgetImpl for ScreenCastPage {
fn map(&self, widget: &Self::Type) {
let ctx = glib::MainContext::default();
ctx.spawn_local(clone!(@weak widget as page => async move {
let imp = page.imp();
if let Ok((cursor_modes, source_types)) = available_types().await {
imp.virtual_check.set_sensitive(source_types.contains(SourceType::Virtual));
imp.monitor_check.set_sensitive(source_types.contains(SourceType::Monitor));
imp.window_check.set_sensitive(source_types.contains(SourceType::Window));
// imp.hidden_check.set_sensitive(cursor_modes.contains(CursorMode::Hidden));
// imp.metadata_check.set_sensitive(cursor_modes.contains(CursorMode::Metadata));
// imp.embedded_check.set_sensitive(cursor_modes.contains(CursorMode::Embedded));
}
}));
self.parent_map(widget);
}
}
impl BinImpl for ScreenCastPage {}
impl PortalPageImpl for ScreenCastPage {}
}
glib::wrapper! {
pub struct ScreenCastPage(ObjectSubclass<imp::ScreenCastPage>) @extends gtk::Widget, adw::Bin, PortalPage;
}
impl ScreenCastPage {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
glib::Object::new(&[]).expect("Failed to create a ScreenCastPage")
}
/// Returns the selected SourceType
fn selected_sources(&self) -> BitFlags<SourceType> {
let imp = self.imp();
let mut sources: BitFlags<SourceType> = BitFlags::empty();
if imp.monitor_check.is_active() {
sources.insert(SourceType::Monitor);
}
if imp.window_check.is_active() {
sources.insert(SourceType::Window);
}
sources
}
/// Returns the selected CursorMode
fn selected_cursor_mode(&self) -> CursorMode {
match self.imp().cursor_mode_combo.selected() {
0 => CursorMode::Hidden,
1 => CursorMode::Embedded,
2 => CursorMode::Metadata,
_ => unreachable!(),
}
}
fn selected_persist_mode(&self) -> PersistMode {
match self.imp().persist_mode_combo.selected() {
0 => PersistMode::DoNot,
1 => PersistMode::Application,
2 => PersistMode::ExplicitlyRevoked,
_ => unreachable!(),
}
}
async fn start_session(&self) {
let imp = self.imp();
self.action_set_enabled("screencast.start", false);
self.action_set_enabled("screencast.stop", true);
match self.screencast().await {
Ok((streams, fd, session)) => {
self.send_notification(
"Screen cast session started successfully",
NotificationKind::Success,
);
streams.iter().for_each(|stream| {
let paintable = CameraPaintable::new();
let picture = gtk::Picture::builder()
.paintable(&paintable)
.hexpand(true)
.vexpand(true)
.build();
paintable.set_pipewire_node_id(fd, Some(stream.pipe_wire_node_id()));
imp.streams_carousel.append(&picture);
});
imp.response_group.show();
imp.session.lock().await.replace(session);
}
Err(err) => {
tracing::error!("{:#?}", err);
self.send_notification(
"Failed to start a screen cast session",
NotificationKind::Error,
);
self.stop_session().await;
}
};
}
async fn stop_session(&self) {
let imp = self.imp();
self.action_set_enabled("screencast.start", true);
self.action_set_enabled("screencast.stop", false);
if let Some(session) = imp.session.lock().await.take() {
let _ = session.close().await;
}
if let Some(mut child) = imp.streams_carousel.first_child() {
loop {
let picture = child.downcast_ref::<gtk::Picture>().unwrap();
let paintable = picture
.paintable()
.unwrap()
.downcast::<CameraPaintable>()
.unwrap();
paintable.close_pipeline();
imp.streams_carousel.remove(picture);
if let Some(next_child) = child.next_sibling() {
child = next_child;
} else {
break;
}
}
}
imp.response_group.hide();
}
async fn screencast(&self) -> ashpd::Result<(Vec<Stream>, RawFd, SessionProxy<'static>)> {
let imp = self.imp();
let sources = self.selected_sources();
let cursor_mode = self.selected_cursor_mode();
let persist_mode = self.selected_persist_mode();
let multiple = imp.multiple_switch.is_active();
let root = self.native().unwrap();
let identifier = WindowIdentifier::from_native(&root).await;
let proxy = ScreenCastProxy::new().await?;
let session = proxy.create_session().await?;
let mut token = imp.session_token.lock().await;
proxy
.select_sources(
&session,
cursor_mode,
sources,
multiple,
token.as_deref(),
persist_mode,
)
.await?;
self.send_notification("Starting a screen cast session", NotificationKind::Info);
let (streams, new_token) = proxy.start(&session, &identifier).await?;
if let Some(t) = new_token {
token.replace(t);
}
let fd = proxy.open_pipe_wire_remote(&session).await?;
Ok((streams, fd, session))
}
}
pub async fn available_types() -> ashpd::Result<(BitFlags<CursorMode>, BitFlags<SourceType>)> {
let proxy = ScreenCastProxy::new().await?;
let cursor_modes = proxy.available_cursor_modes().await?;
let source_types = proxy.available_source_types().await?;
Ok((cursor_modes, source_types))
}
| 35.599222 | 110 | 0.565854 |
f83e30bb5f555ab7a5757a847a59d51a64d7fc68 | 745 | use crate::object::*;
use std::os::raw::c_int;
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub static mut PySeqIter_Type: PyTypeObject;
pub static mut PyCallIter_Type: PyTypeObject;
}
#[inline]
pub unsafe fn PySeqIter_Check(op: *mut PyObject) -> c_int {
(Py_TYPE(op) == &mut PySeqIter_Type) as c_int
}
extern "C" {
#[cfg_attr(PyPy, link_name = "PyPySeqIter_New")]
pub fn PySeqIter_New(arg1: *mut PyObject) -> *mut PyObject;
}
#[inline]
pub unsafe fn PyCallIter_Check(op: *mut PyObject) -> c_int {
(Py_TYPE(op) == &mut PyCallIter_Type) as c_int
}
extern "C" {
#[cfg_attr(PyPy, link_name = "PyPyCallIter_New")]
pub fn PyCallIter_New(arg1: *mut PyObject, arg2: *mut PyObject) -> *mut PyObject;
}
| 25.689655 | 85 | 0.67651 |
e2640d195a0524cb198ccfd5f1bb8b9e5c7899a1 | 2,320 |
use image::{GenericImage, ImageBuffer, Pixel};
use crate::definitions::{Clamp, Image};
use conv::ValueInto;
use std::f32;
use std::i32;
use crate::pixelops::weighted_sum;
use rusttype::{Font, Scale, point, PositionedGlyph};
/// Draws colored text on an image in place. `scale` is augmented font scaling on both the x and y axis (in pixels). Note that this function *does not* support newlines, you must do this manually
pub fn draw_text_mut<'a, I>(
image: &'a mut I,
color: I::Pixel,
x: u32,
y: u32,
scale: Scale,
font: &'a Font<'a>,
text: &'a str,
) where
I: GenericImage,
<I::Pixel as Pixel>::Subpixel: ValueInto<f32> + Clamp<f32>,
{
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
let glyphs: Vec<PositionedGlyph<'_>> = font.layout(text, scale, offset).collect();
for g in glyphs {
if let Some(bb) = g.pixel_bounding_box() {
g.draw(|gx, gy, gv| {
let gx = gx as i32 + bb.min.x;
let gy = gy as i32 + bb.min.y;
let image_x = gx + x as i32;
let image_y = gy + y as i32;
let image_width = image.width() as i32;
let image_height = image.height() as i32;
if image_x >= 0 && image_x < image_width && image_y >= 0 && image_y < image_height {
let pixel = image.get_pixel(image_x as u32, image_y as u32);
let weighted_color = weighted_sum(pixel, color, 1.0 - gv, gv);
image.put_pixel(image_x as u32, image_y as u32, weighted_color);
}
})
}
}
}
/// Draws colored text on an image in place. `scale` is augmented font scaling on both the x and y axis (in pixels). Note that this function *does not* support newlines, you must do this manually
pub fn draw_text<'a, I>(
image: &'a mut I,
color: I::Pixel,
x: u32,
y: u32,
scale: Scale,
font: &'a Font<'a>,
text: &'a str,
) -> Image<I::Pixel>
where
I: GenericImage,
<I::Pixel as Pixel>::Subpixel: ValueInto<f32> + Clamp<f32>,
I::Pixel: 'static,
{
let mut out = ImageBuffer::new(image.width(), image.height());
out.copy_from(image, 0, 0);
draw_text_mut(&mut out, color, x, y, scale, font, text);
out
}
| 32.676056 | 195 | 0.5875 |
d7fefc2ef161fb06942ead6a31b9bfc267861ba1 | 9,734 | // Copyright 2018 sqlparser-rs contributors. All rights reserved.
// Copyright Materialize, Inc. All rights reserved.
//
// This file is derived from the sqlparser-rs project, available at
// https://github.com/andygrove/sqlparser-rs. It was incorporated
// directly into Materialize on December 21, 2019.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file at the
// root of this repository, or online at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashSet;
use lazy_static::lazy_static;
///! This module defines
/// 1) a list of constants for every keyword that
/// can appear in [Word::keyword]:
/// pub const KEYWORD = "KEYWORD"
/// 2) an `ALL_KEYWORDS` array with every keyword in it
/// This is not a list of *reserved* keywords: some of these can be
/// parsed as identifiers if the parser decides so. This means that
/// new keywords can be added here without affecting the parse result.
///
/// As a matter of fact, most of these keywords are not used at all
/// and could be removed.
/// 3) a `RESERVED_FOR_TABLE_ALIAS` array with keywords reserved in a
/// "table alias" context.
/// Defines a string constant for a single keyword: `kw_def!(SELECT);`
/// expands to `pub const SELECT = "SELECT";`
macro_rules! kw_def {
($ident:ident = $string_keyword:expr) => {
pub const $ident: &'static str = $string_keyword;
};
($ident:ident) => {
kw_def!($ident = stringify!($ident));
};
}
/// Expands to a list of `kw_def!()` invocations for each keyword
/// and defines an ALL_KEYWORDS array of the defined constants.
macro_rules! define_keywords {
($(
$ident:ident $(= $string_keyword:expr)?
),*) => {
$(kw_def!($ident $(= $string_keyword)?);)*
pub const ALL_KEYWORDS: &[&str] = &[
$($ident),*
];
}
}
define_keywords!(
ABS,
ADD,
ALL,
ALLOCATE,
ALTER,
AND,
ANY,
APPLY,
ARE,
ARN,
ARRAY,
ARRAY_AGG,
ARRAY_MAX_CARDINALITY,
AS,
ASC,
ASENSITIVE,
ASYMMETRIC,
AT,
ATOMIC,
AUTHORIZATION,
AVG,
AVRO,
BEGIN,
BEGIN_FRAME,
BEGIN_PARTITION,
BETWEEN,
BIGINT,
BINARY,
BLOB,
BOOL,
BOOLEAN,
BOTH,
BROKER,
BY,
BYTEA,
CALL,
CALLED,
CARDINALITY,
CASCADE,
CASCADED,
CASE,
CAST,
CEIL,
CEILING,
CENTURY,
CHAIN,
CHAR,
CHARACTER,
CHARACTER_LENGTH,
CHAR_LENGTH,
CHECK,
CLOB,
CLOSE,
COALESCE,
COLLATE,
COLLECT,
COLUMN,
COLUMNS,
COMMIT,
COMMITTED,
CONDITION,
CONFLUENT,
CONNECT,
CONSISTENCY,
CONSTRAINT,
CONTAINS,
CONVERT,
COPY,
CORR,
CORRESPONDING,
COUNT,
COVAR_POP,
COVAR_SAMP,
CREATE,
CROSS,
CSV,
CUBE,
CUME_DIST,
CURRENT,
CURRENT_CATALOG,
CURRENT_DATE,
CURRENT_DEFAULT_TRANSFORM_GROUP,
CURRENT_PATH,
CURRENT_ROLE,
CURRENT_ROW,
CURRENT_SCHEMA,
CURRENT_TIME,
CURRENT_TIMESTAMP,
CURRENT_TRANSFORM_GROUP_FOR_TYPE,
CURRENT_USER,
CURSOR,
CYCLE,
DATABASE,
DATABASES,
DATAFLOW,
DATE,
DAY,
DAYS,
DEALLOCATE,
DEBEZIUM,
DEC,
DECADE,
DECIMAL,
DECLARE,
DECORRELATED,
DEFAULT,
DELETE,
DELIMITED,
DENSE_RANK,
DEREF,
DESC,
DESCRIBE,
DETERMINISTIC,
DISCONNECT,
DISTINCT,
DOUBLE,
DOW,
DOY,
DROP,
DYNAMIC,
EACH,
ELEMENT,
ELSE,
END,
END_FRAME,
END_PARTITION,
ENVELOPE,
EPOCH,
EQUALS,
ESCAPE,
EVERY,
EXCEPT,
EXEC,
EXECUTE,
EXISTS,
EXP,
EXPLAIN,
EXTENDED,
EXTERNAL,
EXTRACT,
FALSE,
FETCH,
FIELDS,
FILE,
FILTER,
FIRST,
FIRST_VALUE,
FLOAT,
FLOAT4,
FLOAT8,
FLOOR,
FOLLOWING,
FOR,
FOREIGN,
FORMAT,
FRAME_ROW,
FREE,
FROM,
FULL,
FUNCTION,
FUSION,
GET,
GLOBAL,
GRANT,
GROUP,
GROUPING,
GROUPS,
HAVING,
HEADER,
HEADERS,
HOLD,
HOUR,
HOURS,
IDENTITY,
IF,
IMMEDIATE,
IN,
INDEX,
INDEXES,
INDICATOR,
INNER,
INOUT,
INSENSITIVE,
INSERT,
INT,
INT4,
INT8,
INTEGER,
INTERSECT,
INTERSECTION,
INTERVAL,
INTO,
IS,
ISODOW,
ISOLATION,
ISOYEAR,
JOIN,
JSON,
JSONB,
KAFKA,
KEY,
KEYS,
KINESIS,
LAG,
LANGUAGE,
LARGE,
LAST_VALUE,
LATERAL,
LEAD,
LEADING,
LEFT,
LEVEL,
LIKE,
LIKE_REGEX,
LIST,
LIMIT,
LN,
LOCAL,
LOCALTIME,
LOCALTIMESTAMP,
LOCATION,
LOWER,
MATCH,
MATERIALIZED,
MAX,
MEMBER,
MERGE,
MESSAGE,
METHOD,
MICROSECONDS,
MILLENIUM,
MILLISECONDS,
MIN,
MINUTE,
MINUTES,
MOD,
MODIFIES,
MODULE,
MONTH,
MONTHS,
MULTISET,
NATURAL,
NCHAR,
NCLOB,
NEW,
NEXT,
NO,
NONE,
NORMALIZE,
NOT,
NTH_VALUE,
NTILE,
NULL,
NULLIF,
NUMERIC,
OBJECT,
OCCURRENCES_REGEX,
OCF,
OCTET_LENGTH,
OF,
OFFSET,
OLD,
ON,
ONLY,
OPEN,
OPTIMIZED,
OR,
ORDER,
OUT,
OUTER,
OVER,
OVERLAPS,
OVERLAY,
PARAMETER,
PARQUET,
PARTITION,
PERCENT,
PERCENT_RANK,
PERCENTILE_CONT,
PERCENTILE_DISC,
PERIOD,
PLAN,
PORTION,
POSITION,
POSITION_REGEX,
POWER,
PRECEDES,
PRECEDING,
PRECISION,
PREPARE,
PRIMARY,
PROCEDURE,
PROTOBUF,
QUARTER,
RANGE,
RANK,
RAW,
BYTES,
READ,
READS,
REAL,
RECURSIVE,
REF,
REFERENCES,
REFERENCING,
REGCLASS,
REGEX,
REGISTRY,
REGR_AVGX,
REGR_AVGY,
REGR_COUNT,
REGR_INTERCEPT,
REGR_R2,
REGR_SLOPE,
REGR_SXX,
REGR_SXY,
REGR_SYY,
RELEASE,
RENAME,
REPEATABLE,
REPLACE,
RESET,
RESTRICT,
RESULT,
RETURN,
RETURNS,
REVOKE,
RIGHT,
ROLLBACK,
ROLLUP,
ROW,
ROW_NUMBER,
ROWS,
SAVEPOINT,
SCHEMA,
SCHEMAS,
SCOPE,
SCROLL,
SEARCH,
SECOND,
SECONDS,
SEED,
SELECT,
SENSITIVE,
SERIALIZABLE,
SESSION,
SESSION_USER,
SET,
SHOW,
SIMILAR,
SINK,
SINKS,
SMALLINT,
SNAPSHOT,
SOME,
SOURCE,
SOURCES,
SPECIFIC,
SPECIFICTYPE,
SQL,
SQLEXCEPTION,
SQLSTATE,
SQLWARNING,
SQRT,
START,
STATIC,
STDDEV_POP,
STDDEV_SAMP,
STDIN,
STORED,
STRING,
SUBMULTISET,
SUBSTRING,
SUBSTRING_REGEX,
SUCCEEDS,
SUM,
SYMMETRIC,
SYSTEM,
SYSTEM_TIME,
SYSTEM_USER,
TABLE,
TABLES,
TABLESAMPLE,
TAIL,
TEMP,
TEMPORARY,
TEXT,
THEN,
TIES,
TIME,
TIMESTAMP,
TIMESTAMPTZ,
TIMEZONE,
TIMEZONE_HOUR,
TIMEZONE_MINUTE,
TO,
TOPIC,
TRAILING,
TRANSACTION,
TRANSLATE,
TRANSLATE_REGEX,
TRANSLATION,
TREAT,
TRIGGER,
TRIM,
TRIM_ARRAY,
TRUE,
TRUNCATE,
TYPED,
UESCAPE,
UNBOUNDED,
UNCOMMITTED,
UNION,
UNIQUE,
UNKNOWN,
UNNEST,
UPDATE,
UPSERT,
UPPER,
USER,
USING,
UUID,
VALUE,
VALUES,
VALUE_OF,
VAR_POP,
VAR_SAMP,
VARBINARY,
VARCHAR,
VARYING,
VERSIONING,
VIEW,
VIEWS,
WEEK,
WHEN,
WHENEVER,
WHERE,
WIDTH_BUCKET,
WINDOW,
WITH,
WITHIN,
WITHOUT,
WORK,
WRITE,
YEAR,
YEARS,
ZONE,
END_EXEC = "END-EXEC"
);
/// These keywords can't be used as a table alias, so that `FROM table_name alias`
/// can be parsed unambiguously without looking ahead.
pub const RESERVED_FOR_TABLE_ALIAS: &[&str] = &[
// Reserved as both a table and a column alias:
WITH, SELECT, WHERE, GROUP, HAVING, ORDER, LIMIT, OFFSET, FETCH, UNION, EXCEPT, INTERSECT,
// Reserved only as a table alias in the `FROM`/`JOIN` clauses:
ON, JOIN, INNER, CROSS, FULL, LEFT, RIGHT, NATURAL, USING,
// Prevents `a OUTER JOIN b` from parsing as `a AS outer JOIN b`, instead
// producing a nice syntax error.
OUTER,
];
/// Can't be used as a column alias, so that `SELECT <expr> alias`
/// can be parsed unambiguously without looking ahead.
pub const RESERVED_FOR_COLUMN_ALIAS: &[&str] = &[
// Reserved as both a table and a column alias:
WITH, SELECT, WHERE, GROUP, HAVING, ORDER, LIMIT, OFFSET, FETCH, UNION, EXCEPT, INTERSECT,
// Reserved only as a column alias in the `SELECT` clause:
FROM,
];
// Can't be used as an identifier in expressions.
pub const RESERVED_FOR_EXPRESSIONS: &[&str] = &[FROM];
lazy_static! {
static ref RESERVED_KEYWORD_SET: HashSet<String> = {
let mut kw = HashSet::new();
for k in RESERVED_FOR_TABLE_ALIAS {
kw.insert((*k).to_string());
}
for k in RESERVED_FOR_COLUMN_ALIAS {
kw.insert((*k).to_string());
}
for k in RESERVED_FOR_EXPRESSIONS {
kw.insert((*k).to_string());
}
kw
};
}
pub fn is_reserved_keyword(s: &str) -> bool {
RESERVED_KEYWORD_SET.contains(&s.to_uppercase())
}
| 17.444444 | 94 | 0.588145 |
7aa5e3513eb2624916bdad99fded6ce0aa26ac60 | 304,950 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[derive(Debug)]
pub(crate) struct Handle<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
client: aws_smithy_client::Client<C, M, R>,
conf: crate::Config,
}
/// An ergonomic service client for `AWSElasticBeanstalkService`.
///
/// This client allows ergonomic access to a `AWSElasticBeanstalkService`-shaped service.
/// Each method corresponds to an endpoint defined in the service's Smithy model,
/// and the request and response shapes are auto-generated from that same model.
///
/// # Using a Client
///
/// Once you have a client set up, you can access the service's endpoints
/// by calling the appropriate method on [`Client`]. Each such method
/// returns a request builder for that endpoint, with methods for setting
/// the various fields of the request. Once your request is complete, use
/// the `send` method to send the request. `send` returns a future, which
/// you then have to `.await` to get the service's response.
///
/// [builder pattern]: https://rust-lang.github.io/api-guidelines/type-safety.html#c-builder
/// [SigV4-signed requests]: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
#[derive(std::fmt::Debug)]
pub struct Client<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<Handle<C, M, R>>,
}
impl<C, M, R> std::clone::Clone for Client<C, M, R> {
fn clone(&self) -> Self {
Self {
handle: self.handle.clone(),
}
}
}
#[doc(inline)]
pub use aws_smithy_client::Builder;
impl<C, M, R> From<aws_smithy_client::Client<C, M, R>> for Client<C, M, R> {
fn from(client: aws_smithy_client::Client<C, M, R>) -> Self {
Self::with_config(client, crate::Config::builder().build())
}
}
impl<C, M, R> Client<C, M, R> {
/// Creates a client with the given service configuration.
pub fn with_config(client: aws_smithy_client::Client<C, M, R>, conf: crate::Config) -> Self {
Self {
handle: std::sync::Arc::new(Handle { client, conf }),
}
}
/// Returns the client's configuration.
pub fn conf(&self) -> &crate::Config {
&self.handle.conf
}
}
impl<C, M, R> Client<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Constructs a fluent builder for the `AbortEnvironmentUpdate` operation.
///
/// See [`AbortEnvironmentUpdate`](crate::client::fluent_builders::AbortEnvironmentUpdate) for more information about the
/// operation and its arguments.
pub fn abort_environment_update(&self) -> fluent_builders::AbortEnvironmentUpdate<C, M, R> {
fluent_builders::AbortEnvironmentUpdate::new(self.handle.clone())
}
/// Constructs a fluent builder for the `ApplyEnvironmentManagedAction` operation.
///
/// See [`ApplyEnvironmentManagedAction`](crate::client::fluent_builders::ApplyEnvironmentManagedAction) for more information about the
/// operation and its arguments.
pub fn apply_environment_managed_action(
&self,
) -> fluent_builders::ApplyEnvironmentManagedAction<C, M, R> {
fluent_builders::ApplyEnvironmentManagedAction::new(self.handle.clone())
}
/// Constructs a fluent builder for the `AssociateEnvironmentOperationsRole` operation.
///
/// See [`AssociateEnvironmentOperationsRole`](crate::client::fluent_builders::AssociateEnvironmentOperationsRole) for more information about the
/// operation and its arguments.
pub fn associate_environment_operations_role(
&self,
) -> fluent_builders::AssociateEnvironmentOperationsRole<C, M, R> {
fluent_builders::AssociateEnvironmentOperationsRole::new(self.handle.clone())
}
/// Constructs a fluent builder for the `CheckDNSAvailability` operation.
///
/// See [`CheckDNSAvailability`](crate::client::fluent_builders::CheckDNSAvailability) for more information about the
/// operation and its arguments.
pub fn check_dns_availability(&self) -> fluent_builders::CheckDNSAvailability<C, M, R> {
fluent_builders::CheckDNSAvailability::new(self.handle.clone())
}
/// Constructs a fluent builder for the `ComposeEnvironments` operation.
///
/// See [`ComposeEnvironments`](crate::client::fluent_builders::ComposeEnvironments) for more information about the
/// operation and its arguments.
pub fn compose_environments(&self) -> fluent_builders::ComposeEnvironments<C, M, R> {
fluent_builders::ComposeEnvironments::new(self.handle.clone())
}
/// Constructs a fluent builder for the `CreateApplication` operation.
///
/// See [`CreateApplication`](crate::client::fluent_builders::CreateApplication) for more information about the
/// operation and its arguments.
pub fn create_application(&self) -> fluent_builders::CreateApplication<C, M, R> {
fluent_builders::CreateApplication::new(self.handle.clone())
}
/// Constructs a fluent builder for the `CreateApplicationVersion` operation.
///
/// See [`CreateApplicationVersion`](crate::client::fluent_builders::CreateApplicationVersion) for more information about the
/// operation and its arguments.
pub fn create_application_version(&self) -> fluent_builders::CreateApplicationVersion<C, M, R> {
fluent_builders::CreateApplicationVersion::new(self.handle.clone())
}
/// Constructs a fluent builder for the `CreateConfigurationTemplate` operation.
///
/// See [`CreateConfigurationTemplate`](crate::client::fluent_builders::CreateConfigurationTemplate) for more information about the
/// operation and its arguments.
pub fn create_configuration_template(
&self,
) -> fluent_builders::CreateConfigurationTemplate<C, M, R> {
fluent_builders::CreateConfigurationTemplate::new(self.handle.clone())
}
/// Constructs a fluent builder for the `CreateEnvironment` operation.
///
/// See [`CreateEnvironment`](crate::client::fluent_builders::CreateEnvironment) for more information about the
/// operation and its arguments.
pub fn create_environment(&self) -> fluent_builders::CreateEnvironment<C, M, R> {
fluent_builders::CreateEnvironment::new(self.handle.clone())
}
/// Constructs a fluent builder for the `CreatePlatformVersion` operation.
///
/// See [`CreatePlatformVersion`](crate::client::fluent_builders::CreatePlatformVersion) for more information about the
/// operation and its arguments.
pub fn create_platform_version(&self) -> fluent_builders::CreatePlatformVersion<C, M, R> {
fluent_builders::CreatePlatformVersion::new(self.handle.clone())
}
/// Constructs a fluent builder for the `CreateStorageLocation` operation.
///
/// See [`CreateStorageLocation`](crate::client::fluent_builders::CreateStorageLocation) for more information about the
/// operation and its arguments.
pub fn create_storage_location(&self) -> fluent_builders::CreateStorageLocation<C, M, R> {
fluent_builders::CreateStorageLocation::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DeleteApplication` operation.
///
/// See [`DeleteApplication`](crate::client::fluent_builders::DeleteApplication) for more information about the
/// operation and its arguments.
pub fn delete_application(&self) -> fluent_builders::DeleteApplication<C, M, R> {
fluent_builders::DeleteApplication::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DeleteApplicationVersion` operation.
///
/// See [`DeleteApplicationVersion`](crate::client::fluent_builders::DeleteApplicationVersion) for more information about the
/// operation and its arguments.
pub fn delete_application_version(&self) -> fluent_builders::DeleteApplicationVersion<C, M, R> {
fluent_builders::DeleteApplicationVersion::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DeleteConfigurationTemplate` operation.
///
/// See [`DeleteConfigurationTemplate`](crate::client::fluent_builders::DeleteConfigurationTemplate) for more information about the
/// operation and its arguments.
pub fn delete_configuration_template(
&self,
) -> fluent_builders::DeleteConfigurationTemplate<C, M, R> {
fluent_builders::DeleteConfigurationTemplate::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DeleteEnvironmentConfiguration` operation.
///
/// See [`DeleteEnvironmentConfiguration`](crate::client::fluent_builders::DeleteEnvironmentConfiguration) for more information about the
/// operation and its arguments.
pub fn delete_environment_configuration(
&self,
) -> fluent_builders::DeleteEnvironmentConfiguration<C, M, R> {
fluent_builders::DeleteEnvironmentConfiguration::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DeletePlatformVersion` operation.
///
/// See [`DeletePlatformVersion`](crate::client::fluent_builders::DeletePlatformVersion) for more information about the
/// operation and its arguments.
pub fn delete_platform_version(&self) -> fluent_builders::DeletePlatformVersion<C, M, R> {
fluent_builders::DeletePlatformVersion::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeAccountAttributes` operation.
///
/// See [`DescribeAccountAttributes`](crate::client::fluent_builders::DescribeAccountAttributes) for more information about the
/// operation and its arguments.
pub fn describe_account_attributes(
&self,
) -> fluent_builders::DescribeAccountAttributes<C, M, R> {
fluent_builders::DescribeAccountAttributes::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeApplications` operation.
///
/// See [`DescribeApplications`](crate::client::fluent_builders::DescribeApplications) for more information about the
/// operation and its arguments.
pub fn describe_applications(&self) -> fluent_builders::DescribeApplications<C, M, R> {
fluent_builders::DescribeApplications::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeApplicationVersions` operation.
///
/// See [`DescribeApplicationVersions`](crate::client::fluent_builders::DescribeApplicationVersions) for more information about the
/// operation and its arguments.
pub fn describe_application_versions(
&self,
) -> fluent_builders::DescribeApplicationVersions<C, M, R> {
fluent_builders::DescribeApplicationVersions::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeConfigurationOptions` operation.
///
/// See [`DescribeConfigurationOptions`](crate::client::fluent_builders::DescribeConfigurationOptions) for more information about the
/// operation and its arguments.
pub fn describe_configuration_options(
&self,
) -> fluent_builders::DescribeConfigurationOptions<C, M, R> {
fluent_builders::DescribeConfigurationOptions::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeConfigurationSettings` operation.
///
/// See [`DescribeConfigurationSettings`](crate::client::fluent_builders::DescribeConfigurationSettings) for more information about the
/// operation and its arguments.
pub fn describe_configuration_settings(
&self,
) -> fluent_builders::DescribeConfigurationSettings<C, M, R> {
fluent_builders::DescribeConfigurationSettings::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeEnvironmentHealth` operation.
///
/// See [`DescribeEnvironmentHealth`](crate::client::fluent_builders::DescribeEnvironmentHealth) for more information about the
/// operation and its arguments.
pub fn describe_environment_health(
&self,
) -> fluent_builders::DescribeEnvironmentHealth<C, M, R> {
fluent_builders::DescribeEnvironmentHealth::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeEnvironmentManagedActionHistory` operation.
///
/// See [`DescribeEnvironmentManagedActionHistory`](crate::client::fluent_builders::DescribeEnvironmentManagedActionHistory) for more information about the
/// operation and its arguments.
pub fn describe_environment_managed_action_history(
&self,
) -> fluent_builders::DescribeEnvironmentManagedActionHistory<C, M, R> {
fluent_builders::DescribeEnvironmentManagedActionHistory::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeEnvironmentManagedActions` operation.
///
/// See [`DescribeEnvironmentManagedActions`](crate::client::fluent_builders::DescribeEnvironmentManagedActions) for more information about the
/// operation and its arguments.
pub fn describe_environment_managed_actions(
&self,
) -> fluent_builders::DescribeEnvironmentManagedActions<C, M, R> {
fluent_builders::DescribeEnvironmentManagedActions::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeEnvironmentResources` operation.
///
/// See [`DescribeEnvironmentResources`](crate::client::fluent_builders::DescribeEnvironmentResources) for more information about the
/// operation and its arguments.
pub fn describe_environment_resources(
&self,
) -> fluent_builders::DescribeEnvironmentResources<C, M, R> {
fluent_builders::DescribeEnvironmentResources::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeEnvironments` operation.
///
/// See [`DescribeEnvironments`](crate::client::fluent_builders::DescribeEnvironments) for more information about the
/// operation and its arguments.
pub fn describe_environments(&self) -> fluent_builders::DescribeEnvironments<C, M, R> {
fluent_builders::DescribeEnvironments::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeEvents` operation.
///
/// See [`DescribeEvents`](crate::client::fluent_builders::DescribeEvents) for more information about the
/// operation and its arguments.
pub fn describe_events(&self) -> fluent_builders::DescribeEvents<C, M, R> {
fluent_builders::DescribeEvents::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribeInstancesHealth` operation.
///
/// See [`DescribeInstancesHealth`](crate::client::fluent_builders::DescribeInstancesHealth) for more information about the
/// operation and its arguments.
pub fn describe_instances_health(&self) -> fluent_builders::DescribeInstancesHealth<C, M, R> {
fluent_builders::DescribeInstancesHealth::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DescribePlatformVersion` operation.
///
/// See [`DescribePlatformVersion`](crate::client::fluent_builders::DescribePlatformVersion) for more information about the
/// operation and its arguments.
pub fn describe_platform_version(&self) -> fluent_builders::DescribePlatformVersion<C, M, R> {
fluent_builders::DescribePlatformVersion::new(self.handle.clone())
}
/// Constructs a fluent builder for the `DisassociateEnvironmentOperationsRole` operation.
///
/// See [`DisassociateEnvironmentOperationsRole`](crate::client::fluent_builders::DisassociateEnvironmentOperationsRole) for more information about the
/// operation and its arguments.
pub fn disassociate_environment_operations_role(
&self,
) -> fluent_builders::DisassociateEnvironmentOperationsRole<C, M, R> {
fluent_builders::DisassociateEnvironmentOperationsRole::new(self.handle.clone())
}
/// Constructs a fluent builder for the `ListAvailableSolutionStacks` operation.
///
/// See [`ListAvailableSolutionStacks`](crate::client::fluent_builders::ListAvailableSolutionStacks) for more information about the
/// operation and its arguments.
pub fn list_available_solution_stacks(
&self,
) -> fluent_builders::ListAvailableSolutionStacks<C, M, R> {
fluent_builders::ListAvailableSolutionStacks::new(self.handle.clone())
}
/// Constructs a fluent builder for the `ListPlatformBranches` operation.
///
/// See [`ListPlatformBranches`](crate::client::fluent_builders::ListPlatformBranches) for more information about the
/// operation and its arguments.
pub fn list_platform_branches(&self) -> fluent_builders::ListPlatformBranches<C, M, R> {
fluent_builders::ListPlatformBranches::new(self.handle.clone())
}
/// Constructs a fluent builder for the `ListPlatformVersions` operation.
///
/// See [`ListPlatformVersions`](crate::client::fluent_builders::ListPlatformVersions) for more information about the
/// operation and its arguments.
pub fn list_platform_versions(&self) -> fluent_builders::ListPlatformVersions<C, M, R> {
fluent_builders::ListPlatformVersions::new(self.handle.clone())
}
/// Constructs a fluent builder for the `ListTagsForResource` operation.
///
/// See [`ListTagsForResource`](crate::client::fluent_builders::ListTagsForResource) for more information about the
/// operation and its arguments.
pub fn list_tags_for_resource(&self) -> fluent_builders::ListTagsForResource<C, M, R> {
fluent_builders::ListTagsForResource::new(self.handle.clone())
}
/// Constructs a fluent builder for the `RebuildEnvironment` operation.
///
/// See [`RebuildEnvironment`](crate::client::fluent_builders::RebuildEnvironment) for more information about the
/// operation and its arguments.
pub fn rebuild_environment(&self) -> fluent_builders::RebuildEnvironment<C, M, R> {
fluent_builders::RebuildEnvironment::new(self.handle.clone())
}
/// Constructs a fluent builder for the `RequestEnvironmentInfo` operation.
///
/// See [`RequestEnvironmentInfo`](crate::client::fluent_builders::RequestEnvironmentInfo) for more information about the
/// operation and its arguments.
pub fn request_environment_info(&self) -> fluent_builders::RequestEnvironmentInfo<C, M, R> {
fluent_builders::RequestEnvironmentInfo::new(self.handle.clone())
}
/// Constructs a fluent builder for the `RestartAppServer` operation.
///
/// See [`RestartAppServer`](crate::client::fluent_builders::RestartAppServer) for more information about the
/// operation and its arguments.
pub fn restart_app_server(&self) -> fluent_builders::RestartAppServer<C, M, R> {
fluent_builders::RestartAppServer::new(self.handle.clone())
}
/// Constructs a fluent builder for the `RetrieveEnvironmentInfo` operation.
///
/// See [`RetrieveEnvironmentInfo`](crate::client::fluent_builders::RetrieveEnvironmentInfo) for more information about the
/// operation and its arguments.
pub fn retrieve_environment_info(&self) -> fluent_builders::RetrieveEnvironmentInfo<C, M, R> {
fluent_builders::RetrieveEnvironmentInfo::new(self.handle.clone())
}
/// Constructs a fluent builder for the `SwapEnvironmentCNAMEs` operation.
///
/// See [`SwapEnvironmentCNAMEs`](crate::client::fluent_builders::SwapEnvironmentCNAMEs) for more information about the
/// operation and its arguments.
pub fn swap_environment_cnam_es(&self) -> fluent_builders::SwapEnvironmentCNAMEs<C, M, R> {
fluent_builders::SwapEnvironmentCNAMEs::new(self.handle.clone())
}
/// Constructs a fluent builder for the `TerminateEnvironment` operation.
///
/// See [`TerminateEnvironment`](crate::client::fluent_builders::TerminateEnvironment) for more information about the
/// operation and its arguments.
pub fn terminate_environment(&self) -> fluent_builders::TerminateEnvironment<C, M, R> {
fluent_builders::TerminateEnvironment::new(self.handle.clone())
}
/// Constructs a fluent builder for the `UpdateApplication` operation.
///
/// See [`UpdateApplication`](crate::client::fluent_builders::UpdateApplication) for more information about the
/// operation and its arguments.
pub fn update_application(&self) -> fluent_builders::UpdateApplication<C, M, R> {
fluent_builders::UpdateApplication::new(self.handle.clone())
}
/// Constructs a fluent builder for the `UpdateApplicationResourceLifecycle` operation.
///
/// See [`UpdateApplicationResourceLifecycle`](crate::client::fluent_builders::UpdateApplicationResourceLifecycle) for more information about the
/// operation and its arguments.
pub fn update_application_resource_lifecycle(
&self,
) -> fluent_builders::UpdateApplicationResourceLifecycle<C, M, R> {
fluent_builders::UpdateApplicationResourceLifecycle::new(self.handle.clone())
}
/// Constructs a fluent builder for the `UpdateApplicationVersion` operation.
///
/// See [`UpdateApplicationVersion`](crate::client::fluent_builders::UpdateApplicationVersion) for more information about the
/// operation and its arguments.
pub fn update_application_version(&self) -> fluent_builders::UpdateApplicationVersion<C, M, R> {
fluent_builders::UpdateApplicationVersion::new(self.handle.clone())
}
/// Constructs a fluent builder for the `UpdateConfigurationTemplate` operation.
///
/// See [`UpdateConfigurationTemplate`](crate::client::fluent_builders::UpdateConfigurationTemplate) for more information about the
/// operation and its arguments.
pub fn update_configuration_template(
&self,
) -> fluent_builders::UpdateConfigurationTemplate<C, M, R> {
fluent_builders::UpdateConfigurationTemplate::new(self.handle.clone())
}
/// Constructs a fluent builder for the `UpdateEnvironment` operation.
///
/// See [`UpdateEnvironment`](crate::client::fluent_builders::UpdateEnvironment) for more information about the
/// operation and its arguments.
pub fn update_environment(&self) -> fluent_builders::UpdateEnvironment<C, M, R> {
fluent_builders::UpdateEnvironment::new(self.handle.clone())
}
/// Constructs a fluent builder for the `UpdateTagsForResource` operation.
///
/// See [`UpdateTagsForResource`](crate::client::fluent_builders::UpdateTagsForResource) for more information about the
/// operation and its arguments.
pub fn update_tags_for_resource(&self) -> fluent_builders::UpdateTagsForResource<C, M, R> {
fluent_builders::UpdateTagsForResource::new(self.handle.clone())
}
/// Constructs a fluent builder for the `ValidateConfigurationSettings` operation.
///
/// See [`ValidateConfigurationSettings`](crate::client::fluent_builders::ValidateConfigurationSettings) for more information about the
/// operation and its arguments.
pub fn validate_configuration_settings(
&self,
) -> fluent_builders::ValidateConfigurationSettings<C, M, R> {
fluent_builders::ValidateConfigurationSettings::new(self.handle.clone())
}
}
pub mod fluent_builders {
//!
//! Utilities to ergonomically construct a request to the service.
//!
//! Fluent builders are created through the [`Client`](crate::client::Client) by calling
//! one if its operation methods. After parameters are set using the builder methods,
//! the `send` method can be called to initiate the request.
//!
/// Fluent builder constructing a request to `AbortEnvironmentUpdate`.
///
/// <p>Cancels in-progress environment configuration update or application version
/// deployment.</p>
#[derive(std::fmt::Debug)]
pub struct AbortEnvironmentUpdate<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::abort_environment_update_input::Builder,
}
impl<C, M, R> AbortEnvironmentUpdate<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `AbortEnvironmentUpdate`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::AbortEnvironmentUpdateOutput,
aws_smithy_http::result::SdkError<crate::error::AbortEnvironmentUpdateError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::AbortEnvironmentUpdateInputOperationOutputAlias,
crate::output::AbortEnvironmentUpdateOutput,
crate::error::AbortEnvironmentUpdateError,
crate::input::AbortEnvironmentUpdateInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>This specifies the ID of the environment with the in-progress update that you want to
/// cancel.</p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>This specifies the ID of the environment with the in-progress update that you want to
/// cancel.</p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>This specifies the name of the environment with the in-progress update that you want to
/// cancel.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>This specifies the name of the environment with the in-progress update that you want to
/// cancel.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
}
/// Fluent builder constructing a request to `ApplyEnvironmentManagedAction`.
///
/// <p>Applies a scheduled managed action immediately. A managed action can be applied only if
/// its status is <code>Scheduled</code>. Get the status and action ID of a managed action with
/// <a>DescribeEnvironmentManagedActions</a>.</p>
#[derive(std::fmt::Debug)]
pub struct ApplyEnvironmentManagedAction<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::apply_environment_managed_action_input::Builder,
}
impl<C, M, R> ApplyEnvironmentManagedAction<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `ApplyEnvironmentManagedAction`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::ApplyEnvironmentManagedActionOutput,
aws_smithy_http::result::SdkError<crate::error::ApplyEnvironmentManagedActionError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::ApplyEnvironmentManagedActionInputOperationOutputAlias,
crate::output::ApplyEnvironmentManagedActionOutput,
crate::error::ApplyEnvironmentManagedActionError,
crate::input::ApplyEnvironmentManagedActionInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the target environment.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the target environment.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>The environment ID of the target environment.</p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>The environment ID of the target environment.</p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>The action ID of the scheduled managed action to execute.</p>
pub fn action_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.action_id(inp);
self
}
/// <p>The action ID of the scheduled managed action to execute.</p>
pub fn set_action_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_action_id(input);
self
}
}
/// Fluent builder constructing a request to `AssociateEnvironmentOperationsRole`.
///
/// <p>Add or change the operations role used by an environment. After this call is made, Elastic Beanstalk
/// uses the associated operations role for permissions to downstream services during subsequent
/// calls acting on this environment. For more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html">Operations roles</a> in the
/// <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
#[derive(std::fmt::Debug)]
pub struct AssociateEnvironmentOperationsRole<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::associate_environment_operations_role_input::Builder,
}
impl<C, M, R> AssociateEnvironmentOperationsRole<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `AssociateEnvironmentOperationsRole`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::AssociateEnvironmentOperationsRoleOutput,
aws_smithy_http::result::SdkError<
crate::error::AssociateEnvironmentOperationsRoleError,
>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::AssociateEnvironmentOperationsRoleInputOperationOutputAlias,
crate::output::AssociateEnvironmentOperationsRoleOutput,
crate::error::AssociateEnvironmentOperationsRoleError,
crate::input::AssociateEnvironmentOperationsRoleInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the environment to which to set the operations role.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment to which to set the operations role.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>The Amazon Resource Name (ARN) of an existing IAM role to be used as the environment's
/// operations role.</p>
pub fn operations_role(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.operations_role(inp);
self
}
/// <p>The Amazon Resource Name (ARN) of an existing IAM role to be used as the environment's
/// operations role.</p>
pub fn set_operations_role(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_operations_role(input);
self
}
}
/// Fluent builder constructing a request to `CheckDNSAvailability`.
///
/// <p>Checks if the specified CNAME is available.</p>
#[derive(std::fmt::Debug)]
pub struct CheckDNSAvailability<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::check_dns_availability_input::Builder,
}
impl<C, M, R> CheckDNSAvailability<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `CheckDNSAvailability`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::CheckDnsAvailabilityOutput,
aws_smithy_http::result::SdkError<crate::error::CheckDNSAvailabilityError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::CheckDnsAvailabilityInputOperationOutputAlias,
crate::output::CheckDnsAvailabilityOutput,
crate::error::CheckDNSAvailabilityError,
crate::input::CheckDnsAvailabilityInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The prefix used when this CNAME is reserved.</p>
pub fn cname_prefix(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.cname_prefix(inp);
self
}
/// <p>The prefix used when this CNAME is reserved.</p>
pub fn set_cname_prefix(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_cname_prefix(input);
self
}
}
/// Fluent builder constructing a request to `ComposeEnvironments`.
///
/// <p>Create or update a group of environments that each run a separate component of a single
/// application. Takes a list of version labels that specify application source bundles for each
/// of the environments to create or update. The name of each environment and other required
/// information must be included in the source bundles in an environment manifest named
/// <code>env.yaml</code>. See <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-mgmt-compose.html">Compose Environments</a>
/// for details.</p>
#[derive(std::fmt::Debug)]
pub struct ComposeEnvironments<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::compose_environments_input::Builder,
}
impl<C, M, R> ComposeEnvironments<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `ComposeEnvironments`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::ComposeEnvironmentsOutput,
aws_smithy_http::result::SdkError<crate::error::ComposeEnvironmentsError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::ComposeEnvironmentsInputOperationOutputAlias,
crate::output::ComposeEnvironmentsOutput,
crate::error::ComposeEnvironmentsError,
crate::input::ComposeEnvironmentsInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application to which the specified source bundles belong.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application to which the specified source bundles belong.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The name of the group to which the target environments belong. Specify a group name
/// only if the environment name defined in each target environment's manifest ends with a +
/// (plus) character. See <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-cfg-manifest.html">Environment Manifest
/// (env.yaml)</a> for details.</p>
pub fn group_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.group_name(inp);
self
}
/// <p>The name of the group to which the target environments belong. Specify a group name
/// only if the environment name defined in each target environment's manifest ends with a +
/// (plus) character. See <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-cfg-manifest.html">Environment Manifest
/// (env.yaml)</a> for details.</p>
pub fn set_group_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_group_name(input);
self
}
/// Appends an item to `VersionLabels`.
///
/// To override the contents of this collection use [`set_version_labels`](Self::set_version_labels).
///
/// <p>A list of version labels, specifying one or more application source bundles that belong
/// to the target application. Each source bundle must include an environment manifest that
/// specifies the name of the environment and the name of the solution stack to use, and
/// optionally can specify environment links to create.</p>
pub fn version_labels(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.version_labels(inp);
self
}
/// <p>A list of version labels, specifying one or more application source bundles that belong
/// to the target application. Each source bundle must include an environment manifest that
/// specifies the name of the environment and the name of the solution stack to use, and
/// optionally can specify environment links to create.</p>
pub fn set_version_labels(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_version_labels(input);
self
}
}
/// Fluent builder constructing a request to `CreateApplication`.
///
/// <p>Creates an application that has one configuration template named <code>default</code>
/// and no application versions.</p>
#[derive(std::fmt::Debug)]
pub struct CreateApplication<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::create_application_input::Builder,
}
impl<C, M, R> CreateApplication<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `CreateApplication`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::CreateApplicationOutput,
aws_smithy_http::result::SdkError<crate::error::CreateApplicationError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::CreateApplicationInputOperationOutputAlias,
crate::output::CreateApplicationOutput,
crate::error::CreateApplicationError,
crate::input::CreateApplicationInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application. Must be unique within your account.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application. Must be unique within your account.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>Your description of the application.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
/// <p>Your description of the application.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(input);
self
}
/// <p>Specifies an application resource lifecycle configuration to prevent your application
/// from accumulating too many versions.</p>
pub fn resource_lifecycle_config(
mut self,
inp: crate::model::ApplicationResourceLifecycleConfig,
) -> Self {
self.inner = self.inner.resource_lifecycle_config(inp);
self
}
/// <p>Specifies an application resource lifecycle configuration to prevent your application
/// from accumulating too many versions.</p>
pub fn set_resource_lifecycle_config(
mut self,
input: std::option::Option<crate::model::ApplicationResourceLifecycleConfig>,
) -> Self {
self.inner = self.inner.set_resource_lifecycle_config(input);
self
}
/// Appends an item to `Tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
///
/// <p>Specifies the tags applied to the application.</p>
/// <p>Elastic Beanstalk applies these tags only to the application. Environments that you create in the
/// application don't inherit the tags.</p>
pub fn tags(mut self, inp: impl Into<crate::model::Tag>) -> Self {
self.inner = self.inner.tags(inp);
self
}
/// <p>Specifies the tags applied to the application.</p>
/// <p>Elastic Beanstalk applies these tags only to the application. Environments that you create in the
/// application don't inherit the tags.</p>
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.inner = self.inner.set_tags(input);
self
}
}
/// Fluent builder constructing a request to `CreateApplicationVersion`.
///
/// <p>Creates an application version for the specified application. You can create an
/// application version from a source bundle in Amazon S3, a commit in AWS CodeCommit, or the
/// output of an AWS CodeBuild build as follows:</p>
/// <p>Specify a commit in an AWS CodeCommit repository with
/// <code>SourceBuildInformation</code>.</p>
/// <p>Specify a build in an AWS CodeBuild with <code>SourceBuildInformation</code> and
/// <code>BuildConfiguration</code>.</p>
/// <p>Specify a source bundle in S3 with <code>SourceBundle</code>
/// </p>
/// <p>Omit both <code>SourceBuildInformation</code> and <code>SourceBundle</code> to use the
/// default sample application.</p>
/// <note>
/// <p>After you create an application version with a specified Amazon S3 bucket and key
/// location, you can't change that Amazon S3 location. If you change the Amazon S3 location,
/// you receive an exception when you attempt to launch an environment from the application
/// version.</p>
/// </note>
#[derive(std::fmt::Debug)]
pub struct CreateApplicationVersion<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::create_application_version_input::Builder,
}
impl<C, M, R> CreateApplicationVersion<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `CreateApplicationVersion`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::CreateApplicationVersionOutput,
aws_smithy_http::result::SdkError<crate::error::CreateApplicationVersionError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::CreateApplicationVersionInputOperationOutputAlias,
crate::output::CreateApplicationVersionOutput,
crate::error::CreateApplicationVersionError,
crate::input::CreateApplicationVersionInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p> The name of the application. If no application is found with this name, and
/// <code>AutoCreateApplication</code> is <code>false</code>, returns an
/// <code>InvalidParameterValue</code> error. </p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p> The name of the application. If no application is found with this name, and
/// <code>AutoCreateApplication</code> is <code>false</code>, returns an
/// <code>InvalidParameterValue</code> error. </p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>A label identifying this version.</p>
/// <p>Constraint: Must be unique per application. If an application version already exists
/// with this label for the specified application, AWS Elastic Beanstalk returns an
/// <code>InvalidParameterValue</code> error. </p>
pub fn version_label(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.version_label(inp);
self
}
/// <p>A label identifying this version.</p>
/// <p>Constraint: Must be unique per application. If an application version already exists
/// with this label for the specified application, AWS Elastic Beanstalk returns an
/// <code>InvalidParameterValue</code> error. </p>
pub fn set_version_label(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_version_label(input);
self
}
/// <p>A description of this application version.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
/// <p>A description of this application version.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(input);
self
}
/// <p>Specify a commit in an AWS CodeCommit Git repository to use as the source code for the
/// application version.</p>
pub fn source_build_information(
mut self,
inp: crate::model::SourceBuildInformation,
) -> Self {
self.inner = self.inner.source_build_information(inp);
self
}
/// <p>Specify a commit in an AWS CodeCommit Git repository to use as the source code for the
/// application version.</p>
pub fn set_source_build_information(
mut self,
input: std::option::Option<crate::model::SourceBuildInformation>,
) -> Self {
self.inner = self.inner.set_source_build_information(input);
self
}
/// <p>The Amazon S3 bucket and key that identify the location of the source bundle for this
/// version.</p>
/// <note>
/// <p>The Amazon S3 bucket must be in the same region as the
/// environment.</p>
/// </note>
/// <p>Specify a source bundle in S3 or a commit in an AWS CodeCommit repository (with
/// <code>SourceBuildInformation</code>), but not both. If neither <code>SourceBundle</code> nor
/// <code>SourceBuildInformation</code> are provided, Elastic Beanstalk uses a sample
/// application.</p>
pub fn source_bundle(mut self, inp: crate::model::S3Location) -> Self {
self.inner = self.inner.source_bundle(inp);
self
}
/// <p>The Amazon S3 bucket and key that identify the location of the source bundle for this
/// version.</p>
/// <note>
/// <p>The Amazon S3 bucket must be in the same region as the
/// environment.</p>
/// </note>
/// <p>Specify a source bundle in S3 or a commit in an AWS CodeCommit repository (with
/// <code>SourceBuildInformation</code>), but not both. If neither <code>SourceBundle</code> nor
/// <code>SourceBuildInformation</code> are provided, Elastic Beanstalk uses a sample
/// application.</p>
pub fn set_source_bundle(
mut self,
input: std::option::Option<crate::model::S3Location>,
) -> Self {
self.inner = self.inner.set_source_bundle(input);
self
}
/// <p>Settings for an AWS CodeBuild build.</p>
pub fn build_configuration(mut self, inp: crate::model::BuildConfiguration) -> Self {
self.inner = self.inner.build_configuration(inp);
self
}
/// <p>Settings for an AWS CodeBuild build.</p>
pub fn set_build_configuration(
mut self,
input: std::option::Option<crate::model::BuildConfiguration>,
) -> Self {
self.inner = self.inner.set_build_configuration(input);
self
}
/// <p>Set to <code>true</code> to create an application with the specified name if it doesn't
/// already exist.</p>
pub fn auto_create_application(mut self, inp: bool) -> Self {
self.inner = self.inner.auto_create_application(inp);
self
}
/// <p>Set to <code>true</code> to create an application with the specified name if it doesn't
/// already exist.</p>
pub fn set_auto_create_application(mut self, input: std::option::Option<bool>) -> Self {
self.inner = self.inner.set_auto_create_application(input);
self
}
/// <p>Pre-processes and validates the environment manifest (<code>env.yaml</code>) and
/// configuration files (<code>*.config</code> files in the <code>.ebextensions</code> folder) in
/// the source bundle. Validating configuration files can identify issues prior to deploying the
/// application version to an environment.</p>
/// <p>You must turn processing on for application versions that you create using AWS
/// CodeBuild or AWS CodeCommit. For application versions built from a source bundle in Amazon S3,
/// processing is optional.</p>
/// <note>
/// <p>The <code>Process</code> option validates Elastic Beanstalk configuration files. It
/// doesn't validate your application's configuration files, like proxy server or Docker
/// configuration.</p>
/// </note>
pub fn process(mut self, inp: bool) -> Self {
self.inner = self.inner.process(inp);
self
}
/// <p>Pre-processes and validates the environment manifest (<code>env.yaml</code>) and
/// configuration files (<code>*.config</code> files in the <code>.ebextensions</code> folder) in
/// the source bundle. Validating configuration files can identify issues prior to deploying the
/// application version to an environment.</p>
/// <p>You must turn processing on for application versions that you create using AWS
/// CodeBuild or AWS CodeCommit. For application versions built from a source bundle in Amazon S3,
/// processing is optional.</p>
/// <note>
/// <p>The <code>Process</code> option validates Elastic Beanstalk configuration files. It
/// doesn't validate your application's configuration files, like proxy server or Docker
/// configuration.</p>
/// </note>
pub fn set_process(mut self, input: std::option::Option<bool>) -> Self {
self.inner = self.inner.set_process(input);
self
}
/// Appends an item to `Tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
///
/// <p>Specifies the tags applied to the application version.</p>
/// <p>Elastic Beanstalk applies these tags only to the application version. Environments that use the
/// application version don't inherit the tags.</p>
pub fn tags(mut self, inp: impl Into<crate::model::Tag>) -> Self {
self.inner = self.inner.tags(inp);
self
}
/// <p>Specifies the tags applied to the application version.</p>
/// <p>Elastic Beanstalk applies these tags only to the application version. Environments that use the
/// application version don't inherit the tags.</p>
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.inner = self.inner.set_tags(input);
self
}
}
/// Fluent builder constructing a request to `CreateConfigurationTemplate`.
///
/// <p>Creates an AWS Elastic Beanstalk configuration template, associated with a specific Elastic Beanstalk
/// application. You define application configuration settings in a configuration template. You
/// can then use the configuration template to deploy different versions of the application with
/// the same configuration settings.</p>
/// <p>Templates aren't associated with any environment. The <code>EnvironmentName</code>
/// response element is always <code>null</code>.</p>
/// <p>Related Topics</p>
/// <ul>
/// <li>
/// <p>
/// <a>DescribeConfigurationOptions</a>
/// </p>
/// </li>
/// <li>
/// <p>
/// <a>DescribeConfigurationSettings</a>
/// </p>
/// </li>
/// <li>
/// <p>
/// <a>ListAvailableSolutionStacks</a>
/// </p>
/// </li>
/// </ul>
#[derive(std::fmt::Debug)]
pub struct CreateConfigurationTemplate<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::create_configuration_template_input::Builder,
}
impl<C, M, R> CreateConfigurationTemplate<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `CreateConfigurationTemplate`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::CreateConfigurationTemplateOutput,
aws_smithy_http::result::SdkError<crate::error::CreateConfigurationTemplateError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::CreateConfigurationTemplateInputOperationOutputAlias,
crate::output::CreateConfigurationTemplateOutput,
crate::error::CreateConfigurationTemplateError,
crate::input::CreateConfigurationTemplateInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the Elastic Beanstalk application to associate with this configuration
/// template.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the Elastic Beanstalk application to associate with this configuration
/// template.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The name of the configuration template.</p>
/// <p>Constraint: This name must be unique per application.</p>
pub fn template_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.template_name(inp);
self
}
/// <p>The name of the configuration template.</p>
/// <p>Constraint: This name must be unique per application.</p>
pub fn set_template_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_template_name(input);
self
}
/// <p>The name of an Elastic Beanstalk solution stack (platform version) that this configuration uses. For
/// example, <code>64bit Amazon Linux 2013.09 running Tomcat 7 Java 7</code>. A solution stack
/// specifies the operating system, runtime, and application server for a configuration template.
/// It also determines the set of configuration options as well as the possible and default
/// values. For more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.platforms.html">Supported Platforms</a> in the
/// <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
/// <p>You must specify <code>SolutionStackName</code> if you don't specify
/// <code>PlatformArn</code>, <code>EnvironmentId</code>, or
/// <code>SourceConfiguration</code>.</p>
/// <p>Use the <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/api/API_ListAvailableSolutionStacks.html">
/// <code>ListAvailableSolutionStacks</code>
/// </a> API to obtain a list of available
/// solution stacks.</p>
pub fn solution_stack_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.solution_stack_name(inp);
self
}
/// <p>The name of an Elastic Beanstalk solution stack (platform version) that this configuration uses. For
/// example, <code>64bit Amazon Linux 2013.09 running Tomcat 7 Java 7</code>. A solution stack
/// specifies the operating system, runtime, and application server for a configuration template.
/// It also determines the set of configuration options as well as the possible and default
/// values. For more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.platforms.html">Supported Platforms</a> in the
/// <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
/// <p>You must specify <code>SolutionStackName</code> if you don't specify
/// <code>PlatformArn</code>, <code>EnvironmentId</code>, or
/// <code>SourceConfiguration</code>.</p>
/// <p>Use the <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/api/API_ListAvailableSolutionStacks.html">
/// <code>ListAvailableSolutionStacks</code>
/// </a> API to obtain a list of available
/// solution stacks.</p>
pub fn set_solution_stack_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_solution_stack_name(input);
self
}
/// <p>The Amazon Resource Name (ARN) of the custom platform. For more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/custom-platforms.html"> Custom
/// Platforms</a> in the <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
/// <note>
///
/// <p>If you specify <code>PlatformArn</code>, then don't specify
/// <code>SolutionStackName</code>.</p>
/// </note>
pub fn platform_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.platform_arn(inp);
self
}
/// <p>The Amazon Resource Name (ARN) of the custom platform. For more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/custom-platforms.html"> Custom
/// Platforms</a> in the <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
/// <note>
///
/// <p>If you specify <code>PlatformArn</code>, then don't specify
/// <code>SolutionStackName</code>.</p>
/// </note>
pub fn set_platform_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_platform_arn(input);
self
}
/// <p>An Elastic Beanstalk configuration template to base this one on. If specified, Elastic Beanstalk uses the configuration values from the specified
/// configuration template to create a new configuration.</p>
/// <p>Values specified in <code>OptionSettings</code> override any values obtained from the
/// <code>SourceConfiguration</code>.</p>
/// <p>You must specify <code>SourceConfiguration</code> if you don't specify
/// <code>PlatformArn</code>, <code>EnvironmentId</code>, or
/// <code>SolutionStackName</code>.</p>
/// <p>Constraint: If both solution stack name and source configuration are specified, the
/// solution stack of the source configuration template must match the specified solution stack
/// name.</p>
pub fn source_configuration(mut self, inp: crate::model::SourceConfiguration) -> Self {
self.inner = self.inner.source_configuration(inp);
self
}
/// <p>An Elastic Beanstalk configuration template to base this one on. If specified, Elastic Beanstalk uses the configuration values from the specified
/// configuration template to create a new configuration.</p>
/// <p>Values specified in <code>OptionSettings</code> override any values obtained from the
/// <code>SourceConfiguration</code>.</p>
/// <p>You must specify <code>SourceConfiguration</code> if you don't specify
/// <code>PlatformArn</code>, <code>EnvironmentId</code>, or
/// <code>SolutionStackName</code>.</p>
/// <p>Constraint: If both solution stack name and source configuration are specified, the
/// solution stack of the source configuration template must match the specified solution stack
/// name.</p>
pub fn set_source_configuration(
mut self,
input: std::option::Option<crate::model::SourceConfiguration>,
) -> Self {
self.inner = self.inner.set_source_configuration(input);
self
}
/// <p>The ID of an environment whose settings you want to use to create the configuration
/// template. You must specify <code>EnvironmentId</code> if you don't specify
/// <code>PlatformArn</code>, <code>SolutionStackName</code>, or
/// <code>SourceConfiguration</code>.</p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>The ID of an environment whose settings you want to use to create the configuration
/// template. You must specify <code>EnvironmentId</code> if you don't specify
/// <code>PlatformArn</code>, <code>SolutionStackName</code>, or
/// <code>SourceConfiguration</code>.</p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>An optional description for this configuration.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
/// <p>An optional description for this configuration.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(input);
self
}
/// Appends an item to `OptionSettings`.
///
/// To override the contents of this collection use [`set_option_settings`](Self::set_option_settings).
///
/// <p>Option values for the Elastic Beanstalk configuration, such as the instance type. If specified, these
/// values override the values obtained from the solution stack or the source configuration
/// template. For a complete list of Elastic Beanstalk configuration options, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html">Option Values</a> in the
/// <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
pub fn option_settings(
mut self,
inp: impl Into<crate::model::ConfigurationOptionSetting>,
) -> Self {
self.inner = self.inner.option_settings(inp);
self
}
/// <p>Option values for the Elastic Beanstalk configuration, such as the instance type. If specified, these
/// values override the values obtained from the solution stack or the source configuration
/// template. For a complete list of Elastic Beanstalk configuration options, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html">Option Values</a> in the
/// <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
pub fn set_option_settings(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ConfigurationOptionSetting>>,
) -> Self {
self.inner = self.inner.set_option_settings(input);
self
}
/// Appends an item to `Tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
///
/// <p>Specifies the tags applied to the configuration template.</p>
pub fn tags(mut self, inp: impl Into<crate::model::Tag>) -> Self {
self.inner = self.inner.tags(inp);
self
}
/// <p>Specifies the tags applied to the configuration template.</p>
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.inner = self.inner.set_tags(input);
self
}
}
/// Fluent builder constructing a request to `CreateEnvironment`.
///
/// <p>Launches an AWS Elastic Beanstalk environment for the specified application using the specified
/// configuration.</p>
#[derive(std::fmt::Debug)]
pub struct CreateEnvironment<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::create_environment_input::Builder,
}
impl<C, M, R> CreateEnvironment<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `CreateEnvironment`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::CreateEnvironmentOutput,
aws_smithy_http::result::SdkError<crate::error::CreateEnvironmentError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::CreateEnvironmentInputOperationOutputAlias,
crate::output::CreateEnvironmentOutput,
crate::error::CreateEnvironmentError,
crate::input::CreateEnvironmentInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application that is associated with this environment.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application that is associated with this environment.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>A unique name for the environment.</p>
/// <p>Constraint: Must be from 4 to 40 characters in length. The name can contain only
/// letters, numbers, and hyphens. It can't start or end with a hyphen. This name must be unique
/// within a region in your account. If the specified name already exists in the region, Elastic Beanstalk returns an
/// <code>InvalidParameterValue</code> error. </p>
/// <p>If you don't specify the <code>CNAMEPrefix</code> parameter, the environment name becomes part of
/// the CNAME, and therefore part of the visible URL for your application.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>A unique name for the environment.</p>
/// <p>Constraint: Must be from 4 to 40 characters in length. The name can contain only
/// letters, numbers, and hyphens. It can't start or end with a hyphen. This name must be unique
/// within a region in your account. If the specified name already exists in the region, Elastic Beanstalk returns an
/// <code>InvalidParameterValue</code> error. </p>
/// <p>If you don't specify the <code>CNAMEPrefix</code> parameter, the environment name becomes part of
/// the CNAME, and therefore part of the visible URL for your application.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>The name of the group to which the target environment belongs. Specify a group name
/// only if the environment's name is specified in an environment manifest and not with the
/// environment name parameter. See <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-cfg-manifest.html">Environment Manifest
/// (env.yaml)</a> for details.</p>
pub fn group_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.group_name(inp);
self
}
/// <p>The name of the group to which the target environment belongs. Specify a group name
/// only if the environment's name is specified in an environment manifest and not with the
/// environment name parameter. See <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-cfg-manifest.html">Environment Manifest
/// (env.yaml)</a> for details.</p>
pub fn set_group_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_group_name(input);
self
}
/// <p>Your description for this environment.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
/// <p>Your description for this environment.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(input);
self
}
/// <p>If specified, the environment attempts to use this value as the prefix for the CNAME in
/// your Elastic Beanstalk environment URL. If not specified, the CNAME is generated automatically by
/// appending a random alphanumeric string to the environment name.</p>
pub fn cname_prefix(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.cname_prefix(inp);
self
}
/// <p>If specified, the environment attempts to use this value as the prefix for the CNAME in
/// your Elastic Beanstalk environment URL. If not specified, the CNAME is generated automatically by
/// appending a random alphanumeric string to the environment name.</p>
pub fn set_cname_prefix(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_cname_prefix(input);
self
}
/// <p>Specifies the tier to use in creating this environment. The environment tier that you
/// choose determines whether Elastic Beanstalk provisions resources to support a web application that handles
/// HTTP(S) requests or a web application that handles background-processing tasks.</p>
pub fn tier(mut self, inp: crate::model::EnvironmentTier) -> Self {
self.inner = self.inner.tier(inp);
self
}
/// <p>Specifies the tier to use in creating this environment. The environment tier that you
/// choose determines whether Elastic Beanstalk provisions resources to support a web application that handles
/// HTTP(S) requests or a web application that handles background-processing tasks.</p>
pub fn set_tier(
mut self,
input: std::option::Option<crate::model::EnvironmentTier>,
) -> Self {
self.inner = self.inner.set_tier(input);
self
}
/// Appends an item to `Tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
///
/// <p>Specifies the tags applied to resources in the environment.</p>
pub fn tags(mut self, inp: impl Into<crate::model::Tag>) -> Self {
self.inner = self.inner.tags(inp);
self
}
/// <p>Specifies the tags applied to resources in the environment.</p>
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.inner = self.inner.set_tags(input);
self
}
/// <p>The name of the application version to deploy.</p>
/// <p>Default: If not specified, Elastic Beanstalk attempts to deploy the sample application.</p>
pub fn version_label(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.version_label(inp);
self
}
/// <p>The name of the application version to deploy.</p>
/// <p>Default: If not specified, Elastic Beanstalk attempts to deploy the sample application.</p>
pub fn set_version_label(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_version_label(input);
self
}
/// <p>The name of the Elastic Beanstalk configuration template to use with the environment.</p>
/// <note>
/// <p>If you specify <code>TemplateName</code>, then don't specify
/// <code>SolutionStackName</code>.</p>
/// </note>
pub fn template_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.template_name(inp);
self
}
/// <p>The name of the Elastic Beanstalk configuration template to use with the environment.</p>
/// <note>
/// <p>If you specify <code>TemplateName</code>, then don't specify
/// <code>SolutionStackName</code>.</p>
/// </note>
pub fn set_template_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_template_name(input);
self
}
/// <p>The name of an Elastic Beanstalk solution stack (platform version) to use with the environment. If
/// specified, Elastic Beanstalk sets the configuration values to the default values associated with the
/// specified solution stack. For a list of current solution stacks, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html">Elastic Beanstalk Supported Platforms</a> in the <i>AWS Elastic Beanstalk
/// Platforms</i> guide.</p>
/// <note>
/// <p>If you specify <code>SolutionStackName</code>, don't specify <code>PlatformArn</code> or
/// <code>TemplateName</code>.</p>
/// </note>
pub fn solution_stack_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.solution_stack_name(inp);
self
}
/// <p>The name of an Elastic Beanstalk solution stack (platform version) to use with the environment. If
/// specified, Elastic Beanstalk sets the configuration values to the default values associated with the
/// specified solution stack. For a list of current solution stacks, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html">Elastic Beanstalk Supported Platforms</a> in the <i>AWS Elastic Beanstalk
/// Platforms</i> guide.</p>
/// <note>
/// <p>If you specify <code>SolutionStackName</code>, don't specify <code>PlatformArn</code> or
/// <code>TemplateName</code>.</p>
/// </note>
pub fn set_solution_stack_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_solution_stack_name(input);
self
}
/// <p>The Amazon Resource Name (ARN) of the custom platform to use with the environment. For
/// more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/custom-platforms.html">Custom Platforms</a> in the
/// <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
/// <note>
///
/// <p>If you specify <code>PlatformArn</code>, don't specify
/// <code>SolutionStackName</code>.</p>
/// </note>
pub fn platform_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.platform_arn(inp);
self
}
/// <p>The Amazon Resource Name (ARN) of the custom platform to use with the environment. For
/// more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/custom-platforms.html">Custom Platforms</a> in the
/// <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
/// <note>
///
/// <p>If you specify <code>PlatformArn</code>, don't specify
/// <code>SolutionStackName</code>.</p>
/// </note>
pub fn set_platform_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_platform_arn(input);
self
}
/// Appends an item to `OptionSettings`.
///
/// To override the contents of this collection use [`set_option_settings`](Self::set_option_settings).
///
/// <p>If specified, AWS Elastic Beanstalk sets the specified configuration options to the
/// requested value in the configuration set for the new environment. These override the values
/// obtained from the solution stack or the configuration template.</p>
pub fn option_settings(
mut self,
inp: impl Into<crate::model::ConfigurationOptionSetting>,
) -> Self {
self.inner = self.inner.option_settings(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk sets the specified configuration options to the
/// requested value in the configuration set for the new environment. These override the values
/// obtained from the solution stack or the configuration template.</p>
pub fn set_option_settings(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ConfigurationOptionSetting>>,
) -> Self {
self.inner = self.inner.set_option_settings(input);
self
}
/// Appends an item to `OptionsToRemove`.
///
/// To override the contents of this collection use [`set_options_to_remove`](Self::set_options_to_remove).
///
/// <p>A list of custom user-defined configuration options to remove from the configuration
/// set for this new environment.</p>
pub fn options_to_remove(
mut self,
inp: impl Into<crate::model::OptionSpecification>,
) -> Self {
self.inner = self.inner.options_to_remove(inp);
self
}
/// <p>A list of custom user-defined configuration options to remove from the configuration
/// set for this new environment.</p>
pub fn set_options_to_remove(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::OptionSpecification>>,
) -> Self {
self.inner = self.inner.set_options_to_remove(input);
self
}
/// <p>The Amazon Resource Name (ARN) of an existing IAM role to be used as the environment's
/// operations role. If specified, Elastic Beanstalk uses the operations role for permissions to downstream
/// services during this call and during subsequent calls acting on this environment. To specify
/// an operations role, you must have the <code>iam:PassRole</code> permission for the role. For
/// more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html">Operations roles</a> in the
/// <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
pub fn operations_role(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.operations_role(inp);
self
}
/// <p>The Amazon Resource Name (ARN) of an existing IAM role to be used as the environment's
/// operations role. If specified, Elastic Beanstalk uses the operations role for permissions to downstream
/// services during this call and during subsequent calls acting on this environment. To specify
/// an operations role, you must have the <code>iam:PassRole</code> permission for the role. For
/// more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html">Operations roles</a> in the
/// <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
pub fn set_operations_role(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_operations_role(input);
self
}
}
/// Fluent builder constructing a request to `CreatePlatformVersion`.
///
/// <p>Create a new version of your custom platform.</p>
#[derive(std::fmt::Debug)]
pub struct CreatePlatformVersion<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::create_platform_version_input::Builder,
}
impl<C, M, R> CreatePlatformVersion<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `CreatePlatformVersion`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::CreatePlatformVersionOutput,
aws_smithy_http::result::SdkError<crate::error::CreatePlatformVersionError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::CreatePlatformVersionInputOperationOutputAlias,
crate::output::CreatePlatformVersionOutput,
crate::error::CreatePlatformVersionError,
crate::input::CreatePlatformVersionInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of your custom platform.</p>
pub fn platform_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.platform_name(inp);
self
}
/// <p>The name of your custom platform.</p>
pub fn set_platform_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_platform_name(input);
self
}
/// <p>The number, such as 1.0.2, for the new platform version.</p>
pub fn platform_version(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.platform_version(inp);
self
}
/// <p>The number, such as 1.0.2, for the new platform version.</p>
pub fn set_platform_version(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_platform_version(input);
self
}
/// <p>The location of the platform definition archive in Amazon S3.</p>
pub fn platform_definition_bundle(mut self, inp: crate::model::S3Location) -> Self {
self.inner = self.inner.platform_definition_bundle(inp);
self
}
/// <p>The location of the platform definition archive in Amazon S3.</p>
pub fn set_platform_definition_bundle(
mut self,
input: std::option::Option<crate::model::S3Location>,
) -> Self {
self.inner = self.inner.set_platform_definition_bundle(input);
self
}
/// <p>The name of the builder environment.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the builder environment.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// Appends an item to `OptionSettings`.
///
/// To override the contents of this collection use [`set_option_settings`](Self::set_option_settings).
///
/// <p>The configuration option settings to apply to the builder environment.</p>
pub fn option_settings(
mut self,
inp: impl Into<crate::model::ConfigurationOptionSetting>,
) -> Self {
self.inner = self.inner.option_settings(inp);
self
}
/// <p>The configuration option settings to apply to the builder environment.</p>
pub fn set_option_settings(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ConfigurationOptionSetting>>,
) -> Self {
self.inner = self.inner.set_option_settings(input);
self
}
/// Appends an item to `Tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
///
/// <p>Specifies the tags applied to the new platform version.</p>
/// <p>Elastic Beanstalk applies these tags only to the platform version. Environments that you create using
/// the platform version don't inherit the tags.</p>
pub fn tags(mut self, inp: impl Into<crate::model::Tag>) -> Self {
self.inner = self.inner.tags(inp);
self
}
/// <p>Specifies the tags applied to the new platform version.</p>
/// <p>Elastic Beanstalk applies these tags only to the platform version. Environments that you create using
/// the platform version don't inherit the tags.</p>
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.inner = self.inner.set_tags(input);
self
}
}
/// Fluent builder constructing a request to `CreateStorageLocation`.
///
/// <p>Creates a bucket in Amazon S3 to store application versions, logs, and other files used
/// by Elastic Beanstalk environments. The Elastic Beanstalk console and EB CLI call this API the
/// first time you create an environment in a region. If the storage location already exists,
/// <code>CreateStorageLocation</code> still returns the bucket name but does not create a new
/// bucket.</p>
#[derive(std::fmt::Debug)]
pub struct CreateStorageLocation<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::create_storage_location_input::Builder,
}
impl<C, M, R> CreateStorageLocation<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `CreateStorageLocation`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::CreateStorageLocationOutput,
aws_smithy_http::result::SdkError<crate::error::CreateStorageLocationError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::CreateStorageLocationInputOperationOutputAlias,
crate::output::CreateStorageLocationOutput,
crate::error::CreateStorageLocationError,
crate::input::CreateStorageLocationInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
}
/// Fluent builder constructing a request to `DeleteApplication`.
///
/// <p>Deletes the specified application along with all associated versions and
/// configurations. The application versions will not be deleted from your Amazon S3
/// bucket.</p>
/// <note>
/// <p>You cannot delete an application that has a running environment.</p>
/// </note>
#[derive(std::fmt::Debug)]
pub struct DeleteApplication<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::delete_application_input::Builder,
}
impl<C, M, R> DeleteApplication<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DeleteApplication`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DeleteApplicationOutput,
aws_smithy_http::result::SdkError<crate::error::DeleteApplicationError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DeleteApplicationInputOperationOutputAlias,
crate::output::DeleteApplicationOutput,
crate::error::DeleteApplicationError,
crate::input::DeleteApplicationInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application to delete.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application to delete.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>When set to true, running environments will be terminated before deleting the
/// application.</p>
pub fn terminate_env_by_force(mut self, inp: bool) -> Self {
self.inner = self.inner.terminate_env_by_force(inp);
self
}
/// <p>When set to true, running environments will be terminated before deleting the
/// application.</p>
pub fn set_terminate_env_by_force(mut self, input: std::option::Option<bool>) -> Self {
self.inner = self.inner.set_terminate_env_by_force(input);
self
}
}
/// Fluent builder constructing a request to `DeleteApplicationVersion`.
///
/// <p>Deletes the specified version from the specified application.</p>
/// <note>
/// <p>You cannot delete an application version that is associated with a running
/// environment.</p>
/// </note>
#[derive(std::fmt::Debug)]
pub struct DeleteApplicationVersion<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::delete_application_version_input::Builder,
}
impl<C, M, R> DeleteApplicationVersion<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DeleteApplicationVersion`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DeleteApplicationVersionOutput,
aws_smithy_http::result::SdkError<crate::error::DeleteApplicationVersionError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DeleteApplicationVersionInputOperationOutputAlias,
crate::output::DeleteApplicationVersionOutput,
crate::error::DeleteApplicationVersionError,
crate::input::DeleteApplicationVersionInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application to which the version belongs.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application to which the version belongs.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The label of the version to delete.</p>
pub fn version_label(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.version_label(inp);
self
}
/// <p>The label of the version to delete.</p>
pub fn set_version_label(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_version_label(input);
self
}
/// <p>Set to <code>true</code> to delete the source bundle from your storage bucket.
/// Otherwise, the application version is deleted only from Elastic Beanstalk and the source
/// bundle remains in Amazon S3.</p>
pub fn delete_source_bundle(mut self, inp: bool) -> Self {
self.inner = self.inner.delete_source_bundle(inp);
self
}
/// <p>Set to <code>true</code> to delete the source bundle from your storage bucket.
/// Otherwise, the application version is deleted only from Elastic Beanstalk and the source
/// bundle remains in Amazon S3.</p>
pub fn set_delete_source_bundle(mut self, input: std::option::Option<bool>) -> Self {
self.inner = self.inner.set_delete_source_bundle(input);
self
}
}
/// Fluent builder constructing a request to `DeleteConfigurationTemplate`.
///
/// <p>Deletes the specified configuration template.</p>
/// <note>
/// <p>When you launch an environment using a configuration template, the environment gets a
/// copy of the template. You can delete or modify the environment's copy of the template
/// without affecting the running environment.</p>
/// </note>
#[derive(std::fmt::Debug)]
pub struct DeleteConfigurationTemplate<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::delete_configuration_template_input::Builder,
}
impl<C, M, R> DeleteConfigurationTemplate<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DeleteConfigurationTemplate`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DeleteConfigurationTemplateOutput,
aws_smithy_http::result::SdkError<crate::error::DeleteConfigurationTemplateError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DeleteConfigurationTemplateInputOperationOutputAlias,
crate::output::DeleteConfigurationTemplateOutput,
crate::error::DeleteConfigurationTemplateError,
crate::input::DeleteConfigurationTemplateInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application to delete the configuration template from.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application to delete the configuration template from.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The name of the configuration template to delete.</p>
pub fn template_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.template_name(inp);
self
}
/// <p>The name of the configuration template to delete.</p>
pub fn set_template_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_template_name(input);
self
}
}
/// Fluent builder constructing a request to `DeleteEnvironmentConfiguration`.
///
/// <p>Deletes the draft configuration associated with the running environment.</p>
/// <p>Updating a running environment with any configuration changes creates a draft
/// configuration set. You can get the draft configuration using <a>DescribeConfigurationSettings</a> while the update is in progress or if the update
/// fails. The <code>DeploymentStatus</code> for the draft configuration indicates whether the
/// deployment is in process or has failed. The draft configuration remains in existence until it
/// is deleted with this action.</p>
#[derive(std::fmt::Debug)]
pub struct DeleteEnvironmentConfiguration<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::delete_environment_configuration_input::Builder,
}
impl<C, M, R> DeleteEnvironmentConfiguration<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DeleteEnvironmentConfiguration`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DeleteEnvironmentConfigurationOutput,
aws_smithy_http::result::SdkError<crate::error::DeleteEnvironmentConfigurationError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DeleteEnvironmentConfigurationInputOperationOutputAlias,
crate::output::DeleteEnvironmentConfigurationOutput,
crate::error::DeleteEnvironmentConfigurationError,
crate::input::DeleteEnvironmentConfigurationInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application the environment is associated with.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application the environment is associated with.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The name of the environment to delete the draft configuration from.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment to delete the draft configuration from.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
}
/// Fluent builder constructing a request to `DeletePlatformVersion`.
///
/// <p>Deletes the specified version of a custom platform.</p>
#[derive(std::fmt::Debug)]
pub struct DeletePlatformVersion<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::delete_platform_version_input::Builder,
}
impl<C, M, R> DeletePlatformVersion<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DeletePlatformVersion`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DeletePlatformVersionOutput,
aws_smithy_http::result::SdkError<crate::error::DeletePlatformVersionError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DeletePlatformVersionInputOperationOutputAlias,
crate::output::DeletePlatformVersionOutput,
crate::error::DeletePlatformVersionError,
crate::input::DeletePlatformVersionInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The ARN of the version of the custom platform.</p>
pub fn platform_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.platform_arn(inp);
self
}
/// <p>The ARN of the version of the custom platform.</p>
pub fn set_platform_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_platform_arn(input);
self
}
}
/// Fluent builder constructing a request to `DescribeAccountAttributes`.
///
/// <p>Returns attributes related to AWS Elastic Beanstalk that are associated with the calling AWS
/// account.</p>
/// <p>The result currently has one set of attributes—resource quotas.</p>
#[derive(std::fmt::Debug)]
pub struct DescribeAccountAttributes<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_account_attributes_input::Builder,
}
impl<C, M, R> DescribeAccountAttributes<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeAccountAttributes`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeAccountAttributesOutput,
aws_smithy_http::result::SdkError<crate::error::DescribeAccountAttributesError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeAccountAttributesInputOperationOutputAlias,
crate::output::DescribeAccountAttributesOutput,
crate::error::DescribeAccountAttributesError,
crate::input::DescribeAccountAttributesInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
}
/// Fluent builder constructing a request to `DescribeApplications`.
///
/// <p>Returns the descriptions of existing applications.</p>
#[derive(std::fmt::Debug)]
pub struct DescribeApplications<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_applications_input::Builder,
}
impl<C, M, R> DescribeApplications<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeApplications`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeApplicationsOutput,
aws_smithy_http::result::SdkError<crate::error::DescribeApplicationsError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeApplicationsInputOperationOutputAlias,
crate::output::DescribeApplicationsOutput,
crate::error::DescribeApplicationsError,
crate::input::DescribeApplicationsInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// Appends an item to `ApplicationNames`.
///
/// To override the contents of this collection use [`set_application_names`](Self::set_application_names).
///
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to only include
/// those with the specified names.</p>
pub fn application_names(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_names(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to only include
/// those with the specified names.</p>
pub fn set_application_names(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_application_names(input);
self
}
}
/// Fluent builder constructing a request to `DescribeApplicationVersions`.
///
/// <p>Retrieve a list of application versions.</p>
#[derive(std::fmt::Debug)]
pub struct DescribeApplicationVersions<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_application_versions_input::Builder,
}
impl<C, M, R> DescribeApplicationVersions<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeApplicationVersions`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeApplicationVersionsOutput,
aws_smithy_http::result::SdkError<crate::error::DescribeApplicationVersionsError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeApplicationVersionsInputOperationOutputAlias,
crate::output::DescribeApplicationVersionsOutput,
crate::error::DescribeApplicationVersionsError,
crate::input::DescribeApplicationVersionsInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>Specify an application name to show only application versions for that
/// application.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>Specify an application name to show only application versions for that
/// application.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// Appends an item to `VersionLabels`.
///
/// To override the contents of this collection use [`set_version_labels`](Self::set_version_labels).
///
/// <p>Specify a version label to show a specific application version.</p>
pub fn version_labels(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.version_labels(inp);
self
}
/// <p>Specify a version label to show a specific application version.</p>
pub fn set_version_labels(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_version_labels(input);
self
}
/// <p>For a paginated request. Specify a maximum number of application versions to include in
/// each response.</p>
/// <p>If no <code>MaxRecords</code> is specified, all available application versions are
/// retrieved in a single response.</p>
pub fn max_records(mut self, inp: i32) -> Self {
self.inner = self.inner.max_records(inp);
self
}
/// <p>For a paginated request. Specify a maximum number of application versions to include in
/// each response.</p>
/// <p>If no <code>MaxRecords</code> is specified, all available application versions are
/// retrieved in a single response.</p>
pub fn set_max_records(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_records(input);
self
}
/// <p>For a paginated request. Specify a token from a previous response page to retrieve the next response page. All other
/// parameter values must be identical to the ones specified in the initial request.</p>
/// <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
/// <p>For a paginated request. Specify a token from a previous response page to retrieve the next response page. All other
/// parameter values must be identical to the ones specified in the initial request.</p>
/// <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
}
/// Fluent builder constructing a request to `DescribeConfigurationOptions`.
///
/// <p>Describes the configuration options that are used in a particular configuration
/// template or environment, or that a specified solution stack defines. The description includes
/// the values the options, their default values, and an indication of the required action on a
/// running environment if an option value is changed.</p>
#[derive(std::fmt::Debug)]
pub struct DescribeConfigurationOptions<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_configuration_options_input::Builder,
}
impl<C, M, R> DescribeConfigurationOptions<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeConfigurationOptions`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeConfigurationOptionsOutput,
aws_smithy_http::result::SdkError<crate::error::DescribeConfigurationOptionsError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeConfigurationOptionsInputOperationOutputAlias,
crate::output::DescribeConfigurationOptionsOutput,
crate::error::DescribeConfigurationOptionsError,
crate::input::DescribeConfigurationOptionsInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application associated with the configuration template or environment.
/// Only needed if you want to describe the configuration options associated with either the
/// configuration template or environment.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application associated with the configuration template or environment.
/// Only needed if you want to describe the configuration options associated with either the
/// configuration template or environment.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The name of the configuration template whose configuration options you want to
/// describe.</p>
pub fn template_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.template_name(inp);
self
}
/// <p>The name of the configuration template whose configuration options you want to
/// describe.</p>
pub fn set_template_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_template_name(input);
self
}
/// <p>The name of the environment whose configuration options you want to describe.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment whose configuration options you want to describe.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>The name of the solution stack whose configuration options you want to
/// describe.</p>
pub fn solution_stack_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.solution_stack_name(inp);
self
}
/// <p>The name of the solution stack whose configuration options you want to
/// describe.</p>
pub fn set_solution_stack_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_solution_stack_name(input);
self
}
/// <p>The ARN of the custom platform.</p>
pub fn platform_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.platform_arn(inp);
self
}
/// <p>The ARN of the custom platform.</p>
pub fn set_platform_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_platform_arn(input);
self
}
/// Appends an item to `Options`.
///
/// To override the contents of this collection use [`set_options`](Self::set_options).
///
/// <p>If specified, restricts the descriptions to only the specified options.</p>
pub fn options(mut self, inp: impl Into<crate::model::OptionSpecification>) -> Self {
self.inner = self.inner.options(inp);
self
}
/// <p>If specified, restricts the descriptions to only the specified options.</p>
pub fn set_options(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::OptionSpecification>>,
) -> Self {
self.inner = self.inner.set_options(input);
self
}
}
/// Fluent builder constructing a request to `DescribeConfigurationSettings`.
///
/// <p>Returns a description of the settings for the specified configuration set, that is,
/// either a configuration template or the configuration set associated with a running
/// environment.</p>
/// <p>When describing the settings for the configuration set associated with a running
/// environment, it is possible to receive two sets of setting descriptions. One is the deployed
/// configuration set, and the other is a draft configuration of an environment that is either in
/// the process of deployment or that failed to deploy.</p>
/// <p>Related Topics</p>
/// <ul>
/// <li>
/// <p>
/// <a>DeleteEnvironmentConfiguration</a>
/// </p>
/// </li>
/// </ul>
#[derive(std::fmt::Debug)]
pub struct DescribeConfigurationSettings<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_configuration_settings_input::Builder,
}
impl<C, M, R> DescribeConfigurationSettings<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeConfigurationSettings`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeConfigurationSettingsOutput,
aws_smithy_http::result::SdkError<crate::error::DescribeConfigurationSettingsError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeConfigurationSettingsInputOperationOutputAlias,
crate::output::DescribeConfigurationSettingsOutput,
crate::error::DescribeConfigurationSettingsError,
crate::input::DescribeConfigurationSettingsInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The application for the environment or configuration template.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The application for the environment or configuration template.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The name of the configuration template to describe.</p>
/// <p> Conditional: You must specify either this parameter or an EnvironmentName, but not
/// both. If you specify both, AWS Elastic Beanstalk returns an
/// <code>InvalidParameterCombination</code> error. If you do not specify either, AWS Elastic
/// Beanstalk returns a <code>MissingRequiredParameter</code> error. </p>
pub fn template_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.template_name(inp);
self
}
/// <p>The name of the configuration template to describe.</p>
/// <p> Conditional: You must specify either this parameter or an EnvironmentName, but not
/// both. If you specify both, AWS Elastic Beanstalk returns an
/// <code>InvalidParameterCombination</code> error. If you do not specify either, AWS Elastic
/// Beanstalk returns a <code>MissingRequiredParameter</code> error. </p>
pub fn set_template_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_template_name(input);
self
}
/// <p>The name of the environment to describe.</p>
/// <p> Condition: You must specify either this or a TemplateName, but not both. If you
/// specify both, AWS Elastic Beanstalk returns an <code>InvalidParameterCombination</code> error.
/// If you do not specify either, AWS Elastic Beanstalk returns
/// <code>MissingRequiredParameter</code> error. </p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment to describe.</p>
/// <p> Condition: You must specify either this or a TemplateName, but not both. If you
/// specify both, AWS Elastic Beanstalk returns an <code>InvalidParameterCombination</code> error.
/// If you do not specify either, AWS Elastic Beanstalk returns
/// <code>MissingRequiredParameter</code> error. </p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
}
/// Fluent builder constructing a request to `DescribeEnvironmentHealth`.
///
/// <p>Returns information about the overall health of the specified environment. The
/// <b>DescribeEnvironmentHealth</b> operation is only available with
/// AWS Elastic Beanstalk Enhanced Health.</p>
#[derive(std::fmt::Debug)]
pub struct DescribeEnvironmentHealth<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_environment_health_input::Builder,
}
impl<C, M, R> DescribeEnvironmentHealth<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeEnvironmentHealth`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeEnvironmentHealthOutput,
aws_smithy_http::result::SdkError<crate::error::DescribeEnvironmentHealthError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeEnvironmentHealthInputOperationOutputAlias,
crate::output::DescribeEnvironmentHealthOutput,
crate::error::DescribeEnvironmentHealthError,
crate::input::DescribeEnvironmentHealthInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>Specify the environment by name.</p>
/// <p>You must specify either this or an EnvironmentName, or both.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>Specify the environment by name.</p>
/// <p>You must specify either this or an EnvironmentName, or both.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>Specify the environment by ID.</p>
/// <p>You must specify either this or an EnvironmentName, or both.</p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>Specify the environment by ID.</p>
/// <p>You must specify either this or an EnvironmentName, or both.</p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// Appends an item to `AttributeNames`.
///
/// To override the contents of this collection use [`set_attribute_names`](Self::set_attribute_names).
///
/// <p>Specify the response elements to return. To retrieve all attributes, set to
/// <code>All</code>. If no attribute names are specified, returns the name of the
/// environment.</p>
pub fn attribute_names(
mut self,
inp: impl Into<crate::model::EnvironmentHealthAttribute>,
) -> Self {
self.inner = self.inner.attribute_names(inp);
self
}
/// <p>Specify the response elements to return. To retrieve all attributes, set to
/// <code>All</code>. If no attribute names are specified, returns the name of the
/// environment.</p>
pub fn set_attribute_names(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::EnvironmentHealthAttribute>>,
) -> Self {
self.inner = self.inner.set_attribute_names(input);
self
}
}
/// Fluent builder constructing a request to `DescribeEnvironmentManagedActionHistory`.
///
/// <p>Lists an environment's completed and failed managed actions.</p>
#[derive(std::fmt::Debug)]
pub struct DescribeEnvironmentManagedActionHistory<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_environment_managed_action_history_input::Builder,
}
impl<C, M, R> DescribeEnvironmentManagedActionHistory<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeEnvironmentManagedActionHistory`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeEnvironmentManagedActionHistoryOutput,
aws_smithy_http::result::SdkError<
crate::error::DescribeEnvironmentManagedActionHistoryError,
>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeEnvironmentManagedActionHistoryInputOperationOutputAlias,
crate::output::DescribeEnvironmentManagedActionHistoryOutput,
crate::error::DescribeEnvironmentManagedActionHistoryError,
crate::input::DescribeEnvironmentManagedActionHistoryInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The environment ID of the target environment.</p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>The environment ID of the target environment.</p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>The name of the target environment.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the target environment.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>The pagination token returned by a previous request.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
/// <p>The pagination token returned by a previous request.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
/// <p>The maximum number of items to return for a single request.</p>
pub fn max_items(mut self, inp: i32) -> Self {
self.inner = self.inner.max_items(inp);
self
}
/// <p>The maximum number of items to return for a single request.</p>
pub fn set_max_items(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_items(input);
self
}
}
/// Fluent builder constructing a request to `DescribeEnvironmentManagedActions`.
///
/// <p>Lists an environment's upcoming and in-progress managed actions.</p>
#[derive(std::fmt::Debug)]
pub struct DescribeEnvironmentManagedActions<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_environment_managed_actions_input::Builder,
}
impl<C, M, R> DescribeEnvironmentManagedActions<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeEnvironmentManagedActions`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeEnvironmentManagedActionsOutput,
aws_smithy_http::result::SdkError<crate::error::DescribeEnvironmentManagedActionsError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeEnvironmentManagedActionsInputOperationOutputAlias,
crate::output::DescribeEnvironmentManagedActionsOutput,
crate::error::DescribeEnvironmentManagedActionsError,
crate::input::DescribeEnvironmentManagedActionsInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the target environment.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the target environment.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>The environment ID of the target environment.</p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>The environment ID of the target environment.</p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>To show only actions with a particular status, specify a status.</p>
pub fn status(mut self, inp: crate::model::ActionStatus) -> Self {
self.inner = self.inner.status(inp);
self
}
/// <p>To show only actions with a particular status, specify a status.</p>
pub fn set_status(
mut self,
input: std::option::Option<crate::model::ActionStatus>,
) -> Self {
self.inner = self.inner.set_status(input);
self
}
}
/// Fluent builder constructing a request to `DescribeEnvironmentResources`.
///
/// <p>Returns AWS resources for this environment.</p>
#[derive(std::fmt::Debug)]
pub struct DescribeEnvironmentResources<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_environment_resources_input::Builder,
}
impl<C, M, R> DescribeEnvironmentResources<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeEnvironmentResources`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeEnvironmentResourcesOutput,
aws_smithy_http::result::SdkError<crate::error::DescribeEnvironmentResourcesError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeEnvironmentResourcesInputOperationOutputAlias,
crate::output::DescribeEnvironmentResourcesOutput,
crate::error::DescribeEnvironmentResourcesError,
crate::input::DescribeEnvironmentResourcesInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The ID of the environment to retrieve AWS resource usage data.</p>
/// <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>The ID of the environment to retrieve AWS resource usage data.</p>
/// <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>The name of the environment to retrieve AWS resource usage data.</p>
/// <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment to retrieve AWS resource usage data.</p>
/// <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
}
/// Fluent builder constructing a request to `DescribeEnvironments`.
///
/// <p>Returns descriptions for existing environments.</p>
#[derive(std::fmt::Debug)]
pub struct DescribeEnvironments<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_environments_input::Builder,
}
impl<C, M, R> DescribeEnvironments<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeEnvironments`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeEnvironmentsOutput,
aws_smithy_http::result::SdkError<crate::error::DescribeEnvironmentsError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeEnvironmentsInputOperationOutputAlias,
crate::output::DescribeEnvironmentsOutput,
crate::error::DescribeEnvironmentsError,
crate::input::DescribeEnvironmentsInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only
/// those that are associated with this application.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only
/// those that are associated with this application.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only
/// those that are associated with this application version.</p>
pub fn version_label(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.version_label(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only
/// those that are associated with this application version.</p>
pub fn set_version_label(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_version_label(input);
self
}
/// Appends an item to `EnvironmentIds`.
///
/// To override the contents of this collection use [`set_environment_ids`](Self::set_environment_ids).
///
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only
/// those that have the specified IDs.</p>
pub fn environment_ids(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_ids(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only
/// those that have the specified IDs.</p>
pub fn set_environment_ids(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_environment_ids(input);
self
}
/// Appends an item to `EnvironmentNames`.
///
/// To override the contents of this collection use [`set_environment_names`](Self::set_environment_names).
///
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only
/// those that have the specified names.</p>
pub fn environment_names(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_names(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only
/// those that have the specified names.</p>
pub fn set_environment_names(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_environment_names(input);
self
}
/// <p>Indicates whether to include deleted environments:</p>
/// <p>
/// <code>true</code>: Environments that have been deleted after
/// <code>IncludedDeletedBackTo</code> are displayed.</p>
/// <p>
/// <code>false</code>: Do not include deleted environments.</p>
pub fn include_deleted(mut self, inp: bool) -> Self {
self.inner = self.inner.include_deleted(inp);
self
}
/// <p>Indicates whether to include deleted environments:</p>
/// <p>
/// <code>true</code>: Environments that have been deleted after
/// <code>IncludedDeletedBackTo</code> are displayed.</p>
/// <p>
/// <code>false</code>: Do not include deleted environments.</p>
pub fn set_include_deleted(mut self, input: std::option::Option<bool>) -> Self {
self.inner = self.inner.set_include_deleted(input);
self
}
/// <p> If specified when <code>IncludeDeleted</code> is set to <code>true</code>, then
/// environments deleted after this date are displayed. </p>
pub fn included_deleted_back_to(mut self, inp: aws_smithy_types::Instant) -> Self {
self.inner = self.inner.included_deleted_back_to(inp);
self
}
/// <p> If specified when <code>IncludeDeleted</code> is set to <code>true</code>, then
/// environments deleted after this date are displayed. </p>
pub fn set_included_deleted_back_to(
mut self,
input: std::option::Option<aws_smithy_types::Instant>,
) -> Self {
self.inner = self.inner.set_included_deleted_back_to(input);
self
}
/// <p>For a paginated request. Specify a maximum number of environments to include in
/// each response.</p>
/// <p>If no <code>MaxRecords</code> is specified, all available environments are
/// retrieved in a single response.</p>
pub fn max_records(mut self, inp: i32) -> Self {
self.inner = self.inner.max_records(inp);
self
}
/// <p>For a paginated request. Specify a maximum number of environments to include in
/// each response.</p>
/// <p>If no <code>MaxRecords</code> is specified, all available environments are
/// retrieved in a single response.</p>
pub fn set_max_records(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_records(input);
self
}
/// <p>For a paginated request. Specify a token from a previous response page to retrieve the next response page. All other
/// parameter values must be identical to the ones specified in the initial request.</p>
/// <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
/// <p>For a paginated request. Specify a token from a previous response page to retrieve the next response page. All other
/// parameter values must be identical to the ones specified in the initial request.</p>
/// <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
}
/// Fluent builder constructing a request to `DescribeEvents`.
///
/// <p>Returns list of event descriptions matching criteria up to the last 6 weeks.</p>
/// <note>
/// <p>This action returns the most recent 1,000 events from the specified
/// <code>NextToken</code>.</p>
/// </note>
#[derive(std::fmt::Debug)]
pub struct DescribeEvents<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_events_input::Builder,
}
impl<C, M, R> DescribeEvents<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeEvents`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeEventsOutput,
aws_smithy_http::result::SdkError<crate::error::DescribeEventsError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeEventsInputOperationOutputAlias,
crate::output::DescribeEventsOutput,
crate::error::DescribeEventsError,
crate::input::DescribeEventsInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only
/// those associated with this application.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only
/// those associated with this application.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those
/// associated with this application version.</p>
pub fn version_label(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.version_label(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those
/// associated with this application version.</p>
pub fn set_version_label(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_version_label(input);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that
/// are associated with this environment configuration.</p>
pub fn template_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.template_name(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that
/// are associated with this environment configuration.</p>
pub fn set_template_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_template_name(input);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those
/// associated with this environment.</p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those
/// associated with this environment.</p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those
/// associated with this environment.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those
/// associated with this environment.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>The ARN of a custom platform version. If specified, AWS Elastic Beanstalk restricts the
/// returned descriptions to those associated with this custom platform version.</p>
pub fn platform_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.platform_arn(inp);
self
}
/// <p>The ARN of a custom platform version. If specified, AWS Elastic Beanstalk restricts the
/// returned descriptions to those associated with this custom platform version.</p>
pub fn set_platform_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_platform_arn(input);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the described events to include only
/// those associated with this request ID.</p>
pub fn request_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.request_id(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the described events to include only
/// those associated with this request ID.</p>
pub fn set_request_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_request_id(input);
self
}
/// <p>If specified, limits the events returned from this call to include only those with the
/// specified severity or higher.</p>
pub fn severity(mut self, inp: crate::model::EventSeverity) -> Self {
self.inner = self.inner.severity(inp);
self
}
/// <p>If specified, limits the events returned from this call to include only those with the
/// specified severity or higher.</p>
pub fn set_severity(
mut self,
input: std::option::Option<crate::model::EventSeverity>,
) -> Self {
self.inner = self.inner.set_severity(input);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that
/// occur on or after this time.</p>
pub fn start_time(mut self, inp: aws_smithy_types::Instant) -> Self {
self.inner = self.inner.start_time(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that
/// occur on or after this time.</p>
pub fn set_start_time(
mut self,
input: std::option::Option<aws_smithy_types::Instant>,
) -> Self {
self.inner = self.inner.set_start_time(input);
self
}
/// <p> If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that
/// occur up to, but not including, the <code>EndTime</code>. </p>
pub fn end_time(mut self, inp: aws_smithy_types::Instant) -> Self {
self.inner = self.inner.end_time(inp);
self
}
/// <p> If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that
/// occur up to, but not including, the <code>EndTime</code>. </p>
pub fn set_end_time(
mut self,
input: std::option::Option<aws_smithy_types::Instant>,
) -> Self {
self.inner = self.inner.set_end_time(input);
self
}
/// <p>Specifies the maximum number of events that can be returned, beginning with the most
/// recent event.</p>
pub fn max_records(mut self, inp: i32) -> Self {
self.inner = self.inner.max_records(inp);
self
}
/// <p>Specifies the maximum number of events that can be returned, beginning with the most
/// recent event.</p>
pub fn set_max_records(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_records(input);
self
}
/// <p>Pagination token. If specified, the events return the next batch of results.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
/// <p>Pagination token. If specified, the events return the next batch of results.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
}
/// Fluent builder constructing a request to `DescribeInstancesHealth`.
///
/// <p>Retrieves detailed information about the health of instances in your AWS Elastic
/// Beanstalk. This operation requires <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/health-enhanced.html">enhanced health
/// reporting</a>.</p>
#[derive(std::fmt::Debug)]
pub struct DescribeInstancesHealth<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_instances_health_input::Builder,
}
impl<C, M, R> DescribeInstancesHealth<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribeInstancesHealth`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribeInstancesHealthOutput,
aws_smithy_http::result::SdkError<crate::error::DescribeInstancesHealthError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribeInstancesHealthInputOperationOutputAlias,
crate::output::DescribeInstancesHealthOutput,
crate::error::DescribeInstancesHealthError,
crate::input::DescribeInstancesHealthInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>Specify the AWS Elastic Beanstalk environment by name.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>Specify the AWS Elastic Beanstalk environment by name.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>Specify the AWS Elastic Beanstalk environment by ID.</p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>Specify the AWS Elastic Beanstalk environment by ID.</p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// Appends an item to `AttributeNames`.
///
/// To override the contents of this collection use [`set_attribute_names`](Self::set_attribute_names).
///
/// <p>Specifies the response elements you wish to receive. To retrieve all attributes, set to
/// <code>All</code>. If no attribute names are specified, returns a list of
/// instances.</p>
pub fn attribute_names(
mut self,
inp: impl Into<crate::model::InstancesHealthAttribute>,
) -> Self {
self.inner = self.inner.attribute_names(inp);
self
}
/// <p>Specifies the response elements you wish to receive. To retrieve all attributes, set to
/// <code>All</code>. If no attribute names are specified, returns a list of
/// instances.</p>
pub fn set_attribute_names(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::InstancesHealthAttribute>>,
) -> Self {
self.inner = self.inner.set_attribute_names(input);
self
}
/// <p>Specify the pagination token returned by a previous call.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
/// <p>Specify the pagination token returned by a previous call.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
}
/// Fluent builder constructing a request to `DescribePlatformVersion`.
///
/// <p>Describes a platform version. Provides full details. Compare to <a>ListPlatformVersions</a>, which provides summary information about a list of
/// platform versions.</p>
/// <p>For definitions of platform version and other platform-related terms, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-glossary.html">AWS Elastic Beanstalk
/// Platforms Glossary</a>.</p>
#[derive(std::fmt::Debug)]
pub struct DescribePlatformVersion<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::describe_platform_version_input::Builder,
}
impl<C, M, R> DescribePlatformVersion<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DescribePlatformVersion`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DescribePlatformVersionOutput,
aws_smithy_http::result::SdkError<crate::error::DescribePlatformVersionError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DescribePlatformVersionInputOperationOutputAlias,
crate::output::DescribePlatformVersionOutput,
crate::error::DescribePlatformVersionError,
crate::input::DescribePlatformVersionInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The ARN of the platform version.</p>
pub fn platform_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.platform_arn(inp);
self
}
/// <p>The ARN of the platform version.</p>
pub fn set_platform_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_platform_arn(input);
self
}
}
/// Fluent builder constructing a request to `DisassociateEnvironmentOperationsRole`.
///
/// <p>Disassociate the operations role from an environment. After this call is made, Elastic Beanstalk uses
/// the caller's permissions for permissions to downstream services during subsequent calls acting
/// on this environment. For more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html">Operations roles</a> in the
/// <i>AWS Elastic Beanstalk Developer Guide</i>.</p>
#[derive(std::fmt::Debug)]
pub struct DisassociateEnvironmentOperationsRole<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::disassociate_environment_operations_role_input::Builder,
}
impl<C, M, R> DisassociateEnvironmentOperationsRole<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `DisassociateEnvironmentOperationsRole`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::DisassociateEnvironmentOperationsRoleOutput,
aws_smithy_http::result::SdkError<
crate::error::DisassociateEnvironmentOperationsRoleError,
>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::DisassociateEnvironmentOperationsRoleInputOperationOutputAlias,
crate::output::DisassociateEnvironmentOperationsRoleOutput,
crate::error::DisassociateEnvironmentOperationsRoleError,
crate::input::DisassociateEnvironmentOperationsRoleInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the environment from which to disassociate the operations role.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment from which to disassociate the operations role.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
}
/// Fluent builder constructing a request to `ListAvailableSolutionStacks`.
///
/// <p>Returns a list of the available solution stack names, with the public version first and
/// then in reverse chronological order.</p>
#[derive(std::fmt::Debug)]
pub struct ListAvailableSolutionStacks<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::list_available_solution_stacks_input::Builder,
}
impl<C, M, R> ListAvailableSolutionStacks<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `ListAvailableSolutionStacks`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListAvailableSolutionStacksOutput,
aws_smithy_http::result::SdkError<crate::error::ListAvailableSolutionStacksError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::ListAvailableSolutionStacksInputOperationOutputAlias,
crate::output::ListAvailableSolutionStacksOutput,
crate::error::ListAvailableSolutionStacksError,
crate::input::ListAvailableSolutionStacksInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
}
/// Fluent builder constructing a request to `ListPlatformBranches`.
///
/// <p>Lists the platform branches available for your account in an AWS Region. Provides
/// summary information about each platform branch.</p>
/// <p>For definitions of platform branch and other platform-related terms, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-glossary.html">AWS Elastic Beanstalk
/// Platforms Glossary</a>.</p>
#[derive(std::fmt::Debug)]
pub struct ListPlatformBranches<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::list_platform_branches_input::Builder,
}
impl<C, M, R> ListPlatformBranches<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `ListPlatformBranches`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListPlatformBranchesOutput,
aws_smithy_http::result::SdkError<crate::error::ListPlatformBranchesError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::ListPlatformBranchesInputOperationOutputAlias,
crate::output::ListPlatformBranchesOutput,
crate::error::ListPlatformBranchesError,
crate::input::ListPlatformBranchesInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// Appends an item to `Filters`.
///
/// To override the contents of this collection use [`set_filters`](Self::set_filters).
///
/// <p>Criteria for restricting the resulting list of platform branches. The filter is evaluated
/// as a logical conjunction (AND) of the separate <code>SearchFilter</code> terms.</p>
/// <p>The following list shows valid attribute values for each of the <code>SearchFilter</code>
/// terms. Most operators take a single value. The <code>in</code> and <code>not_in</code>
/// operators can take multiple values.</p>
/// <ul>
/// <li>
/// <p>
/// <code>Attribute = BranchName</code>:</p>
/// <ul>
/// <li>
/// <p>
/// <code>Operator</code>: <code>=</code> | <code>!=</code> | <code>begins_with</code>
/// | <code>ends_with</code> | <code>contains</code> | <code>in</code> |
/// <code>not_in</code>
/// </p>
/// </li>
/// </ul>
/// </li>
/// <li>
/// <p>
/// <code>Attribute = LifecycleState</code>:</p>
/// <ul>
/// <li>
/// <p>
/// <code>Operator</code>: <code>=</code> | <code>!=</code> | <code>in</code> |
/// <code>not_in</code>
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>Values</code>: <code>beta</code> | <code>supported</code> |
/// <code>deprecated</code> | <code>retired</code>
/// </p>
/// </li>
/// </ul>
/// </li>
/// <li>
/// <p>
/// <code>Attribute = PlatformName</code>:</p>
/// <ul>
/// <li>
/// <p>
/// <code>Operator</code>: <code>=</code> | <code>!=</code> | <code>begins_with</code>
/// | <code>ends_with</code> | <code>contains</code> | <code>in</code> |
/// <code>not_in</code>
/// </p>
/// </li>
/// </ul>
/// </li>
/// <li>
/// <p>
/// <code>Attribute = TierType</code>:</p>
/// <ul>
/// <li>
/// <p>
/// <code>Operator</code>: <code>=</code> | <code>!=</code>
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>Values</code>: <code>WebServer/Standard</code> | <code>Worker/SQS/HTTP</code>
/// </p>
/// </li>
/// </ul>
/// </li>
/// </ul>
/// <p>Array size: limited to 10 <code>SearchFilter</code> objects.</p>
/// <p>Within each <code>SearchFilter</code> item, the <code>Values</code> array is limited to 10
/// items.</p>
pub fn filters(mut self, inp: impl Into<crate::model::SearchFilter>) -> Self {
self.inner = self.inner.filters(inp);
self
}
/// <p>Criteria for restricting the resulting list of platform branches. The filter is evaluated
/// as a logical conjunction (AND) of the separate <code>SearchFilter</code> terms.</p>
/// <p>The following list shows valid attribute values for each of the <code>SearchFilter</code>
/// terms. Most operators take a single value. The <code>in</code> and <code>not_in</code>
/// operators can take multiple values.</p>
/// <ul>
/// <li>
/// <p>
/// <code>Attribute = BranchName</code>:</p>
/// <ul>
/// <li>
/// <p>
/// <code>Operator</code>: <code>=</code> | <code>!=</code> | <code>begins_with</code>
/// | <code>ends_with</code> | <code>contains</code> | <code>in</code> |
/// <code>not_in</code>
/// </p>
/// </li>
/// </ul>
/// </li>
/// <li>
/// <p>
/// <code>Attribute = LifecycleState</code>:</p>
/// <ul>
/// <li>
/// <p>
/// <code>Operator</code>: <code>=</code> | <code>!=</code> | <code>in</code> |
/// <code>not_in</code>
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>Values</code>: <code>beta</code> | <code>supported</code> |
/// <code>deprecated</code> | <code>retired</code>
/// </p>
/// </li>
/// </ul>
/// </li>
/// <li>
/// <p>
/// <code>Attribute = PlatformName</code>:</p>
/// <ul>
/// <li>
/// <p>
/// <code>Operator</code>: <code>=</code> | <code>!=</code> | <code>begins_with</code>
/// | <code>ends_with</code> | <code>contains</code> | <code>in</code> |
/// <code>not_in</code>
/// </p>
/// </li>
/// </ul>
/// </li>
/// <li>
/// <p>
/// <code>Attribute = TierType</code>:</p>
/// <ul>
/// <li>
/// <p>
/// <code>Operator</code>: <code>=</code> | <code>!=</code>
/// </p>
/// </li>
/// <li>
/// <p>
/// <code>Values</code>: <code>WebServer/Standard</code> | <code>Worker/SQS/HTTP</code>
/// </p>
/// </li>
/// </ul>
/// </li>
/// </ul>
/// <p>Array size: limited to 10 <code>SearchFilter</code> objects.</p>
/// <p>Within each <code>SearchFilter</code> item, the <code>Values</code> array is limited to 10
/// items.</p>
pub fn set_filters(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::SearchFilter>>,
) -> Self {
self.inner = self.inner.set_filters(input);
self
}
/// <p>The maximum number of platform branch values returned in one call.</p>
pub fn max_records(mut self, inp: i32) -> Self {
self.inner = self.inner.max_records(inp);
self
}
/// <p>The maximum number of platform branch values returned in one call.</p>
pub fn set_max_records(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_records(input);
self
}
/// <p>For a paginated request. Specify a token from a previous response page to retrieve the
/// next response page. All other parameter values must be identical to the ones specified in the
/// initial request.</p>
/// <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
/// <p>For a paginated request. Specify a token from a previous response page to retrieve the
/// next response page. All other parameter values must be identical to the ones specified in the
/// initial request.</p>
/// <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
}
/// Fluent builder constructing a request to `ListPlatformVersions`.
///
/// <p>Lists the platform versions available for your account in an AWS Region. Provides
/// summary information about each platform version. Compare to <a>DescribePlatformVersion</a>, which provides full details about a single platform
/// version.</p>
/// <p>For definitions of platform version and other platform-related terms, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-glossary.html">AWS Elastic Beanstalk
/// Platforms Glossary</a>.</p>
#[derive(std::fmt::Debug)]
pub struct ListPlatformVersions<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::list_platform_versions_input::Builder,
}
impl<C, M, R> ListPlatformVersions<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `ListPlatformVersions`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListPlatformVersionsOutput,
aws_smithy_http::result::SdkError<crate::error::ListPlatformVersionsError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::ListPlatformVersionsInputOperationOutputAlias,
crate::output::ListPlatformVersionsOutput,
crate::error::ListPlatformVersionsError,
crate::input::ListPlatformVersionsInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// Appends an item to `Filters`.
///
/// To override the contents of this collection use [`set_filters`](Self::set_filters).
///
/// <p>Criteria for restricting the resulting list of platform versions. The filter is
/// interpreted as a logical conjunction (AND) of the separate <code>PlatformFilter</code>
/// terms.</p>
pub fn filters(mut self, inp: impl Into<crate::model::PlatformFilter>) -> Self {
self.inner = self.inner.filters(inp);
self
}
/// <p>Criteria for restricting the resulting list of platform versions. The filter is
/// interpreted as a logical conjunction (AND) of the separate <code>PlatformFilter</code>
/// terms.</p>
pub fn set_filters(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::PlatformFilter>>,
) -> Self {
self.inner = self.inner.set_filters(input);
self
}
/// <p>The maximum number of platform version values returned in one call.</p>
pub fn max_records(mut self, inp: i32) -> Self {
self.inner = self.inner.max_records(inp);
self
}
/// <p>The maximum number of platform version values returned in one call.</p>
pub fn set_max_records(mut self, input: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_records(input);
self
}
/// <p>For a paginated request. Specify a token from a previous response page to retrieve the
/// next response page. All other parameter values must be identical to the ones specified in the
/// initial request.</p>
/// <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p>
pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.next_token(inp);
self
}
/// <p>For a paginated request. Specify a token from a previous response page to retrieve the
/// next response page. All other parameter values must be identical to the ones specified in the
/// initial request.</p>
/// <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_next_token(input);
self
}
}
/// Fluent builder constructing a request to `ListTagsForResource`.
///
/// <p>Return the tags applied to an AWS Elastic Beanstalk resource. The response contains a list of tag key-value pairs.</p>
/// <p>Elastic Beanstalk supports tagging of all of its resources. For details about resource tagging, see
/// <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/applications-tagging-resources.html">Tagging Application
/// Resources</a>.</p>
#[derive(std::fmt::Debug)]
pub struct ListTagsForResource<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::list_tags_for_resource_input::Builder,
}
impl<C, M, R> ListTagsForResource<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `ListTagsForResource`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::ListTagsForResourceOutput,
aws_smithy_http::result::SdkError<crate::error::ListTagsForResourceError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::ListTagsForResourceInputOperationOutputAlias,
crate::output::ListTagsForResourceOutput,
crate::error::ListTagsForResourceError,
crate::input::ListTagsForResourceInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the resouce for which a tag list is requested.</p>
/// <p>Must be the ARN of an Elastic Beanstalk resource.</p>
pub fn resource_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.resource_arn(inp);
self
}
/// <p>The Amazon Resource Name (ARN) of the resouce for which a tag list is requested.</p>
/// <p>Must be the ARN of an Elastic Beanstalk resource.</p>
pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_resource_arn(input);
self
}
}
/// Fluent builder constructing a request to `RebuildEnvironment`.
///
/// <p>Deletes and recreates all of the AWS resources (for example: the Auto Scaling group,
/// load balancer, etc.) for a specified environment and forces a restart.</p>
#[derive(std::fmt::Debug)]
pub struct RebuildEnvironment<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::rebuild_environment_input::Builder,
}
impl<C, M, R> RebuildEnvironment<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `RebuildEnvironment`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::RebuildEnvironmentOutput,
aws_smithy_http::result::SdkError<crate::error::RebuildEnvironmentError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::RebuildEnvironmentInputOperationOutputAlias,
crate::output::RebuildEnvironmentOutput,
crate::error::RebuildEnvironmentError,
crate::input::RebuildEnvironmentInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The ID of the environment to rebuild.</p>
/// <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>The ID of the environment to rebuild.</p>
/// <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>The name of the environment to rebuild.</p>
/// <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment to rebuild.</p>
/// <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
}
/// Fluent builder constructing a request to `RequestEnvironmentInfo`.
///
/// <p>Initiates a request to compile the specified type of information of the deployed
/// environment.</p>
/// <p> Setting the <code>InfoType</code> to <code>tail</code> compiles the last lines from
/// the application server log files of every Amazon EC2 instance in your environment. </p>
/// <p> Setting the <code>InfoType</code> to <code>bundle</code> compresses the application
/// server log files for every Amazon EC2 instance into a <code>.zip</code> file. Legacy and .NET
/// containers do not support bundle logs. </p>
/// <p> Use <a>RetrieveEnvironmentInfo</a> to obtain the set of logs. </p>
/// <p>Related Topics</p>
/// <ul>
/// <li>
/// <p>
/// <a>RetrieveEnvironmentInfo</a>
/// </p>
/// </li>
/// </ul>
#[derive(std::fmt::Debug)]
pub struct RequestEnvironmentInfo<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::request_environment_info_input::Builder,
}
impl<C, M, R> RequestEnvironmentInfo<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `RequestEnvironmentInfo`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::RequestEnvironmentInfoOutput,
aws_smithy_http::result::SdkError<crate::error::RequestEnvironmentInfoError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::RequestEnvironmentInfoInputOperationOutputAlias,
crate::output::RequestEnvironmentInfoOutput,
crate::error::RequestEnvironmentInfoError,
crate::input::RequestEnvironmentInfoInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The ID of the environment of the requested data.</p>
/// <p>If no such environment is found, <code>RequestEnvironmentInfo</code> returns an
/// <code>InvalidParameterValue</code> error. </p>
/// <p>Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>The ID of the environment of the requested data.</p>
/// <p>If no such environment is found, <code>RequestEnvironmentInfo</code> returns an
/// <code>InvalidParameterValue</code> error. </p>
/// <p>Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>The name of the environment of the requested data.</p>
/// <p>If no such environment is found, <code>RequestEnvironmentInfo</code> returns an
/// <code>InvalidParameterValue</code> error. </p>
/// <p>Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment of the requested data.</p>
/// <p>If no such environment is found, <code>RequestEnvironmentInfo</code> returns an
/// <code>InvalidParameterValue</code> error. </p>
/// <p>Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>The type of information to request.</p>
pub fn info_type(mut self, inp: crate::model::EnvironmentInfoType) -> Self {
self.inner = self.inner.info_type(inp);
self
}
/// <p>The type of information to request.</p>
pub fn set_info_type(
mut self,
input: std::option::Option<crate::model::EnvironmentInfoType>,
) -> Self {
self.inner = self.inner.set_info_type(input);
self
}
}
/// Fluent builder constructing a request to `RestartAppServer`.
///
/// <p>Causes the environment to restart the application container server running on each
/// Amazon EC2 instance.</p>
#[derive(std::fmt::Debug)]
pub struct RestartAppServer<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::restart_app_server_input::Builder,
}
impl<C, M, R> RestartAppServer<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `RestartAppServer`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::RestartAppServerOutput,
aws_smithy_http::result::SdkError<crate::error::RestartAppServerError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::RestartAppServerInputOperationOutputAlias,
crate::output::RestartAppServerOutput,
crate::error::RestartAppServerError,
crate::input::RestartAppServerInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The ID of the environment to restart the server for.</p>
/// <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>The ID of the environment to restart the server for.</p>
/// <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>The name of the environment to restart the server for.</p>
/// <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment to restart the server for.</p>
/// <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
}
/// Fluent builder constructing a request to `RetrieveEnvironmentInfo`.
///
/// <p>Retrieves the compiled information from a <a>RequestEnvironmentInfo</a>
/// request.</p>
/// <p>Related Topics</p>
/// <ul>
/// <li>
/// <p>
/// <a>RequestEnvironmentInfo</a>
/// </p>
/// </li>
/// </ul>
#[derive(std::fmt::Debug)]
pub struct RetrieveEnvironmentInfo<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::retrieve_environment_info_input::Builder,
}
impl<C, M, R> RetrieveEnvironmentInfo<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `RetrieveEnvironmentInfo`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::RetrieveEnvironmentInfoOutput,
aws_smithy_http::result::SdkError<crate::error::RetrieveEnvironmentInfoError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::RetrieveEnvironmentInfoInputOperationOutputAlias,
crate::output::RetrieveEnvironmentInfoOutput,
crate::error::RetrieveEnvironmentInfoError,
crate::input::RetrieveEnvironmentInfoInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The ID of the data's environment.</p>
/// <p>If no such environment is found, returns an <code>InvalidParameterValue</code>
/// error.</p>
/// <p>Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code>
/// error.</p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>The ID of the data's environment.</p>
/// <p>If no such environment is found, returns an <code>InvalidParameterValue</code>
/// error.</p>
/// <p>Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code>
/// error.</p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>The name of the data's environment.</p>
/// <p> If no such environment is found, returns an <code>InvalidParameterValue</code> error. </p>
/// <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the data's environment.</p>
/// <p> If no such environment is found, returns an <code>InvalidParameterValue</code> error. </p>
/// <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>The type of information to retrieve.</p>
pub fn info_type(mut self, inp: crate::model::EnvironmentInfoType) -> Self {
self.inner = self.inner.info_type(inp);
self
}
/// <p>The type of information to retrieve.</p>
pub fn set_info_type(
mut self,
input: std::option::Option<crate::model::EnvironmentInfoType>,
) -> Self {
self.inner = self.inner.set_info_type(input);
self
}
}
/// Fluent builder constructing a request to `SwapEnvironmentCNAMEs`.
///
/// <p>Swaps the CNAMEs of two environments.</p>
#[derive(std::fmt::Debug)]
pub struct SwapEnvironmentCNAMEs<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::swap_environment_cnam_es_input::Builder,
}
impl<C, M, R> SwapEnvironmentCNAMEs<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `SwapEnvironmentCNAMEs`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::SwapEnvironmentCnamEsOutput,
aws_smithy_http::result::SdkError<crate::error::SwapEnvironmentCNAMEsError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::SwapEnvironmentCnamEsInputOperationOutputAlias,
crate::output::SwapEnvironmentCnamEsOutput,
crate::error::SwapEnvironmentCNAMEsError,
crate::input::SwapEnvironmentCnamEsInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The ID of the source environment.</p>
/// <p> Condition: You must specify at least the <code>SourceEnvironmentID</code> or the
/// <code>SourceEnvironmentName</code>. You may also specify both. If you specify the
/// <code>SourceEnvironmentId</code>, you must specify the
/// <code>DestinationEnvironmentId</code>. </p>
pub fn source_environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.source_environment_id(inp);
self
}
/// <p>The ID of the source environment.</p>
/// <p> Condition: You must specify at least the <code>SourceEnvironmentID</code> or the
/// <code>SourceEnvironmentName</code>. You may also specify both. If you specify the
/// <code>SourceEnvironmentId</code>, you must specify the
/// <code>DestinationEnvironmentId</code>. </p>
pub fn set_source_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_source_environment_id(input);
self
}
/// <p>The name of the source environment.</p>
/// <p> Condition: You must specify at least the <code>SourceEnvironmentID</code> or the
/// <code>SourceEnvironmentName</code>. You may also specify both. If you specify the
/// <code>SourceEnvironmentName</code>, you must specify the
/// <code>DestinationEnvironmentName</code>. </p>
pub fn source_environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.source_environment_name(inp);
self
}
/// <p>The name of the source environment.</p>
/// <p> Condition: You must specify at least the <code>SourceEnvironmentID</code> or the
/// <code>SourceEnvironmentName</code>. You may also specify both. If you specify the
/// <code>SourceEnvironmentName</code>, you must specify the
/// <code>DestinationEnvironmentName</code>. </p>
pub fn set_source_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_source_environment_name(input);
self
}
/// <p>The ID of the destination environment.</p>
/// <p> Condition: You must specify at least the <code>DestinationEnvironmentID</code> or the
/// <code>DestinationEnvironmentName</code>. You may also specify both. You must specify the
/// <code>SourceEnvironmentId</code> with the <code>DestinationEnvironmentId</code>. </p>
pub fn destination_environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.destination_environment_id(inp);
self
}
/// <p>The ID of the destination environment.</p>
/// <p> Condition: You must specify at least the <code>DestinationEnvironmentID</code> or the
/// <code>DestinationEnvironmentName</code>. You may also specify both. You must specify the
/// <code>SourceEnvironmentId</code> with the <code>DestinationEnvironmentId</code>. </p>
pub fn set_destination_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_destination_environment_id(input);
self
}
/// <p>The name of the destination environment.</p>
/// <p> Condition: You must specify at least the <code>DestinationEnvironmentID</code> or the
/// <code>DestinationEnvironmentName</code>. You may also specify both. You must specify the
/// <code>SourceEnvironmentName</code> with the <code>DestinationEnvironmentName</code>.
/// </p>
pub fn destination_environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.destination_environment_name(inp);
self
}
/// <p>The name of the destination environment.</p>
/// <p> Condition: You must specify at least the <code>DestinationEnvironmentID</code> or the
/// <code>DestinationEnvironmentName</code>. You may also specify both. You must specify the
/// <code>SourceEnvironmentName</code> with the <code>DestinationEnvironmentName</code>.
/// </p>
pub fn set_destination_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_destination_environment_name(input);
self
}
}
/// Fluent builder constructing a request to `TerminateEnvironment`.
///
/// <p>Terminates the specified environment.</p>
#[derive(std::fmt::Debug)]
pub struct TerminateEnvironment<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::terminate_environment_input::Builder,
}
impl<C, M, R> TerminateEnvironment<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `TerminateEnvironment`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::TerminateEnvironmentOutput,
aws_smithy_http::result::SdkError<crate::error::TerminateEnvironmentError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::TerminateEnvironmentInputOperationOutputAlias,
crate::output::TerminateEnvironmentOutput,
crate::error::TerminateEnvironmentError,
crate::input::TerminateEnvironmentInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The ID of the environment to terminate.</p>
/// <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>The ID of the environment to terminate.</p>
/// <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>The name of the environment to terminate.</p>
/// <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment to terminate.</p>
/// <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>Indicates whether the associated AWS resources should shut down when the environment is
/// terminated:</p>
/// <ul>
/// <li>
/// <p>
/// <code>true</code>: The specified environment as well as the associated AWS resources, such
/// as Auto Scaling group and LoadBalancer, are terminated.</p>
/// </li>
/// <li>
/// <p>
/// <code>false</code>: AWS Elastic Beanstalk resource management is removed from the
/// environment, but the AWS resources continue to operate.</p>
/// </li>
/// </ul>
/// <p> For more information, see the <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/ug/"> AWS Elastic Beanstalk User Guide. </a>
/// </p>
/// <p> Default: <code>true</code>
/// </p>
/// <p> Valid Values: <code>true</code> | <code>false</code>
/// </p>
pub fn terminate_resources(mut self, inp: bool) -> Self {
self.inner = self.inner.terminate_resources(inp);
self
}
/// <p>Indicates whether the associated AWS resources should shut down when the environment is
/// terminated:</p>
/// <ul>
/// <li>
/// <p>
/// <code>true</code>: The specified environment as well as the associated AWS resources, such
/// as Auto Scaling group and LoadBalancer, are terminated.</p>
/// </li>
/// <li>
/// <p>
/// <code>false</code>: AWS Elastic Beanstalk resource management is removed from the
/// environment, but the AWS resources continue to operate.</p>
/// </li>
/// </ul>
/// <p> For more information, see the <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/ug/"> AWS Elastic Beanstalk User Guide. </a>
/// </p>
/// <p> Default: <code>true</code>
/// </p>
/// <p> Valid Values: <code>true</code> | <code>false</code>
/// </p>
pub fn set_terminate_resources(mut self, input: std::option::Option<bool>) -> Self {
self.inner = self.inner.set_terminate_resources(input);
self
}
/// <p>Terminates the target environment even if another environment in the same group is
/// dependent on it.</p>
pub fn force_terminate(mut self, inp: bool) -> Self {
self.inner = self.inner.force_terminate(inp);
self
}
/// <p>Terminates the target environment even if another environment in the same group is
/// dependent on it.</p>
pub fn set_force_terminate(mut self, input: std::option::Option<bool>) -> Self {
self.inner = self.inner.set_force_terminate(input);
self
}
}
/// Fluent builder constructing a request to `UpdateApplication`.
///
/// <p>Updates the specified application to have the specified properties.</p>
/// <note>
/// <p>If a property (for example, <code>description</code>) is not provided, the value
/// remains unchanged. To clear these properties, specify an empty string.</p>
/// </note>
#[derive(std::fmt::Debug)]
pub struct UpdateApplication<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::update_application_input::Builder,
}
impl<C, M, R> UpdateApplication<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `UpdateApplication`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::UpdateApplicationOutput,
aws_smithy_http::result::SdkError<crate::error::UpdateApplicationError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::UpdateApplicationInputOperationOutputAlias,
crate::output::UpdateApplicationOutput,
crate::error::UpdateApplicationError,
crate::input::UpdateApplicationInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application to update. If no such application is found,
/// <code>UpdateApplication</code> returns an <code>InvalidParameterValue</code> error.
/// </p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application to update. If no such application is found,
/// <code>UpdateApplication</code> returns an <code>InvalidParameterValue</code> error.
/// </p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>A new description for the application.</p>
/// <p>Default: If not specified, AWS Elastic Beanstalk does not update the
/// description.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
/// <p>A new description for the application.</p>
/// <p>Default: If not specified, AWS Elastic Beanstalk does not update the
/// description.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(input);
self
}
}
/// Fluent builder constructing a request to `UpdateApplicationResourceLifecycle`.
///
/// <p>Modifies lifecycle settings for an application.</p>
#[derive(std::fmt::Debug)]
pub struct UpdateApplicationResourceLifecycle<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::update_application_resource_lifecycle_input::Builder,
}
impl<C, M, R> UpdateApplicationResourceLifecycle<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `UpdateApplicationResourceLifecycle`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::UpdateApplicationResourceLifecycleOutput,
aws_smithy_http::result::SdkError<
crate::error::UpdateApplicationResourceLifecycleError,
>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::UpdateApplicationResourceLifecycleInputOperationOutputAlias,
crate::output::UpdateApplicationResourceLifecycleOutput,
crate::error::UpdateApplicationResourceLifecycleError,
crate::input::UpdateApplicationResourceLifecycleInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The lifecycle configuration.</p>
pub fn resource_lifecycle_config(
mut self,
inp: crate::model::ApplicationResourceLifecycleConfig,
) -> Self {
self.inner = self.inner.resource_lifecycle_config(inp);
self
}
/// <p>The lifecycle configuration.</p>
pub fn set_resource_lifecycle_config(
mut self,
input: std::option::Option<crate::model::ApplicationResourceLifecycleConfig>,
) -> Self {
self.inner = self.inner.set_resource_lifecycle_config(input);
self
}
}
/// Fluent builder constructing a request to `UpdateApplicationVersion`.
///
/// <p>Updates the specified application version to have the specified properties.</p>
/// <note>
/// <p>If a property (for example, <code>description</code>) is not provided, the value
/// remains unchanged. To clear properties, specify an empty string.</p>
/// </note>
#[derive(std::fmt::Debug)]
pub struct UpdateApplicationVersion<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::update_application_version_input::Builder,
}
impl<C, M, R> UpdateApplicationVersion<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `UpdateApplicationVersion`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::UpdateApplicationVersionOutput,
aws_smithy_http::result::SdkError<crate::error::UpdateApplicationVersionError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::UpdateApplicationVersionInputOperationOutputAlias,
crate::output::UpdateApplicationVersionOutput,
crate::error::UpdateApplicationVersionError,
crate::input::UpdateApplicationVersionInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application associated with this version.</p>
/// <p> If no application is found with this name, <code>UpdateApplication</code> returns an
/// <code>InvalidParameterValue</code> error.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application associated with this version.</p>
/// <p> If no application is found with this name, <code>UpdateApplication</code> returns an
/// <code>InvalidParameterValue</code> error.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The name of the version to update.</p>
/// <p>If no application version is found with this label, <code>UpdateApplication</code>
/// returns an <code>InvalidParameterValue</code> error. </p>
pub fn version_label(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.version_label(inp);
self
}
/// <p>The name of the version to update.</p>
/// <p>If no application version is found with this label, <code>UpdateApplication</code>
/// returns an <code>InvalidParameterValue</code> error. </p>
pub fn set_version_label(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_version_label(input);
self
}
/// <p>A new description for this version.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
/// <p>A new description for this version.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(input);
self
}
}
/// Fluent builder constructing a request to `UpdateConfigurationTemplate`.
///
/// <p>Updates the specified configuration template to have the specified properties or
/// configuration option values.</p>
/// <note>
/// <p>If a property (for example, <code>ApplicationName</code>) is not provided, its value
/// remains unchanged. To clear such properties, specify an empty string.</p>
/// </note>
/// <p>Related Topics</p>
/// <ul>
/// <li>
/// <p>
/// <a>DescribeConfigurationOptions</a>
/// </p>
/// </li>
/// </ul>
#[derive(std::fmt::Debug)]
pub struct UpdateConfigurationTemplate<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::update_configuration_template_input::Builder,
}
impl<C, M, R> UpdateConfigurationTemplate<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `UpdateConfigurationTemplate`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::UpdateConfigurationTemplateOutput,
aws_smithy_http::result::SdkError<crate::error::UpdateConfigurationTemplateError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::UpdateConfigurationTemplateInputOperationOutputAlias,
crate::output::UpdateConfigurationTemplateOutput,
crate::error::UpdateConfigurationTemplateError,
crate::input::UpdateConfigurationTemplateInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application associated with the configuration template to
/// update.</p>
/// <p> If no application is found with this name, <code>UpdateConfigurationTemplate</code>
/// returns an <code>InvalidParameterValue</code> error. </p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application associated with the configuration template to
/// update.</p>
/// <p> If no application is found with this name, <code>UpdateConfigurationTemplate</code>
/// returns an <code>InvalidParameterValue</code> error. </p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The name of the configuration template to update.</p>
/// <p> If no configuration template is found with this name,
/// <code>UpdateConfigurationTemplate</code> returns an <code>InvalidParameterValue</code>
/// error. </p>
pub fn template_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.template_name(inp);
self
}
/// <p>The name of the configuration template to update.</p>
/// <p> If no configuration template is found with this name,
/// <code>UpdateConfigurationTemplate</code> returns an <code>InvalidParameterValue</code>
/// error. </p>
pub fn set_template_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_template_name(input);
self
}
/// <p>A new description for the configuration.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
/// <p>A new description for the configuration.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(input);
self
}
/// Appends an item to `OptionSettings`.
///
/// To override the contents of this collection use [`set_option_settings`](Self::set_option_settings).
///
/// <p>A list of configuration option settings to update with the new specified option
/// value.</p>
pub fn option_settings(
mut self,
inp: impl Into<crate::model::ConfigurationOptionSetting>,
) -> Self {
self.inner = self.inner.option_settings(inp);
self
}
/// <p>A list of configuration option settings to update with the new specified option
/// value.</p>
pub fn set_option_settings(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ConfigurationOptionSetting>>,
) -> Self {
self.inner = self.inner.set_option_settings(input);
self
}
/// Appends an item to `OptionsToRemove`.
///
/// To override the contents of this collection use [`set_options_to_remove`](Self::set_options_to_remove).
///
/// <p>A list of configuration options to remove from the configuration set.</p>
/// <p> Constraint: You can remove only <code>UserDefined</code> configuration options.
/// </p>
pub fn options_to_remove(
mut self,
inp: impl Into<crate::model::OptionSpecification>,
) -> Self {
self.inner = self.inner.options_to_remove(inp);
self
}
/// <p>A list of configuration options to remove from the configuration set.</p>
/// <p> Constraint: You can remove only <code>UserDefined</code> configuration options.
/// </p>
pub fn set_options_to_remove(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::OptionSpecification>>,
) -> Self {
self.inner = self.inner.set_options_to_remove(input);
self
}
}
/// Fluent builder constructing a request to `UpdateEnvironment`.
///
/// <p>Updates the environment description, deploys a new application version, updates the
/// configuration settings to an entirely new configuration template, or updates select
/// configuration option values in the running environment.</p>
/// <p> Attempting to update both the release and configuration is not allowed and AWS Elastic
/// Beanstalk returns an <code>InvalidParameterCombination</code> error. </p>
/// <p> When updating the configuration settings to a new template or individual settings, a
/// draft configuration is created and <a>DescribeConfigurationSettings</a> for this
/// environment returns two setting descriptions with different <code>DeploymentStatus</code>
/// values. </p>
#[derive(std::fmt::Debug)]
pub struct UpdateEnvironment<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::update_environment_input::Builder,
}
impl<C, M, R> UpdateEnvironment<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `UpdateEnvironment`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::UpdateEnvironmentOutput,
aws_smithy_http::result::SdkError<crate::error::UpdateEnvironmentError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::UpdateEnvironmentInputOperationOutputAlias,
crate::output::UpdateEnvironmentOutput,
crate::error::UpdateEnvironmentError,
crate::input::UpdateEnvironmentInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application with which the environment is associated.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application with which the environment is associated.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The ID of the environment to update.</p>
/// <p>If no environment with this ID exists, AWS Elastic Beanstalk returns an
/// <code>InvalidParameterValue</code> error.</p>
/// <p>Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_id(inp);
self
}
/// <p>The ID of the environment to update.</p>
/// <p>If no environment with this ID exists, AWS Elastic Beanstalk returns an
/// <code>InvalidParameterValue</code> error.</p>
/// <p>Condition: You must specify either this or an EnvironmentName, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_id(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_id(input);
self
}
/// <p>The name of the environment to update. If no environment with this name exists, AWS
/// Elastic Beanstalk returns an <code>InvalidParameterValue</code> error. </p>
/// <p>Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment to update. If no environment with this name exists, AWS
/// Elastic Beanstalk returns an <code>InvalidParameterValue</code> error. </p>
/// <p>Condition: You must specify either this or an EnvironmentId, or both. If you do not
/// specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error.
/// </p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// <p>The name of the group to which the target environment belongs. Specify a group name
/// only if the environment's name is specified in an environment manifest and not with the
/// environment name or environment ID parameters. See <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-cfg-manifest.html">Environment Manifest
/// (env.yaml)</a> for details.</p>
pub fn group_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.group_name(inp);
self
}
/// <p>The name of the group to which the target environment belongs. Specify a group name
/// only if the environment's name is specified in an environment manifest and not with the
/// environment name or environment ID parameters. See <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-cfg-manifest.html">Environment Manifest
/// (env.yaml)</a> for details.</p>
pub fn set_group_name(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_group_name(input);
self
}
/// <p>If this parameter is specified, AWS Elastic Beanstalk updates the description of this
/// environment.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
/// <p>If this parameter is specified, AWS Elastic Beanstalk updates the description of this
/// environment.</p>
pub fn set_description(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(input);
self
}
/// <p>This specifies the tier to use to update the environment.</p>
/// <p>Condition: At this time, if you change the tier version, name, or type, AWS Elastic
/// Beanstalk returns <code>InvalidParameterValue</code> error. </p>
pub fn tier(mut self, inp: crate::model::EnvironmentTier) -> Self {
self.inner = self.inner.tier(inp);
self
}
/// <p>This specifies the tier to use to update the environment.</p>
/// <p>Condition: At this time, if you change the tier version, name, or type, AWS Elastic
/// Beanstalk returns <code>InvalidParameterValue</code> error. </p>
pub fn set_tier(
mut self,
input: std::option::Option<crate::model::EnvironmentTier>,
) -> Self {
self.inner = self.inner.set_tier(input);
self
}
/// <p>If this parameter is specified, AWS Elastic Beanstalk deploys the named application
/// version to the environment. If no such application version is found, returns an
/// <code>InvalidParameterValue</code> error. </p>
pub fn version_label(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.version_label(inp);
self
}
/// <p>If this parameter is specified, AWS Elastic Beanstalk deploys the named application
/// version to the environment. If no such application version is found, returns an
/// <code>InvalidParameterValue</code> error. </p>
pub fn set_version_label(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_version_label(input);
self
}
/// <p>If this parameter is specified, AWS Elastic Beanstalk deploys this configuration
/// template to the environment. If no such configuration template is found, AWS Elastic Beanstalk
/// returns an <code>InvalidParameterValue</code> error. </p>
pub fn template_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.template_name(inp);
self
}
/// <p>If this parameter is specified, AWS Elastic Beanstalk deploys this configuration
/// template to the environment. If no such configuration template is found, AWS Elastic Beanstalk
/// returns an <code>InvalidParameterValue</code> error. </p>
pub fn set_template_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_template_name(input);
self
}
/// <p>This specifies the platform version that the environment will run after the environment
/// is updated.</p>
pub fn solution_stack_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.solution_stack_name(inp);
self
}
/// <p>This specifies the platform version that the environment will run after the environment
/// is updated.</p>
pub fn set_solution_stack_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_solution_stack_name(input);
self
}
/// <p>The ARN of the platform, if used.</p>
pub fn platform_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.platform_arn(inp);
self
}
/// <p>The ARN of the platform, if used.</p>
pub fn set_platform_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_platform_arn(input);
self
}
/// Appends an item to `OptionSettings`.
///
/// To override the contents of this collection use [`set_option_settings`](Self::set_option_settings).
///
/// <p>If specified, AWS Elastic Beanstalk updates the configuration set associated with the
/// running environment and sets the specified configuration options to the requested
/// value.</p>
pub fn option_settings(
mut self,
inp: impl Into<crate::model::ConfigurationOptionSetting>,
) -> Self {
self.inner = self.inner.option_settings(inp);
self
}
/// <p>If specified, AWS Elastic Beanstalk updates the configuration set associated with the
/// running environment and sets the specified configuration options to the requested
/// value.</p>
pub fn set_option_settings(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ConfigurationOptionSetting>>,
) -> Self {
self.inner = self.inner.set_option_settings(input);
self
}
/// Appends an item to `OptionsToRemove`.
///
/// To override the contents of this collection use [`set_options_to_remove`](Self::set_options_to_remove).
///
/// <p>A list of custom user-defined configuration options to remove from the configuration
/// set for this environment.</p>
pub fn options_to_remove(
mut self,
inp: impl Into<crate::model::OptionSpecification>,
) -> Self {
self.inner = self.inner.options_to_remove(inp);
self
}
/// <p>A list of custom user-defined configuration options to remove from the configuration
/// set for this environment.</p>
pub fn set_options_to_remove(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::OptionSpecification>>,
) -> Self {
self.inner = self.inner.set_options_to_remove(input);
self
}
}
/// Fluent builder constructing a request to `UpdateTagsForResource`.
///
/// <p>Update the list of tags applied to an AWS Elastic Beanstalk resource. Two lists can be passed: <code>TagsToAdd</code>
/// for tags to add or update, and <code>TagsToRemove</code>.</p>
/// <p>Elastic Beanstalk supports tagging of all of its resources. For details about resource tagging, see
/// <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/applications-tagging-resources.html">Tagging Application
/// Resources</a>.</p>
/// <p>If you create a custom IAM user policy to control permission to this operation, specify
/// one of the following two virtual actions (or both) instead of the API operation name:</p>
/// <dl>
/// <dt>elasticbeanstalk:AddTags</dt>
/// <dd>
/// <p>Controls permission to call <code>UpdateTagsForResource</code> and pass a list of tags to add in the <code>TagsToAdd</code>
/// parameter.</p>
/// </dd>
/// <dt>elasticbeanstalk:RemoveTags</dt>
/// <dd>
/// <p>Controls permission to call <code>UpdateTagsForResource</code> and pass a list of tag keys to remove in the <code>TagsToRemove</code>
/// parameter.</p>
/// </dd>
/// </dl>
/// <p>For details about creating a custom user policy, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.iam.managed-policies.html#AWSHowTo.iam.policies">Creating a Custom User Policy</a>.</p>
#[derive(std::fmt::Debug)]
pub struct UpdateTagsForResource<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::update_tags_for_resource_input::Builder,
}
impl<C, M, R> UpdateTagsForResource<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `UpdateTagsForResource`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::UpdateTagsForResourceOutput,
aws_smithy_http::result::SdkError<crate::error::UpdateTagsForResourceError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::UpdateTagsForResourceInputOperationOutputAlias,
crate::output::UpdateTagsForResourceOutput,
crate::error::UpdateTagsForResourceError,
crate::input::UpdateTagsForResourceInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the resouce to be updated.</p>
/// <p>Must be the ARN of an Elastic Beanstalk resource.</p>
pub fn resource_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.resource_arn(inp);
self
}
/// <p>The Amazon Resource Name (ARN) of the resouce to be updated.</p>
/// <p>Must be the ARN of an Elastic Beanstalk resource.</p>
pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_resource_arn(input);
self
}
/// Appends an item to `TagsToAdd`.
///
/// To override the contents of this collection use [`set_tags_to_add`](Self::set_tags_to_add).
///
/// <p>A list of tags to add or update. If a key of an existing tag is added, the tag's value is
/// updated.</p>
/// <p>Specify at least one of these parameters: <code>TagsToAdd</code>,
/// <code>TagsToRemove</code>.</p>
pub fn tags_to_add(mut self, inp: impl Into<crate::model::Tag>) -> Self {
self.inner = self.inner.tags_to_add(inp);
self
}
/// <p>A list of tags to add or update. If a key of an existing tag is added, the tag's value is
/// updated.</p>
/// <p>Specify at least one of these parameters: <code>TagsToAdd</code>,
/// <code>TagsToRemove</code>.</p>
pub fn set_tags_to_add(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.inner = self.inner.set_tags_to_add(input);
self
}
/// Appends an item to `TagsToRemove`.
///
/// To override the contents of this collection use [`set_tags_to_remove`](Self::set_tags_to_remove).
///
/// <p>A list of tag keys to remove. If a tag key doesn't exist, it is silently ignored.</p>
/// <p>Specify at least one of these parameters: <code>TagsToAdd</code>,
/// <code>TagsToRemove</code>.</p>
pub fn tags_to_remove(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.tags_to_remove(inp);
self
}
/// <p>A list of tag keys to remove. If a tag key doesn't exist, it is silently ignored.</p>
/// <p>Specify at least one of these parameters: <code>TagsToAdd</code>,
/// <code>TagsToRemove</code>.</p>
pub fn set_tags_to_remove(
mut self,
input: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_tags_to_remove(input);
self
}
}
/// Fluent builder constructing a request to `ValidateConfigurationSettings`.
///
/// <p>Takes a set of configuration settings and either a configuration template or
/// environment, and determines whether those values are valid.</p>
/// <p>This action returns a list of messages indicating any errors or warnings associated
/// with the selection of option values.</p>
#[derive(std::fmt::Debug)]
pub struct ValidateConfigurationSettings<
C = aws_smithy_client::erase::DynConnector,
M = aws_hyper::AwsMiddleware,
R = aws_smithy_client::retry::Standard,
> {
handle: std::sync::Arc<super::Handle<C, M, R>>,
inner: crate::input::validate_configuration_settings_input::Builder,
}
impl<C, M, R> ValidateConfigurationSettings<C, M, R>
where
C: aws_smithy_client::bounds::SmithyConnector,
M: aws_smithy_client::bounds::SmithyMiddleware<C>,
R: aws_smithy_client::retry::NewRequestPolicy,
{
/// Creates a new `ValidateConfigurationSettings`.
pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
/// Sends the request and returns the response.
///
/// If an error occurs, an `SdkError` will be returned with additional details that
/// can be matched against.
///
/// By default, any retryable failures will be retried twice. Retry behavior
/// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be
/// set when configuring the client.
pub async fn send(
self,
) -> std::result::Result<
crate::output::ValidateConfigurationSettingsOutput,
aws_smithy_http::result::SdkError<crate::error::ValidateConfigurationSettingsError>,
>
where
R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy<
crate::input::ValidateConfigurationSettingsInputOperationOutputAlias,
crate::output::ValidateConfigurationSettingsOutput,
crate::error::ValidateConfigurationSettingsError,
crate::input::ValidateConfigurationSettingsInputOperationRetryAlias,
>,
{
let input = self.inner.build().map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
let op = input
.make_operation(&self.handle.conf)
.await
.map_err(|err| {
aws_smithy_http::result::SdkError::ConstructionFailure(err.into())
})?;
self.handle.client.call(op).await
}
/// <p>The name of the application that the configuration template or environment belongs
/// to.</p>
pub fn application_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.application_name(inp);
self
}
/// <p>The name of the application that the configuration template or environment belongs
/// to.</p>
pub fn set_application_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_application_name(input);
self
}
/// <p>The name of the configuration template to validate the settings against.</p>
/// <p>Condition: You cannot specify both this and an environment name.</p>
pub fn template_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.template_name(inp);
self
}
/// <p>The name of the configuration template to validate the settings against.</p>
/// <p>Condition: You cannot specify both this and an environment name.</p>
pub fn set_template_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_template_name(input);
self
}
/// <p>The name of the environment to validate the settings against.</p>
/// <p>Condition: You cannot specify both this and a configuration template name.</p>
pub fn environment_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.environment_name(inp);
self
}
/// <p>The name of the environment to validate the settings against.</p>
/// <p>Condition: You cannot specify both this and a configuration template name.</p>
pub fn set_environment_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_environment_name(input);
self
}
/// Appends an item to `OptionSettings`.
///
/// To override the contents of this collection use [`set_option_settings`](Self::set_option_settings).
///
/// <p>A list of the options and desired values to evaluate.</p>
pub fn option_settings(
mut self,
inp: impl Into<crate::model::ConfigurationOptionSetting>,
) -> Self {
self.inner = self.inner.option_settings(inp);
self
}
/// <p>A list of the options and desired values to evaluate.</p>
pub fn set_option_settings(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ConfigurationOptionSetting>>,
) -> Self {
self.inner = self.inner.set_option_settings(input);
self
}
}
}
impl<C> Client<C, aws_hyper::AwsMiddleware, aws_smithy_client::retry::Standard> {
/// Creates a client with the given service config and connector override.
pub fn from_conf_conn(conf: crate::Config, conn: C) -> Self {
let retry_config = conf.retry_config.as_ref().cloned().unwrap_or_default();
let client = aws_hyper::Client::new(conn).with_retry_config(retry_config.into());
Self {
handle: std::sync::Arc::new(Handle { client, conf }),
}
}
}
impl
Client<
aws_smithy_client::erase::DynConnector,
aws_hyper::AwsMiddleware,
aws_smithy_client::retry::Standard,
>
{
/// Creates a new client from a shared config.
#[cfg(any(feature = "rustls", feature = "native-tls"))]
pub fn new(config: &aws_types::config::Config) -> Self {
Self::from_conf(config.into())
}
/// Creates a new client from the service [`Config`](crate::Config).
#[cfg(any(feature = "rustls", feature = "native-tls"))]
pub fn from_conf(conf: crate::Config) -> Self {
let retry_config = conf.retry_config.as_ref().cloned().unwrap_or_default();
let client = aws_hyper::Client::https().with_retry_config(retry_config.into());
Self {
handle: std::sync::Arc::new(Handle { client, conf }),
}
}
}
| 46.937048 | 251 | 0.604024 |
79f2b72b577cf0e3f43ea6d2a4fbb28036f77ac5 | 2,332 | #![no_std]
extern crate task;
#[macro_use] extern crate terminal_print;
#[macro_use] extern crate alloc;
// #[macro_use] extern crate log;
extern crate fs_node;
extern crate getopts;
extern crate path;
use alloc::vec::Vec;
use alloc::string::String;
use alloc::string::ToString;
use fs_node::{FileOrDir, DirRef};
use getopts::Options;
use path::Path;
use alloc::sync::Arc;
pub fn main(args: Vec<String>) -> isize {
let mut opts = Options::new();
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args) {
Ok(m) => m,
Err(_f) => {
println!("{}", _f);
print_usage(opts);
return -1;
}
};
if matches.opt_present("h") {
print_usage(opts);
return 0;
}
let taskref = match task::get_my_current_task() {
Some(t) => t,
None => {
println!("failed to get current task");
return -1;
}
};
let curr_wd = Arc::clone(&taskref.get_env().lock().working_dir);
// print children of working directory if no child is specified
if matches.free.is_empty() {
print_children(&curr_wd);
return 0;
}
let path = Path::new(matches.free[0].to_string());
// navigate to the path specified by first argument
match path.get(&curr_wd) {
Some(FileOrDir::Dir(dir)) => {
print_children(&dir);
return 0;
}
Some(FileOrDir::File(file)) => {
println!("'{}' is not a directory; `ls` currently only supports listing directory contents.", file.lock().get_name());
return -1;
}
_ => {
println!("Couldn't find path: {}", path);
return -1;
}
};
}
fn print_children(dir: &DirRef) {
let mut child_string = String::new();
let mut child_list = dir.lock().list();
child_list.reverse();
for child in child_list.iter() {
child_string.push_str(&format!("{}\n", child));
}
println!("{}", child_string);
}
fn print_usage(opts: Options) {
println!("{}", opts.usage(USAGE));
}
const USAGE: &'static str = "Usage: ls [DIR | FILE]
List the contents of the given directory or info about the given file.
If no arguments are provided, it lists the contents of the current directory."; | 26.202247 | 130 | 0.580617 |
386bc3bd15478700484e419e753ce25fe335f822 | 8,207 | use crate::model::{OnnxOpRegister, ParsingContext};
use crate::pb::NodeProto;
use tract_core::internal::*;
pub fn register_all_ops(reg: &mut OnnxOpRegister) {
reg.insert("QuantizeLinear", quantize_linear);
reg.insert("DequantizeLinear", dequantize_linear);
}
fn quantize_linear(
_ctx: &ParsingContext,
node: &NodeProto,
) -> TractResult<(Box<dyn InferenceOp>, Vec<String>)> {
let op = QuantizeLinear::new(Some(2).filter(|_| node.get_input().len() == 3));
Ok((Box::new(op), vec![]))
}
#[derive(Debug, Clone, new, Default)]
pub struct QuantizeLinear {
optional_zero_point_input: Option<usize>,
}
impl Op for QuantizeLinear {
fn name(&self) -> Cow<str> {
"onnx.QuantizeLinear".into()
}
not_a_typed_op!();
}
impl StatelessOp for QuantizeLinear {
fn eval(&self, mut inputs: TVec<Arc<Tensor>>) -> TractResult<TVec<Arc<Tensor>>> {
let (x, y_scale, y_zero_point) = if self.optional_zero_point_input.is_some() {
args_3!(inputs)
} else {
let (x, y_scale) = args_2!(inputs);
(x, y_scale, rctensor0(0u8))
};
let y_scale = y_scale.as_slice::<f32>()?[0].recip();
let x = x.cast_to::<f32>()?;
let tensor = if y_zero_point.datum_type() == u8::datum_type() {
let y_zero_point = y_zero_point.as_slice::<u8>()?[0];
x.to_array_view::<f32>()?
.map(|x| ((x * y_scale).round() as i32 + y_zero_point as i32).max(0).min(255) as u8)
.into_arc_tensor()
} else {
let y_zero_point = y_zero_point.as_slice::<i8>()?[0];
x.to_array_view::<f32>()?
.map(|x| {
((x * y_scale).round() as i32 + y_zero_point as i32).max(-128).min(127) as i8
})
.into_arc_tensor()
};
Ok(tvec!(tensor))
}
}
impl InferenceRulesOp for QuantizeLinear {
fn rules<'r, 'p: 'r, 's: 'r>(
&'s self,
s: &mut Solver<'r>,
inputs: &'p [TensorProxy],
outputs: &'p [TensorProxy],
) -> TractResult<()> {
check_input_arity(&inputs, 2 + self.optional_zero_point_input.is_some() as usize)?;
check_output_arity(&outputs, 1)?;
// s.equals(&inputs[1].rank, 0)?; broken in Onnx test suite
s.equals(&inputs[1].datum_type, f32::datum_type())?;
if self.optional_zero_point_input.is_some() {
s.equals(&outputs[0].datum_type, &inputs[2].datum_type)?;
// s.equals(&inputs[2].rank, 0)?; // broken in Onnx test suite
} else {
s.equals(&outputs[0].datum_type, u8::datum_type())?;
}
s.equals(&inputs[0].shape, &outputs[0].shape)?;
Ok(())
}
fn to_typed(
&self,
_source: &InferenceModel,
node: &InferenceNode,
target: &mut TypedModel,
mapping: &HashMap<OutletId, OutletId>,
) -> TractResult<TVec<OutletId>> {
let scale = target
.outlet_fact(mapping[&node.inputs[1]])?
.konst
.as_ref()
.ok_or("y_scale must be a const")?
.as_slice::<f32>()?[0]
.recip();
let zero_point = if self.optional_zero_point_input.is_some() {
target
.outlet_fact(mapping[&node.inputs[2]])?
.konst
.as_ref()
.ok_or("y_zero_point must be a const")?
.clone()
} else {
rctensor0(0u8)
};
let op: Box<dyn TypedOp> = if zero_point.datum_type() == u8::datum_type() {
Box::new(quantize_linear_u8(scale, zero_point.as_slice::<u8>()?[0]))
} else {
Box::new(quantize_linear_i8(scale, zero_point.as_slice::<i8>()?[0]))
};
target.wire_node(&*node.name, op, &[mapping[&node.inputs[0]]])
}
inference_op_as_op!();
}
element_wise_oop!(quantize_linear_u8, QuantizeLinearU8 {scale: f32, zero_point: u8},
[f32,i32] => u8 |op, xs, ys| {
xs.iter().zip(ys.iter_mut()).for_each(|(x,y)|
*y = (((*x as f32 * op.scale).round() as i32) + op.zero_point as i32) as u8
);
Ok(())
};
prefix: "onnx."
);
element_wise_oop!(quantize_linear_i8, QuantizeLinearI8 {scale: f32, zero_point: i8},
[f32,i32] => i8 |op, xs, ys| {
xs.iter().zip(ys.iter_mut()).for_each(|(x,y)|
*y = (((*x as f32 * op.scale).round() as i32) + op.zero_point as i32) as i8
);
Ok(())
};
prefix: "onnx."
);
fn dequantize_linear(
_ctx: &ParsingContext,
node: &NodeProto,
) -> TractResult<(Box<dyn InferenceOp>, Vec<String>)> {
let op = DequantizeLinear::new(Some(2).filter(|_| node.get_input().len() == 3));
Ok((Box::new(op), vec![]))
}
#[derive(Debug, Clone, new, Default)]
pub struct DequantizeLinear {
optional_zero_point_input: Option<usize>,
}
impl Op for DequantizeLinear {
fn name(&self) -> Cow<str> {
"onnx.DequantizeLinear".into()
}
not_a_typed_op!();
}
impl StatelessOp for DequantizeLinear {
fn eval(&self, mut inputs: TVec<Arc<Tensor>>) -> TractResult<TVec<Arc<Tensor>>> {
let (x, y_scale, x_zero_point) = if self.optional_zero_point_input.is_some() {
args_3!(inputs)
} else {
let (x, y_scale) = args_2!(inputs);
(x, y_scale, rctensor0(0u8))
};
let x_scale = y_scale.as_slice::<f32>()?[0];
let x_zero_point = x_zero_point.cast_to::<i32>()?.as_slice::<i32>()?[0];
let x = x.cast_to::<i32>()?;
let tensor = x
.to_array_view::<i32>()?
.map(|&x| ((x - x_zero_point) as f32) * x_scale)
.into_arc_tensor();
Ok(tvec!(tensor))
}
}
impl InferenceRulesOp for DequantizeLinear {
fn rules<'r, 'p: 'r, 's: 'r>(
&'s self,
s: &mut Solver<'r>,
inputs: &'p [TensorProxy],
outputs: &'p [TensorProxy],
) -> TractResult<()> {
check_input_arity(&inputs, 2 + self.optional_zero_point_input.is_some() as usize)?;
check_output_arity(&outputs, 1)?;
// s.equals(&inputs[1].rank, 0)?; broken in Onnx test suite
s.equals(&inputs[1].datum_type, f32::datum_type())?;
s.equals(&outputs[0].datum_type, f32::datum_type())?;
if self.optional_zero_point_input.is_some() {
s.equals(&inputs[0].datum_type, &inputs[2].datum_type)?;
// s.equals(&inputs[2].rank, 0)?; // broken in Onnx test suite
}
s.equals(&inputs[0].shape, &outputs[0].shape)?;
Ok(())
}
fn to_typed(
&self,
_source: &InferenceModel,
node: &InferenceNode,
target: &mut TypedModel,
mapping: &HashMap<OutletId, OutletId>,
) -> TractResult<TVec<OutletId>> {
let scale = target
.outlet_fact(mapping[&node.inputs[1]])?
.konst
.as_ref()
.ok_or("y_scale must be a const")?
.as_slice::<f32>()?[0];
let zero_point = if self.optional_zero_point_input.is_some() {
target
.outlet_fact(mapping[&node.inputs[2]])?
.konst
.as_ref()
.ok_or("y_zero_point must be a const")?
.clone()
} else {
rctensor0(0u8)
};
let op: Box<dyn TypedOp> = if zero_point.datum_type() == u8::datum_type() {
Box::new(dequantize_linear_f32(scale, zero_point.as_slice::<u8>()?[0] as i32))
} else if zero_point.datum_type() == i8::datum_type() {
Box::new(dequantize_linear_f32(scale, zero_point.as_slice::<i8>()?[0] as i32))
} else {
Box::new(dequantize_linear_f32(scale, zero_point.as_slice::<i32>()?[0] as i32))
};
target.wire_node(&*node.name, op, &[mapping[&node.inputs[0]]])
}
inference_op_as_op!();
}
element_wise_oop!(dequantize_linear_f32, DequantizeLinearF32 {scale: f32, zero_point: i32},
[i8,i32,u8] => f32 |op, xs, ys| {
xs.iter().zip(ys.iter_mut()).for_each(|(x,y)|
*y = (*x as i32 - op.zero_point) as f32 * op.scale
);
Ok(())
};
prefix: "onnx."
);
| 34.338912 | 100 | 0.550018 |
767537027e76f92ad2a9066ac6a1b9c63e1cb74d | 5,124 | #![crate_name = "msp432"]
#![crate_type = "rlib"]
#![feature(asm, const_fn)]
#![no_std]
use cortexm4::{
generic_isr, hard_fault_handler, svc_handler, systick_handler, unhandled_interrupt,
};
pub mod adc;
pub mod chip;
pub mod cs;
pub mod dma;
pub mod flctl;
pub mod gpio;
pub mod nvic;
pub mod pcm;
pub mod ref_module;
pub mod sysctl;
pub mod timer;
pub mod uart;
pub mod usci;
pub mod wdt;
extern "C" {
// _estack is not really a function, but it makes the types work
// You should never actually invoke it!!
fn _estack();
// Defined by platform
fn reset_handler();
}
#[cfg_attr(
all(target_arch = "arm", target_os = "none"),
link_section = ".vectors"
)]
// used Ensures that the symbol is kept until the final binary
#[cfg_attr(all(target_arch = "arm", target_os = "none"), used)]
pub static BASE_VECTORS: [unsafe extern "C" fn(); 16] = [
_estack,
reset_handler,
unhandled_interrupt, // NMI
hard_fault_handler, // Hard Fault
unhandled_interrupt, // MemManage
unhandled_interrupt, // BusFault
unhandled_interrupt, // UsageFault
unhandled_interrupt,
unhandled_interrupt,
unhandled_interrupt,
unhandled_interrupt,
svc_handler, // SVC
unhandled_interrupt, // DebugMon
unhandled_interrupt,
unhandled_interrupt, // PendSV
systick_handler, // SysTick
];
#[cfg_attr(all(target_arch = "arm", target_os = "none"), link_section = ".irqs")]
// used Ensures that the symbol is kept until the final binary
#[cfg_attr(all(target_arch = "arm", target_os = "none"), used)]
pub static IRQS: [unsafe extern "C" fn(); 64] = [
generic_isr, // Power Supply System (PSS) (0)
generic_isr, // Clock System (CS) (1)
generic_isr, // Power Control Manager (PCM) (2)
generic_isr, // Watchdog Timer A (WDT_A) (3)
generic_isr, // FPU_INT, Combined interrupt from flags in FPSCR (4)
generic_isr, // FLash Controller (FLCTL) (5)
generic_isr, // Comparator E0 (6)
generic_isr, // Comparator E1 (7)
generic_isr, // Timer A0 TA0CCTL0.CCIFG (8)
generic_isr, // Timer A0 TA0CCTLx.CCIFG (x = 1 to 4), TA0CTL.TAIFG (9)
generic_isr, // Timer A1 TA1CCTL0.CCIFG (10)
generic_isr, // Timer A1 TA1CCTLx.CCIFG (x = 1 to 4), TA1CTL.TAIFG (11)
generic_isr, // Timer A2 TA2CCTL0.CCIFG (12)
generic_isr, // Timer A2 TA2CCTLx.CCIFG (x = 1 to 4), TA2CTL.TAIFG (13)
generic_isr, // Timer A3 TA3CCTL0.CCIFG (13)
generic_isr, // Timer A3 TA3CCTLx.CCIFG (x = 1 to 4), TA3CTL.TAIFG (15)
generic_isr, // eUSCI A0 (16)
generic_isr, // eUSCI A1 (17)
generic_isr, // eUSCI A2 (18)
generic_isr, // eUSCI A3 (19)
generic_isr, // eUSCI B0 (20)
generic_isr, // eUSCI B1 (21)
generic_isr, // eUSCI B2 (22)
generic_isr, // eUSCI B3 (23)
generic_isr, // Precision ADC (24)
generic_isr, // Timer32 INT1 (25)
generic_isr, // Timer32 INT2 (26)
generic_isr, // Timer32 combined interrupt (27)
generic_isr, // AES256 (28)
generic_isr, // RTC_C (29)
generic_isr, // DMA error (30)
generic_isr, // DMA INT3 (31)
generic_isr, // DMA INT2 (32)
generic_isr, // DMA INT1 (33)
generic_isr, // DMA INT0 (34)
generic_isr, // IO Port 1 (35)
generic_isr, // IO Port 2 (36)
generic_isr, // IO Port 3 (37)
generic_isr, // IO Port 4 (38)
generic_isr, // IO Port 5 (39)
generic_isr, // IO Port 6 (40)
unhandled_interrupt, // Reserved (41)
unhandled_interrupt, // Reserved (42)
unhandled_interrupt, // Reserved (43)
unhandled_interrupt, // Reserved (44)
unhandled_interrupt, // Reserved (45)
unhandled_interrupt, // Reserved (46)
unhandled_interrupt, // Reserved (47)
unhandled_interrupt, // Reserved (48)
unhandled_interrupt, // Reserved (49)
unhandled_interrupt, // Reserved (50)
unhandled_interrupt, // Reserved (51)
unhandled_interrupt, // Reserved (52)
unhandled_interrupt, // Reserved (53)
unhandled_interrupt, // Reserved (54)
unhandled_interrupt, // Reserved (55)
unhandled_interrupt, // Reserved (56)
unhandled_interrupt, // Reserved (57)
unhandled_interrupt, // Reserved (58)
unhandled_interrupt, // Reserved (59)
unhandled_interrupt, // Reserved (60)
unhandled_interrupt, // Reserved (61)
unhandled_interrupt, // Reserved (62)
unhandled_interrupt, // Reserved (63)
];
extern "C" {
static mut _szero: usize;
static mut _ezero: usize;
static mut _etext: usize;
static mut _srelocate: usize;
static mut _erelocate: usize;
}
pub unsafe fn init() {
tock_rt0::init_data(&mut _etext, &mut _srelocate, &mut _erelocate);
tock_rt0::zero_bss(&mut _szero, &mut _ezero);
cortexm4::nvic::disable_all();
cortexm4::nvic::clear_all_pending();
cortexm4::nvic::enable_all();
}
| 35.337931 | 87 | 0.619048 |
bfc7e838dc2cfae1eb6f1b8905c6718c8e321a7b | 77 | pub mod alert;
#[cfg(feature = "engine")]
pub use alert::{Alert, AlertOpts};
| 19.25 | 34 | 0.675325 |
f5deb4b925c79881f3c8f3a67eb26ee31f87583a | 22,805 | use command_executor::{Command, CommandContext, CommandMetadata, CommandParams, CommandGroup, CommandGroupMetadata};
use commands::*;
use utils::table::print_list_table;
use libindy::ErrorCode;
use libindy::did::Did;
use libindy::ledger::Ledger;
use std::fs::File;
use serde_json::Value as JSONValue;
use serde_json::Map as JSONMap;
use commands::ledger::{handle_transaction_error, handle_transaction_response, Response};
pub mod group {
use super::*;
command_group!(CommandGroupMetadata::new("did", "Identity management commands"));
}
pub mod new_command {
use super::*;
command!(CommandMetadata::build("new", "Create new DID")
.add_optional_param("did", "Known DID for new wallet instance")
.add_optional_deferred_param("seed", "Seed for creating DID key-pair")
.add_optional_param("metadata", "DID metadata")
.add_example("did new")
.add_example("did new did=VsKV7grR1BUE29mG2Fm2kX")
.add_example("did new did=VsKV7grR1BUE29mG2Fm2kX seed=00000000000000000000000000000My1")
.add_example("did new seed=00000000000000000000000000000My1 metadata=did_metadata")
.finalize()
);
fn execute(ctx: &CommandContext, params: &CommandParams) -> Result<(), ()> {
trace!("execute >> ctx {:?} params {:?}", ctx, params);
let wallet_handle = ensure_opened_wallet_handle(&ctx)?;
let did = get_opt_str_param("did", params).map_err(error_err!())?;
let seed = get_opt_str_param("seed", params).map_err(error_err!())?;
let metadata = get_opt_empty_str_param("metadata", params).map_err(error_err!())?;
let config = {
let mut json = JSONMap::new();
update_json_map_opt_key!(json, "did", did);
update_json_map_opt_key!(json, "seed", seed);
JSONValue::from(json).to_string()
};
trace!(r#"Did::new try: config {:?}"#, config);
let res =
Did::new(wallet_handle, config.as_str())
.and_then(|(did, vk)|
match Did::abbreviate_verkey(&did, &vk) {
Ok(vk) => Ok((did, vk)),
Err(err) => Err(err)
});
trace!(r#"Did::new return: {:?}"#, res);
let res = match res {
Ok((did, vk)) => {
println_succ!("Did \"{}\" has been created with \"{}\" verkey", did, vk);
Ok(did)
}
Err(ErrorCode::DidAlreadyExistsError) => Err(println_err!("Did already exists: {:?}", did.unwrap_or(""))),
Err(ErrorCode::UnknownCryptoTypeError) => Err(println_err!("Unknown crypto type")),
Err(ErrorCode::CommonInvalidStructure) => Err(println_err!("Invalid format of command params. Please check format of posted JSONs, Keys, DIDs and etc...")),
Err(err) => Err(println_err!("Indy SDK error occurred {:?}", err)),
};
let res = if let Some(metadata) = metadata {
res.and_then(|did| {
let res = Did::set_metadata(wallet_handle, &did, metadata);
match res {
Ok(()) => Ok(println_succ!("Metadata has been saved for DID \"{}\"", did)),
Err(ErrorCode::CommonInvalidStructure) => Err(println_err!("Invalid format of command params. Please check format of posted JSONs, Keys, DIDs and etc...")),
Err(err) => Err(println_err!("Indy SDK error occurred {:?}", err)),
}
})
} else {
res.map(|_| ())
};
trace!("execute << {:?}", res);
res
}
}
pub mod import_command {
use super::*;
use std::io::Read;
command!(CommandMetadata::build("import", "Import DIDs entities from file to the current wallet.
File format:
{
\"version\": 1,
\"dids\": [{
\"did\": \"did\",
\"seed\": \"UTF-8 or base64 seed string\"
}]
}")
.add_main_param("file", "Path to file with DIDs")
.finalize()
);
fn execute(ctx: &CommandContext, params: &CommandParams) -> Result<(), ()> {
trace!("execute >> ctx {:?} params {:?}", ctx, params);
let wallet_handle = ensure_opened_wallet_handle(&ctx)?;
let path = get_str_param("file", params).map_err(error_err!())?;
let mut buf = String::new();
let res = File::open(path)
.and_then(|mut file| {
file.read_to_string(&mut buf)
})
.map_err(|err| format!("Error during reading file {}", err))
.and_then(|_| {
serde_json::from_str::<JSONValue>(&buf)
.map_err(|err| format!("Can't parse JSON {:?}", err))
.and_then(|json: JSONValue| -> Result<JSONValue, String> {
let is_correct_version = json["version"].as_i64().map(|ver| (ver == 1)).unwrap_or(false);
if is_correct_version { Ok(json) } else { Err("Invalid or missed version".to_owned()) }
})
.and_then(|json| {
json["dids"].as_array().map(Clone::clone).ok_or("missed DIDs".to_owned())
})
.and_then(|dids| {
for did in dids {
match Did::new(wallet_handle, &did.to_string())
.and_then(|(did, vk)|
match Did::abbreviate_verkey(&did, &vk) {
Ok(vk) => Ok((did, vk)),
Err(err) => Err(err)
}) {
Ok((did, vk)) =>
println_succ!("Did \"{}\" has been created with \"{}\" verkey", did, vk),
Err(err) =>
println_warn!("Indy SDK error occured {:?} while importing DID {}", err, did)
}
}
Ok(())
})
});
let res = if let Err(err) = res {
Err(println_err!("{}", err))
} else {
Ok(println_succ!("DIDs import finished"))
};
trace!("execute << {:?}", res);
res
}
}
pub mod use_command {
use super::*;
command!(CommandMetadata::build("use", "Use DID")
.add_main_param("did", "Did stored in wallet")
.add_example("did use VsKV7grR1BUE29mG2Fm2kX")
.finalize());
fn execute(ctx: &CommandContext, params: &CommandParams) -> Result<(), ()> {
trace!("execute >> ctx {:?}, params {:?}", ctx, params);
let did = get_str_param("did", params).map_err(error_err!())?;
let wallet_handle = ensure_opened_wallet_handle(ctx)?;
let res = match Did::get_did_with_meta(wallet_handle, did) {
Ok(_) => {
set_active_did(ctx, Some(did.to_owned()));
Ok(println_succ!("Did \"{}\" has been set as active", did))
}
Err(ErrorCode::CommonInvalidStructure) => Err(println_err!("Invalid DID format")),
Err(ErrorCode::WalletItemNotFound) => Err(println_err!("Requested DID not found")),
Err(err) => Err(println_err!("Indy SDK error occurred {:?}", err))
};
trace!("execute << {:?}", res);
res
}
}
pub mod rotate_key_command {
use super::*;
command!(CommandMetadata::build("rotate-key", "Rotate keys for active did")
.add_optional_deferred_param("seed", "If not provide then a random one will be created")
.add_example("did rotate-key")
.add_example("did rotate-key seed=00000000000000000000000000000My2")
.finalize());
fn execute(ctx: &CommandContext, params: &CommandParams) -> Result<(), ()> {
trace!("execute >> ctx {:?} params {:?}", ctx, params);
let seed = get_opt_str_param("seed", params).map_err(error_err!())?;
let did = ensure_active_did(&ctx)?;
let (pool_handle, pool_name) = ensure_connected_pool(&ctx)?;
let (wallet_handle, wallet_name) = ensure_opened_wallet(&ctx)?;
let identity_json = {
let mut json = JSONMap::new();
update_json_map_opt_key!(json, "seed", seed);
JSONValue::from(json).to_string()
};
let new_verkey = match Did::replace_keys_start(wallet_handle, &did, &identity_json) {
Ok(request) => Ok(request),
Err(ErrorCode::WalletItemNotFound) => Err(println_err!("Active DID: \"{}\" not found", did)),
Err(_) => return Err(println_err!("Invalid format of command params. Please check format of posted JSONs, Keys, DIDs and etc...")),
}?;
let nym_res = Ledger::build_nym_request(&did, &did, Some(&new_verkey), None, None)
.and_then(|request| Ledger::sign_and_submit_request(pool_handle, wallet_handle, &did, &request));
match nym_res {
Ok(response) => {
let response: Response<serde_json::Value> = serde_json::from_str::<Response<serde_json::Value>>(&response)
.map_err(|err| println_err!("Invalid data has been received: {:?}", err))?;
handle_transaction_response(response)?;
}
Err(err) => {
handle_transaction_error(err, Some(&did), Some(&pool_name), Some(&wallet_name));
}
};
let res =
match Did::replace_keys_apply(wallet_handle, &did)
.and_then(|_| Did::abbreviate_verkey(&did, &new_verkey)) {
Ok(vk) => Ok(println_succ!("Verkey for did \"{}\" has been updated. New verkey: \"{}\"", did, vk)),
Err(ErrorCode::WalletItemNotFound) => Err(println_err!("Active DID: \"{}\" not found", did)),
Err(_) => return Err(println_err!("Invalid format of command params. Please check format of posted JSONs, Keys, DIDs and etc...")),
};
trace!("execute << {:?}", res);
res
}
}
pub mod list_command {
use super::*;
command!(CommandMetadata::build("list", "List my DIDs stored in the opened wallet.")
.finalize());
fn execute(ctx: &CommandContext, params: &CommandParams) -> Result<(), ()> {
trace!("execute >> ctx {:?} params {:?}", ctx, params);
let wallet_handle = ensure_opened_wallet_handle(&ctx)?;
let res = match Did::list_dids_with_meta(wallet_handle) {
Ok(dids) => {
let mut dids: Vec<serde_json::Value> = serde_json::from_str(&dids)
.map_err(|_| println_err!("Wrong data has been received"))?;
for did_info in dids.iter_mut() {
match Did::abbreviate_verkey(did_info["did"].as_str().unwrap_or(""),
did_info["verkey"].as_str().unwrap_or("")) {
Ok(vk) => did_info["verkey"] = serde_json::Value::String(vk),
Err(err) => return Err(println_err!("Indy SDK error occurred {:?}", err))
}
}
print_list_table(&dids,
&vec![("did", "Did"),
("verkey", "Verkey"),
("metadata", "Metadata")],
"There are no dids");
if let Some(cur_did) = get_active_did(ctx) {
println_succ!("Current did \"{}\"", cur_did);
}
Ok(())
}
Err(err) => Err(println_err!("Indy SDK error occurred {:?}", err)),
};
trace!("execute << {:?}", res);
res
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use utils::test::TestUtils;
use libindy::did::Did;
use commands::wallet::tests::{create_and_open_wallet, close_and_delete_wallet};
use commands::pool::tests::{create_and_connect_pool, disconnect_and_delete_pool};
use commands::ledger::tests::send_nym;
pub const SEED_TRUSTEE: &'static str = "000000000000000000000000Trustee1";
pub const DID_TRUSTEE: &'static str = "V4SGRU86Z58d6TV7PBUe6f";
pub const VERKEY_TRUSTEE: &'static str = "GJ1SzoWzavQYfNL9XkaJdrQejfztN4XqdsiV4ct3LXKL";
pub const SEED_MY1: &'static str = "00000000000000000000000000000My1";
pub const DID_MY1: &'static str = "VsKV7grR1BUE29mG2Fm2kX";
pub const VERKEY_MY1: &'static str = "GjZWsBLgZCR18aL468JAT7w9CZRiBnpxUPPgyQxh4voa";
pub const SEED_MY2: &'static str = "00000000000000000000000000000My2";
pub const DID_MY2: &'static str = "2PRyVHmkXQnQzJQKxHxnXC";
pub const VERKEY_MY2: &'static str = "kqa2HyagzfMAq42H5f9u3UMwnSBPQx2QfrSyXbUPxMn";
pub const SEED_MY3: &'static str = "00000000000000000000000000000My3";
pub const DID_MY3: &'static str = "5Uu7YveFSGcT3dSzjpvPab";
pub const VERKEY_MY3: &'static str = "3SeuRm3uYuQDYmHeuMLu1xNHozNTtzS3kbZRFMMCWrX4";
mod did_new {
use super::*;
#[test]
pub fn new_works() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
let wallet_handle = create_and_open_wallet(&ctx);
{
let cmd = new_command::new();
let params = CommandParams::new();
cmd.execute(&ctx, ¶ms).unwrap();
}
let dids = get_dids(wallet_handle);
assert_eq!(1, dids.len());
close_and_delete_wallet(&ctx);
TestUtils::cleanup_storage();
}
#[test]
pub fn new_works_for_did() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
let wallet_handle = create_and_open_wallet(&ctx);
{
let cmd = new_command::new();
let mut params = CommandParams::new();
params.insert("did", DID_TRUSTEE.to_string());
cmd.execute(&ctx, ¶ms).unwrap();
}
let did = get_did_info(wallet_handle, DID_TRUSTEE);
assert_eq!(did["did"].as_str().unwrap(), DID_TRUSTEE);
close_and_delete_wallet(&ctx);
TestUtils::cleanup_storage();
}
#[test]
pub fn new_works_for_seed() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
let wallet_handle = create_and_open_wallet(&ctx);
{
let cmd = new_command::new();
let mut params = CommandParams::new();
params.insert("seed", SEED_TRUSTEE.to_string());
cmd.execute(&ctx, ¶ms).unwrap();
}
let did = get_did_info(wallet_handle, DID_TRUSTEE);
assert_eq!(did["did"].as_str().unwrap(), DID_TRUSTEE);
assert_eq!(did["verkey"].as_str().unwrap(), VERKEY_TRUSTEE);
close_and_delete_wallet(&ctx);
TestUtils::cleanup_storage();
}
#[test]
pub fn new_works_for_meta() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
let metadata = "metadata";
let wallet_handle = create_and_open_wallet(&ctx);
{
let cmd = new_command::new();
let mut params = CommandParams::new();
params.insert("metadata", metadata.to_string());
cmd.execute(&ctx, ¶ms).unwrap();
}
let dids = get_dids(wallet_handle);
assert_eq!(1, dids.len());
assert_eq!(dids[0]["metadata"].as_str().unwrap(), metadata);
close_and_delete_wallet(&ctx);
TestUtils::cleanup_storage();
}
#[test]
pub fn new_works_for_no_opened_wallet() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
{
let cmd = new_command::new();
let params = CommandParams::new();
cmd.execute(&ctx, ¶ms).unwrap_err();
}
TestUtils::cleanup_storage();
}
#[test]
pub fn new_works_for_wrong_seed() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
create_and_open_wallet(&ctx);
{
let cmd = new_command::new();
let mut params = CommandParams::new();
params.insert("seed", "invalid_base58_string".to_string());
cmd.execute(&ctx, ¶ms).unwrap_err();
}
close_and_delete_wallet(&ctx);
TestUtils::cleanup_storage();
}
}
mod did_use {
use super::*;
#[test]
pub fn use_works() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
create_and_open_wallet(&ctx);
new_did(&ctx, SEED_TRUSTEE);
{
let cmd = use_command::new();
let mut params = CommandParams::new();
params.insert("did", DID_TRUSTEE.to_string());
cmd.execute(&ctx, ¶ms).unwrap();
}
assert_eq!(ensure_active_did(&ctx).unwrap(), DID_TRUSTEE);
close_and_delete_wallet(&ctx);
TestUtils::cleanup_storage();
}
#[test]
pub fn use_works_for_unknown_did() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
create_and_open_wallet(&ctx);
{
let cmd = use_command::new();
let mut params = CommandParams::new();
params.insert("did", DID_TRUSTEE.to_string());
cmd.execute(&ctx, ¶ms).unwrap_err();
}
close_and_delete_wallet(&ctx);
TestUtils::cleanup_storage();
}
#[test]
pub fn use_works_for_closed_wallet() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
create_and_open_wallet(&ctx);
new_did(&ctx, SEED_TRUSTEE);
close_and_delete_wallet(&ctx);
{
let cmd = new_command::new();
let params = CommandParams::new();
cmd.execute(&ctx, ¶ms).unwrap_err();
}
TestUtils::cleanup_storage();
}
}
mod did_list {
use super::*;
#[test]
pub fn list_works() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
create_and_open_wallet(&ctx);
new_did(&ctx, SEED_TRUSTEE);
{
let cmd = list_command::new();
let params = CommandParams::new();
cmd.execute(&ctx, ¶ms).unwrap();
}
close_and_delete_wallet(&ctx);
TestUtils::cleanup_storage();
}
#[test]
pub fn list_works_for_empty_result() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
create_and_open_wallet(&ctx);
{
let cmd = list_command::new();
let params = CommandParams::new();
cmd.execute(&ctx, ¶ms).unwrap();
}
close_and_delete_wallet(&ctx);
TestUtils::cleanup_storage();
}
#[test]
pub fn list_works_for_closed_wallet() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
create_and_open_wallet(&ctx);
new_did(&ctx, SEED_TRUSTEE);
close_and_delete_wallet(&ctx);
{
let cmd = list_command::new();
let params = CommandParams::new();
cmd.execute(&ctx, ¶ms).unwrap_err();
}
TestUtils::cleanup_storage();
}
}
mod did_rotate_key {
use super::*;
#[test]
pub fn rotate_works() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
let wallet_handle = create_and_open_wallet(&ctx);
create_and_connect_pool(&ctx);
new_did(&ctx, SEED_TRUSTEE);
new_did(&ctx, SEED_MY2);
use_did(&ctx, DID_TRUSTEE);
send_nym(&ctx, DID_MY2, VERKEY_MY2, None);
use_did(&ctx, DID_MY2);
let did_info = get_did_info(wallet_handle,DID_MY2);
assert_eq!(did_info["verkey"].as_str().unwrap(), VERKEY_MY2);
{
let cmd = rotate_key_command::new();
let params = CommandParams::new();
cmd.execute(&ctx, ¶ms).unwrap();
}
let did_info = get_did_info(wallet_handle,DID_MY2);
assert_ne!(did_info["verkey"].as_str().unwrap(), VERKEY_MY2);
close_and_delete_wallet(&ctx);
disconnect_and_delete_pool(&ctx);
TestUtils::cleanup_storage();
}
#[test]
pub fn rotate_works_for_no_active_did() {
TestUtils::cleanup_storage();
let ctx = CommandContext::new();
create_and_open_wallet(&ctx);
create_and_connect_pool(&ctx);
{
let cmd = rotate_key_command::new();
let params = CommandParams::new();
cmd.execute(&ctx, ¶ms).unwrap_err();
}
close_and_delete_wallet(&ctx);
disconnect_and_delete_pool(&ctx);
TestUtils::cleanup_storage();
}
}
fn get_did_info(wallet_handle: i32, did: &str) -> serde_json::Value {
let did_info = Did::get_did_with_meta(wallet_handle, did).unwrap();
serde_json::from_str(&did_info).unwrap()
}
fn get_dids(wallet_handle: i32) -> Vec<serde_json::Value> {
let dids = Did::list_dids_with_meta(wallet_handle).unwrap();
serde_json::from_str(&dids).unwrap()
}
pub fn new_did(ctx: &CommandContext, seed: &str) {
{
let cmd = new_command::new();
let mut params = CommandParams::new();
params.insert("seed", seed.to_string());
cmd.execute(&ctx, ¶ms).unwrap();
}
}
pub fn use_did(ctx: &CommandContext, did: &str) {
{
let cmd = use_command::new();
let mut params = CommandParams::new();
params.insert("did", did.to_string());
cmd.execute(&ctx, ¶ms).unwrap();
}
}
} | 37.324059 | 176 | 0.528437 |
716c0c328c8172602ed95b728a1e52a21a36fa83 | 2,120 | // Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_exception::Result;
use super::CreateTableInterpreter;
use super::ExplainInterpreterV2;
use super::InterpreterPtr;
use super::SelectInterpreterV2;
use crate::sessions::QueryContext;
use crate::sql::plans::Plan;
use crate::sql::DfStatement;
/// InterpreterFactory is the entry of Interpreter.
pub struct InterpreterFactoryV2;
/// InterpreterFactoryV2 provides `get` method which transforms `Plan` into the corresponding interpreter.
/// Such as: Plan::Query -> InterpreterSelectV2
impl InterpreterFactoryV2 {
/// Check if statement is supported by InterpreterFactoryV2
pub fn check(stmt: &DfStatement) -> bool {
matches!(
stmt,
DfStatement::Query(_) | DfStatement::Explain(_) | DfStatement::CreateTable(_)
)
}
pub fn get(ctx: Arc<QueryContext>, plan: &Plan) -> Result<InterpreterPtr> {
let inner = match plan {
Plan::Query {
s_expr,
bind_context,
metadata,
} => SelectInterpreterV2::try_create(
ctx,
*bind_context.clone(),
s_expr.clone(),
metadata.clone(),
),
Plan::Explain { kind, plan } => {
ExplainInterpreterV2::try_create(ctx, *plan.clone(), kind.clone())
}
Plan::CreateTable(create_table) => {
CreateTableInterpreter::try_create(ctx, create_table.clone())
}
}?;
Ok(inner)
}
}
| 33.650794 | 106 | 0.638679 |
bf3452f07327115466beb0f64d6da80c22ab7c7c | 16,410 | //! Network upgrade consensus parameters for Zcash.
use NetworkUpgrade::*;
use crate::block;
use crate::parameters::{Network, Network::*};
use std::collections::{BTreeMap, HashMap};
use std::ops::Bound::*;
use chrono::{DateTime, Duration, Utc};
#[cfg(any(test, feature = "proptest-impl"))]
use proptest_derive::Arbitrary;
/// A Zcash network upgrade.
///
/// Network upgrades can change the Zcash network protocol or consensus rules in
/// incompatible ways.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
#[cfg_attr(any(test, feature = "proptest-impl"), derive(Arbitrary))]
pub enum NetworkUpgrade {
/// The Zcash protocol for a Genesis block.
///
/// Zcash genesis blocks use a different set of consensus rules from
/// other BeforeOverwinter blocks, so we treat them like a separate network
/// upgrade.
Genesis,
/// The Zcash protocol before the Overwinter upgrade.
///
/// We avoid using `Sprout`, because the specification says that Sprout
/// is the name of the pre-Sapling protocol, before and after Overwinter.
BeforeOverwinter,
/// The Zcash protocol after the Overwinter upgrade.
Overwinter,
/// The Zcash protocol after the Sapling upgrade.
Sapling,
/// The Zcash protocol after the Blossom upgrade.
Blossom,
/// The Zcash protocol after the Heartwood upgrade.
Heartwood,
/// The Zcash protocol after the Canopy upgrade.
Canopy,
/// The Zcash protocol after the Nu5 upgrade.
///
/// Note: Network Upgrade 5 includes the Orchard Shielded Protocol, and
/// other changes. The Nu5 code name has not been chosen yet.
Nu5,
}
/// Mainnet network upgrade activation heights.
///
/// This is actually a bijective map, but it is const, so we use a vector, and
/// do the uniqueness check in the unit tests.
///
/// # Correctness
///
/// Don't use this directly; use NetworkUpgrade::activation_list() so that
/// we can switch to fake activation heights for some tests.
#[allow(unused)]
pub(super) const MAINNET_ACTIVATION_HEIGHTS: &[(block::Height, NetworkUpgrade)] = &[
(block::Height(0), Genesis),
(block::Height(1), BeforeOverwinter),
(block::Height(347_500), Overwinter),
(block::Height(419_200), Sapling),
(block::Height(653_600), Blossom),
(block::Height(903_000), Heartwood),
(block::Height(1_046_400), Canopy),
// TODO: Add Nu5 mainnet activation height
];
/// Fake mainnet network upgrade activation heights, used in tests.
#[allow(unused)]
const FAKE_MAINNET_ACTIVATION_HEIGHTS: &[(block::Height, NetworkUpgrade)] = &[
(block::Height(0), Genesis),
(block::Height(5), BeforeOverwinter),
(block::Height(10), Overwinter),
(block::Height(15), Sapling),
(block::Height(20), Blossom),
(block::Height(25), Heartwood),
(block::Height(30), Canopy),
(block::Height(35), Nu5),
];
/// Testnet network upgrade activation heights.
///
/// This is actually a bijective map, but it is const, so we use a vector, and
/// do the uniqueness check in the unit tests.
///
/// # Correctness
///
/// Don't use this directly; use NetworkUpgrade::activation_list() so that
/// we can switch to fake activation heights for some tests.
#[allow(unused)]
pub(super) const TESTNET_ACTIVATION_HEIGHTS: &[(block::Height, NetworkUpgrade)] = &[
(block::Height(0), Genesis),
(block::Height(1), BeforeOverwinter),
(block::Height(207_500), Overwinter),
(block::Height(280_000), Sapling),
(block::Height(584_000), Blossom),
(block::Height(903_800), Heartwood),
(block::Height(1_028_500), Canopy),
(block::Height(1_599_200), Nu5),
];
/// Fake testnet network upgrade activation heights, used in tests.
#[allow(unused)]
const FAKE_TESTNET_ACTIVATION_HEIGHTS: &[(block::Height, NetworkUpgrade)] = &[
(block::Height(0), Genesis),
(block::Height(5), BeforeOverwinter),
(block::Height(10), Overwinter),
(block::Height(15), Sapling),
(block::Height(20), Blossom),
(block::Height(25), Heartwood),
(block::Height(30), Canopy),
(block::Height(35), Nu5),
];
/// The Consensus Branch Id, used to bind transactions and blocks to a
/// particular network upgrade.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct ConsensusBranchId(u32);
impl From<ConsensusBranchId> for u32 {
fn from(branch: ConsensusBranchId) -> u32 {
branch.0
}
}
/// Network Upgrade Consensus Branch Ids.
///
/// Branch ids are the same for mainnet and testnet. If there is a testnet
/// rollback after a bug, the branch id changes.
///
/// Branch ids were introduced in the Overwinter upgrade, so there are no
/// Genesis or BeforeOverwinter branch ids.
///
/// This is actually a bijective map, but it is const, so we use a vector, and
/// do the uniqueness check in the unit tests.
pub(crate) const CONSENSUS_BRANCH_IDS: &[(NetworkUpgrade, ConsensusBranchId)] = &[
(Overwinter, ConsensusBranchId(0x5ba81b19)),
(Sapling, ConsensusBranchId(0x76b809bb)),
(Blossom, ConsensusBranchId(0x2bb40e60)),
(Heartwood, ConsensusBranchId(0xf5b9230b)),
(Canopy, ConsensusBranchId(0xe9ff75a6)),
(Nu5, ConsensusBranchId(0x37519621)),
];
/// The target block spacing before Blossom.
const PRE_BLOSSOM_POW_TARGET_SPACING: i64 = 150;
/// The target block spacing after Blossom activation.
pub const POST_BLOSSOM_POW_TARGET_SPACING: i64 = 75;
/// The averaging window for difficulty threshold arithmetic mean calculations.
///
/// `PoWAveragingWindow` in the Zcash specification.
pub const POW_AVERAGING_WINDOW: usize = 17;
/// The multiplier used to derive the testnet minimum difficulty block time gap
/// threshold.
///
/// Based on https://zips.z.cash/zip-0208#minimum-difficulty-blocks-on-the-test-network
const TESTNET_MINIMUM_DIFFICULTY_GAP_MULTIPLIER: i32 = 6;
/// The start height for the testnet minimum difficulty consensus rule.
///
/// Based on https://zips.z.cash/zip-0208#minimum-difficulty-blocks-on-the-test-network
const TESTNET_MINIMUM_DIFFICULTY_START_HEIGHT: block::Height = block::Height(299_188);
/// The activation height for the block maximum time rule on Testnet.
///
/// Part of the block header consensus rules in the Zcash specification at
/// https://zips.z.cash/protocol/protocol.pdf#blockheader
pub const TESTNET_MAX_TIME_START_HEIGHT: block::Height = block::Height(653_606);
impl NetworkUpgrade {
/// Returns a BTreeMap of activation heights and network upgrades for
/// `network`.
///
/// If the activation height of a future upgrade is not known, that
/// network upgrade does not appear in the list.
///
/// This is actually a bijective map.
///
/// When the environment variable TEST_FAKE_ACTIVATION_HEIGHTS is set
/// and it's a test build, this returns a list of fake activation heights
/// used by some tests.
pub(crate) fn activation_list(network: Network) -> BTreeMap<block::Height, NetworkUpgrade> {
let (mainnet_heights, testnet_heights) = {
#[cfg(not(feature = "zebra-test"))]
{
(MAINNET_ACTIVATION_HEIGHTS, TESTNET_ACTIVATION_HEIGHTS)
}
// To prevent accidentally setting this somehow, only check the env var
// when being compiled for tests. We can't use cfg(test) since the
// test that uses this is in zebra-state, and cfg(test) is not
// set for dependencies. However, zebra-state does set the
// zebra-test feature of zebra-chain if it's a dev dependency.
//
// Cargo features are additive, so all test binaries built along with
// zebra-state will have this feature enabled. But we are using
// Rust Edition 2021 and Cargo resolver version 2, so the "zebra-test"
// feature should only be enabled for tests:
// https://doc.rust-lang.org/cargo/reference/features.html#resolver-version-2-command-line-flags
#[cfg(feature = "zebra-test")]
if std::env::var_os("TEST_FAKE_ACTIVATION_HEIGHTS").is_some() {
(
FAKE_MAINNET_ACTIVATION_HEIGHTS,
FAKE_TESTNET_ACTIVATION_HEIGHTS,
)
} else {
(MAINNET_ACTIVATION_HEIGHTS, TESTNET_ACTIVATION_HEIGHTS)
}
};
match network {
Mainnet => mainnet_heights,
Testnet => testnet_heights,
}
.iter()
.cloned()
.collect()
}
/// Returns the current network upgrade for `network` and `height`.
pub fn current(network: Network, height: block::Height) -> NetworkUpgrade {
NetworkUpgrade::activation_list(network)
.range(..=height)
.map(|(_, nu)| *nu)
.next_back()
.expect("every height has a current network upgrade")
}
/// Returns the next network upgrade for `network` and `height`.
///
/// Returns None if the next upgrade has not been implemented in Zebra
/// yet.
pub fn next(network: Network, height: block::Height) -> Option<NetworkUpgrade> {
NetworkUpgrade::activation_list(network)
.range((Excluded(height), Unbounded))
.map(|(_, nu)| *nu)
.next()
}
/// Returns the activation height for this network upgrade on `network`.
///
/// Returns None if this network upgrade is a future upgrade, and its
/// activation height has not been set yet.
pub fn activation_height(&self, network: Network) -> Option<block::Height> {
NetworkUpgrade::activation_list(network)
.iter()
.filter(|(_, nu)| nu == &self)
.map(|(height, _)| *height)
.next()
}
/// Returns `true` if `height` is the activation height of any network upgrade
/// on `network`.
///
/// Use [`activation_height`] to get the specific network upgrade.
pub fn is_activation_height(network: Network, height: block::Height) -> bool {
NetworkUpgrade::activation_list(network).contains_key(&height)
}
/// Returns a BTreeMap of NetworkUpgrades and their ConsensusBranchIds.
///
/// Branch ids are the same for mainnet and testnet.
///
/// If network upgrade does not have a branch id, that network upgrade does
/// not appear in the list.
///
/// This is actually a bijective map.
pub(crate) fn branch_id_list() -> HashMap<NetworkUpgrade, ConsensusBranchId> {
CONSENSUS_BRANCH_IDS.iter().cloned().collect()
}
/// Returns the consensus branch id for this network upgrade.
///
/// Returns None if this network upgrade has no consensus branch id.
pub fn branch_id(&self) -> Option<ConsensusBranchId> {
NetworkUpgrade::branch_id_list().get(self).cloned()
}
/// Returns the target block spacing for the network upgrade.
///
/// Based on `PRE_BLOSSOM_POW_TARGET_SPACING` and
/// `POST_BLOSSOM_POW_TARGET_SPACING` from the Zcash specification.
pub fn target_spacing(&self) -> Duration {
let spacing_seconds = match self {
Genesis | BeforeOverwinter | Overwinter | Sapling => PRE_BLOSSOM_POW_TARGET_SPACING,
Blossom | Heartwood | Canopy | Nu5 => POST_BLOSSOM_POW_TARGET_SPACING,
};
Duration::seconds(spacing_seconds)
}
/// Returns the target block spacing for `network` and `height`.
///
/// See [`target_spacing()`] for details.
pub fn target_spacing_for_height(network: Network, height: block::Height) -> Duration {
NetworkUpgrade::current(network, height).target_spacing()
}
/// Returns all the target block spacings for `network` and the heights where they start.
pub fn target_spacings(network: Network) -> impl Iterator<Item = (block::Height, Duration)> {
[
(NetworkUpgrade::Genesis, PRE_BLOSSOM_POW_TARGET_SPACING),
(NetworkUpgrade::Blossom, POST_BLOSSOM_POW_TARGET_SPACING),
]
.into_iter()
.map(move |(upgrade, spacing_seconds)| {
let activation_height = upgrade
.activation_height(network)
.expect("missing activation height for target spacing change");
let target_spacing = Duration::seconds(spacing_seconds);
(activation_height, target_spacing)
})
}
/// Returns the minimum difficulty block spacing for `network` and `height`.
/// Returns `None` if the testnet minimum difficulty consensus rule is not active.
///
/// Based on https://zips.z.cash/zip-0208#minimum-difficulty-blocks-on-the-test-network
pub fn minimum_difficulty_spacing_for_height(
network: Network,
height: block::Height,
) -> Option<Duration> {
match (network, height) {
(Network::Testnet, height) if height < TESTNET_MINIMUM_DIFFICULTY_START_HEIGHT => None,
(Network::Mainnet, _) => None,
(Network::Testnet, _) => {
let network_upgrade = NetworkUpgrade::current(network, height);
Some(network_upgrade.target_spacing() * TESTNET_MINIMUM_DIFFICULTY_GAP_MULTIPLIER)
}
}
}
/// Returns true if the gap between `block_time` and `previous_block_time` is
/// greater than the Testnet minimum difficulty time gap. This time gap
/// depends on the `network` and `block_height`.
///
/// Returns false on Mainnet, when `block_height` is less than the minimum
/// difficulty start height, and when the time gap is too small.
///
/// `block_time` can be less than, equal to, or greater than
/// `previous_block_time`, because block times are provided by miners.
///
/// Implements the Testnet minimum difficulty adjustment from ZIPs 205 and 208.
///
/// Spec Note: Some parts of ZIPs 205 and 208 previously specified an incorrect
/// check for the time gap. This function implements the correct "greater than"
/// check.
pub fn is_testnet_min_difficulty_block(
network: Network,
block_height: block::Height,
block_time: DateTime<Utc>,
previous_block_time: DateTime<Utc>,
) -> bool {
let block_time_gap = block_time - previous_block_time;
if let Some(min_difficulty_gap) =
NetworkUpgrade::minimum_difficulty_spacing_for_height(network, block_height)
{
block_time_gap > min_difficulty_gap
} else {
false
}
}
/// Returns the averaging window timespan for the network upgrade.
///
/// `AveragingWindowTimespan` from the Zcash specification.
pub fn averaging_window_timespan(&self) -> Duration {
self.target_spacing() * POW_AVERAGING_WINDOW.try_into().expect("fits in i32")
}
/// Returns the averaging window timespan for `network` and `height`.
///
/// See [`averaging_window_timespan()`] for details.
pub fn averaging_window_timespan_for_height(
network: Network,
height: block::Height,
) -> Duration {
NetworkUpgrade::current(network, height).averaging_window_timespan()
}
/// Returns true if the maximum block time rule is active for `network` and `height`.
///
/// Always returns true if `network` is the Mainnet.
/// If `network` is the Testnet, the `height` should be at least
/// TESTNET_MAX_TIME_START_HEIGHT to return true.
/// Returns false otherwise.
///
/// Part of the consensus rules at https://zips.z.cash/protocol/protocol.pdf#blockheader
pub fn is_max_block_time_enforced(network: Network, height: block::Height) -> bool {
match network {
Network::Mainnet => true,
Network::Testnet => height >= TESTNET_MAX_TIME_START_HEIGHT,
}
}
/// Returns the NetworkUpgrade given an u32 as ConsensusBranchId
pub fn from_branch_id(branch_id: u32) -> Option<NetworkUpgrade> {
CONSENSUS_BRANCH_IDS
.iter()
.find(|id| id.1 == ConsensusBranchId(branch_id))
.map(|nu| nu.0)
}
}
impl ConsensusBranchId {
/// Returns the current consensus branch id for `network` and `height`.
///
/// Returns None if the network has no branch id at this height.
pub fn current(network: Network, height: block::Height) -> Option<ConsensusBranchId> {
NetworkUpgrade::current(network, height).branch_id()
}
}
| 39.071429 | 108 | 0.661121 |
bf62986c31d7b33fe8c5d80af8acf3e8bd01e4ec | 13,191 | // In this file we define the PackedFile type RigidModel for decoding and encoding it.
// This is the type used by 3D model files of units and buildings. Both are different, so we need to
// take the type in count while processing them.
extern crate failure;
use common::coding_helpers;
use self::failure::Error;
/// Struct "RigidModel". For more info about this, check the comment at the start of "packedfile/
/// rigidmodel/mod.rs".
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RigidModel {
pub packed_file_header: RigidModelHeader,
pub packed_file_data: RigidModelData,
}
/// Struct "RigidModelHeader". For more info about this, check the comment at the start of "packedfile/
/// rigidmodel/mod.rs".
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RigidModelHeader {
pub packed_file_header_signature: String,
pub packed_file_header_model_type: u32,
pub packed_file_header_lods_count: u32,
pub packed_file_data_base_skeleton: (String, usize),
}
/// Struct "RigidModelData". For more info about this, check the comment at the start of "packedfile/
/// rigidmodel/mod.rs".
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RigidModelData {
pub packed_file_data_lods_header: Vec<RigidModelLodHeader>,
pub packed_file_data_lods_data: Vec<u8>,
}
/// Struct "RigidModelLodHeader". For more info about this, check the comment at the start of "packedfile/
/// rigidmodel/mod.rs".
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RigidModelLodHeader {
pub groups_count: u32,
pub vertices_data_length: u32,
pub indices_data_length: u32,
pub start_offset: u32,
pub lod_zoom_factor: f32,
pub mysterious_data_1: Option<u32>,
pub mysterious_data_2: Option<u32>,
}
/// Implementation of "RigidModel"
impl RigidModel {
/// This function creates a new empty RigidModel. Only for initialization.
pub fn new() -> Self {
Self{
packed_file_header: RigidModelHeader::new(),
packed_file_data: RigidModelData::new(),
}
}
/// This function reads the data from a Vec<u8> and decode it into a RigidModel. This CAN FAIL,
/// so we return Result<RigidModel, Error>.
pub fn read(packed_file_data: &[u8]) -> Result<RigidModel, Error> {
match RigidModelHeader::read(&packed_file_data[..140]) {
Ok(packed_file_header) => {
match RigidModelData::read(
&packed_file_data[140..],
&packed_file_header.packed_file_header_model_type,
&packed_file_header.packed_file_header_lods_count
) {
Ok(packed_file_data) =>
Ok(RigidModel {
packed_file_header,
packed_file_data,
}),
Err(error) => Err(error)
}
}
Err(error) => Err(error)
}
}
/// This function reads the data from a RigidModel and encode it into a Vec<u8>. This CAN FAIL,
/// so we return Result<Vec<u8>, Error>.
pub fn save(rigid_model_data: &RigidModel) -> Result<Vec<u8>, Error> {
let mut packed_file_data_encoded = RigidModelData::save(&rigid_model_data.packed_file_data);
let mut packed_file_header_encoded = RigidModelHeader::save(&rigid_model_data.packed_file_header)?;
let mut packed_file_encoded = vec![];
packed_file_encoded.append(&mut packed_file_header_encoded);
packed_file_encoded.append(&mut packed_file_data_encoded);
Ok(packed_file_encoded)
}
}
/// Implementation of "RigidModelHeader"
impl RigidModelHeader {
/// This function creates a new empty RigidModel. Only for initialization.
pub fn new() -> Self {
Self{
packed_file_header_signature: String::new(),
packed_file_header_model_type: 0,
packed_file_header_lods_count: 0,
packed_file_data_base_skeleton: (String::new(), 0),
}
}
/// This function reads the data from a Vec<u8> and decode it into a RigidModelHeader. This CAN FAIL,
/// so we return Result<RigidModelHeader, Error>.
pub fn read(packed_file_data: &[u8]) -> Result<RigidModelHeader, Error> {
let mut packed_file_header = RigidModelHeader {
packed_file_header_signature: String::new(),
packed_file_header_model_type: 0,
packed_file_header_lods_count: 0,
packed_file_data_base_skeleton: (String::new(), 0),
};
match coding_helpers::decode_string_u8(&packed_file_data[0..4]) {
Ok(data) => packed_file_header.packed_file_header_signature = data,
Err(error) => return Err(error)
}
// We check this, just in case we try to read some malformed file with a string in the first
// four bytes (which is not uncommon).
if packed_file_header.packed_file_header_signature != "RMV2" {
return Err(format_err!("This is not a RMV2 RigidModel."))
}
match coding_helpers::decode_integer_u32(&packed_file_data[4..8]) {
Ok(data) => packed_file_header.packed_file_header_model_type = data,
Err(error) => return Err(error)
}
match coding_helpers::decode_integer_u32(&packed_file_data[8..12]) {
Ok(data) => packed_file_header.packed_file_header_lods_count = data,
Err(error) => return Err(error)
}
match coding_helpers::decode_string_u8_0padded(&packed_file_data[12..140]) {
Ok(data) => packed_file_header.packed_file_data_base_skeleton = data,
Err(error) => return Err(error)
}
Ok(packed_file_header)
}
/// This function reads the data from a RigidModelHeader and encode it into a Vec<u8>. This CAN FAIL,
/// so we return Result<Vec<u8>, Error>.
pub fn save(rigid_model_header: &RigidModelHeader) -> Result<Vec<u8>, Error> {
let mut packed_file_data: Vec<u8> = vec![];
let mut packed_file_header_signature = coding_helpers::encode_string_u8(&rigid_model_header.packed_file_header_signature);
let mut packed_file_header_model_type = coding_helpers::encode_integer_u32(rigid_model_header.packed_file_header_model_type);
let mut packed_file_header_lods_count = coding_helpers::encode_integer_u32(rigid_model_header.packed_file_header_lods_count);
let mut packed_file_data_base_skeleton = coding_helpers::encode_string_u8_0padded(&rigid_model_header.packed_file_data_base_skeleton)?;
packed_file_data.append(&mut packed_file_header_signature);
packed_file_data.append(&mut packed_file_header_model_type);
packed_file_data.append(&mut packed_file_header_lods_count);
packed_file_data.append(&mut packed_file_data_base_skeleton);
Ok(packed_file_data)
}
}
/// Implementation of "RigidModelData"
impl RigidModelData {
/// This function creates a new empty RigidModel. Only for initialization.
pub fn new() -> Self {
Self{
packed_file_data_lods_header: vec![],
packed_file_data_lods_data: vec![],
}
}
/// This function reads the data from a Vec<u8> and decode it into a RigidModelData. This CAN FAIL,
/// so we return Result<RigidModelData, Error>.
pub fn read(packed_file_data: &[u8], packed_file_header_model_type: &u32, packed_file_header_lods_count: &u32) -> Result<RigidModelData, Error> {
let mut packed_file_data_lods_header: Vec<RigidModelLodHeader> = vec![];
let mut index: usize = 0;
let offset: usize = match *packed_file_header_model_type {
6 => 20, // Attila
7 => 28, // Warhammer 1&2
_ => return Err(format_err!("RigidModel model not yet decodeable."))
};
// We get the "headers" of every lod.
for _ in 0..*packed_file_header_lods_count {
let lod_header = match RigidModelLodHeader::read(&packed_file_data[index..(index + offset)]) {
Ok(data) => data,
Err(error) => return Err(error)
};
packed_file_data_lods_header.push(lod_header);
index += offset;
}
let packed_file_data_lods_data = packed_file_data[index..].to_vec();
Ok(RigidModelData {
packed_file_data_lods_header,
packed_file_data_lods_data,
})
}
/// This function reads the data from a RigidModelData and encode it into a Vec<u8>. This CAN FAIL,
/// so we return Result<Vec<u8>, Error>.
pub fn save(rigid_model_data: &RigidModelData) -> Vec<u8> {
let mut packed_file_data = vec![];
// For each Lod, we save it, and add it to the "Encoded Data" vector. After that, we add to that
// vector the extra data, and return it.
for lod in &rigid_model_data.packed_file_data_lods_header {
packed_file_data.append(&mut RigidModelLodHeader::save(lod));
}
packed_file_data.extend_from_slice(&rigid_model_data.packed_file_data_lods_data);
packed_file_data
}
}
/// Implementation of "RigidModelLodHeader"
impl RigidModelLodHeader {
/// This function reads the data from a Vec<u8> and decode it into a RigidModelLodHeader. This CAN FAIL,
/// so we return Result<RigidModelLodHeader, Error>.
pub fn read(packed_file_data: &[u8]) -> Result<RigidModelLodHeader, Error> {
let mut header = RigidModelLodHeader {
groups_count: 0,
vertices_data_length: 0,
indices_data_length: 0,
start_offset: 0,
lod_zoom_factor: 0.0,
mysterious_data_1: None,
mysterious_data_2: None,
};
match coding_helpers::decode_integer_u32(&packed_file_data[0..4]) {
Ok(data) => header.groups_count = data,
Err(error) => return Err(error)
}
match coding_helpers::decode_integer_u32(&packed_file_data[4..8]) {
Ok(data) => header.vertices_data_length = data,
Err(error) => return Err(error)
}
match coding_helpers::decode_integer_u32(&packed_file_data[8..12]) {
Ok(data) => header.indices_data_length = data,
Err(error) => return Err(error)
}
match coding_helpers::decode_integer_u32(&packed_file_data[12..16]) {
Ok(data) => header.start_offset = data,
Err(error) => return Err(error)
}
match coding_helpers::decode_float_f32(&packed_file_data[16..20]) {
Ok(data) => header.lod_zoom_factor = data,
Err(error) => return Err(error)
}
// These two we only decode them if the RigidModel is v7 (Warhammer 1&2), as these doesn't exist
// in Attila's RigidModels.
if packed_file_data.len() == 28 {
match coding_helpers::decode_integer_u32(&packed_file_data[20..24]) {
Ok(data) => header.mysterious_data_1 = Some(data),
Err(error) => return Err(error)
}
match coding_helpers::decode_integer_u32(&packed_file_data[24..28]) {
Ok(data) => header.mysterious_data_2 = Some(data),
Err(error) => return Err(error)
}
}
Ok(header)
}
/// This function reads the data from a RigidModelLodHeader and encode it into a Vec<u8>.
pub fn save(rigid_model_lod: &RigidModelLodHeader) -> Vec<u8> {
let mut packed_file_data: Vec<u8> = vec![];
let mut groups_count = coding_helpers::encode_integer_u32(rigid_model_lod.groups_count);
let mut vertex_data_length = coding_helpers::encode_integer_u32(rigid_model_lod.vertices_data_length);
let mut index_data_length = coding_helpers::encode_integer_u32(rigid_model_lod.indices_data_length);
let mut start_offset = coding_helpers::encode_integer_u32(rigid_model_lod.start_offset);
let mut lod_zoom_factor = coding_helpers::encode_float_f32(rigid_model_lod.lod_zoom_factor);
let mysterious_data_1 = match rigid_model_lod.mysterious_data_1 {
Some(data) => Some(data),
None => None,
};
let mysterious_data_2 = match rigid_model_lod.mysterious_data_2 {
Some(data) => Some(data),
None => None,
};
packed_file_data.append(&mut groups_count);
packed_file_data.append(&mut vertex_data_length);
packed_file_data.append(&mut index_data_length);
packed_file_data.append(&mut start_offset);
packed_file_data.append(&mut lod_zoom_factor);
// These two are only added if they are something (Warhammer1&2 RigidModels).
if mysterious_data_1 != None {
let mut mysterious_data_1 = coding_helpers::encode_integer_u32(mysterious_data_1.unwrap());
packed_file_data.append(&mut mysterious_data_1);
}
if mysterious_data_2 != None {
let mut mysterious_data_2 = coding_helpers::encode_integer_u32(mysterious_data_2.unwrap());
packed_file_data.append(&mut mysterious_data_2);
}
packed_file_data
}
}
| 42.278846 | 149 | 0.657115 |
e68fab59073b40cf328fbd060afafd529c778773 | 1,976 | use crate::boards::CoordIdxConverter;
use regex::Regex;
use std::fmt;
use std::fmt::{Debug, Formatter};
pub struct ChessBoard {
converter: Box<dyn CoordIdxConverter>,
pub rows: usize,
pub cols: usize,
row_char_count: usize,
col_char_count: usize,
regex: Regex,
}
impl Debug for ChessBoard {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "ChessBoard")
}
}
impl ChessBoard {
pub fn new(converter: Box<dyn CoordIdxConverter>, rows: usize, cols: usize) -> Self {
let row_char_count = if rows >= 26 { 2 } else { 1 };
let col_char_count = if rows >= 10 { 2 } else { 1 };
let regex = Regex::new(&format!(
"([a-zA-Z]{{1,{}}})([0-9]{{1,{}}})",
row_char_count, col_char_count
))
.expect("Failed to make board regex");
ChessBoard {
converter,
rows,
cols,
row_char_count,
col_char_count,
regex,
}
}
}
impl ChessBoard {
#[allow(clippy::iter_nth_zero)] //as there is also an nth(1) I think nth(0) looks nicer than next()
fn coord_to_idx(&self, coord: &str) -> Option<usize> {
if !(coord.is_ascii()) {
return None;
}
let matches = self.regex.captures(coord);
if let Some(matches) = matches {
if matches.len() == 2 {
let alpha = matches.iter().nth(0).unwrap().unwrap().as_str();
let num = matches.iter().nth(1).unwrap().unwrap().as_str();
if self.converter.is_valid_coord(alpha, num) {
return Some(self.converter.coord_to_idx(alpha, num));
}
}
}
None
}
fn idx_to_coord(&self, idx: usize) -> Option<String> {
if idx >= self.cols * self.rows {
return None;
}
let (a, n) = self.converter.idx_to_coord(idx);
Some(format!("{}{}", a, n))
}
}
| 28.637681 | 103 | 0.529352 |
9b1625786294ad3758e27a18e2822523618729cf | 1,309 | #![cfg_attr(
feature = "dev",
allow(dead_code, unused_variables, unused_imports, unreachable_code)
)]
#![cfg_attr(feature = "ci", deny(warnings))]
#![deny(clippy::all)]
use path::PathBuf;
use scriptkeeper::{context::Context, run_scriptkeeper, ExitCode, R};
use std::*;
pub fn test_run_from_directory(directory: &str) -> R<()> {
let directory = PathBuf::from("./tests/examples").join(directory);
let script_file = directory.join("script");
let context = &Context::new_mock();
let exitcode = run_scriptkeeper(context, &script_file)
.map_err(|error| format!("can't execute {:?}: {}", &script_file, error))?;
let expected_file = directory.join("expected");
let expected = String::from_utf8(
fs::read(&expected_file)
.map_err(|error| format!("error reading {:?}: {}", &expected_file, error))?,
)?;
print!("{}", context.get_captured_stdout());
eprintln!("{}", context.get_captured_stderr());
assert_eq!(exitcode, ExitCode(0));
assert_eq!(context.get_captured_stdout(), expected);
Ok(())
}
macro_rules! example {
($directory:ident) => {
#[test]
fn $directory() -> R<()> {
test_run_from_directory(stringify!($directory))?;
Ok(())
}
};
}
example!(simple);
example!(bigger);
| 31.166667 | 88 | 0.622613 |
019603b3622c2d3aca50aaa057541d95b78e554c | 3,741 | use std::sync::Arc;
use waithandle::{EventWaitHandle, WaitHandle};
use crate::builds::{Build, BuildBuilder, BuildProvider, BuildStatus};
use crate::config::AzureDevOpsConfiguration;
use crate::providers::collectors::{Collector, CollectorInfo};
use crate::utils::{date, DuckResult};
use self::client::*;
mod client;
mod validation;
pub struct AzureDevOpsCollector {
client: AzureDevOpsClient,
branches: Vec<String>,
definitions: Vec<String>,
info: CollectorInfo,
}
impl AzureDevOpsCollector {
pub fn new(config: &AzureDevOpsConfiguration) -> Self {
return AzureDevOpsCollector {
client: AzureDevOpsClient::new(config),
branches: config.branches.clone(),
definitions: config.definitions.clone(),
info: CollectorInfo {
id: config.id.clone(),
enabled: match config.enabled {
Option::None => true,
Option::Some(e) => e,
},
provider: BuildProvider::AzureDevOps,
},
};
}
}
impl Collector for AzureDevOpsCollector {
fn info(&self) -> &CollectorInfo {
&self.info
}
fn collect(
&self,
handle: Arc<EventWaitHandle>,
callback: &mut dyn FnMut(Build),
) -> DuckResult<()> {
for branch in self.branches.iter() {
if handle.check().unwrap() {
return Ok(());
}
let builds = self.client.get_builds(branch, &self.definitions)?;
for build in builds.value.iter() {
callback(
BuildBuilder::new()
.build_id(build.id.to_string())
.provider(BuildProvider::AzureDevOps)
.collector(&self.info.id)
.project_id(&build.project.id)
.project_name(&build.project.name)
.definition_id(build.definition.id.to_string())
.definition_name(&build.definition.name)
.build_number(&build.build_number)
.status(build.get_build_status())
.url(&build.links.web.href)
.started_at(date::to_timestamp(
&build.start_time,
date::AZURE_DEVOPS_FORMAT,
)?)
.finished_at(match &build.finish_time {
Option::None => None,
Option::Some(value) => Option::Some(date::to_timestamp(
&value[..],
date::AZURE_DEVOPS_FORMAT,
)?),
})
.branch(&build.branch)
.build()
.unwrap(),
);
}
// Wait for a litle time between calls.
if handle.wait(std::time::Duration::from_millis(300)).unwrap() {
return Ok(());
}
}
return Ok(());
}
}
impl AzureBuild {
pub fn get_build_status(&self) -> BuildStatus {
if self.result.is_none() {
return BuildStatus::Running;
} else {
match &self.status[..] {
"notStarted" => return BuildStatus::Queued,
"inProgress" => return BuildStatus::Running,
_ => {}
}
match self.result.as_ref().unwrap().as_ref() {
"succeeded" => BuildStatus::Success,
"canceled" => BuildStatus::Canceled,
_ => BuildStatus::Failed,
}
}
}
}
| 32.815789 | 83 | 0.483828 |
0a683fcdd8cdd931df7becedb09ee6c919cd829b | 4,300 | use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use futures::stream::StreamExt;
use maplit::btreeset;
use openraft::Config;
use openraft::State;
use tokio::time::sleep;
use crate::fixtures::RaftRouter;
/// Dynamic membership test.
///
/// What does this test do?
///
/// - bring a single-node cluster online.
/// - add a few new nodes and assert that they've joined the cluster properly.
/// - propose a new config change where the old master is not present, and assert that it steps down.
/// - temporarily isolate the new master, and assert that a new master takes over.
/// - restore the isolated node and assert that it becomes a follower.
#[tokio::test(flavor = "multi_thread", worker_threads = 6)]
async fn leader_election_after_changing_0_to_01234() -> Result<()> {
let (_log_guard, ut_span) = init_ut!();
let _ent = ut_span.enter();
let span = tracing::debug_span!("ut-dynamic_membership");
let _ent = span.enter();
// Setup test dependencies.
let config = Arc::new(Config::default().validate()?);
let router = Arc::new(RaftRouter::new(config.clone()));
router.new_raft_node(0).await;
let mut n_logs = 0;
// Assert all nodes are in learner state & have no entries.
router.wait_for_log(&btreeset![0], n_logs, None, "empty").await?;
router.wait_for_state(&btreeset![0], State::Learner, None, "empty").await?;
router.assert_pristine_cluster().await;
// Initialize the cluster, then assert that a stable cluster was formed & held.
tracing::info!("--- initializing cluster");
router.initialize_from_single_node(0).await?;
n_logs += 1;
router.wait_for_log(&btreeset![0], n_logs, None, "init").await?;
router.assert_stable_cluster(Some(1), Some(n_logs)).await;
// Sync some new nodes.
router.new_raft_node(1).await;
router.new_raft_node(2).await;
router.new_raft_node(3).await;
router.new_raft_node(4).await;
tracing::info!("--- adding new nodes to cluster");
let mut new_nodes = futures::stream::FuturesUnordered::new();
new_nodes.push(router.add_learner(0, 1));
new_nodes.push(router.add_learner(0, 2));
new_nodes.push(router.add_learner(0, 3));
new_nodes.push(router.add_learner(0, 4));
while let Some(inner) = new_nodes.next().await {
inner?;
}
tracing::info!("--- changing cluster config");
router.change_membership(0, btreeset![0, 1, 2, 3, 4]).await?;
n_logs += 2;
router.wait_for_log(&btreeset![0, 1, 2, 3, 4], n_logs, None, "cluster of 5 candidates").await?;
router.assert_stable_cluster(Some(1), Some(n_logs)).await; // Still in term 1, so leader is still node 0.
// Isolate old leader and assert that a new leader takes over.
tracing::info!("--- isolating master node 0");
router.isolate_node(0).await;
router
.wait_for_metrics(
&1,
|x| x.current_leader.is_some() && x.current_leader.unwrap() != 0,
Some(Duration::from_millis(1000)),
"wait for new leader",
)
.await?;
// need some time to stabilize.
// TODO: it can not be sure that no new leader is elected after a leader detected on node-1
// Wait for election and for everything to stabilize (this is way longer than needed).
sleep(Duration::from_millis(1000)).await;
let metrics = &router.latest_metrics().await[1];
let term = metrics.current_term;
let applied = metrics.last_applied;
let leader_id = metrics.current_leader;
router.assert_stable_cluster(Some(term), Some(applied)).await;
let leader = router.leader().await.expect("expected new leader");
assert!(leader != 0, "expected new leader to be different from the old leader");
// Restore isolated node.
router.restore_node(0).await;
router
.wait_for_metrics(
&0,
|x| x.current_leader == leader_id && x.last_applied == applied,
Some(Duration::from_millis(1000)),
"wait for restored node-0 to sync",
)
.await?;
router.assert_stable_cluster(Some(term), Some(applied)).await;
let current_leader = router.leader().await.expect("expected to find current leader");
assert_eq!(leader, current_leader, "expected cluster leadership to stay the same");
Ok(())
}
| 36.752137 | 109 | 0.666977 |
482a0f3d677af0d2fe18877c2cccc4301b0ed1f3 | 5,672 | //! internal ghost actor file wrapper
use crate::*;
ghost_actor::ghost_chan! {
/// chan wrapper for file access
pub(crate) chan EntryStoreFile<LairError> {
/// init and load up the "unlock" entry if it exists
fn init_load_unlock() -> Option<Vec<u8>>;
/// write the unlock entry to the file
fn write_unlock(entry_data: Vec<u8>) -> ();
/// loading all entries from the file
fn load_all_entries() -> Vec<(super::KeystoreIndex, Vec<u8>)>;
/// write a new entry to the store file
fn write_next_entry(entry_data: Vec<u8>) -> super::KeystoreIndex;
}
}
pub(crate) async fn spawn_entry_store_file_task(
store_file: tokio::fs::File,
) -> LairResult<futures::channel::mpsc::Sender<EntryStoreFile>> {
let (s, r) = futures::channel::mpsc::channel(10);
tokio::task::spawn(entry_store_file_task(store_file, r));
Ok(s)
}
/// this is not an actor, because we cannot do parallel file access
/// we actually need to process requests in series.
async fn entry_store_file_task(
mut store_file: tokio::fs::File,
mut recv: futures::channel::mpsc::Receiver<EntryStoreFile>,
) -> LairResult<()> {
use futures::{future::FutureExt, stream::StreamExt};
while let Some(req) = recv.next().await {
match req {
EntryStoreFile::InitLoadUnlock { respond, .. } => {
let res = init_load_unlock(&mut store_file).await;
respond.r(Ok(async move { res }.boxed().into()));
}
EntryStoreFile::WriteUnlock {
respond,
entry_data,
..
} => {
let res = write_unlock(&mut store_file, entry_data).await;
respond.r(Ok(async move { res }.boxed().into()));
}
EntryStoreFile::LoadAllEntries { respond, .. } => {
let res = load_all_entries(&mut store_file).await;
respond.r(Ok(async move { res }.boxed().into()));
}
EntryStoreFile::WriteNextEntry {
respond,
entry_data,
..
} => {
let res = write_next_entry(&mut store_file, entry_data).await;
respond.r(Ok(async move { res }.boxed().into()));
}
}
}
Ok(())
}
async fn init_load_unlock(
store_file: &mut tokio::fs::File,
) -> LairResult<Option<Vec<u8>>> {
use tokio::io::AsyncReadExt;
use tokio::io::AsyncSeekExt;
let meta = store_file.metadata().await.map_err(LairError::other)?;
let total_size = meta.len();
if total_size >= entry::ENTRY_SIZE as u64 {
store_file
.seek(std::io::SeekFrom::Start(0))
.await
.map_err(LairError::other)?;
let mut buf = vec![0; entry::ENTRY_SIZE];
store_file
.read_exact(&mut buf)
.await
.map_err(LairError::other)?;
Ok(Some(buf))
} else {
Ok(None)
}
}
async fn write_unlock(
store_file: &mut tokio::fs::File,
entry_data: Vec<u8>,
) -> LairResult<()> {
use tokio::io::AsyncSeekExt;
use tokio::io::AsyncWriteExt;
store_file
.seek(std::io::SeekFrom::Start(0))
.await
.map_err(LairError::other)?;
store_file
.write_all(&entry_data)
.await
.map_err(LairError::other)?;
store_file.sync_all().await.map_err(LairError::other)?;
Ok(())
}
async fn query_entry_count(
store_file: &mut tokio::fs::File,
) -> LairResult<u64> {
let meta = store_file.metadata().await.map_err(LairError::other)?;
let total_size = meta.len();
let entry_count = total_size / entry::ENTRY_SIZE as u64;
if entry_count * entry::ENTRY_SIZE as u64 != total_size {
// @todo - panic for now... eventually cover over invalid entry
panic!(
"BAD entry size {} count * {} size != {} file size",
entry_count,
entry::ENTRY_SIZE,
total_size
);
}
Ok(entry_count)
}
async fn load_all_entries(
store_file: &mut tokio::fs::File,
) -> LairResult<Vec<(super::KeystoreIndex, Vec<u8>)>> {
use tokio::io::AsyncReadExt;
use tokio::io::AsyncSeekExt;
let entry_count = query_entry_count(store_file).await?;
if entry_count <= 1 {
return Ok(Vec::with_capacity(0));
}
store_file
.seek(std::io::SeekFrom::Start(entry::ENTRY_SIZE as u64))
.await
.map_err(LairError::other)?;
let mut out = Vec::new();
for i in 1..(entry_count as u32) {
let mut buf = vec![0; entry::ENTRY_SIZE];
store_file
.read_exact(&mut buf)
.await
.map_err(LairError::other)?;
out.push((i.into(), buf));
}
Ok(out)
}
async fn write_next_entry(
store_file: &mut tokio::fs::File,
entry_data: Vec<u8>,
) -> LairResult<super::KeystoreIndex> {
use tokio::io::AsyncSeekExt;
use tokio::io::AsyncWriteExt;
if entry_data.len() != entry::ENTRY_SIZE {
return Err(format!(
"bad entry size, expected {}, got {}",
entry::ENTRY_SIZE,
entry_data.len(),
)
.into());
}
let entry_count = query_entry_count(store_file).await?;
let start_loc = entry_count * entry::ENTRY_SIZE as u64;
store_file
.seek(std::io::SeekFrom::Start(start_loc))
.await
.map_err(LairError::other)?;
store_file
.write_all(&entry_data)
.await
.map_err(LairError::other)?;
store_file.sync_all().await.map_err(LairError::other)?;
Ok((entry_count as u32).into())
}
| 27.668293 | 78 | 0.573166 |
096716ccb37a595c117ee36431a2e74c9f8d9c40 | 4,169 | #![crate_name = "uu_tr"]
#![feature(io)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <[email protected]>
* (c) kwantam <[email protected]>
* 20150428 created `expand` module to eliminate most allocs during setup
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate bit_set;
extern crate getopts;
extern crate vec_map;
#[macro_use]
extern crate uucore;
use bit_set::BitSet;
use getopts::Options;
use std::io::{stdin, stdout, BufReader, Read, Write};
use vec_map::VecMap;
use expand::ExpandSet;
mod expand;
static NAME: &'static str = "tr";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
const BUFFER_LEN: usize = 1024;
fn delete<'a>(set: ExpandSet<'a>, complement: bool) {
let mut bset = BitSet::new();
let mut stdout = stdout();
let mut buf = String::with_capacity(BUFFER_LEN + 4);
for c in set {
bset.insert(c as usize);
}
let is_allowed = |c : char| {
if complement {
bset.contains(&(c as usize))
} else {
!bset.contains(&(c as usize))
}
};
for c in BufReader::new(stdin()).chars() {
match c {
Ok(c) if is_allowed(c) => buf.push(c),
Ok(_) => (),
Err(err) => panic!("{}", err),
};
if buf.len() >= BUFFER_LEN {
safe_unwrap!(stdout.write_all(&buf[..].as_bytes()));
}
}
if buf.len() > 0 {
safe_unwrap!(stdout.write_all(&buf[..].as_bytes()));
pipe_flush!();
}
}
fn tr<'a>(set1: ExpandSet<'a>, mut set2: ExpandSet<'a>) {
let mut map = VecMap::new();
let mut stdout = stdout();
let mut buf = String::with_capacity(BUFFER_LEN + 4);
let mut s2_prev = '_';
for i in set1 {
s2_prev = set2.next().unwrap_or(s2_prev);
map.insert(i as usize, s2_prev);
}
for c in BufReader::new(stdin()).chars() {
match c {
Ok(inc) => {
let trc = match map.get(&(inc as usize)) {
Some(t) => *t,
None => inc,
};
buf.push(trc);
if buf.len() >= BUFFER_LEN {
safe_unwrap!(stdout.write_all(&buf[..].as_bytes()));
buf.truncate(0);
}
}
Err(err) => {
panic!("{}", err);
}
}
}
if buf.len() > 0 {
safe_unwrap!(stdout.write_all(&buf[..].as_bytes()));
pipe_flush!();
}
}
fn usage(opts: &Options) {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTIONS] SET1 [SET2]", NAME);
println!("");
println!("{}", opts.usage("Translate or delete characters."));
}
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = Options::new();
opts.optflag("c", "complement", "use the complement of SET1");
opts.optflag("C", "", "same as -c");
opts.optflag("d", "delete", "delete characters in SET1");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(err) => {
show_error!("{}", err);
return 1;
}
};
if matches.opt_present("help") {
usage(&opts);
return 0;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.free.len() == 0 {
usage(&opts);
return 1;
}
let dflag = matches.opt_present("d");
let cflag = matches.opts_present(&["c".to_string(), "C".to_string()]);
let sets = matches.free;
if cflag && !dflag {
show_error!("-c is only supported with -d");
return 1;
}
if dflag {
let set1 = ExpandSet::new(sets[0].as_ref());
delete(set1, cflag);
} else {
let set1 = ExpandSet::new(sets[0].as_ref());
let set2 = ExpandSet::new(sets[1].as_ref());
tr(set1, set2);
}
0
}
| 25.266667 | 77 | 0.524826 |
f419699b06df23f4a791cd7889c8ddaef55cd51a | 2,089 | use http::header::ACCEPT;
use mime::Mime;
use super::QualityItem;
header! {
/// `Accept` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.2)
///
/// The `Accept` header field can be used by user agents to specify
/// response media types that are acceptable. Accept header fields can
/// be used to indicate that the request is specifically limited to a
/// small set of desired types, as in the case of a request for an
/// in-line image
///
/// # ABNF
///
/// ```text
/// Accept = #( media-range [ accept-params ] )
///
/// media-range = ( "*/*"
/// / ( type "/" "*" )
/// / ( type "/" subtype )
/// ) *( OWS ";" OWS parameter )
/// accept-params = weight *( accept-ext )
/// accept-ext = OWS ";" OWS token [ "=" ( token / quoted-string ) ]
/// ```
///
/// # Example values
/// * `audio/*; q=0.2, audio/basic`
/// * `text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c`
(Accept, ACCEPT) => (QualityItem<Mime>)*
}
#[cfg(test)]
mod test {
use crate::{util, Quality, QualityItem};
use super::*;
#[test]
fn rfc1() {
util::test_round_trip(
&Accept(vec![
QualityItem::new("audio/*".parse().unwrap(), Quality::from_u16(200)),
QualityItem::new("audio/basic".parse().unwrap(), Quality::from_u16(1000)),
]),
&["audio/*; q=0.2, audio/basic"],
);
}
#[test]
fn rfc2() {
util::test_round_trip(
&Accept(vec![
QualityItem::new("text/plain".parse().unwrap(), Quality::from_u16(500)),
QualityItem::new("text/html".parse().unwrap(), Quality::from_u16(1000)),
QualityItem::new("text/x-dvi".parse().unwrap(), Quality::from_u16(800)),
QualityItem::new("text/x-c".parse().unwrap(), Quality::from_u16(1000)),
]),
&["text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c"],
);
}
}
| 32.640625 | 95 | 0.509335 |
48a53a62679d51fa7c468b48e5cf67681e2f0575 | 5,524 | #[doc = "Register `rf_singen_3` reader"]
pub struct R(crate::R<RF_SINGEN_3_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<RF_SINGEN_3_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<RF_SINGEN_3_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<RF_SINGEN_3_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `rf_singen_3` writer"]
pub struct W(crate::W<RF_SINGEN_3_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<RF_SINGEN_3_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<RF_SINGEN_3_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<RF_SINGEN_3_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `singen_start_addr0_q` reader - "]
pub struct SINGEN_START_ADDR0_Q_R(crate::FieldReader<u16, u16>);
impl SINGEN_START_ADDR0_Q_R {
pub(crate) fn new(bits: u16) -> Self {
SINGEN_START_ADDR0_Q_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SINGEN_START_ADDR0_Q_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `singen_start_addr0_q` writer - "]
pub struct SINGEN_START_ADDR0_Q_W<'a> {
w: &'a mut W,
}
impl<'a> SINGEN_START_ADDR0_Q_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03ff << 22)) | ((value as u32 & 0x03ff) << 22);
self.w
}
}
#[doc = "Field `singen_start_addr1_q` reader - "]
pub struct SINGEN_START_ADDR1_Q_R(crate::FieldReader<u16, u16>);
impl SINGEN_START_ADDR1_Q_R {
pub(crate) fn new(bits: u16) -> Self {
SINGEN_START_ADDR1_Q_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SINGEN_START_ADDR1_Q_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `singen_start_addr1_q` writer - "]
pub struct SINGEN_START_ADDR1_Q_W<'a> {
w: &'a mut W,
}
impl<'a> SINGEN_START_ADDR1_Q_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03ff << 12)) | ((value as u32 & 0x03ff) << 12);
self.w
}
}
#[doc = "Field `singen_gain_q` reader - "]
pub struct SINGEN_GAIN_Q_R(crate::FieldReader<u16, u16>);
impl SINGEN_GAIN_Q_R {
pub(crate) fn new(bits: u16) -> Self {
SINGEN_GAIN_Q_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SINGEN_GAIN_Q_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `singen_gain_q` writer - "]
pub struct SINGEN_GAIN_Q_W<'a> {
w: &'a mut W,
}
impl<'a> SINGEN_GAIN_Q_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07ff) | (value as u32 & 0x07ff);
self.w
}
}
impl R {
#[doc = "Bits 22:31"]
#[inline(always)]
pub fn singen_start_addr0_q(&self) -> SINGEN_START_ADDR0_Q_R {
SINGEN_START_ADDR0_Q_R::new(((self.bits >> 22) & 0x03ff) as u16)
}
#[doc = "Bits 12:21"]
#[inline(always)]
pub fn singen_start_addr1_q(&self) -> SINGEN_START_ADDR1_Q_R {
SINGEN_START_ADDR1_Q_R::new(((self.bits >> 12) & 0x03ff) as u16)
}
#[doc = "Bits 0:10"]
#[inline(always)]
pub fn singen_gain_q(&self) -> SINGEN_GAIN_Q_R {
SINGEN_GAIN_Q_R::new((self.bits & 0x07ff) as u16)
}
}
impl W {
#[doc = "Bits 22:31"]
#[inline(always)]
pub fn singen_start_addr0_q(&mut self) -> SINGEN_START_ADDR0_Q_W {
SINGEN_START_ADDR0_Q_W { w: self }
}
#[doc = "Bits 12:21"]
#[inline(always)]
pub fn singen_start_addr1_q(&mut self) -> SINGEN_START_ADDR1_Q_W {
SINGEN_START_ADDR1_Q_W { w: self }
}
#[doc = "Bits 0:10"]
#[inline(always)]
pub fn singen_gain_q(&mut self) -> SINGEN_GAIN_Q_W {
SINGEN_GAIN_Q_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "rf_singen_3.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [rf_singen_3](index.html) module"]
pub struct RF_SINGEN_3_SPEC;
impl crate::RegisterSpec for RF_SINGEN_3_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [rf_singen_3::R](R) reader structure"]
impl crate::Readable for RF_SINGEN_3_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [rf_singen_3::W](W) writer structure"]
impl crate::Writable for RF_SINGEN_3_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets rf_singen_3 to value 0"]
impl crate::Resettable for RF_SINGEN_3_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 31.565714 | 404 | 0.61966 |
23dc8e8f8933dc35380cb776dfcd62d473fbbf4c | 2,525 | use optarg2chain::*;
#[optarg_fn(JoinStringBuilder, exec)]
fn join_strings(
mut a: String,
#[optarg_default] b: String,
#[optarg("ccc".to_owned())] c: String,
) -> String {
a.push_str(&b);
a.push_str(&c);
a
}
#[test]
fn join_strings_test() {
assert_eq!(join_strings("aaa".to_owned()).exec(), "aaaccc");
assert_eq!(
join_strings("xxx".to_owned())
.b("yyy".to_owned())
.c("zzz".to_owned())
.exec(),
"xxxyyyzzz"
);
}
#[optarg_fn(JoinVecBuilder, exec)]
fn join_vecs<T>(
mut a: Vec<T>,
#[optarg_default] mut b: Vec<T>,
#[optarg(vec![T::default()])] mut c: Vec<T>,
) -> Vec<T>
where
T: Default,
{
a.append(&mut b);
a.append(&mut c);
a
}
#[test]
fn join_vec_test() {
assert_eq!(join_vecs(vec![3, 2, 1]).exec(), [3, 2, 1, 0]);
assert_eq!(
join_vecs(vec![2, 3, 5])
.b(vec![7, 9])
.c(vec![11, 13])
.exec(),
[2, 3, 5, 7, 9, 11, 13]
);
}
#[optarg_fn(ConvertBuilder, exec)]
fn add_and_convert<T: Default, R>(a: T, #[optarg_default] b: T) -> R
where
T: core::ops::Add<Output = T>,
R: From<T>,
{
(a + b).into()
}
#[test]
fn add_and_convert_test() {
assert_eq!(add_and_convert::<i8, i32>(1).b(2).exec(), 3i32);
assert_eq!(add_and_convert::<u8, u32>(42).exec(), 42u32);
}
#[optarg_fn(EmptyArg, exec)]
fn empty_arg() -> i32 {
42
}
#[test]
fn empty_arg_test() {
assert_eq!(empty_arg().exec(), 42);
}
#[optarg_fn(Convert, get)]
fn convert<T: Into<U> + Default, U>(#[optarg_default] target: T) -> U {
target.into()
}
#[test]
fn convert_test() {
assert_eq!(convert::<i8, i32>().get(), 0i32);
assert_eq!(convert::<i8, i32>().target(42i8).get(), 42i32);
}
#[optarg_fn(IterImplTrait, iter)]
fn iter_impl_trait<T: Default>(
#[optarg_default] a: T,
#[optarg_default] b: T,
#[optarg_default] c: T,
) -> impl Iterator<Item = T> {
vec![a, b, c].into_iter()
}
#[test]
fn convert_impl_trait_test() {
let iter = iter_impl_trait::<i32>().iter();
assert_eq!(iter.collect::<Vec<i32>>(), vec![0, 0, 0]);
let iter = iter_impl_trait::<i32>().a(1).b(2).c(3).iter();
assert_eq!(iter.collect::<Vec<i32>>(), vec![1, 2, 3]);
}
#[optarg_fn(Async, exec)]
async fn async_fn<'a>(#[optarg("foo")] a: &'a str) -> &'a str {
a
}
#[test]
fn async_test() {
use futures::executor::block_on;
assert_eq!(block_on(async_fn().exec()), "foo");
assert_eq!(block_on(async_fn().a("bar").exec()), "bar");
}
| 21.767241 | 71 | 0.560396 |
fc52f46a5141a3fdae1b8596817c1420bf8da406 | 31,179 | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! [Flexible target specification.](https://github.com/rust-lang/rfcs/pull/131)
//!
//! Rust targets a wide variety of usecases, and in the interest of flexibility,
//! allows new target triples to be defined in configuration files. Most users
//! will not need to care about these, but this is invaluable when porting Rust
//! to a new platform, and allows for an unprecedented level of control over how
//! the compiler works.
//!
//! # Using custom targets
//!
//! A target triple, as passed via `rustc --target=TRIPLE`, will first be
//! compared against the list of built-in targets. This is to ease distributing
//! rustc (no need for configuration files) and also to hold these built-in
//! targets as immutable and sacred. If `TRIPLE` is not one of the built-in
//! targets, rustc will check if a file named `TRIPLE` exists. If it does, it
//! will be loaded as the target configuration. If the file does not exist,
//! rustc will search each directory in the environment variable
//! `RUST_TARGET_PATH` for a file named `TRIPLE.json`. The first one found will
//! be loaded. If no file is found in any of those directories, a fatal error
//! will be given.
//!
//! Projects defining their own targets should use
//! `--target=path/to/my-awesome-platform.json` instead of adding to
//! `RUST_TARGET_PATH`.
//!
//! # Defining a new target
//!
//! Targets are defined using [JSON](http://json.org/). The `Target` struct in
//! this module defines the format the JSON file should take, though each
//! underscore in the field names should be replaced with a hyphen (`-`) in the
//! JSON file. Some fields are required in every target specification, such as
//! `llvm-target`, `target-endian`, `target-pointer-width`, `data-layout`,
//! `arch`, and `os`. In general, options passed to rustc with `-C` override
//! the target's settings, though `target-feature` and `link-args` will *add*
//! to the list specified by the target, rather than replace.
use serialize::json::{Json, ToJson};
use std::collections::BTreeMap;
use std::default::Default;
use std::io::prelude::*;
use syntax::abi::{Abi, lookup as lookup_abi};
use PanicStrategy;
mod android_base;
mod apple_base;
mod apple_ios_base;
mod arm_base;
mod bitrig_base;
mod dragonfly_base;
mod freebsd_base;
mod haiku_base;
mod linux_base;
mod linux_musl_base;
mod openbsd_base;
mod netbsd_base;
mod solaris_base;
mod windows_base;
mod windows_msvc_base;
mod thumb_base;
mod fuchsia_base;
pub type TargetResult = Result<Target, String>;
macro_rules! supported_targets {
( $(($triple:expr, $module:ident),)+ ) => (
$(mod $module;)*
/// List of supported targets
const TARGETS: &'static [&'static str] = &[$($triple),*];
fn load_specific(target: &str) -> TargetResult {
match target {
$(
$triple => {
let mut t = $module::target()?;
t.options.is_builtin = true;
// round-trip through the JSON parser to ensure at
// run-time that the parser works correctly
t = Target::from_json(t.to_json())?;
debug!("Got builtin target: {:?}", t);
Ok(t)
},
)+
_ => Err(format!("Unable to find target: {}", target))
}
}
pub fn get_targets() -> Box<Iterator<Item=String>> {
Box::new(TARGETS.iter().filter_map(|t| -> Option<String> {
load_specific(t)
.and(Ok(t.to_string()))
.ok()
}))
}
#[cfg(test)]
mod test_json_encode_decode {
use serialize::json::ToJson;
use super::Target;
$(use super::$module;)*
$(
#[test]
fn $module() {
// Grab the TargetResult struct. If we successfully retrieved
// a Target, then the test JSON encoding/decoding can run for this
// Target on this testing platform (i.e., checking the iOS targets
// only on a Mac test platform).
let _ = $module::target().map(|original| {
let as_json = original.to_json();
let parsed = Target::from_json(as_json).unwrap();
assert_eq!(original, parsed);
});
}
)*
}
)
}
supported_targets! {
("x86_64-unknown-linux-gnu", x86_64_unknown_linux_gnu),
("i686-unknown-linux-gnu", i686_unknown_linux_gnu),
("i586-unknown-linux-gnu", i586_unknown_linux_gnu),
("mips-unknown-linux-gnu", mips_unknown_linux_gnu),
("mips64-unknown-linux-gnuabi64", mips64_unknown_linux_gnuabi64),
("mips64el-unknown-linux-gnuabi64", mips64el_unknown_linux_gnuabi64),
("mipsel-unknown-linux-gnu", mipsel_unknown_linux_gnu),
("powerpc-unknown-linux-gnu", powerpc_unknown_linux_gnu),
("powerpc64-unknown-linux-gnu", powerpc64_unknown_linux_gnu),
("powerpc64le-unknown-linux-gnu", powerpc64le_unknown_linux_gnu),
("s390x-unknown-linux-gnu", s390x_unknown_linux_gnu),
("arm-unknown-linux-gnueabi", arm_unknown_linux_gnueabi),
("arm-unknown-linux-gnueabihf", arm_unknown_linux_gnueabihf),
("arm-unknown-linux-musleabi", arm_unknown_linux_musleabi),
("arm-unknown-linux-musleabihf", arm_unknown_linux_musleabihf),
("armv7-unknown-linux-gnueabihf", armv7_unknown_linux_gnueabihf),
("armv7-unknown-linux-musleabihf", armv7_unknown_linux_musleabihf),
("aarch64-unknown-linux-gnu", aarch64_unknown_linux_gnu),
("x86_64-unknown-linux-musl", x86_64_unknown_linux_musl),
("i686-unknown-linux-musl", i686_unknown_linux_musl),
("mips-unknown-linux-musl", mips_unknown_linux_musl),
("mipsel-unknown-linux-musl", mipsel_unknown_linux_musl),
("mips-unknown-linux-uclibc", mips_unknown_linux_uclibc),
("mipsel-unknown-linux-uclibc", mipsel_unknown_linux_uclibc),
("i686-linux-android", i686_linux_android),
("arm-linux-androideabi", arm_linux_androideabi),
("armv7-linux-androideabi", armv7_linux_androideabi),
("aarch64-linux-android", aarch64_linux_android),
("i686-unknown-freebsd", i686_unknown_freebsd),
("x86_64-unknown-freebsd", x86_64_unknown_freebsd),
("i686-unknown-dragonfly", i686_unknown_dragonfly),
("x86_64-unknown-dragonfly", x86_64_unknown_dragonfly),
("x86_64-unknown-bitrig", x86_64_unknown_bitrig),
("x86_64-unknown-openbsd", x86_64_unknown_openbsd),
("x86_64-unknown-netbsd", x86_64_unknown_netbsd),
("x86_64-rumprun-netbsd", x86_64_rumprun_netbsd),
("i686-unknown-haiku", i686_unknown_haiku),
("x86_64-unknown-haiku", x86_64_unknown_haiku),
("x86_64-apple-darwin", x86_64_apple_darwin),
("i686-apple-darwin", i686_apple_darwin),
("x86_64-unknown-fuchsia", x86_64_unknown_fuchsia),
("i386-apple-ios", i386_apple_ios),
("x86_64-apple-ios", x86_64_apple_ios),
("aarch64-apple-ios", aarch64_apple_ios),
("armv7-apple-ios", armv7_apple_ios),
("armv7s-apple-ios", armv7s_apple_ios),
("x86_64-sun-solaris", x86_64_sun_solaris),
("x86_64-pc-windows-gnu", x86_64_pc_windows_gnu),
("i686-pc-windows-gnu", i686_pc_windows_gnu),
("x86_64-pc-windows-msvc", x86_64_pc_windows_msvc),
("i686-pc-windows-msvc", i686_pc_windows_msvc),
("i586-pc-windows-msvc", i586_pc_windows_msvc),
("le32-unknown-nacl", le32_unknown_nacl),
("asmjs-unknown-emscripten", asmjs_unknown_emscripten),
("wasm32-unknown-emscripten", wasm32_unknown_emscripten),
("thumbv6m-none-eabi", thumbv6m_none_eabi),
("thumbv7m-none-eabi", thumbv7m_none_eabi),
("thumbv7em-none-eabi", thumbv7em_none_eabi),
("thumbv7em-none-eabihf", thumbv7em_none_eabihf),
}
/// Everything `rustc` knows about how to compile for a specific target.
///
/// Every field here must be specified, and has no default value.
#[derive(PartialEq, Clone, Debug)]
pub struct Target {
/// Target triple to pass to LLVM.
pub llvm_target: String,
/// String to use as the `target_endian` `cfg` variable.
pub target_endian: String,
/// String to use as the `target_pointer_width` `cfg` variable.
pub target_pointer_width: String,
/// OS name to use for conditional compilation.
pub target_os: String,
/// Environment name to use for conditional compilation.
pub target_env: String,
/// Vendor name to use for conditional compilation.
pub target_vendor: String,
/// Architecture to use for ABI considerations. Valid options: "x86",
/// "x86_64", "arm", "aarch64", "mips", "powerpc", and "powerpc64".
pub arch: String,
/// [Data layout](http://llvm.org/docs/LangRef.html#data-layout) to pass to LLVM.
pub data_layout: String,
/// Optional settings with defaults.
pub options: TargetOptions,
}
/// Optional aspects of a target specification.
///
/// This has an implementation of `Default`, see each field for what the default is. In general,
/// these try to take "minimal defaults" that don't assume anything about the runtime they run in.
#[derive(PartialEq, Clone, Debug)]
pub struct TargetOptions {
/// Whether the target is built-in or loaded from a custom target specification.
pub is_builtin: bool,
/// Linker to invoke. Defaults to "cc".
pub linker: String,
/// Archive utility to use when managing archives. Defaults to "ar".
pub ar: String,
/// Linker arguments that are unconditionally passed *before* any
/// user-defined libraries.
pub pre_link_args: Vec<String>,
/// Objects to link before all others, always found within the
/// sysroot folder.
pub pre_link_objects_exe: Vec<String>, // ... when linking an executable
pub pre_link_objects_dll: Vec<String>, // ... when linking a dylib
/// Linker arguments that are unconditionally passed after any
/// user-defined but before post_link_objects. Standard platform
/// libraries that should be always be linked to, usually go here.
pub late_link_args: Vec<String>,
/// Objects to link after all others, always found within the
/// sysroot folder.
pub post_link_objects: Vec<String>,
/// Linker arguments that are unconditionally passed *after* any
/// user-defined libraries.
pub post_link_args: Vec<String>,
/// Default CPU to pass to LLVM. Corresponds to `llc -mcpu=$cpu`. Defaults
/// to "generic".
pub cpu: String,
/// Default target features to pass to LLVM. These features will *always* be
/// passed, and cannot be disabled even via `-C`. Corresponds to `llc
/// -mattr=$features`.
pub features: String,
/// Whether dynamic linking is available on this target. Defaults to false.
pub dynamic_linking: bool,
/// Whether executables are available on this target. iOS, for example, only allows static
/// libraries. Defaults to false.
pub executables: bool,
/// Relocation model to use in object file. Corresponds to `llc
/// -relocation-model=$relocation_model`. Defaults to "pic".
pub relocation_model: String,
/// Code model to use. Corresponds to `llc -code-model=$code_model`. Defaults to "default".
pub code_model: String,
/// Do not emit code that uses the "red zone", if the ABI has one. Defaults to false.
pub disable_redzone: bool,
/// Eliminate frame pointers from stack frames if possible. Defaults to true.
pub eliminate_frame_pointer: bool,
/// Emit each function in its own section. Defaults to true.
pub function_sections: bool,
/// String to prepend to the name of every dynamic library. Defaults to "lib".
pub dll_prefix: String,
/// String to append to the name of every dynamic library. Defaults to ".so".
pub dll_suffix: String,
/// String to append to the name of every executable.
pub exe_suffix: String,
/// String to prepend to the name of every static library. Defaults to "lib".
pub staticlib_prefix: String,
/// String to append to the name of every static library. Defaults to ".a".
pub staticlib_suffix: String,
/// OS family to use for conditional compilation. Valid options: "unix", "windows".
pub target_family: Option<String>,
/// Whether the target toolchain is like OSX's. Only useful for compiling against iOS/OS X, in
/// particular running dsymutil and some other stuff like `-dead_strip`. Defaults to false.
pub is_like_osx: bool,
/// Whether the target toolchain is like Solaris's.
/// Only useful for compiling against Illumos/Solaris,
/// as they have a different set of linker flags. Defaults to false.
pub is_like_solaris: bool,
/// Whether the target toolchain is like Windows'. Only useful for compiling against Windows,
/// only really used for figuring out how to find libraries, since Windows uses its own
/// library naming convention. Defaults to false.
pub is_like_windows: bool,
pub is_like_msvc: bool,
/// Whether the target toolchain is like Android's. Only useful for compiling against Android.
/// Defaults to false.
pub is_like_android: bool,
/// Whether the linker support GNU-like arguments such as -O. Defaults to false.
pub linker_is_gnu: bool,
/// The MinGW toolchain has a known issue that prevents it from correctly
/// handling COFF object files with more than 2^15 sections. Since each weak
/// symbol needs its own COMDAT section, weak linkage implies a large
/// number sections that easily exceeds the given limit for larger
/// codebases. Consequently we want a way to disallow weak linkage on some
/// platforms.
pub allows_weak_linkage: bool,
/// Whether the linker support rpaths or not. Defaults to false.
pub has_rpath: bool,
/// Whether to disable linking to the default libraries, typically corresponds
/// to `-nodefaultlibs`. Defaults to true.
pub no_default_libraries: bool,
/// Dynamically linked executables can be compiled as position independent
/// if the default relocation model of position independent code is not
/// changed. This is a requirement to take advantage of ASLR, as otherwise
/// the functions in the executable are not randomized and can be used
/// during an exploit of a vulnerability in any code.
pub position_independent_executables: bool,
/// Format that archives should be emitted in. This affects whether we use
/// LLVM to assemble an archive or fall back to the system linker, and
/// currently only "gnu" is used to fall into LLVM. Unknown strings cause
/// the system linker to be used.
pub archive_format: String,
/// Is asm!() allowed? Defaults to true.
pub allow_asm: bool,
/// Whether the target uses a custom unwind resumption routine.
/// By default LLVM lowers `resume` instructions into calls to `_Unwind_Resume`
/// defined in libgcc. If this option is enabled, the target must provide
/// `eh_unwind_resume` lang item.
pub custom_unwind_resume: bool,
/// Default crate for allocation symbols to link against
pub lib_allocation_crate: String,
pub exe_allocation_crate: String,
/// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for
/// this target.
pub has_elf_tls: bool,
// This is mainly for easy compatibility with emscripten.
// If we give emcc .o files that are actually .bc files it
// will 'just work'.
pub obj_is_bitcode: bool,
/// Don't use this field; instead use the `.max_atomic_width()` method.
pub max_atomic_width: Option<u64>,
/// Panic strategy: "unwind" or "abort"
pub panic_strategy: PanicStrategy,
/// A blacklist of ABIs unsupported by the current target. Note that generic
/// ABIs are considered to be supported on all platforms and cannot be blacklisted.
pub abi_blacklist: Vec<Abi>,
}
impl Default for TargetOptions {
/// Create a set of "sane defaults" for any target. This is still
/// incomplete, and if used for compilation, will certainly not work.
fn default() -> TargetOptions {
TargetOptions {
is_builtin: false,
linker: option_env!("CFG_DEFAULT_LINKER").unwrap_or("cc").to_string(),
ar: option_env!("CFG_DEFAULT_AR").unwrap_or("ar").to_string(),
pre_link_args: Vec::new(),
post_link_args: Vec::new(),
cpu: "generic".to_string(),
features: "".to_string(),
dynamic_linking: false,
executables: false,
relocation_model: "pic".to_string(),
code_model: "default".to_string(),
disable_redzone: false,
eliminate_frame_pointer: true,
function_sections: true,
dll_prefix: "lib".to_string(),
dll_suffix: ".so".to_string(),
exe_suffix: "".to_string(),
staticlib_prefix: "lib".to_string(),
staticlib_suffix: ".a".to_string(),
target_family: None,
is_like_osx: false,
is_like_solaris: false,
is_like_windows: false,
is_like_android: false,
is_like_msvc: false,
linker_is_gnu: false,
allows_weak_linkage: true,
has_rpath: false,
no_default_libraries: true,
position_independent_executables: false,
pre_link_objects_exe: Vec::new(),
pre_link_objects_dll: Vec::new(),
post_link_objects: Vec::new(),
late_link_args: Vec::new(),
archive_format: "gnu".to_string(),
custom_unwind_resume: false,
lib_allocation_crate: "alloc_system".to_string(),
exe_allocation_crate: "alloc_system".to_string(),
allow_asm: true,
has_elf_tls: false,
obj_is_bitcode: false,
max_atomic_width: None,
panic_strategy: PanicStrategy::Unwind,
abi_blacklist: vec![],
}
}
}
impl Target {
/// Given a function ABI, turn "System" into the correct ABI for this target.
pub fn adjust_abi(&self, abi: Abi) -> Abi {
match abi {
Abi::System => {
if self.options.is_like_windows && self.arch == "x86" {
Abi::Stdcall
} else {
Abi::C
}
},
abi => abi
}
}
/// Maximum integer size in bits that this target can perform atomic
/// operations on.
pub fn max_atomic_width(&self) -> u64 {
self.options.max_atomic_width.unwrap_or(self.target_pointer_width.parse().unwrap())
}
pub fn is_abi_supported(&self, abi: Abi) -> bool {
abi.generic() || !self.options.abi_blacklist.contains(&abi)
}
/// Load a target descriptor from a JSON object.
pub fn from_json(obj: Json) -> TargetResult {
// While ugly, this code must remain this way to retain
// compatibility with existing JSON fields and the internal
// expected naming of the Target and TargetOptions structs.
// To ensure compatibility is retained, the built-in targets
// are round-tripped through this code to catch cases where
// the JSON parser is not updated to match the structs.
let get_req_field = |name: &str| {
match obj.find(name)
.map(|s| s.as_string())
.and_then(|os| os.map(|s| s.to_string())) {
Some(val) => Ok(val),
None => {
return Err(format!("Field {} in target specification is required", name))
}
}
};
let get_opt_field = |name: &str, default: &str| {
obj.find(name).and_then(|s| s.as_string())
.map(|s| s.to_string())
.unwrap_or(default.to_string())
};
let mut base = Target {
llvm_target: get_req_field("llvm-target")?,
target_endian: get_req_field("target-endian")?,
target_pointer_width: get_req_field("target-pointer-width")?,
data_layout: get_req_field("data-layout")?,
arch: get_req_field("arch")?,
target_os: get_req_field("os")?,
target_env: get_opt_field("env", ""),
target_vendor: get_opt_field("vendor", "unknown"),
options: Default::default(),
};
macro_rules! key {
($key_name:ident) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..]).map(|o| o.as_string()
.map(|s| base.options.$key_name = s.to_string()));
} );
($key_name:ident, bool) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..])
.map(|o| o.as_boolean()
.map(|s| base.options.$key_name = s));
} );
($key_name:ident, Option<u64>) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..])
.map(|o| o.as_u64()
.map(|s| base.options.$key_name = Some(s)));
} );
($key_name:ident, PanicStrategy) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..]).and_then(|o| o.as_string().and_then(|s| {
match s {
"unwind" => base.options.$key_name = PanicStrategy::Unwind,
"abort" => base.options.$key_name = PanicStrategy::Abort,
_ => return Some(Err(format!("'{}' is not a valid value for \
panic-strategy. Use 'unwind' or 'abort'.",
s))),
}
Some(Ok(()))
})).unwrap_or(Ok(()))
} );
($key_name:ident, list) => ( {
let name = (stringify!($key_name)).replace("_", "-");
obj.find(&name[..]).map(|o| o.as_array()
.map(|v| base.options.$key_name = v.iter()
.map(|a| a.as_string().unwrap().to_string()).collect()
)
);
} );
($key_name:ident, optional) => ( {
let name = (stringify!($key_name)).replace("_", "-");
if let Some(o) = obj.find(&name[..]) {
base.options.$key_name = o
.as_string()
.map(|s| s.to_string() );
}
} );
}
key!(is_builtin, bool);
key!(linker);
key!(ar);
key!(pre_link_args, list);
key!(pre_link_objects_exe, list);
key!(pre_link_objects_dll, list);
key!(late_link_args, list);
key!(post_link_objects, list);
key!(post_link_args, list);
key!(cpu);
key!(features);
key!(dynamic_linking, bool);
key!(executables, bool);
key!(relocation_model);
key!(code_model);
key!(disable_redzone, bool);
key!(eliminate_frame_pointer, bool);
key!(function_sections, bool);
key!(dll_prefix);
key!(dll_suffix);
key!(exe_suffix);
key!(staticlib_prefix);
key!(staticlib_suffix);
key!(target_family, optional);
key!(is_like_osx, bool);
key!(is_like_solaris, bool);
key!(is_like_windows, bool);
key!(is_like_msvc, bool);
key!(is_like_android, bool);
key!(linker_is_gnu, bool);
key!(allows_weak_linkage, bool);
key!(has_rpath, bool);
key!(no_default_libraries, bool);
key!(position_independent_executables, bool);
key!(archive_format);
key!(allow_asm, bool);
key!(custom_unwind_resume, bool);
key!(lib_allocation_crate);
key!(exe_allocation_crate);
key!(has_elf_tls, bool);
key!(obj_is_bitcode, bool);
key!(max_atomic_width, Option<u64>);
try!(key!(panic_strategy, PanicStrategy));
if let Some(array) = obj.find("abi-blacklist").and_then(Json::as_array) {
for name in array.iter().filter_map(|abi| abi.as_string()) {
match lookup_abi(name) {
Some(abi) => {
if abi.generic() {
return Err(format!("The ABI \"{}\" is considered to be supported on \
all targets and cannot be blacklisted", abi))
}
base.options.abi_blacklist.push(abi)
}
None => return Err(format!("Unknown ABI \"{}\" in target specification", name))
}
}
}
Ok(base)
}
/// Search RUST_TARGET_PATH for a JSON file specifying the given target
/// triple. Note that it could also just be a bare filename already, so also
/// check for that. If one of the hardcoded targets we know about, just
/// return it directly.
///
/// The error string could come from any of the APIs called, including
/// filesystem access and JSON decoding.
pub fn search(target: &str) -> Result<Target, String> {
use std::env;
use std::ffi::OsString;
use std::fs::File;
use std::path::{Path, PathBuf};
use serialize::json;
fn load_file(path: &Path) -> Result<Target, String> {
let mut f = File::open(path).map_err(|e| e.to_string())?;
let mut contents = Vec::new();
f.read_to_end(&mut contents).map_err(|e| e.to_string())?;
let obj = json::from_reader(&mut &contents[..])
.map_err(|e| e.to_string())?;
Target::from_json(obj)
}
if let Ok(t) = load_specific(target) {
return Ok(t)
}
let path = Path::new(target);
if path.is_file() {
return load_file(&path);
}
let path = {
let mut target = target.to_string();
target.push_str(".json");
PathBuf::from(target)
};
let target_path = env::var_os("RUST_TARGET_PATH")
.unwrap_or(OsString::new());
// FIXME 16351: add a sane default search path?
for dir in env::split_paths(&target_path) {
let p = dir.join(&path);
if p.is_file() {
return load_file(&p);
}
}
Err(format!("Could not find specification for target {:?}", target))
}
}
impl ToJson for Target {
fn to_json(&self) -> Json {
let mut d = BTreeMap::new();
let default: TargetOptions = Default::default();
macro_rules! target_val {
($attr:ident) => ( {
let name = (stringify!($attr)).replace("_", "-");
d.insert(name.to_string(), self.$attr.to_json());
} );
($attr:ident, $key_name:expr) => ( {
let name = $key_name;
d.insert(name.to_string(), self.$attr.to_json());
} );
}
macro_rules! target_option_val {
($attr:ident) => ( {
let name = (stringify!($attr)).replace("_", "-");
if default.$attr != self.options.$attr {
d.insert(name.to_string(), self.options.$attr.to_json());
}
} );
($attr:ident, $key_name:expr) => ( {
let name = $key_name;
if default.$attr != self.options.$attr {
d.insert(name.to_string(), self.options.$attr.to_json());
}
} );
}
target_val!(llvm_target);
target_val!(target_endian);
target_val!(target_pointer_width);
target_val!(arch);
target_val!(target_os, "os");
target_val!(target_env, "env");
target_val!(target_vendor, "vendor");
target_val!(arch);
target_val!(data_layout);
target_option_val!(is_builtin);
target_option_val!(linker);
target_option_val!(ar);
target_option_val!(pre_link_args);
target_option_val!(pre_link_objects_exe);
target_option_val!(pre_link_objects_dll);
target_option_val!(late_link_args);
target_option_val!(post_link_objects);
target_option_val!(post_link_args);
target_option_val!(cpu);
target_option_val!(features);
target_option_val!(dynamic_linking);
target_option_val!(executables);
target_option_val!(relocation_model);
target_option_val!(code_model);
target_option_val!(disable_redzone);
target_option_val!(eliminate_frame_pointer);
target_option_val!(function_sections);
target_option_val!(dll_prefix);
target_option_val!(dll_suffix);
target_option_val!(exe_suffix);
target_option_val!(staticlib_prefix);
target_option_val!(staticlib_suffix);
target_option_val!(target_family);
target_option_val!(is_like_osx);
target_option_val!(is_like_solaris);
target_option_val!(is_like_windows);
target_option_val!(is_like_msvc);
target_option_val!(is_like_android);
target_option_val!(linker_is_gnu);
target_option_val!(allows_weak_linkage);
target_option_val!(has_rpath);
target_option_val!(no_default_libraries);
target_option_val!(position_independent_executables);
target_option_val!(archive_format);
target_option_val!(allow_asm);
target_option_val!(custom_unwind_resume);
target_option_val!(lib_allocation_crate);
target_option_val!(exe_allocation_crate);
target_option_val!(has_elf_tls);
target_option_val!(obj_is_bitcode);
target_option_val!(max_atomic_width);
target_option_val!(panic_strategy);
if default.abi_blacklist != self.options.abi_blacklist {
d.insert("abi-blacklist".to_string(), self.options.abi_blacklist.iter()
.map(Abi::name).map(|name| name.to_json())
.collect::<Vec<_>>().to_json());
}
Json::Object(d)
}
}
fn maybe_jemalloc() -> String {
if cfg!(feature = "jemalloc") {
"alloc_jemalloc".to_string()
} else {
"alloc_system".to_string()
}
}
| 41.242063 | 99 | 0.609737 |
03df51ebf2c3ee4a9b97f501221974fb7129ca2e | 1,363 | use serde_json::Number;
#[derive(Serialize, Deserialize, Debug)]
pub struct GroupResponse {
pub id: Number,
pub name: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct ProjectResponse {
pub id: Number,
pub name: String,
pub ssh_url_to_repo: String,
pub http_url_to_repo: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct MergeRequestResponse {
pub id: Number,
pub title: String,
pub author: Author,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Author {
pub id: Number,
pub name: String,
pub username: String,
}
#[derive(Debug, Deserialize)]
pub struct MRResponse {
pub web_url: String,
}
#[derive(Debug, Serialize, Clone)]
pub struct MRPayload {
pub id: String,
pub title: String,
pub description: String,
pub source_branch: String,
pub target_branch: String,
pub labels: String,
pub remove_source_branch: bool,
pub squash: bool,
}
#[derive(Debug, Deserialize, Clone)]
pub struct Config {
pub group: Option<String>,
pub user: Option<String>,
pub mr_labels: Option<Vec<String>>,
}
#[derive(Debug, Serialize, Clone)]
pub struct MRRequest<'a> {
pub access_token: String,
pub project: &'a ProjectResponse,
pub title: String,
pub description: String,
pub source_branch: String,
pub target_branch: String,
}
| 21.296875 | 40 | 0.683786 |
0382a9beaf54cbafe57de408d0bbc833a63ce6b5 | 2,670 | // Copyright 2020 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Implements hex-encoding from bytes to string and decoding of strings
/// to bytes. Given that rustc-serialize is deprecated and serde doesn't
/// provide easy hex encoding, hex is a bit in limbo right now in Rust-
/// land. It's simple enough that we can just have our own.
use std::fmt::Write;
/// Encode the provided bytes into a hex string
pub fn to_hex(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for byte in bytes {
write!(&mut s, "{:02x}", byte).expect("Unable to write hex");
}
s
}
/// Convert to hex
pub trait ToHex {
/// convert to hex
fn to_hex(&self) -> String;
}
impl<T: AsRef<[u8]>> ToHex for T {
fn to_hex(&self) -> String {
to_hex(self.as_ref())
}
}
/// Decode a hex string into bytes.
pub fn from_hex(hex: &str) -> Result<Vec<u8>, String> {
let hex = hex.trim().trim_start_matches("0x");
if hex.len() % 2 != 0 {
Err(hex.to_string())
} else {
(0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16).map_err(|_| hex.to_string()))
.collect()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_to_hex() {
assert_eq!(vec![0, 0, 0, 0].to_hex(), "00000000");
assert_eq!(vec![10, 11, 12, 13].to_hex(), "0a0b0c0d");
assert_eq!([0, 0, 0, 255].to_hex(), "000000ff");
}
#[test]
fn test_to_hex_trait() {
assert_eq!(vec![0, 0, 0, 0].to_hex(), "00000000");
assert_eq!(vec![10, 11, 12, 13].to_hex(), "0a0b0c0d");
assert_eq!([0, 0, 0, 255].to_hex(), "000000ff");
}
#[test]
fn test_from_hex() {
assert_eq!(from_hex(""), Ok(vec![]));
assert_eq!(from_hex("00000000"), Ok(vec![0, 0, 0, 0]));
assert_eq!(from_hex("0a0b0c0d"), Ok(vec![10, 11, 12, 13]));
assert_eq!(from_hex("000000ff"), Ok(vec![0, 0, 0, 255]));
assert_eq!(from_hex("0x000000ff"), Ok(vec![0, 0, 0, 255]));
assert_eq!(from_hex("0x000000fF"), Ok(vec![0, 0, 0, 255]));
assert_eq!(from_hex("0x000000fg"), Err("000000fg".to_string()));
assert_eq!(
from_hex("not a hex string"),
Err("not a hex string".to_string())
);
assert_eq!(from_hex("0"), Err("0".to_string()));
}
}
| 30 | 80 | 0.646067 |
f8e4fd20ead43f91733ac2d7e687a6cfe2860ebf | 3,388 | use {
lewp::{
config::{ModuleConfig, PageConfig},
dom::{NodeCreator, Nodes},
module::{Module, Modules, RuntimeInformation},
page::Page,
Charset,
LanguageTag,
LewpError,
},
std::rc::Rc,
};
struct HelloWorld {
pub config: ModuleConfig,
head_tags: Nodes,
data: String,
}
impl HelloWorld {
pub fn new() -> Self {
Self {
config: ModuleConfig::new(),
head_tags: vec![],
data: String::from("hello-world"),
}
}
}
impl From<ModuleConfig> for HelloWorld {
fn from(config: ModuleConfig) -> Self {
Self {
config,
head_tags: vec![],
data: String::from("hello-world"),
}
}
}
impl Module for HelloWorld {
fn head_tags(&self) -> &Nodes {
&self.head_tags
}
fn id(&self) -> &str {
"hello-world"
}
fn config(&self) -> &ModuleConfig {
&self.config
}
fn run(
&mut self,
_runtime_info: Rc<RuntimeInformation>,
) -> Result<(), LewpError> {
Ok(())
}
fn view(&self) -> Nodes {
let headline = NodeCreator::headline(1, &self.data, vec![]);
vec![headline]
}
}
struct HelloWorldPage {
modules: Modules,
config: PageConfig,
}
impl Page for HelloWorldPage {
fn modules(&self) -> &Modules {
&self.modules
}
fn modules_mut(&mut self) -> &mut Modules {
&mut self.modules
}
fn title(&self) -> &str {
"Hello World from lewp!"
}
fn description(&self) -> &str {
"My first page using lewp!"
}
fn language(&self) -> LanguageTag {
LanguageTag::parse("de-DE").unwrap()
}
fn charset(&self) -> Charset {
Charset::Utf8
}
fn config(&self) -> &PageConfig {
&self.config
}
fn run(&mut self) {}
}
const HELLO_WORLD_RESULT: &str = "<!DOCTYPE html><html lang=\"de\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"><title>Hello World from lewp!</title><meta name=\"description\" content=\"My first page using lewp!\"></head><body><div class=\"hello-world\" data-lewp-component=\"module\"><h1>hello-world</h1></div></body></html>";
const HELLO_WORLD_RESULT_SKIPPED_WRAPPER: &str = "<!DOCTYPE html><html lang=\"de\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"><title>Hello World from lewp!</title><meta name=\"description\" content=\"My first page using lewp!\"></head><body><h1>hello-world</h1></body></html>";
#[test]
fn hello_world_with_module_wrapper() {
let module = HelloWorld::new();
let mut page = HelloWorldPage {
modules: vec![],
config: PageConfig::new(),
};
page.add_module(module.into_module_ptr());
let html_string = page.build();
assert_eq!(HELLO_WORLD_RESULT, html_string);
}
#[test]
fn hello_world_skipped_wrapper() {
let module_config = ModuleConfig { skip_wrapper: true };
let module = HelloWorld::from(module_config);
let mut page = HelloWorldPage {
modules: vec![],
config: PageConfig::new(),
};
page.add_module(module.into_module_ptr());
let html_string = page.build();
assert_eq!(HELLO_WORLD_RESULT_SKIPPED_WRAPPER, html_string);
}
| 26.263566 | 404 | 0.589433 |
f95df2caef9da54070a7bc64f2f4625db329620b | 1,609 | //! Temperature sensor interface.
use crate::pac::TEMP;
use fixed::types::I30F2;
use void::Void;
/// Integrated temperature sensor.
pub struct Temp(TEMP);
impl Temp {
/// Creates a new `Temp`, taking ownership of the temperature sensor's register block.
pub fn new(raw: TEMP) -> Self {
Temp(raw)
}
/// Starts a new measurement and blocks until completion.
///
/// If a measurement was already started, it will be canceled.
pub fn measure(&mut self) -> I30F2 {
self.stop_measurement();
self.start_measurement();
nb::block!(self.read()).unwrap()
}
/// Kicks off a temperature measurement.
///
/// The measurement can be retrieved by calling `read`.
pub fn start_measurement(&mut self) {
unsafe {
self.0.tasks_start.write(|w| w.bits(1));
}
}
/// Cancels an in-progress temperature measurement.
pub fn stop_measurement(&mut self) {
unsafe {
self.0.tasks_stop.write(|w| w.bits(1));
self.0.events_datardy.reset();
}
}
/// Tries to read a started measurement (non-blocking).
///
/// Before calling this, `start_measurement` must be called.
///
/// Returns the measured temperature in °C.
pub fn read(&mut self) -> nb::Result<I30F2, Void> {
if self.0.events_datardy.read().bits() == 0 {
Err(nb::Error::WouldBlock)
} else {
self.0.events_datardy.reset(); // clear event
let raw = self.0.temp.read().bits();
Ok(I30F2::from_bits(raw as i32))
}
}
}
| 27.741379 | 90 | 0.584214 |
5d34b784c3c0d5d652c91833be1e7d2ddada779a | 30,486 | //! Implements module serialization.
//!
//! This module implements the serialization format for `wasmtime::Module`.
//! This includes both the binary format of the final artifact as well as
//! validation on ingestion of artifacts.
//!
//! There are two main pieces of data associated with a binary artifact:
//!
//! 1. A list of compiled modules. The reason this is a list as opposed to one
//! singular module is that a module-linking module may encompass a number
//! of other modules.
//! 2. Compilation metadata shared by all modules, including the global
//! `TypeTables` information. This metadata is validated for compilation
//! settings and also has information shared by all modules (such as the
//! shared `TypeTables`).
//!
//! Compiled modules are, at this time, represented as an ELF file. This ELF
//! file contains all the necessary data needed to decode each individual
//! module, and conveniently also handles things like alignment so we can
//! actually directly `mmap` compilation artifacts from disk.
//!
//! With all this in mind, the current serialization format is as follows:
//!
//! * The first, primary, module starts the final artifact. This means that the
//! final artifact is actually, and conveniently, a valid ELF file. ELF files
//! don't place any restrictions on data coming after the ELF file itself,
//! so that's where everything else will go. Another reason for using this
//! format is that our compilation artifacts are then consumable by standard
//! debugging tools like `objdump` to poke around and see what's what.
//!
//! * Next, all other modules are encoded. Each module has its own alignment,
//! though, so modules aren't simply concatenated. Instead directly after an
//! ELF file there is a 64-bit little-endian integer which is the offset,
//! from the end of the previous ELF file, to the next ELF file.
//!
//! * Finally, once all modules have been encoded (there's always at least
//! one), the 8-byte value `u64::MAX` is encoded. Following this is a
//! number of fields:
//!
//! 1. The `HEADER` value
//! 2. A byte indicating how long the next field is
//! 3. A version string of the length of the previous byte value
//! 4. A `bincode`-encoded `Metadata` structure.
//!
//! This is hoped to help distinguish easily Wasmtime-based ELF files from
//! other random ELF files, as well as provide better error messages for
//! using wasmtime artifacts across versions.
//!
//! This format is implemented by the `to_bytes` and `from_mmap` function.
use crate::{Engine, Module, ModuleVersionStrategy};
use anyhow::{anyhow, bail, Context, Result};
use object::read::elf::FileHeader;
use object::{Bytes, File, Object, ObjectSection};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;
use wasmtime_environ::{FlagValue, Tunables};
use wasmtime_jit::{subslice_range, CompiledModule, CompiledModuleInfo, TypeTables};
use wasmtime_runtime::MmapVec;
const HEADER: &[u8] = b"\0wasmtime-aot";
// This exists because `wasmparser::WasmFeatures` isn't serializable
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
struct WasmFeatures {
pub reference_types: bool,
pub multi_value: bool,
pub bulk_memory: bool,
pub module_linking: bool,
pub simd: bool,
pub threads: bool,
pub tail_call: bool,
pub deterministic_only: bool,
pub multi_memory: bool,
pub exceptions: bool,
pub memory64: bool,
pub relaxed_simd: bool,
pub extended_const: bool,
}
impl From<&wasmparser::WasmFeatures> for WasmFeatures {
fn from(other: &wasmparser::WasmFeatures) -> Self {
let wasmparser::WasmFeatures {
reference_types,
multi_value,
bulk_memory,
module_linking,
simd,
threads,
tail_call,
deterministic_only,
multi_memory,
exceptions,
memory64,
relaxed_simd,
extended_const,
// Always on; we don't currently have knobs for these.
mutable_global: _,
saturating_float_to_int: _,
sign_extension: _,
} = *other;
Self {
reference_types,
multi_value,
bulk_memory,
module_linking,
simd,
threads,
tail_call,
deterministic_only,
multi_memory,
exceptions,
memory64,
relaxed_simd,
extended_const,
}
}
}
// This is like `std::borrow::Cow` but it doesn't have a `Clone` bound on `T`
enum MyCow<'a, T> {
Borrowed(&'a T),
Owned(T),
}
impl<'a, T> MyCow<'a, T> {
fn as_ref(&self) -> &T {
match self {
MyCow::Owned(val) => val,
MyCow::Borrowed(val) => val,
}
}
fn unwrap_owned(self) -> T {
match self {
MyCow::Owned(val) => val,
MyCow::Borrowed(_) => unreachable!(),
}
}
}
impl<'a, T: Serialize> Serialize for MyCow<'a, T> {
fn serialize<S>(&self, dst: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
match self {
MyCow::Borrowed(val) => val.serialize(dst),
MyCow::Owned(val) => val.serialize(dst),
}
}
}
impl<'a, 'b, T: Deserialize<'a>> Deserialize<'a> for MyCow<'b, T> {
fn deserialize<D>(src: D) -> Result<Self, D::Error>
where
D: serde::de::Deserializer<'a>,
{
Ok(MyCow::Owned(T::deserialize(src)?))
}
}
/// A small helper struct for serialized module upvars.
#[derive(Serialize, Deserialize)]
pub struct SerializedModuleUpvar {
/// The module's index into the compilation artifact.
pub index: usize,
/// Indexes into the list of all compilation artifacts for this module.
pub artifact_upvars: Vec<usize>,
/// Closed-over module values that are also needed for this module.
pub module_upvars: Vec<SerializedModuleUpvar>,
}
impl SerializedModuleUpvar {
pub fn new(module: &Module, artifacts: &[Arc<CompiledModule>]) -> Self {
// TODO: improve upon the linear searches in the artifact list
let index = artifacts
.iter()
.position(|a| Arc::as_ptr(a) == Arc::as_ptr(&module.inner.module))
.expect("module should be in artifacts list");
SerializedModuleUpvar {
index,
artifact_upvars: module
.inner
.artifact_upvars
.iter()
.map(|m| {
artifacts
.iter()
.position(|a| Arc::as_ptr(a) == Arc::as_ptr(m))
.expect("artifact should be in artifacts list")
})
.collect(),
module_upvars: module
.inner
.module_upvars
.iter()
.map(|m| SerializedModuleUpvar::new(m, artifacts))
.collect(),
}
}
}
pub struct SerializedModule<'a> {
artifacts: Vec<MyCow<'a, MmapVec>>,
metadata: Metadata<'a>,
}
#[derive(Serialize, Deserialize)]
struct Metadata<'a> {
target: String,
shared_flags: BTreeMap<String, FlagValue>,
isa_flags: BTreeMap<String, FlagValue>,
tunables: Tunables,
features: WasmFeatures,
module_upvars: Vec<SerializedModuleUpvar>,
types: MyCow<'a, TypeTables>,
}
impl<'a> SerializedModule<'a> {
#[cfg(compiler)]
pub fn new(module: &'a Module) -> Self {
let artifacts = module
.inner
.artifact_upvars
.iter()
.map(|m| MyCow::Borrowed(m.mmap()))
.chain(Some(MyCow::Borrowed(module.inner.module.mmap())))
.collect::<Vec<_>>();
let module_upvars = module
.inner
.module_upvars
.iter()
.map(|m| SerializedModuleUpvar::new(m, &module.inner.artifact_upvars))
.collect::<Vec<_>>();
Self::with_data(
module.engine(),
artifacts,
module_upvars,
MyCow::Borrowed(module.types()),
)
}
#[cfg(compiler)]
pub fn from_artifacts(
engine: &Engine,
artifacts: impl IntoIterator<Item = &'a MmapVec>,
types: &'a TypeTables,
) -> Self {
Self::with_data(
engine,
artifacts.into_iter().map(MyCow::Borrowed).collect(),
Vec::new(),
MyCow::Borrowed(types),
)
}
#[cfg(compiler)]
fn with_data(
engine: &Engine,
artifacts: Vec<MyCow<'a, MmapVec>>,
module_upvars: Vec<SerializedModuleUpvar>,
types: MyCow<'a, TypeTables>,
) -> Self {
Self {
artifacts,
metadata: Metadata {
target: engine.compiler().triple().to_string(),
shared_flags: engine.compiler().flags(),
isa_flags: engine.compiler().isa_flags(),
tunables: engine.config().tunables.clone(),
features: (&engine.config().features).into(),
module_upvars,
types,
},
}
}
pub fn into_module(self, engine: &Engine) -> Result<Module> {
let (main_module, modules, types, upvars) = self.into_parts(engine)?;
let modules = engine.run_maybe_parallel(modules, |(i, m)| {
CompiledModule::from_artifacts(
i,
m,
&*engine.config().profiler,
engine.unique_id_allocator(),
)
})?;
Module::from_parts(engine, modules, main_module, Arc::new(types), &upvars)
}
pub fn into_parts(
mut self,
engine: &Engine,
) -> Result<(
usize,
Vec<(MmapVec, Option<CompiledModuleInfo>)>,
TypeTables,
Vec<SerializedModuleUpvar>,
)> {
// Verify that the compilation settings in the engine match the
// compilation settings of the module that's being loaded.
self.check_triple(engine)?;
self.check_shared_flags(engine)?;
self.check_isa_flags(engine)?;
self.check_tunables(&engine.config().tunables)?;
self.check_features(&engine.config().features)?;
assert!(!self.artifacts.is_empty());
let modules = self.artifacts.into_iter().map(|i| (i.unwrap_owned(), None));
let main_module = modules.len() - 1;
Ok((
main_module,
modules.collect(),
self.metadata.types.unwrap_owned(),
self.metadata.module_upvars,
))
}
pub fn to_bytes(&self, version_strat: &ModuleVersionStrategy) -> Result<Vec<u8>> {
// First up, create a linked-ish list of ELF files. For more
// information on this format, see the doc comment on this module.
// The only semi-tricky bit here is that we leave an
// offset-to-the-next-file between each set of ELF files. The list
// is then terminated with `u64::MAX`.
let mut ret = Vec::new();
for (i, obj) in self.artifacts.iter().enumerate() {
// Anything after the first object needs to respect the alignment of
// the object's sections, so insert padding as necessary. Note that
// the +8 to the length here is to accomodate the size we'll write
// to get to the next object.
if i > 0 {
let obj = File::parse(&obj.as_ref()[..])?;
let align = obj.sections().map(|s| s.align()).max().unwrap_or(0).max(1);
let align = usize::try_from(align).unwrap();
let new_size = align_to(ret.len() + 8, align);
ret.extend_from_slice(&(new_size as u64).to_le_bytes());
ret.resize(new_size, 0);
}
ret.extend_from_slice(obj.as_ref());
}
ret.extend_from_slice(&[0xff; 8]);
// The last part of our artifact is the bincode-encoded `Metadata`
// section with a few other guards to help give better error messages.
ret.extend_from_slice(HEADER);
let version = match version_strat {
ModuleVersionStrategy::WasmtimeVersion => env!("CARGO_PKG_VERSION"),
ModuleVersionStrategy::Custom(c) => &c,
ModuleVersionStrategy::None => "",
};
// This precondition is checked in Config::module_version:
assert!(
version.len() < 256,
"package version must be less than 256 bytes"
);
ret.push(version.len() as u8);
ret.extend_from_slice(version.as_bytes());
bincode::serialize_into(&mut ret, &self.metadata)?;
Ok(ret)
}
pub fn from_bytes(bytes: &[u8], version_strat: &ModuleVersionStrategy) -> Result<Self> {
Self::from_mmap(MmapVec::from_slice(bytes)?, version_strat)
}
pub fn from_file(path: &Path, version_strat: &ModuleVersionStrategy) -> Result<Self> {
Self::from_mmap(
MmapVec::from_file(path).with_context(|| {
format!("failed to create file mapping for: {}", path.display())
})?,
version_strat,
)
}
pub fn from_mmap(mut mmap: MmapVec, version_strat: &ModuleVersionStrategy) -> Result<Self> {
// Artifacts always start with an ELF file, so read that first.
// Afterwards we continually read ELF files until we see the `u64::MAX`
// marker, meaning we've reached the end.
let first_module = read_file(&mut mmap)?;
let mut pos = first_module.len();
let mut artifacts = vec![MyCow::Owned(first_module)];
let metadata = loop {
if mmap.len() < 8 {
bail!("invalid serialized data");
}
let next_file_start = u64::from_le_bytes([
mmap[0], mmap[1], mmap[2], mmap[3], mmap[4], mmap[5], mmap[6], mmap[7],
]);
if next_file_start == u64::MAX {
mmap.drain(..8);
break mmap;
}
// Remove padding leading up to the next file
let next_file_start = usize::try_from(next_file_start).unwrap();
let _padding = mmap.drain(..next_file_start - pos);
let data = read_file(&mut mmap)?;
pos = next_file_start + data.len();
artifacts.push(MyCow::Owned(data));
};
// Once we've reached the end we parse a `Metadata` object. This has a
// few guards up front which we process first, and eventually this
// bottoms out in a `bincode::deserialize` call.
let metadata = metadata
.strip_prefix(HEADER)
.ok_or_else(|| anyhow!("bytes are not a compatible serialized wasmtime module"))?;
if metadata.is_empty() {
bail!("serialized data data is empty");
}
let version_len = metadata[0] as usize;
if metadata.len() < version_len + 1 {
bail!("serialized data is malformed");
}
match version_strat {
ModuleVersionStrategy::WasmtimeVersion => {
let version = std::str::from_utf8(&metadata[1..1 + version_len])?;
if version != env!("CARGO_PKG_VERSION") {
bail!(
"Module was compiled with incompatible Wasmtime version '{}'",
version
);
}
}
ModuleVersionStrategy::Custom(v) => {
let version = std::str::from_utf8(&metadata[1..1 + version_len])?;
if version != v {
bail!(
"Module was compiled with incompatible version '{}'",
version
);
}
}
ModuleVersionStrategy::None => { /* ignore the version info, accept all */ }
}
let metadata = bincode::deserialize::<Metadata>(&metadata[1 + version_len..])
.context("deserialize compilation artifacts")?;
return Ok(SerializedModule {
artifacts,
metadata,
});
/// This function will drain the beginning contents of `mmap` which
/// correspond to an ELF object file. The ELF file is only very lightly
/// validated.
///
/// The `mmap` passed in will be reset to just after the ELF file, and
/// the `MmapVec` returned represents the extend of the ELF file
/// itself.
fn read_file(mmap: &mut MmapVec) -> Result<MmapVec> {
use object::NativeEndian as NE;
// There's not actually a great utility for figuring out where
// the end of an ELF file is in the `object` crate. In lieu of that
// we build our own which leverages the format of ELF files, which
// is that the header comes first, that tells us where the section
// headers are, and for our ELF files the end of the file is the
// end of the section headers.
let mut bytes = Bytes(mmap);
let header = bytes
.read::<object::elf::FileHeader64<NE>>()
.map_err(|()| anyhow!("artifact truncated, can't read header"))?;
if !header.is_supported() {
bail!("invalid elf header");
}
let sections = header
.section_headers(NE, &mmap[..])
.context("failed to read section headers")?;
let range = subslice_range(object::bytes_of_slice(sections), mmap);
Ok(mmap.drain(..range.end))
}
}
fn check_triple(&self, engine: &Engine) -> Result<()> {
let engine_target = engine.target();
let module_target =
target_lexicon::Triple::from_str(&self.metadata.target).map_err(|e| anyhow!(e))?;
if module_target.architecture != engine_target.architecture {
bail!(
"Module was compiled for architecture '{}'",
module_target.architecture
);
}
if module_target.operating_system != engine_target.operating_system {
bail!(
"Module was compiled for operating system '{}'",
module_target.operating_system
);
}
Ok(())
}
fn check_shared_flags(&mut self, engine: &Engine) -> Result<()> {
for (name, val) in self.metadata.shared_flags.iter() {
engine
.check_compatible_with_shared_flag(name, val)
.map_err(|s| anyhow::Error::msg(s))
.context("compilation settings of module incompatible with native host")?;
}
Ok(())
}
fn check_isa_flags(&mut self, engine: &Engine) -> Result<()> {
for (name, val) in self.metadata.isa_flags.iter() {
engine
.check_compatible_with_isa_flag(name, val)
.map_err(|s| anyhow::Error::msg(s))
.context("compilation settings of module incompatible with native host")?;
}
Ok(())
}
fn check_int<T: Eq + std::fmt::Display>(found: T, expected: T, feature: &str) -> Result<()> {
if found == expected {
return Ok(());
}
bail!(
"Module was compiled with a {} of '{}' but '{}' is expected for the host",
feature,
found,
expected
);
}
fn check_bool(found: bool, expected: bool, feature: &str) -> Result<()> {
if found == expected {
return Ok(());
}
bail!(
"Module was compiled {} {} but it {} enabled for the host",
if found { "with" } else { "without" },
feature,
if expected { "is" } else { "is not" }
);
}
fn check_tunables(&mut self, other: &Tunables) -> Result<()> {
let Tunables {
static_memory_bound,
static_memory_offset_guard_size,
dynamic_memory_offset_guard_size,
generate_native_debuginfo,
parse_wasm_debuginfo,
interruptable,
consume_fuel,
epoch_interruption,
static_memory_bound_is_maximum,
guard_before_linear_memory,
// This doesn't affect compilation, it's just a runtime setting.
dynamic_memory_growth_reserve: _,
// This does technically affect compilation but modules with/without
// trap information can be loaded into engines with the opposite
// setting just fine (it's just a section in the compiled file and
// whether it's present or not)
generate_address_map: _,
} = self.metadata.tunables;
Self::check_int(
static_memory_bound,
other.static_memory_bound,
"static memory bound",
)?;
Self::check_int(
static_memory_offset_guard_size,
other.static_memory_offset_guard_size,
"static memory guard size",
)?;
Self::check_int(
dynamic_memory_offset_guard_size,
other.dynamic_memory_offset_guard_size,
"dynamic memory guard size",
)?;
Self::check_bool(
generate_native_debuginfo,
other.generate_native_debuginfo,
"debug information support",
)?;
Self::check_bool(
parse_wasm_debuginfo,
other.parse_wasm_debuginfo,
"WebAssembly backtrace support",
)?;
Self::check_bool(interruptable, other.interruptable, "interruption support")?;
Self::check_bool(consume_fuel, other.consume_fuel, "fuel support")?;
Self::check_bool(
epoch_interruption,
other.epoch_interruption,
"epoch interruption",
)?;
Self::check_bool(
static_memory_bound_is_maximum,
other.static_memory_bound_is_maximum,
"pooling allocation support",
)?;
Self::check_bool(
guard_before_linear_memory,
other.guard_before_linear_memory,
"guard before linear memory",
)?;
Ok(())
}
fn check_features(&mut self, other: &wasmparser::WasmFeatures) -> Result<()> {
let WasmFeatures {
reference_types,
multi_value,
bulk_memory,
module_linking,
simd,
threads,
tail_call,
deterministic_only,
multi_memory,
exceptions,
memory64,
relaxed_simd,
extended_const,
} = self.metadata.features;
Self::check_bool(
reference_types,
other.reference_types,
"WebAssembly reference types support",
)?;
Self::check_bool(
multi_value,
other.multi_value,
"WebAssembly multi-value support",
)?;
Self::check_bool(
bulk_memory,
other.bulk_memory,
"WebAssembly bulk memory support",
)?;
Self::check_bool(
module_linking,
other.module_linking,
"WebAssembly module linking support",
)?;
Self::check_bool(simd, other.simd, "WebAssembly SIMD support")?;
Self::check_bool(threads, other.threads, "WebAssembly threads support")?;
Self::check_bool(tail_call, other.tail_call, "WebAssembly tail-call support")?;
Self::check_bool(
deterministic_only,
other.deterministic_only,
"WebAssembly deterministic-only support",
)?;
Self::check_bool(
multi_memory,
other.multi_memory,
"WebAssembly multi-memory support",
)?;
Self::check_bool(
exceptions,
other.exceptions,
"WebAssembly exceptions support",
)?;
Self::check_bool(
memory64,
other.memory64,
"WebAssembly 64-bit memory support",
)?;
Self::check_bool(
extended_const,
other.extended_const,
"WebAssembly extended-const support",
)?;
Self::check_bool(
relaxed_simd,
other.relaxed_simd,
"WebAssembly relaxed-simd support",
)?;
Ok(())
}
}
/// Aligns the `val` specified up to `align`, which must be a power of two
fn align_to(val: usize, align: usize) -> usize {
debug_assert!(align.is_power_of_two());
(val + (align - 1)) & (!(align - 1))
}
#[cfg(test)]
mod test {
use super::*;
use crate::Config;
#[test]
fn test_architecture_mismatch() -> Result<()> {
let engine = Engine::default();
let module = Module::new(&engine, "(module)")?;
let mut serialized = SerializedModule::new(&module);
serialized.metadata.target = "unknown-generic-linux".to_string();
match serialized.into_module(&engine) {
Ok(_) => unreachable!(),
Err(e) => assert_eq!(
e.to_string(),
"Module was compiled for architecture 'unknown'",
),
}
Ok(())
}
#[test]
fn test_os_mismatch() -> Result<()> {
let engine = Engine::default();
let module = Module::new(&engine, "(module)")?;
let mut serialized = SerializedModule::new(&module);
serialized.metadata.target = format!(
"{}-generic-unknown",
target_lexicon::Triple::host().architecture
);
match serialized.into_module(&engine) {
Ok(_) => unreachable!(),
Err(e) => assert_eq!(
e.to_string(),
"Module was compiled for operating system 'unknown'",
),
}
Ok(())
}
#[test]
fn test_cranelift_flags_mismatch() -> Result<()> {
let engine = Engine::default();
let module = Module::new(&engine, "(module)")?;
let mut serialized = SerializedModule::new(&module);
serialized
.metadata
.shared_flags
.insert("avoid_div_traps".to_string(), FlagValue::Bool(false));
match serialized.into_module(&engine) {
Ok(_) => unreachable!(),
Err(e) => assert_eq!(
format!("{:?}", e),
"\
compilation settings of module incompatible with native host
Caused by:
setting \"avoid_div_traps\" is configured to Bool(false) which is not supported"
),
}
Ok(())
}
#[test]
fn test_isa_flags_mismatch() -> Result<()> {
let engine = Engine::default();
let module = Module::new(&engine, "(module)")?;
let mut serialized = SerializedModule::new(&module);
serialized
.metadata
.isa_flags
.insert("not_a_flag".to_string(), FlagValue::Bool(true));
match serialized.into_module(&engine) {
Ok(_) => unreachable!(),
Err(e) => assert_eq!(
format!("{:?}", e),
"\
compilation settings of module incompatible with native host
Caused by:
cannot test if target-specific flag \"not_a_flag\" is available at runtime",
),
}
Ok(())
}
#[test]
fn test_tunables_int_mismatch() -> Result<()> {
let engine = Engine::default();
let module = Module::new(&engine, "(module)")?;
let mut serialized = SerializedModule::new(&module);
serialized.metadata.tunables.static_memory_offset_guard_size = 0;
match serialized.into_module(&engine) {
Ok(_) => unreachable!(),
Err(e) => assert_eq!(e.to_string(), "Module was compiled with a static memory guard size of '0' but '2147483648' is expected for the host"),
}
Ok(())
}
#[test]
fn test_tunables_bool_mismatch() -> Result<()> {
let mut config = Config::new();
config.interruptable(true);
let engine = Engine::new(&config)?;
let module = Module::new(&engine, "(module)")?;
let mut serialized = SerializedModule::new(&module);
serialized.metadata.tunables.interruptable = false;
match serialized.into_module(&engine) {
Ok(_) => unreachable!(),
Err(e) => assert_eq!(
e.to_string(),
"Module was compiled without interruption support but it is enabled for the host"
),
}
let mut config = Config::new();
config.interruptable(false);
let engine = Engine::new(&config)?;
let module = Module::new(&engine, "(module)")?;
let mut serialized = SerializedModule::new(&module);
serialized.metadata.tunables.interruptable = true;
match serialized.into_module(&engine) {
Ok(_) => unreachable!(),
Err(e) => assert_eq!(
e.to_string(),
"Module was compiled with interruption support but it is not enabled for the host"
),
}
Ok(())
}
#[test]
fn test_feature_mismatch() -> Result<()> {
let mut config = Config::new();
config.wasm_simd(true);
let engine = Engine::new(&config)?;
let module = Module::new(&engine, "(module)")?;
let mut serialized = SerializedModule::new(&module);
serialized.metadata.features.simd = false;
match serialized.into_module(&engine) {
Ok(_) => unreachable!(),
Err(e) => assert_eq!(e.to_string(), "Module was compiled without WebAssembly SIMD support but it is enabled for the host"),
}
let mut config = Config::new();
config.wasm_simd(false);
let engine = Engine::new(&config)?;
let module = Module::new(&engine, "(module)")?;
let mut serialized = SerializedModule::new(&module);
serialized.metadata.features.simd = true;
match serialized.into_module(&engine) {
Ok(_) => unreachable!(),
Err(e) => assert_eq!(e.to_string(), "Module was compiled with WebAssembly SIMD support but it is not enabled for the host"),
}
Ok(())
}
}
| 34.06257 | 152 | 0.564489 |
233a7b8fcf8365007003f245ee9ff6ddb9a4ae02 | 2,266 | fn print(count: &mut usize, id: usize, layout: &layout::tree::LayoutR) {
*count += 1;
debug_println!("result: {:?} {:?} {:?}", *count, id, layout);
}
pub fn compute() {
let mut layout_tree = layout::tree::LayoutTree::default();
layout_tree.insert(
1,
0,
0,
layout::idtree::InsertType::Back,
layout::style::Style {
position_type: layout::style::PositionType::Absolute,
size: layout::geometry::Size {
width: layout::style::Dimension::Points(1920.0),
height: layout::style::Dimension::Points(1024.0),
},
..Default::default()
},
);
layout_tree.insert(
2,
1,
0,
layout::idtree::InsertType::Back,
layout::style::Style {
flex_direction: layout::style::FlexDirection::Column,
size: layout::geometry::Size {
width: layout::style::Dimension::Points(100f32),
height: layout::style::Dimension::Points(100f32),
..Default::default()
},
..Default::default()
},
);
layout_tree.insert(
3,
2,
0,
layout::idtree::InsertType::Back,
layout::style::Style {
size: layout::geometry::Size {
height: layout::style::Dimension::Points(10f32),
..Default::default()
},
position: layout::geometry::Rect {
top: layout::style::Dimension::Points(15f32),
..Default::default()
},
..Default::default()
},
);
layout_tree.insert(
4,
2,
0,
layout::idtree::InsertType::Back,
layout::style::Style {
size: layout::geometry::Size {
height: layout::style::Dimension::Points(10f32),
..Default::default()
},
position: layout::geometry::Rect {
top: layout::style::Dimension::Points(15f32),
..Default::default()
},
..Default::default()
},
);
layout_tree.compute(print, &mut 0);
}
| 31.472222 | 73 | 0.469109 |
e8c3dc49f39c21ed5d494e150f6d618094030f02 | 1,644 | // Copyright 2018-2020 Cargill Incorporated
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::UserStoreOperations;
use crate::biome::user::store::diesel::models::UserModel;
use crate::biome::user::store::diesel::schema::splinter_user;
use crate::biome::user::store::error::UserStoreError;
use diesel::{dsl::insert_into, prelude::*};
pub(in crate::biome::user) trait UserStoreAddUserOperation {
fn add_user(&self, user_model: UserModel) -> Result<(), UserStoreError>;
}
impl<'a, C> UserStoreAddUserOperation for UserStoreOperations<'a, C>
where
C: diesel::Connection,
<C as diesel::Connection>::Backend: diesel::backend::SupportsDefaultKeyword,
<C as diesel::Connection>::Backend: 'static,
{
fn add_user(&self, user_model: UserModel) -> Result<(), UserStoreError> {
insert_into(splinter_user::table)
.values(&vec![user_model])
.execute(self.conn)
.map(|_| ())
.map_err(|err| UserStoreError::OperationError {
context: "Failed to add user".to_string(),
source: Box::new(err),
})?;
Ok(())
}
}
| 37.363636 | 80 | 0.680049 |
29ea47603308f57491ae152a8be12f440384d3c0 | 14,191 | use log::*;
/// Cluster independent integration tests
///
/// All tests must start from an entry point and a funding keypair and
/// discover the rest of the network.
use rand::{thread_rng, Rng};
use rayon::prelude::*;
use solana_client::thin_client::create_client;
use solana_core::validator::ValidatorExit;
use solana_core::{
cluster_info::VALIDATOR_PORT_RANGE, consensus::VOTE_THRESHOLD_DEPTH, contact_info::ContactInfo,
gossip_service::discover_cluster,
};
use solana_ledger::{
blockstore::Blockstore,
entry::{Entry, EntrySlice},
};
use solana_sdk::{
client::SyncClient,
clock::{self, Slot, NUM_CONSECUTIVE_LEADER_SLOTS},
commitment_config::CommitmentConfig,
epoch_schedule::MINIMUM_SLOTS_PER_EPOCH,
hash::Hash,
poh_config::PohConfig,
pubkey::Pubkey,
signature::{Keypair, Signature, Signer},
system_transaction,
timing::duration_as_ms,
transport::TransportError,
};
use std::{
collections::{HashMap, HashSet},
path::Path,
sync::{Arc, RwLock},
thread::sleep,
time::{Duration, Instant},
};
/// Spend and verify from every node in the network
pub fn spend_and_verify_all_nodes<S: ::std::hash::BuildHasher + Sync + Send>(
entry_point_info: &ContactInfo,
funding_keypair: &Keypair,
nodes: usize,
ignore_nodes: HashSet<Pubkey, S>,
) {
let cluster_nodes = discover_cluster(&entry_point_info.gossip, nodes).unwrap();
assert!(cluster_nodes.len() >= nodes);
let ignore_nodes = Arc::new(ignore_nodes);
cluster_nodes.par_iter().for_each(|ingress_node| {
if ignore_nodes.contains(&ingress_node.id) {
return;
}
let random_keypair = Keypair::new();
let client = create_client(ingress_node.client_facing_addr(), VALIDATOR_PORT_RANGE);
let bal = client
.poll_get_balance_with_commitment(
&funding_keypair.pubkey(),
CommitmentConfig::processed(),
)
.expect("balance in source");
assert!(bal > 0);
let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::confirmed())
.unwrap();
let mut transaction =
system_transaction::transfer(&funding_keypair, &random_keypair.pubkey(), 1, blockhash);
let confs = VOTE_THRESHOLD_DEPTH + 1;
let sig = client
.retry_transfer_until_confirmed(&funding_keypair, &mut transaction, 10, confs)
.unwrap();
for validator in &cluster_nodes {
if ignore_nodes.contains(&validator.id) {
continue;
}
let client = create_client(validator.client_facing_addr(), VALIDATOR_PORT_RANGE);
client.poll_for_signature_confirmation(&sig, confs).unwrap();
}
});
}
pub fn verify_balances<S: ::std::hash::BuildHasher>(
expected_balances: HashMap<Pubkey, u64, S>,
node: &ContactInfo,
) {
let client = create_client(node.client_facing_addr(), VALIDATOR_PORT_RANGE);
for (pk, b) in expected_balances {
let bal = client
.poll_get_balance_with_commitment(&pk, CommitmentConfig::processed())
.expect("balance in source");
assert_eq!(bal, b);
}
}
pub fn send_many_transactions(
node: &ContactInfo,
funding_keypair: &Keypair,
max_tokens_per_transfer: u64,
num_txs: u64,
) -> HashMap<Pubkey, u64> {
let client = create_client(node.client_facing_addr(), VALIDATOR_PORT_RANGE);
let mut expected_balances = HashMap::new();
for _ in 0..num_txs {
let random_keypair = Keypair::new();
let bal = client
.poll_get_balance_with_commitment(
&funding_keypair.pubkey(),
CommitmentConfig::processed(),
)
.expect("balance in source");
assert!(bal > 0);
let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.unwrap();
let transfer_amount = thread_rng().gen_range(1, max_tokens_per_transfer);
let mut transaction = system_transaction::transfer(
&funding_keypair,
&random_keypair.pubkey(),
transfer_amount,
blockhash,
);
client
.retry_transfer(&funding_keypair, &mut transaction, 5)
.unwrap();
expected_balances.insert(random_keypair.pubkey(), transfer_amount);
}
expected_balances
}
pub fn verify_ledger_ticks(ledger_path: &Path, ticks_per_slot: usize) {
let ledger = Blockstore::open(ledger_path).unwrap();
let zeroth_slot = ledger.get_slot_entries(0, 0).unwrap();
let last_id = zeroth_slot.last().unwrap().hash;
let next_slots = ledger.get_slots_since(&[0]).unwrap().remove(&0).unwrap();
let mut pending_slots: Vec<_> = next_slots
.into_iter()
.map(|slot| (slot, 0, last_id))
.collect();
while !pending_slots.is_empty() {
let (slot, parent_slot, last_id) = pending_slots.pop().unwrap();
let next_slots = ledger
.get_slots_since(&[slot])
.unwrap()
.remove(&slot)
.unwrap();
// If you're not the last slot, you should have a full set of ticks
let should_verify_ticks = if !next_slots.is_empty() {
Some((slot - parent_slot) as usize * ticks_per_slot)
} else {
None
};
let last_id = verify_slot_ticks(&ledger, slot, &last_id, should_verify_ticks);
pending_slots.extend(
next_slots
.into_iter()
.map(|child_slot| (child_slot, slot, last_id)),
);
}
}
pub fn sleep_n_epochs(
num_epochs: f64,
config: &PohConfig,
ticks_per_slot: u64,
slots_per_epoch: u64,
) {
let num_ticks_per_second = (1000 / duration_as_ms(&config.target_tick_duration)) as f64;
let num_ticks_to_sleep = num_epochs * ticks_per_slot as f64 * slots_per_epoch as f64;
let secs = ((num_ticks_to_sleep + num_ticks_per_second - 1.0) / num_ticks_per_second) as u64;
warn!("sleep_n_epochs: {} seconds", secs);
sleep(Duration::from_secs(secs));
}
pub fn kill_entry_and_spend_and_verify_rest(
entry_point_info: &ContactInfo,
entry_point_validator_exit: &Arc<RwLock<ValidatorExit>>,
funding_keypair: &Keypair,
nodes: usize,
slot_millis: u64,
) {
info!("kill_entry_and_spend_and_verify_rest...");
let cluster_nodes = discover_cluster(&entry_point_info.gossip, nodes).unwrap();
assert!(cluster_nodes.len() >= nodes);
let client = create_client(entry_point_info.client_facing_addr(), VALIDATOR_PORT_RANGE);
// sleep long enough to make sure we are in epoch 3
let first_two_epoch_slots = MINIMUM_SLOTS_PER_EPOCH * (3 + 1);
for ingress_node in &cluster_nodes {
client
.poll_get_balance_with_commitment(&ingress_node.id, CommitmentConfig::processed())
.unwrap_or_else(|err| panic!("Node {} has no balance: {}", ingress_node.id, err));
}
info!("sleeping for 2 leader fortnights");
sleep(Duration::from_millis(
slot_millis * first_two_epoch_slots as u64,
));
info!("done sleeping for first 2 warmup epochs");
info!("killing entry point: {}", entry_point_info.id);
entry_point_validator_exit.write().unwrap().exit();
info!("sleeping for some time");
sleep(Duration::from_millis(
slot_millis * NUM_CONSECUTIVE_LEADER_SLOTS,
));
info!("done sleeping for 2 fortnights");
for ingress_node in &cluster_nodes {
if ingress_node.id == entry_point_info.id {
info!("ingress_node.id == entry_point_info.id, continuing...");
continue;
}
let client = create_client(ingress_node.client_facing_addr(), VALIDATOR_PORT_RANGE);
let balance = client
.poll_get_balance_with_commitment(
&funding_keypair.pubkey(),
CommitmentConfig::processed(),
)
.expect("balance in source");
assert_ne!(balance, 0);
let mut result = Ok(());
let mut retries = 0;
loop {
retries += 1;
if retries > 5 {
result.unwrap();
}
let random_keypair = Keypair::new();
let (blockhash, _fee_calculator, _last_valid_slot) = client
.get_recent_blockhash_with_commitment(CommitmentConfig::processed())
.unwrap();
let mut transaction = system_transaction::transfer(
&funding_keypair,
&random_keypair.pubkey(),
1,
blockhash,
);
let confs = VOTE_THRESHOLD_DEPTH + 1;
let sig = {
let sig = client.retry_transfer_until_confirmed(
&funding_keypair,
&mut transaction,
5,
confs,
);
match sig {
Err(e) => {
result = Err(e);
continue;
}
Ok(sig) => sig,
}
};
info!("poll_all_nodes_for_signature()");
match poll_all_nodes_for_signature(&entry_point_info, &cluster_nodes, &sig, confs) {
Err(e) => {
info!("poll_all_nodes_for_signature() failed {:?}", e);
result = Err(e);
}
Ok(()) => {
info!("poll_all_nodes_for_signature() succeeded, done.");
break;
}
}
}
}
}
pub fn check_for_new_roots(num_new_roots: usize, contact_infos: &[ContactInfo], test_name: &str) {
let mut roots = vec![HashSet::new(); contact_infos.len()];
let mut done = false;
let mut last_print = Instant::now();
let loop_start = Instant::now();
let loop_timeout = Duration::from_secs(60);
while !done {
assert!(loop_start.elapsed() < loop_timeout);
for (i, ingress_node) in contact_infos.iter().enumerate() {
let client = create_client(ingress_node.client_facing_addr(), VALIDATOR_PORT_RANGE);
let slot = client.get_slot().unwrap_or(0);
roots[i].insert(slot);
let min_node = roots.iter().map(|r| r.len()).min().unwrap_or(0);
done = min_node >= num_new_roots;
if done || last_print.elapsed().as_secs() > 3 {
info!("{} min observed roots {}/16", test_name, min_node);
last_print = Instant::now();
}
}
sleep(Duration::from_millis(clock::DEFAULT_MS_PER_SLOT / 2));
}
}
pub fn check_no_new_roots(
num_slots_to_wait: usize,
contact_infos: &[ContactInfo],
test_name: &str,
) {
assert!(!contact_infos.is_empty());
let mut roots = vec![0; contact_infos.len()];
let max_slot = contact_infos
.iter()
.enumerate()
.map(|(i, ingress_node)| {
let client = create_client(ingress_node.client_facing_addr(), VALIDATOR_PORT_RANGE);
let initial_root = client
.get_slot()
.unwrap_or_else(|_| panic!("get_slot for {} failed", ingress_node.id));
roots[i] = initial_root;
client
.get_slot_with_commitment(CommitmentConfig::processed())
.unwrap_or_else(|_| panic!("get_slot for {} failed", ingress_node.id))
})
.max()
.unwrap();
let end_slot = max_slot + num_slots_to_wait as u64;
let mut current_slot;
let mut last_print = Instant::now();
let mut reached_end_slot = false;
loop {
for contact_info in contact_infos {
let client = create_client(contact_info.client_facing_addr(), VALIDATOR_PORT_RANGE);
current_slot = client
.get_slot_with_commitment(CommitmentConfig::processed())
.unwrap_or_else(|_| panic!("get_slot for {} failed", contact_infos[0].id));
if current_slot > end_slot {
reached_end_slot = true;
break;
}
if last_print.elapsed().as_secs() > 3 {
info!(
"{} current slot: {} on validator: {}, waiting for any validator with slot: {}",
test_name, current_slot, contact_info.id, end_slot
);
last_print = Instant::now();
}
}
if reached_end_slot {
break;
}
}
for (i, ingress_node) in contact_infos.iter().enumerate() {
let client = create_client(ingress_node.client_facing_addr(), VALIDATOR_PORT_RANGE);
assert_eq!(
client
.get_slot()
.unwrap_or_else(|_| panic!("get_slot for {} failed", ingress_node.id)),
roots[i]
);
}
}
fn poll_all_nodes_for_signature(
entry_point_info: &ContactInfo,
cluster_nodes: &[ContactInfo],
sig: &Signature,
confs: usize,
) -> Result<(), TransportError> {
for validator in cluster_nodes {
if validator.id == entry_point_info.id {
continue;
}
let client = create_client(validator.client_facing_addr(), VALIDATOR_PORT_RANGE);
client.poll_for_signature_confirmation(&sig, confs)?;
}
Ok(())
}
fn get_and_verify_slot_entries(
blockstore: &Blockstore,
slot: Slot,
last_entry: &Hash,
) -> Vec<Entry> {
let entries = blockstore.get_slot_entries(slot, 0).unwrap();
assert_eq!(entries.verify(last_entry), true);
entries
}
fn verify_slot_ticks(
blockstore: &Blockstore,
slot: Slot,
last_entry: &Hash,
expected_num_ticks: Option<usize>,
) -> Hash {
let entries = get_and_verify_slot_entries(blockstore, slot, last_entry);
let num_ticks: usize = entries.iter().map(|entry| entry.is_tick() as usize).sum();
if let Some(expected_num_ticks) = expected_num_ticks {
assert_eq!(num_ticks, expected_num_ticks);
}
entries.last().unwrap().hash
}
| 35.389027 | 100 | 0.603833 |
90f8060f9a5654fe2a008ae7719b8fdbe5d0da34 | 8,148 | // This file is part of Substrate.
// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.
//! Shareable Substrate traits.
use std::{
borrow::Cow,
fmt::{Debug, Display},
panic::UnwindSafe,
};
pub use sp_externalities::{Externalities, ExternalitiesExt};
/// Code execution engine.
pub trait CodeExecutor: Sized + Send + Sync + CallInWasm + Clone + 'static {
/// Externalities error type.
type Error: Display + Debug + Send + Sync + 'static;
/// Call a given method in the runtime. Returns a tuple of the result (either the output data
/// or an execution error) together with a `bool`, which is true if native execution was used.
fn call<
R: codec::Codec + PartialEq,
NC: FnOnce() -> Result<R, Box<dyn std::error::Error + Send + Sync>> + UnwindSafe,
>(
&self,
ext: &mut dyn Externalities,
runtime_code: &RuntimeCode,
method: &str,
data: &[u8],
use_native: bool,
native_call: Option<NC>,
) -> (Result<crate::NativeOrEncoded<R>, Self::Error>, bool);
}
/// Something that can fetch the runtime `:code`.
pub trait FetchRuntimeCode {
/// Fetch the runtime `:code`.
///
/// If the `:code` could not be found/not available, `None` should be returned.
fn fetch_runtime_code<'a>(&'a self) -> Option<Cow<'a, [u8]>>;
}
/// Wrapper to use a `u8` slice or `Vec` as [`FetchRuntimeCode`].
pub struct WrappedRuntimeCode<'a>(pub std::borrow::Cow<'a, [u8]>);
impl<'a> FetchRuntimeCode for WrappedRuntimeCode<'a> {
fn fetch_runtime_code<'b>(&'b self) -> Option<Cow<'b, [u8]>> {
Some(self.0.as_ref().into())
}
}
/// Type that implements [`FetchRuntimeCode`] and always returns `None`.
pub struct NoneFetchRuntimeCode;
impl FetchRuntimeCode for NoneFetchRuntimeCode {
fn fetch_runtime_code<'a>(&'a self) -> Option<Cow<'a, [u8]>> {
None
}
}
/// The Wasm code of a Substrate runtime.
#[derive(Clone)]
pub struct RuntimeCode<'a> {
/// The code fetcher that can be used to lazily fetch the code.
pub code_fetcher: &'a dyn FetchRuntimeCode,
/// The optional heap pages this `code` should be executed with.
///
/// If `None` are given, the default value of the executor will be used.
pub heap_pages: Option<u64>,
/// The SCALE encoded hash of `code`.
///
/// The hashing algorithm isn't that important, as long as all runtime
/// code instances use the same.
pub hash: Vec<u8>,
}
impl<'a> PartialEq for RuntimeCode<'a> {
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash
}
}
impl<'a> RuntimeCode<'a> {
/// Create an empty instance.
///
/// This is only useful for tests that don't want to execute any code.
pub fn empty() -> Self {
Self {
code_fetcher: &NoneFetchRuntimeCode,
hash: Vec::new(),
heap_pages: None,
}
}
}
impl<'a> FetchRuntimeCode for RuntimeCode<'a> {
fn fetch_runtime_code<'b>(&'b self) -> Option<Cow<'b, [u8]>> {
self.code_fetcher.fetch_runtime_code()
}
}
/// Could not find the `:code` in the externalities while initializing the [`RuntimeCode`].
#[derive(Debug)]
pub struct CodeNotFound;
impl std::fmt::Display for CodeNotFound {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "the storage entry `:code` doesn't have any code")
}
}
/// `Allow` or `Disallow` missing host functions when instantiating a WASM blob.
#[derive(Clone, Copy, Debug)]
pub enum MissingHostFunctions {
/// Any missing host function will be replaced by a stub that returns an error when
/// being called.
Allow,
/// Any missing host function will result in an error while instantiating the WASM blob,
Disallow,
}
impl MissingHostFunctions {
/// Are missing host functions allowed?
pub fn allowed(self) -> bool {
matches!(self, Self::Allow)
}
}
/// Something that can call a method in a WASM blob.
pub trait CallInWasm: Send + Sync {
/// Call the given `method` in the given `wasm_blob` using `call_data` (SCALE encoded arguments)
/// to decode the arguments for the method.
///
/// Returns the SCALE encoded return value of the method.
///
/// # Note
///
/// If `code_hash` is `Some(_)` the `wasm_code` module and instance will be cached internally,
/// otherwise it is thrown away after the call.
fn call_in_wasm(
&self,
wasm_code: &[u8],
code_hash: Option<Vec<u8>>,
method: &str,
call_data: &[u8],
ext: &mut dyn Externalities,
missing_host_functions: MissingHostFunctions,
) -> Result<Vec<u8>, String>;
}
sp_externalities::decl_extension! {
/// The call-in-wasm extension to register/retrieve from the externalities.
pub struct CallInWasmExt(Box<dyn CallInWasm>);
}
impl CallInWasmExt {
/// Creates a new instance of `Self`.
pub fn new<T: CallInWasm + 'static>(inner: T) -> Self {
Self(Box::new(inner))
}
}
sp_externalities::decl_extension! {
/// Task executor extension.
pub struct TaskExecutorExt(Box<dyn SpawnNamed>);
}
impl TaskExecutorExt {
/// New instance of task executor extension.
pub fn new(spawn_handle: impl SpawnNamed + Send + 'static) -> Self {
Self(Box::new(spawn_handle))
}
}
/// Runtime spawn extension.
pub trait RuntimeSpawn: Send {
/// Create new runtime instance and use dynamic dispatch to invoke with specified payload.
///
/// Returns handle of the spawned task.
///
/// Function pointers (`dispatcher_ref`, `func`) are WASM pointer types.
fn spawn_call(&self, dispatcher_ref: u32, func: u32, payload: Vec<u8>) -> u64;
/// Join the result of previously created runtime instance invocation.
fn join(&self, handle: u64) -> Vec<u8>;
}
#[cfg(feature = "std")]
sp_externalities::decl_extension! {
/// Extension that supports spawning extra runtime instances in externalities.
pub struct RuntimeSpawnExt(Box<dyn RuntimeSpawn>);
}
/// Something that can spawn tasks (blocking and non-blocking) with an assigned name.
#[dyn_clonable::clonable]
pub trait SpawnNamed: Clone + Send + Sync {
/// Spawn the given blocking future.
///
/// The given `name` is used to identify the future in tracing.
fn spawn_blocking(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>);
/// Spawn the given non-blocking future.
///
/// The given `name` is used to identify the future in tracing.
fn spawn(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>);
}
impl SpawnNamed for Box<dyn SpawnNamed> {
fn spawn_blocking(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>) {
(**self).spawn_blocking(name, future)
}
fn spawn(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>) {
(**self).spawn(name, future)
}
}
/// Something that can spawn essential tasks (blocking and non-blocking) with an assigned name.
///
/// Essential tasks are special tasks that should take down the node when they end.
#[dyn_clonable::clonable]
pub trait SpawnEssentialNamed: Clone + Send + Sync {
/// Spawn the given blocking future.
///
/// The given `name` is used to identify the future in tracing.
fn spawn_essential_blocking(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>);
/// Spawn the given non-blocking future.
///
/// The given `name` is used to identify the future in tracing.
fn spawn_essential(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>);
}
impl SpawnEssentialNamed for Box<dyn SpawnEssentialNamed> {
fn spawn_essential_blocking(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>) {
(**self).spawn_essential_blocking(name, future)
}
fn spawn_essential(&self, name: &'static str, future: futures::future::BoxFuture<'static, ()>) {
(**self).spawn_essential(name, future)
}
}
| 31.952941 | 106 | 0.698085 |
1ef782f890f46411570ba513eefb6d5c442debbc | 3,309 | #[doc = "Register `DSTS` reader"]
pub struct R(crate::R<DSTS_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DSTS_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DSTS_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DSTS_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `SUSPSTS` reader - Suspend status"]
pub struct SUSPSTS_R(crate::FieldReader<bool, bool>);
impl SUSPSTS_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
SUSPSTS_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SUSPSTS_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `ENUMSPD` reader - Enumerated speed"]
pub struct ENUMSPD_R(crate::FieldReader<u8, u8>);
impl ENUMSPD_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
ENUMSPD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for ENUMSPD_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `EERR` reader - Erratic error"]
pub struct EERR_R(crate::FieldReader<bool, bool>);
impl EERR_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
EERR_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for EERR_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `FNSOF` reader - Frame number of the received SOF"]
pub struct FNSOF_R(crate::FieldReader<u16, u16>);
impl FNSOF_R {
#[inline(always)]
pub(crate) fn new(bits: u16) -> Self {
FNSOF_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for FNSOF_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bit 0 - Suspend status"]
#[inline(always)]
pub fn suspsts(&self) -> SUSPSTS_R {
SUSPSTS_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bits 1:2 - Enumerated speed"]
#[inline(always)]
pub fn enumspd(&self) -> ENUMSPD_R {
ENUMSPD_R::new(((self.bits >> 1) & 0x03) as u8)
}
#[doc = "Bit 3 - Erratic error"]
#[inline(always)]
pub fn eerr(&self) -> EERR_R {
EERR_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bits 8:21 - Frame number of the received SOF"]
#[inline(always)]
pub fn fnsof(&self) -> FNSOF_R {
FNSOF_R::new(((self.bits >> 8) & 0x3fff) as u16)
}
}
#[doc = "OTG_FS device status register (OTG_FS_DSTS)\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dsts](index.html) module"]
pub struct DSTS_SPEC;
impl crate::RegisterSpec for DSTS_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [dsts::R](R) reader structure"]
impl crate::Readable for DSTS_SPEC {
type Reader = R;
}
#[doc = "`reset()` method sets DSTS to value 0x10"]
impl crate::Resettable for DSTS_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0x10
}
}
| 29.026316 | 250 | 0.600484 |
2128167b252ed5b40495542890ea4162db468ccf | 13,173 | use data_sep::*;
use molecule::Molecule;
use reaction::{ElemReaction, ReactionCompound};
use ion::Ion;
use trait_element::Element;
use trait_properties::Properties;
use trait_reaction::Reaction;
use types::*;
use reaction::ReactionSide;
use redox::RedoxReaction;
use std::hash::{Hash, Hasher};
#[derive(Debug, Clone)]
/// A container for elements
pub struct Container<E: Element> {
/// A vector with the contents of this container
pub contents: Vec<ContainerCompound<E>>,
/// The amount of energy available
pub available_energy: Energy,
}
#[derive(Debug, Clone)]
/// A compound for containers
pub struct ContainerCompound<E: Element> {
/// The element it contains
pub element: E,
/// The amount of moles of this element
pub moles: Moles,
}
/// Convert a given `ReactionCompound` into a `ContainerCompound`
pub fn rc_to_cc<E: Element>(rc: ReactionCompound<E>) -> ContainerCompound<E> {
ContainerCompound {
element: rc.element,
moles: Moles::from(Moles_type::from(rc.amount)),
}
}
pub fn get_redox_reaction(container: &Container<Ion>) -> Option<RedoxReaction> {
let mut oxidator: Option<(ElemReaction<Ion>, SEP)> = None;
let mut reductor: Option<(ElemReaction<Ion>, SEP)> = None;
for reaction in container.get_redox_reactions() {
// TODO: But what if there exists an oxidator that provides this reductor with its needed molecules?
if !container.has_enough_compounds_for_reaction(&reaction.0) {
continue;
}
print!("{} \twith SEP {} ", reaction.0, reaction.1);
// Find electrons
if reaction.0.lhs.total_atoms(true).contains_key(
&AtomNumber::from(0),
)
{
println!("[oxi]");
if let Some(oxi) = oxidator.clone() {
if reaction.1 > oxi.1 {
oxidator = Some(reaction);
}
} else {
oxidator = Some(reaction);
}
} else {
println!("[red]");
if let Some(red) = reductor.clone() {
if reaction.1 < red.1 {
reductor = Some(reaction);
}
} else {
reductor = Some(reaction);
}
}
}
if let Some(ref oxi) = oxidator {
println!("oxidator: {} \twith SEP {}", oxi.0, oxi.1);
} else {
println!("failed to find oxidator");
}
if let Some(ref red) = reductor {
println!("reductor: {} \twith SEP {}", red.0, red.1);
} else {
println!("failed to find reductor");
}
if oxidator.is_some() && reductor.is_some() {
let oxi = oxidator.unwrap();
let red = reductor.unwrap();
Some(RedoxReaction {
oxidator: oxi.0,
reductor: red.0,
})
} else {
None
}
}
impl<E: Element> Container<E> {
/// Applies given `Reaction` to `Container`
/// Removing the elements on the left-hand side
/// and adding the elements on the right-hand side.
/// If there is enough energy for the reaction, that amount will be consumed
/// otherwise the reaction won't occur.
/// Returns if the reaction succeeded
pub fn react<R: Reaction<E>>(&mut self, reaction: &R) -> bool {
// Get required items
let required_energy = reaction.energy_cost();
let mut required_elements = vec![];
let mut resulting_elements = vec![];
// Convert lhs compounds into `ContainerCompound`s
for rc in &reaction.elem_reaction().lhs.compounds {
let cc = rc_to_cc(rc.clone());
required_elements.push(cc);
}
// Convert rhs compounds into `ContainerCompound`s
for rc in &reaction.elem_reaction().rhs.compounds {
let cc = rc_to_cc(rc.clone());
resulting_elements.push(cc);
}
// Check if the container has enough energy
if self.available_energy < required_energy {
println!("#### Not enough energy");
return false;
}
// Check if the container has the required elements
if !self.has_elements(&required_elements) {
println!("#### Not enough elements");
return false;
}
// Subtract needed energy (or add, in case of an exothermic reaction)
self.available_energy -= required_energy;
// Remove required elements
self.remove_elements(&required_elements);
// Add reaction results
self.add_elements(&resulting_elements);
true
}
/// Check if the container contains a container compound
pub fn contains(&self, element: &ContainerCompound<E>) -> bool {
// Find element in self.contents
if let Some(position) = self.contents.iter().position(|comp| comp == element) {
let compound = &self.contents[position];
// Check if more elements are required than available
if element.moles > compound.moles {
return false;
}
return true;
}
// Element is not available
false
}
/// Check if the container has all given elements
pub fn has_elements(&self, elements: &[ContainerCompound<E>]) -> bool {
for element in elements {
if !self.contains(element) {
return false;
}
}
true
}
/// Check if the container has all required elements for a reaction to occur
/// NOTE: Ignores electrons
pub fn has_enough_compounds_for_reaction(&self, reaction: &ElemReaction<E>) -> bool {
self.has_elements(&reaction
.lhs
.compounds
.iter()
.filter(|x| {
x.element.clone().get_molecule().unwrap().compounds[0]
.atom
.number != AtomNumber::from(0)
})
.map(|x| rc_to_cc(x.clone()))
.collect::<Vec<ContainerCompound<E>>>())
}
/// Remove given elements from container
pub fn remove_elements(&mut self, elements: &[ContainerCompound<E>]) {
for element in elements {
let mut to_remove = None;
// Find element in self.contents
if let Some(position) = self.contents.iter().position(|comp| comp == element) {
let compound = &mut self.contents[position];
// Check if we have enough
if compound.moles < element.moles {
panic!("Can't remove element {} (not enough)", element.symbol());
}
// Remove amount
compound.moles -= element.moles.clone();
// If none is available anymore, let element be removed from container
if compound.moles == Moles::from(0.0) {
to_remove = Some(position);
}
} else {
panic!("Can't remove element {} (not found)", element.symbol());
}
// Remove element if needed
if let Some(pos) = to_remove {
self.contents.remove(pos);
}
}
}
/// Add given elements to container
pub fn add_elements(&mut self, elements: &[ContainerCompound<E>]) {
for element in elements {
// Find element in self.contents
if let Some(position) = self.contents.iter().position(|comp| comp == element) {
let compound = &mut self.contents[position];
// Add amount
compound.moles += element.moles.clone();
} else {
// If the element is not found in the container, add it
self.contents.push(element.clone());
}
}
}
/// Get all possible redox reactions and their SEP's
pub fn get_redox_reactions(&self) -> Vec<(ElemReaction<Ion>, SEP)> {
let mut redox_reactions = vec![];
for container_element in &self.contents {
redox_reactions.append(&mut get_reactions_with_element(
&container_element.clone().get_ion().unwrap(),
));
}
redox_reactions
}
/// Convert container to a nice string for displaying
pub fn stringify(&self) -> String {
let mut string = String::new();
let mut first = true;
for compound in &self.contents {
if compound.moles > Moles::from(0.0) {
if !first {
string += " + ";
}
first = false;
string += &compound.stringify();
}
}
string += " [";
string += &format!("{:.3}", self.available_energy);
string += " J]";
string
}
pub fn ion_from_string(string: &str) -> Option<Container<Ion>> {
let mut token = String::new();
let mut contents = None;
let mut energy = None;
for c in string.chars() {
if c == '[' {
let rs = ReactionSide::<Ion>::ion_from_string(&token)?;
let mut _contents = vec![];
for rc in rs.compounds {
_contents.push(rc_to_cc(rc));
}
contents = Some(_contents);
token = String::new();
} else if c == ']' {
let mut _energy = 0.0f64;
for x in token.chars() {
if is_number!(x) {
_energy *= 10.0;
_energy += f64::from(to_number!(x));
}
}
energy = Some(Energy::from(_energy));
}
token.push(c);
}
if contents.is_some() && energy.is_some() {
Some(Container {
contents: contents.unwrap(),
available_energy: energy.unwrap(),
})
} else {
None
}
}
pub fn molecule_from_string(string: &str) -> Option<Container<Molecule>> {
let mut token = String::new();
let mut contents = None;
let mut energy = None;
for c in string.chars() {
if c == '[' {
let rs = ReactionSide::<Molecule>::molecule_from_string(&token)?;
let mut _contents = vec![];
for rc in rs.compounds {
_contents.push(rc_to_cc(rc));
}
contents = Some(_contents);
token = String::new();
} else if c == ']' {
let mut _energy = 0.0f64;
for x in token.chars() {
if is_number!(x) {
_energy *= 10.0;
_energy += f64::from(to_number!(x));
}
}
energy = Some(Energy::from(_energy));
}
token.push(c);
}
if contents.is_some() && energy.is_some() {
Some(Container {
contents: contents.unwrap(),
available_energy: energy.unwrap(),
})
} else {
None
}
}
}
impl<E: Element> ContainerCompound<E> {
pub fn ion_from_string(string: &str) -> Option<ContainerCompound<Ion>> {
let rc = ReactionCompound::<Ion>::ion_from_string(string)?;
Some(rc_to_cc(rc))
}
pub fn molecule_from_string(string: &str) -> Option<ContainerCompound<Molecule>> {
let rc = ReactionCompound::<Molecule>::molecule_from_string(string)?;
Some(rc_to_cc(rc))
}
}
impl<E: Element> Eq for ContainerCompound<E> {}
impl<E: Element> PartialEq for ContainerCompound<E> {
/// Two container compounds are equal when their elements are equal
fn eq(&self, rhs: &ContainerCompound<E>) -> bool {
self.element == rhs.element
}
}
impl<E: Element> Hash for ContainerCompound<E> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.element.hash(state)
}
}
impl<E: Element> Element for ContainerCompound<E> {
fn get_charge(&self) -> Option<AtomCharge> {
self.element.get_charge()
}
fn get_molecule(self) -> Option<Molecule> {
self.element.get_molecule()
}
fn get_ion(self) -> Option<Ion> {
self.element.get_ion()
}
}
impl<E: Element> Properties for ContainerCompound<E> {
fn symbol(&self) -> String {
let mut symbol = String::new();
if self.moles != Moles::from(1.0) {
symbol += &self.moles.to_string();
symbol += " ";
}
symbol += &self.element.symbol();
symbol
}
fn name(&self) -> String {
let mut name = String::new();
if self.moles != Moles::from(1.0) {
name += &self.moles.to_string();
name += " ";
}
name += &self.element.name();
name
}
fn mass(&self) -> AtomMass {
self.element.mass() * (self.moles.0 as AtomMass_type)
}
fn is_diatomic(&self) -> bool {
self.element.is_diatomic()
}
}
| 27.160825 | 108 | 0.528505 |
d971664e2de9e89f34c975fb44cb6f24fd339bd1 | 849 | use readers::prelude::Value;
use std::io::{BufWriter, Write};
pub mod int_value_fmt;
pub mod float_value_fmt;
pub mod str_value_fmt;
pub mod unspecified_value_fmt;
pub use self::int_value_fmt::*;
pub use self::float_value_fmt::*;
pub use self::str_value_fmt::*;
pub use self::unspecified_value_fmt::*;
/// The value formatter assume that the data is already in the form that complies with
/// the data type specified in the semantic model, and it's totally up to the implementation
/// to do that if they want (you should assume that they don't).
///
/// If you need a value formatter that does the check, you should enable the strict mode of the engine
/// which will handle checking the data type
pub trait JSONValueFmt<W: Write> {
fn get_value(&self, val: &Value) -> String;
fn write_value(&self, writer: &mut BufWriter<W>, val: &Value);
} | 36.913043 | 102 | 0.740872 |
72d6daedddf0a8b29092bbfe1067c0c0e78b02bb | 1,638 | /*
* NHL API
*
* Documenting the publicly accessible portions of the NHL API.
*
* The version of the OpenAPI document: 1.0.0
*
* Generated by: https://openapi-generator.tech
*/
use std::rc::Rc;
use std::borrow::Borrow;
use hyper;
use serde_json;
use futures::Future;
use super::{Error, configuration};
use super::request as __internal_request;
pub struct DivisionsApiClient<C: hyper::client::Connect> {
configuration: Rc<configuration::Configuration<C>>,
}
impl<C: hyper::client::Connect> DivisionsApiClient<C> {
pub fn new(configuration: Rc<configuration::Configuration<C>>) -> DivisionsApiClient<C> {
DivisionsApiClient {
configuration: configuration,
}
}
}
pub trait DivisionsApi {
fn get_division(&self, id: u32) -> Box<Future<Item = crate::models::Division, Error = Error<serde_json::Value>>>;
fn get_divisions(&self, ) -> Box<Future<Item = crate::models::Divisions, Error = Error<serde_json::Value>>>;
}
impl<C: hyper::client::Connect>DivisionsApi for DivisionsApiClient<C> {
fn get_division(&self, id: u32) -> Box<Future<Item = crate::models::Division, Error = Error<serde_json::Value>>> {
__internal_request::Request::new(hyper::Method::Get, "/divisions/{id}".to_string())
.with_path_param("id".to_string(), id.to_string())
.execute(self.configuration.borrow())
}
fn get_divisions(&self, ) -> Box<Future<Item = crate::models::Divisions, Error = Error<serde_json::Value>>> {
__internal_request::Request::new(hyper::Method::Get, "/divisions".to_string())
.execute(self.configuration.borrow())
}
}
| 31.5 | 118 | 0.674603 |
4836a0cf547ff7dc118cdab4608771e5946936a5 | 254 | #[tokio::test]
async fn noarg() {
let script = redis_lua::lua!(
return 1 + 3 + 10;
);
let mut cli = redis::Client::open("redis://127.0.0.1").unwrap();
let res: usize = script.invoke(&mut cli).unwrap();
assert_eq!(res, 14);
}
| 23.090909 | 68 | 0.559055 |
e27c89cda6029a0d2aad9e0c49afe33c250f2978 | 1,473 | use proc_macro::{TokenStream, TokenTree};
pub fn html(input: TokenStream) -> TokenStream {
let mut tokens = input.into_iter();
let html = if let Some(TokenTree::Literal(literal)) = tokens.next() {
let repr = literal.to_string();
let repr = repr.trim();
if repr.starts_with('"') || repr.starts_with('r') {
let begin = repr.find('"').unwrap() + 1;
let end = repr.rfind('"').unwrap();
let open = &repr[..begin];
let (format, args) = split(&repr[begin..end]);
let close = &repr[end..];
format!("Html(format!({open}{format}{close}{args}))")
} else {
panic!("invalid html invocation: argument must be a single string literal")
}
} else {
panic!("invalid html invocation: argument must be a single string literal")
};
assert!(tokens.next().is_none());
html.parse().expect("failed to parse tokens")
}
fn split(content: &str) -> (String, String) {
let mut format = String::new();
let mut args = String::new();
let mut pos = 0;
while let Some(index) = content[pos..].find('{').map(|index| index + pos) {
let close = content[pos..].find('}').expect("no closing bracket") + pos;
format = format + &content[pos..=index] + "}";
args = args + ", " + &content[index + 1..close] + ".to_html().await";
pos = close + 1;
}
format += &content[pos..];
(format, args)
}
| 32.021739 | 87 | 0.551935 |
9cecef6ac5515ef9a882e18eed94406a61ecb9e7 | 1,216 | use ksz8863::smi::{self, Smi};
// Run with `cargo test -- --nocapture`
#[test]
fn smi_map_default() {
let map = smi::Map::default();
for &addr in smi::Address::ALL {
println!("{:#?}", map[addr]);
}
}
#[test]
fn smi_api() {
// Rather than a `Map`, we would normally use a real SMI interface, however for testing the API
// its easier to read and write to a map.
let mut smi = Smi(smi::Map::default());
// Access the Bcr register.
let mut gc1 = smi.gc1();
// Read the value. Should be default.
let a = gc1.read().unwrap();
assert_eq!(a, smi::Gc1::default());
// Overwrite the Gc1 register.
gc1.write(|w| w.aging().clear_bit()).unwrap();
let b = gc1.read().unwrap();
assert!(a != b);
// Modify the Gc1 register.
gc1.modify(|w| w.aggressive_back_off().set_bit()).unwrap();
let c = gc1.read().unwrap();
assert!(c.read().aging().bit_is_clear());
assert!(c.read().aggressive_back_off().bit_is_set());
// Reset the Gc1 register.
gc1.write(|w| w.reset()).unwrap();
let d = gc1.read().unwrap();
assert_eq!(a, d);
// Check non-lexical borrows are working nicely.
assert_eq!(a, smi.gc1().read().unwrap());
}
| 27.636364 | 99 | 0.592105 |
5b25024a554d77e43f4d2e1b21b3a8251449e165 | 9,488 | // Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// Copyright (C) 2020 Red Hat, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! A wrapper over an `ArcSwap<GuestMemory>` struct to support RCU-style mutability.
//!
//! With the `backend-atomic` feature enabled, simply replacing `GuestMemoryMmap`
//! with `GuestMemoryAtomic<GuestMemoryMmap>` will enable support for mutable memory maps.
//! To support mutable memory maps, devices will also need to use
//! `GuestAddressSpace::memory()` to gain temporary access to guest memory.
extern crate arc_swap;
use arc_swap::{ArcSwap, Guard};
use std::ops::Deref;
use std::sync::{Arc, LockResult, Mutex, MutexGuard, PoisonError};
use crate::{GuestAddressSpace, GuestMemory};
/// A fast implementation of a mutable collection of memory regions.
///
/// This implementation uses ArcSwap to provide RCU-like snapshotting of the memory map:
/// every update of the memory map creates a completely new GuestMemory object, and
/// readers will not be blocked because the copies they retrieved will be collected once
/// no one can access them anymore. Under the assumption that updates to the memory map
/// are rare, this allows a very efficient implementation of the `memory()` method.
#[derive(Clone, Debug)]
pub struct GuestMemoryAtomic<M: GuestMemory> {
// GuestAddressSpace<M>, which we want to implement, is basically a drop-in
// replacement for &M. Therefore, we need to pass to devices the GuestMemoryAtomic
// rather than a reference to it. To obtain this effect we wrap the actual fields
// of GuestMemoryAtomic with an Arc, and derive the Clone trait. See the
// documentation for GuestAddressSpace for an example.
inner: Arc<(ArcSwap<M>, Mutex<()>)>,
}
impl<M: GuestMemory> From<Arc<M>> for GuestMemoryAtomic<M> {
/// create a new GuestMemoryAtomic object whose initial contents come from
/// the `map` reference counted GuestMemory.
fn from(map: Arc<M>) -> Self {
let inner = (ArcSwap::new(map), Mutex::new(()));
GuestMemoryAtomic {
inner: Arc::new(inner),
}
}
}
impl<M: GuestMemory> GuestMemoryAtomic<M> {
/// create a new GuestMemoryAtomic object whose initial contents come from
/// the `map` GuestMemory.
pub fn new(map: M) -> Self {
Arc::new(map).into()
}
fn load(&self) -> Guard<'static, Arc<M>> {
self.inner.0.load()
}
/// Acquires the update mutex for the GuestMemoryAtomic, blocking the current
/// thread until it is able to do so. The returned RAII guard allows for
/// scoped unlock of the mutex (that is, the mutex will be unlocked when
/// the guard goes out of scope), and optionally also for replacing the
/// contents of the GuestMemoryAtomic when the lock is dropped.
pub fn lock(&self) -> LockResult<GuestMemoryExclusiveGuard<M>> {
match self.inner.1.lock() {
Ok(guard) => Ok(GuestMemoryExclusiveGuard {
parent: self,
_guard: guard,
}),
Err(err) => Err(PoisonError::new(GuestMemoryExclusiveGuard {
parent: self,
_guard: err.into_inner(),
})),
}
}
}
impl<M: GuestMemory> GuestAddressSpace for GuestMemoryAtomic<M> {
type T = GuestMemoryLoadGuard<M>;
type M = M;
fn memory(&self) -> Self::T {
GuestMemoryLoadGuard { guard: self.load() }
}
}
/// A guard that provides temporary access to a GuestMemoryAtomic. This
/// object is returned from the `memory()` method. It dereference to
/// a snapshot of the GuestMemory, so it can be used transparently to
/// access memory.
#[derive(Debug)]
pub struct GuestMemoryLoadGuard<M: GuestMemory> {
guard: Guard<'static, Arc<M>>,
}
impl<M: GuestMemory> GuestMemoryLoadGuard<M> {
/// Make a clone of the held pointer and returns it. This is more
/// expensive than just using the snapshot, but it allows to hold on
/// to the snapshot outside the scope of the guard. It also allows
/// writers to proceed, so it is recommended if the reference must
/// be held for a long time (including for caching purposes).
pub fn into_inner(self) -> Arc<M> {
Guard::into_inner(self.guard)
}
}
impl<M: GuestMemory> Deref for GuestMemoryLoadGuard<M> {
type Target = M;
fn deref(&self) -> &Self::Target {
&*self.guard
}
}
/// An RAII implementation of a "scoped lock" for GuestMemoryAtomic. When
/// this structure is dropped (falls out of scope) the lock will be unlocked,
/// possibly after updating the memory map represented by the
/// GuestMemoryAtomic that created the guard.
pub struct GuestMemoryExclusiveGuard<'a, M: GuestMemory> {
parent: &'a GuestMemoryAtomic<M>,
_guard: MutexGuard<'a, ()>,
}
impl<M: GuestMemory> GuestMemoryExclusiveGuard<'_, M> {
/// Replace the memory map in the GuestMemoryAtomic that created the guard
/// with the new memory map, `map`. The lock is then dropped since this
/// method consumes the guard.
pub fn replace(self, map: M) {
self.parent.inner.0.store(Arc::new(map))
}
}
#[cfg(test)]
#[cfg(feature = "backend-mmap")]
mod tests {
use super::*;
use crate::{
GuestAddress, GuestMemory, GuestMemoryMmap, GuestMemoryRegion, GuestMemoryResult,
GuestRegionMmap, GuestUsize, MmapRegion,
};
type GuestMemoryMmapAtomic = GuestMemoryAtomic<GuestMemoryMmap>;
#[test]
fn test_atomic_memory() {
let region_size = 0x400;
let regions = vec![
(GuestAddress(0x0), region_size),
(GuestAddress(0x1000), region_size),
];
let mut iterated_regions = Vec::new();
let gmm = GuestMemoryMmap::from_ranges(®ions).unwrap();
let gm = GuestMemoryMmapAtomic::new(gmm);
let mem = gm.memory();
let res: GuestMemoryResult<()> = mem.with_regions(|_, region| {
assert_eq!(region.len(), region_size as GuestUsize);
Ok(())
});
assert!(res.is_ok());
let res: GuestMemoryResult<()> = mem.with_regions_mut(|_, region| {
iterated_regions.push((region.start_addr(), region.len() as usize));
Ok(())
});
assert!(res.is_ok());
assert_eq!(regions, iterated_regions);
assert_eq!(mem.num_regions(), 2);
assert!(mem.find_region(GuestAddress(0x1000)).is_some());
assert!(mem.find_region(GuestAddress(0x10000)).is_none());
assert!(regions
.iter()
.map(|x| (x.0, x.1))
.eq(iterated_regions.iter().map(|x| *x)));
let mem2 = mem.into_inner();
let res: GuestMemoryResult<()> = mem2.with_regions(|_, region| {
assert_eq!(region.len(), region_size as GuestUsize);
Ok(())
});
assert!(res.is_ok());
let res: GuestMemoryResult<()> = mem2.with_regions_mut(|_, _| Ok(()));
assert!(res.is_ok());
assert_eq!(mem2.num_regions(), 2);
assert!(mem2.find_region(GuestAddress(0x1000)).is_some());
assert!(mem2.find_region(GuestAddress(0x10000)).is_none());
assert!(regions
.iter()
.map(|x| (x.0, x.1))
.eq(iterated_regions.iter().map(|x| *x)));
let mem3 = mem2.memory();
let res: GuestMemoryResult<()> = mem3.with_regions(|_, region| {
assert_eq!(region.len(), region_size as GuestUsize);
Ok(())
});
assert!(res.is_ok());
let res: GuestMemoryResult<()> = mem3.with_regions_mut(|_, _| Ok(()));
assert!(res.is_ok());
assert_eq!(mem3.num_regions(), 2);
assert!(mem3.find_region(GuestAddress(0x1000)).is_some());
assert!(mem3.find_region(GuestAddress(0x10000)).is_none());
}
#[test]
fn test_atomic_hotplug() {
let region_size = 0x1000;
let regions = vec![
(GuestAddress(0x0), region_size),
(GuestAddress(0x10_0000), region_size),
];
let mut gmm = Arc::new(GuestMemoryMmap::from_ranges(®ions).unwrap());
let gm: GuestMemoryAtomic<_> = gmm.clone().into();
let mem_orig = gm.memory();
assert_eq!(mem_orig.num_regions(), 2);
{
let guard = gm.lock().unwrap();
let new_gmm = Arc::make_mut(&mut gmm);
let mmap = Arc::new(
GuestRegionMmap::new(MmapRegion::new(0x1000).unwrap(), GuestAddress(0x8000))
.unwrap(),
);
let new_gmm = new_gmm.insert_region(mmap).unwrap();
let mmap = Arc::new(
GuestRegionMmap::new(MmapRegion::new(0x1000).unwrap(), GuestAddress(0x4000))
.unwrap(),
);
let new_gmm = new_gmm.insert_region(mmap).unwrap();
let mmap = Arc::new(
GuestRegionMmap::new(MmapRegion::new(0x1000).unwrap(), GuestAddress(0xc000))
.unwrap(),
);
let new_gmm = new_gmm.insert_region(mmap).unwrap();
let mmap = Arc::new(
GuestRegionMmap::new(MmapRegion::new(0x1000).unwrap(), GuestAddress(0xc000))
.unwrap(),
);
new_gmm.insert_region(mmap).unwrap_err();
guard.replace(new_gmm);
}
assert_eq!(mem_orig.num_regions(), 2);
let mem = gm.memory();
assert_eq!(mem.num_regions(), 5);
}
}
| 38.104418 | 92 | 0.620363 |
483b1d1696178aa8b58b9446aee2b7335e213f7e | 1,861 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 permutation::Permutation;
use cube::Cube;
use crypto::blake2b::Blake2b;
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct SecretKey {
pub a: u64,
pub b: u64,
}
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct PublicKey {
pub key: Permutation,
}
impl SecretKey {
pub fn to_public(&self) -> PublicKey {
let pa = Permutation::parse("U x'").unwrap();
let pb = Permutation::parse("L y'").unwrap();
PublicKey { key: self.a * pa + self.b * pb }
}
pub fn handshake(&self, key: PublicKey, salt: &[u8]) -> [u8; 16] {
let pa = Permutation::parse("U x'").unwrap();
let pb = Permutation::parse("L y'").unwrap();
let cube = Cube::default().apply(self.a * pa + key.key + self.b * pb);
let mut out = [0; 16];
Blake2b::blake2b(&mut out, &cube.serialize().as_bytes(), salt);
out
}
}
impl PublicKey {
pub fn serialize(&self) -> String {
Cube::default().apply(self.key).serialize()
}
pub fn unserialize(s: &str) -> Option<PublicKey> {
if let Some(cube) = Cube::unserialize(s) {
if let Some(perm) = Permutation::from_cube(cube) {
return Some(PublicKey { key: perm });
}
}
None
}
}
| 29.078125 | 78 | 0.61741 |
03c11429e0220bc2cbe73f45ecd9dab482f9894f | 5,583 | #[doc = "Register `EVENTS_RATEBOOST` reader"]
pub struct R(crate::R<EVENTS_RATEBOOST_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<EVENTS_RATEBOOST_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<EVENTS_RATEBOOST_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<EVENTS_RATEBOOST_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `EVENTS_RATEBOOST` writer"]
pub struct W(crate::W<EVENTS_RATEBOOST_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<EVENTS_RATEBOOST_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<EVENTS_RATEBOOST_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<EVENTS_RATEBOOST_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Ble_LR CI field received, receive mode is changed from Ble_LR125Kbit to Ble_LR500Kbit.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EVENTS_RATEBOOST_A {
#[doc = "0: Event not generated"]
NOTGENERATED = 0,
#[doc = "1: Event generated"]
GENERATED = 1,
}
impl From<EVENTS_RATEBOOST_A> for bool {
#[inline(always)]
fn from(variant: EVENTS_RATEBOOST_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `EVENTS_RATEBOOST` reader - Ble_LR CI field received, receive mode is changed from Ble_LR125Kbit to Ble_LR500Kbit."]
pub struct EVENTS_RATEBOOST_R(crate::FieldReader<bool, EVENTS_RATEBOOST_A>);
impl EVENTS_RATEBOOST_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
EVENTS_RATEBOOST_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EVENTS_RATEBOOST_A {
match self.bits {
false => EVENTS_RATEBOOST_A::NOTGENERATED,
true => EVENTS_RATEBOOST_A::GENERATED,
}
}
#[doc = "Checks if the value of the field is `NOTGENERATED`"]
#[inline(always)]
pub fn is_not_generated(&self) -> bool {
**self == EVENTS_RATEBOOST_A::NOTGENERATED
}
#[doc = "Checks if the value of the field is `GENERATED`"]
#[inline(always)]
pub fn is_generated(&self) -> bool {
**self == EVENTS_RATEBOOST_A::GENERATED
}
}
impl core::ops::Deref for EVENTS_RATEBOOST_R {
type Target = crate::FieldReader<bool, EVENTS_RATEBOOST_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `EVENTS_RATEBOOST` writer - Ble_LR CI field received, receive mode is changed from Ble_LR125Kbit to Ble_LR500Kbit."]
pub struct EVENTS_RATEBOOST_W<'a> {
w: &'a mut W,
}
impl<'a> EVENTS_RATEBOOST_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EVENTS_RATEBOOST_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Event not generated"]
#[inline(always)]
pub fn not_generated(self) -> &'a mut W {
self.variant(EVENTS_RATEBOOST_A::NOTGENERATED)
}
#[doc = "Event generated"]
#[inline(always)]
pub fn generated(self) -> &'a mut W {
self.variant(EVENTS_RATEBOOST_A::GENERATED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 0 - Ble_LR CI field received, receive mode is changed from Ble_LR125Kbit to Ble_LR500Kbit."]
#[inline(always)]
pub fn events_rateboost(&self) -> EVENTS_RATEBOOST_R {
EVENTS_RATEBOOST_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Ble_LR CI field received, receive mode is changed from Ble_LR125Kbit to Ble_LR500Kbit."]
#[inline(always)]
pub fn events_rateboost(&mut self) -> EVENTS_RATEBOOST_W {
EVENTS_RATEBOOST_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Ble_LR CI field received, receive mode is changed from Ble_LR125Kbit to Ble_LR500Kbit.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [events_rateboost](index.html) module"]
pub struct EVENTS_RATEBOOST_SPEC;
impl crate::RegisterSpec for EVENTS_RATEBOOST_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [events_rateboost::R](R) reader structure"]
impl crate::Readable for EVENTS_RATEBOOST_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [events_rateboost::W](W) writer structure"]
impl crate::Writable for EVENTS_RATEBOOST_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets EVENTS_RATEBOOST to value 0"]
impl crate::Resettable for EVENTS_RATEBOOST_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 34.677019 | 483 | 0.638904 |
d93c9bafaef27c36c205a5e933f106810aac50f1 | 627 | // 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.
trait Trait {
fn dummy(&self) { }
}
struct Foo<T:Trait> {
x: T,
}
static X: Foo<usize> = Foo {
//~^ ERROR not implemented
x: 1,
};
fn main() {
}
| 24.115385 | 68 | 0.6874 |
dba43bea000e702ba6c08338ec113b512de25195 | 15,596 | use crate::PrintFmt;
use crate::{resolve, resolve_frame, trace, BacktraceFmt, Symbol, SymbolName};
use std::ffi::c_void;
use std::fmt;
use std::path::{Path, PathBuf};
use std::prelude::v1::*;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// Representation of an owned and self-contained backtrace.
///
/// This structure can be used to capture a backtrace at various points in a
/// program and later used to inspect what the backtrace was at that time.
///
/// `Backtrace` supports pretty-printing of backtraces through its `Debug`
/// implementation.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[derive(Clone)]
#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Backtrace {
// Frames here are listed from top-to-bottom of the stack
frames: Vec<BacktraceFrame>,
// The index we believe is the actual start of the backtrace, omitting
// frames like `Backtrace::new` and `backtrace::trace`.
actual_start_index: usize,
}
fn _assert_send_sync() {
fn _assert<T: Send + Sync>() {}
_assert::<Backtrace>();
}
/// Captured version of a frame in a backtrace.
///
/// This type is returned as a list from `Backtrace::frames` and represents one
/// stack frame in a captured backtrace.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[derive(Clone)]
pub struct BacktraceFrame {
frame: Frame,
symbols: Option<Vec<BacktraceSymbol>>,
}
#[derive(Clone)]
enum Frame {
Raw(crate::Frame),
#[allow(dead_code)]
Deserialized {
ip: usize,
symbol_address: usize,
},
}
impl Frame {
fn ip(&self) -> *mut c_void {
match *self {
Frame::Raw(ref f) => f.ip(),
Frame::Deserialized { ip, .. } => ip as *mut c_void,
}
}
fn symbol_address(&self) -> *mut c_void {
match *self {
Frame::Raw(ref f) => f.symbol_address(),
Frame::Deserialized { symbol_address, .. } => symbol_address as *mut c_void,
}
}
}
/// Captured version of a symbol in a backtrace.
///
/// This type is returned as a list from `BacktraceFrame::symbols` and
/// represents the metadata for a symbol in a backtrace.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[derive(Clone)]
#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct BacktraceSymbol {
name: Option<Vec<u8>>,
addr: Option<usize>,
filename: Option<PathBuf>,
lineno: Option<u32>,
}
impl Backtrace {
/// Captures a backtrace at the callsite of this function, returning an
/// owned representation.
///
/// This function is useful for representing a backtrace as an object in
/// Rust. This returned value can be sent across threads and printed
/// elsewhere, and the purpose of this value is to be entirely self
/// contained.
///
/// Note that on some platforms acquiring a full backtrace and resolving it
/// can be extremely expensive. If the cost is too much for your application
/// it's recommended to instead use `Backtrace::new_unresolved()` which
/// avoids the symbol resolution step (which typically takes the longest)
/// and allows deferring that to a later date.
///
/// # Examples
///
/// ```
/// use backtrace::Backtrace;
///
/// let current_backtrace = Backtrace::new();
/// ```
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[inline(never)] // want to make sure there's a frame here to remove
pub fn new() -> Backtrace {
let mut bt = Self::create(Self::new as usize);
bt.resolve();
bt
}
/// Similar to `new` except that this does not resolve any symbols, this
/// simply captures the backtrace as a list of addresses.
///
/// At a later time the `resolve` function can be called to resolve this
/// backtrace's symbols into readable names. This function exists because
/// the resolution process can sometimes take a significant amount of time
/// whereas any one backtrace may only be rarely printed.
///
/// # Examples
///
/// ```
/// use backtrace::Backtrace;
///
/// let mut current_backtrace = Backtrace::new_unresolved();
/// println!("{:?}", current_backtrace); // no symbol names
/// current_backtrace.resolve();
/// println!("{:?}", current_backtrace); // symbol names now present
/// ```
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
#[inline(never)] // want to make sure there's a frame here to remove
pub fn new_unresolved() -> Backtrace {
Self::create(Self::new_unresolved as usize)
}
fn create(ip: usize) -> Backtrace {
let mut frames = Vec::new();
let mut actual_start_index = None;
trace(|frame| {
frames.push(BacktraceFrame {
frame: Frame::Raw(frame.clone()),
symbols: None,
});
if frame.symbol_address() as usize == ip && actual_start_index.is_none() {
actual_start_index = Some(frames.len());
}
true
});
Backtrace {
frames,
actual_start_index: actual_start_index.unwrap_or(0),
}
}
/// Returns the frames from when this backtrace was captured.
///
/// The first entry of this slice is likely the function `Backtrace::new`,
/// and the last frame is likely something about how this thread or the main
/// function started.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn frames(&self) -> &[BacktraceFrame] {
&self.frames[self.actual_start_index..]
}
/// If this backtrace was created from `new_unresolved` then this function
/// will resolve all addresses in the backtrace to their symbolic names.
///
/// If this backtrace has been previously resolved or was created through
/// `new`, this function does nothing.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn resolve(&mut self) {
for frame in self.frames.iter_mut().filter(|f| f.symbols.is_none()) {
let mut symbols = Vec::new();
{
let sym = |symbol: &Symbol| {
symbols.push(BacktraceSymbol {
name: symbol.name().map(|m| m.as_bytes().to_vec()),
addr: symbol.addr().map(|a| a as usize),
filename: symbol.filename().map(|m| m.to_owned()),
lineno: symbol.lineno(),
});
};
match frame.frame {
Frame::Raw(ref f) => resolve_frame(f, sym),
Frame::Deserialized { ip, .. } => {
resolve(ip as *mut c_void, sym);
}
}
}
frame.symbols = Some(symbols);
}
}
}
impl From<Vec<BacktraceFrame>> for Backtrace {
fn from(frames: Vec<BacktraceFrame>) -> Self {
Backtrace {
frames,
actual_start_index: 0,
}
}
}
impl Into<Vec<BacktraceFrame>> for Backtrace {
fn into(self) -> Vec<BacktraceFrame> {
self.frames
}
}
impl BacktraceFrame {
/// Same as `Frame::ip`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn ip(&self) -> *mut c_void {
self.frame.ip() as *mut c_void
}
/// Same as `Frame::symbol_address`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn symbol_address(&self) -> *mut c_void {
self.frame.symbol_address() as *mut c_void
}
/// Returns the list of symbols that this frame corresponds to.
///
/// Normally there is only one symbol per frame, but sometimes if a number
/// of functions are inlined into one frame then multiple symbols will be
/// returned. The first symbol listed is the "innermost function", whereas
/// the last symbol is the outermost (last caller).
///
/// Note that if this frame came from an unresolved backtrace then this will
/// return an empty list.
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn symbols(&self) -> &[BacktraceSymbol] {
self.symbols.as_ref().map(|s| &s[..]).unwrap_or(&[])
}
}
impl BacktraceSymbol {
/// Same as `Symbol::name`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn name(&self) -> Option<SymbolName<'_>> {
self.name.as_ref().map(|s| SymbolName::new(s))
}
/// Same as `Symbol::addr`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn addr(&self) -> Option<*mut c_void> {
self.addr.map(|s| s as *mut c_void)
}
/// Same as `Symbol::filename`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn filename(&self) -> Option<&Path> {
self.filename.as_ref().map(|p| &**p)
}
/// Same as `Symbol::lineno`
///
/// # Required features
///
/// This function requires the `std` feature of the `backtrace` crate to be
/// enabled, and the `std` feature is enabled by default.
pub fn lineno(&self) -> Option<u32> {
self.lineno
}
}
impl fmt::Debug for Backtrace {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let full = fmt.alternate();
let (frames, style) = if full {
(&self.frames[..], PrintFmt::Full)
} else {
(&self.frames[self.actual_start_index..], PrintFmt::Short)
};
// When printing paths we try to strip the cwd if it exists, otherwise
// we just print the path as-is. Note that we also only do this for the
// short format, because if it's full we presumably want to print
// everything.
let cwd = std::env::current_dir();
let mut print_path =
move |fmt: &mut fmt::Formatter<'_>, path: crate::BytesOrWideString<'_>| {
let path = path.into_path_buf();
if !full {
if let Ok(cwd) = &cwd {
if let Ok(suffix) = path.strip_prefix(cwd) {
return fmt::Display::fmt(&suffix.display(), fmt);
}
}
}
fmt::Display::fmt(&path.display(), fmt)
};
let mut f = BacktraceFmt::new(fmt, style, &mut print_path);
f.add_context()?;
for frame in frames {
f.frame().backtrace_frame(frame)?;
}
f.finish()?;
Ok(())
}
}
impl Default for Backtrace {
fn default() -> Backtrace {
Backtrace::new()
}
}
impl fmt::Debug for BacktraceFrame {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("BacktraceFrame")
.field("ip", &self.ip())
.field("symbol_address", &self.symbol_address())
.finish()
}
}
impl fmt::Debug for BacktraceSymbol {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("BacktraceSymbol")
.field("name", &self.name())
.field("addr", &self.addr())
.field("filename", &self.filename())
.field("lineno", &self.lineno())
.finish()
}
}
#[cfg(feature = "serialize-rustc")]
mod rustc_serialize_impls {
use super::*;
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
#[derive(RustcEncodable, RustcDecodable)]
struct SerializedFrame {
ip: usize,
symbol_address: usize,
symbols: Option<Vec<BacktraceSymbol>>,
}
impl Decodable for BacktraceFrame {
fn decode<D>(d: &mut D) -> Result<Self, D::Error>
where
D: Decoder,
{
let frame: SerializedFrame = SerializedFrame::decode(d)?;
Ok(BacktraceFrame {
frame: Frame::Deserialized {
ip: frame.ip,
symbol_address: frame.symbol_address,
},
symbols: frame.symbols,
})
}
}
impl Encodable for BacktraceFrame {
fn encode<E>(&self, e: &mut E) -> Result<(), E::Error>
where
E: Encoder,
{
let BacktraceFrame { frame, symbols } = self;
SerializedFrame {
ip: frame.ip() as usize,
symbol_address: frame.symbol_address() as usize,
symbols: symbols.clone(),
}
.encode(e)
}
}
}
#[cfg(feature = "serde")]
mod serde_impls {
extern crate serde;
use self::serde::de::Deserializer;
use self::serde::ser::Serializer;
use self::serde::{Deserialize, Serialize};
use super::*;
#[derive(Serialize, Deserialize)]
struct SerializedFrame {
ip: usize,
symbol_address: usize,
symbols: Option<Vec<BacktraceSymbol>>,
}
impl Serialize for BacktraceFrame {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let BacktraceFrame { frame, symbols } = self;
SerializedFrame {
ip: frame.ip() as usize,
symbol_address: frame.symbol_address() as usize,
symbols: symbols.clone(),
}
.serialize(s)
}
}
impl<'a> Deserialize<'a> for BacktraceFrame {
fn deserialize<D>(d: D) -> Result<Self, D::Error>
where
D: Deserializer<'a>,
{
let frame: SerializedFrame = SerializedFrame::deserialize(d)?;
Ok(BacktraceFrame {
frame: Frame::Deserialized {
ip: frame.ip,
symbol_address: frame.symbol_address,
},
symbols: frame.symbols,
})
}
}
}
| 32.424116 | 88 | 0.576494 |
23b907791c86f6c25cca766648ba2de017a8581c | 1,211 | use std::io;
use std::sync::Arc;
use async_trait::async_trait;
use log::*;
use crate::{
proxy::{
OutboundConnect, OutboundDatagram, OutboundHandler, OutboundTransport, UdpOutboundHandler,
DatagramTransportType,
},
session::Session,
};
pub struct Handler {
pub actors: Vec<Arc<dyn OutboundHandler>>,
pub attempts: usize,
}
#[async_trait]
impl UdpOutboundHandler for Handler {
fn connect_addr(&self) -> Option<OutboundConnect> {
None
}
fn transport_type(&self) -> DatagramTransportType {
DatagramTransportType::Undefined
}
async fn handle<'a>(
&'a self,
sess: &'a Session,
_transport: Option<OutboundTransport>,
) -> io::Result<Box<dyn OutboundDatagram>> {
for _ in 0..self.attempts {
for a in self.actors.iter() {
debug!("retry handles tcp [{}] to [{}]", sess.destination, a.tag());
match UdpOutboundHandler::handle(a.as_ref(), sess, None).await {
Ok(s) => return Ok(s),
Err(_) => continue,
}
}
}
Err(io::Error::new(io::ErrorKind::Other, "all attempts failed"))
}
}
| 25.765957 | 98 | 0.574732 |
11681dcda2b274bd21e1dc67e50d07e2d09b32bb | 1,801 | use super::{create_collector, Pages, Pagination};
use crate::embeds::CommandCounterEmbed;
use chrono::{DateTime, Utc};
use failure::Error;
use serenity::{
async_trait,
client::Context,
collector::ReactionCollector,
model::{channel::Message, id::UserId},
};
pub struct CommandCountPagination {
msg: Message,
collector: ReactionCollector,
pages: Pages,
booted_up: DateTime<Utc>,
cmd_counts: Vec<(String, u32)>,
}
impl CommandCountPagination {
pub async fn new(
ctx: &Context,
msg: Message,
author: UserId,
cmd_counts: Vec<(String, u32)>,
booted_up: DateTime<Utc>,
) -> Self {
let collector = create_collector(ctx, &msg, author, 60).await;
Self {
msg,
collector,
pages: Pages::new(15, cmd_counts.len()),
cmd_counts,
booted_up,
}
}
}
#[async_trait]
impl Pagination for CommandCountPagination {
type PageData = CommandCounterEmbed;
fn msg(&mut self) -> &mut Message {
&mut self.msg
}
fn collector(&mut self) -> &mut ReactionCollector {
&mut self.collector
}
fn pages(&self) -> Pages {
self.pages
}
fn pages_mut(&mut self) -> &mut Pages {
&mut self.pages
}
async fn build_page(&mut self) -> Result<Self::PageData, Error> {
let sub_list: Vec<(&String, u32)> = self
.cmd_counts
.iter()
.skip(self.pages.index)
.take(self.pages.per_page)
.map(|(name, amount)| (name, *amount))
.collect();
Ok(CommandCounterEmbed::new(
sub_list,
&self.booted_up,
self.pages.index + 1,
(self.page(), self.pages.total_pages),
))
}
}
| 25.013889 | 70 | 0.564131 |
7543dd678d032fdd9a3f730ea0845ae4708a52e4 | 16,259 | use rustc::ty::{self, Ty, TypeAndMut};
use rustc::ty::layout::{self, TyLayout, Size};
use syntax::ast::{FloatTy, IntTy, UintTy};
use rustc_apfloat::ieee::{Single, Double};
use rustc::mir::interpret::{
Scalar, EvalResult, Pointer, PointerArithmetic, EvalErrorKind, truncate
};
use rustc::mir::CastKind;
use rustc_apfloat::Float;
use super::{EvalContext, Machine, PlaceTy, OpTy, ImmTy, Immediate};
impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
fn type_is_fat_ptr(&self, ty: Ty<'tcx>) -> bool {
match ty.sty {
ty::RawPtr(ty::TypeAndMut { ty, .. }) |
ty::Ref(_, ty, _) => !self.type_is_sized(ty),
ty::Adt(def, _) if def.is_box() => !self.type_is_sized(ty.boxed_ty()),
_ => false,
}
}
pub fn cast(
&mut self,
src: OpTy<'tcx, M::PointerTag>,
kind: CastKind,
dest: PlaceTy<'tcx, M::PointerTag>,
) -> EvalResult<'tcx> {
use rustc::mir::CastKind::*;
match kind {
Unsize => {
self.unsize_into(src, dest)?;
}
Misc | MutToConstPointer => {
let src = self.read_immediate(src)?;
if self.type_is_fat_ptr(src.layout.ty) {
match (*src, self.type_is_fat_ptr(dest.layout.ty)) {
// pointers to extern types
(Immediate::Scalar(_),_) |
// slices and trait objects to other slices/trait objects
(Immediate::ScalarPair(..), true) => {
// No change to immediate
self.write_immediate(*src, dest)?;
}
// slices and trait objects to thin pointers (dropping the metadata)
(Immediate::ScalarPair(data, _), false) => {
self.write_scalar(data, dest)?;
}
}
} else {
match src.layout.variants {
layout::Variants::Single { index } => {
if let Some(def) = src.layout.ty.ty_adt_def() {
// Cast from a univariant enum
assert!(src.layout.is_zst());
let discr_val = def
.discriminant_for_variant(*self.tcx, index)
.val;
return self.write_scalar(
Scalar::from_uint(discr_val, dest.layout.size),
dest);
}
}
layout::Variants::Tagged { .. } |
layout::Variants::NicheFilling { .. } => {},
}
let dest_val = self.cast_scalar(src.to_scalar()?, src.layout, dest.layout)?;
self.write_scalar(dest_val, dest)?;
}
}
ReifyFnPointer => {
// The src operand does not matter, just its type
match src.layout.ty.sty {
ty::FnDef(def_id, substs) => {
if self.tcx.has_attr(def_id, "rustc_args_required_const") {
bug!("reifying a fn ptr that requires \
const arguments");
}
let instance: EvalResult<'tcx, _> = ty::Instance::resolve(
*self.tcx,
self.param_env,
def_id,
substs,
).ok_or_else(|| EvalErrorKind::TooGeneric.into());
let fn_ptr = self.memory.create_fn_alloc(instance?).with_default_tag();
self.write_scalar(Scalar::Ptr(fn_ptr.into()), dest)?;
}
_ => bug!("reify fn pointer on {:?}", src.layout.ty),
}
}
UnsafeFnPointer => {
let src = self.read_immediate(src)?;
match dest.layout.ty.sty {
ty::FnPtr(_) => {
// No change to value
self.write_immediate(*src, dest)?;
}
_ => bug!("fn to unsafe fn cast on {:?}", dest.layout.ty),
}
}
ClosureFnPointer => {
// The src operand does not matter, just its type
match src.layout.ty.sty {
ty::Closure(def_id, substs) => {
let substs = self.subst_and_normalize_erasing_regions(substs)?;
let instance = ty::Instance::resolve_closure(
*self.tcx,
def_id,
substs,
ty::ClosureKind::FnOnce,
);
let fn_ptr = self.memory.create_fn_alloc(instance).with_default_tag();
let val = Immediate::Scalar(Scalar::Ptr(fn_ptr.into()).into());
self.write_immediate(val, dest)?;
}
_ => bug!("closure fn pointer on {:?}", src.layout.ty),
}
}
}
Ok(())
}
pub(super) fn cast_scalar(
&self,
val: Scalar<M::PointerTag>,
src_layout: TyLayout<'tcx>,
dest_layout: TyLayout<'tcx>,
) -> EvalResult<'tcx, Scalar<M::PointerTag>> {
use rustc::ty::TyKind::*;
trace!("Casting {:?}: {:?} to {:?}", val, src_layout.ty, dest_layout.ty);
match val {
Scalar::Ptr(ptr) => self.cast_from_ptr(ptr, dest_layout.ty),
Scalar::Bits { bits, size } => {
debug_assert_eq!(size as u64, src_layout.size.bytes());
debug_assert_eq!(truncate(bits, Size::from_bytes(size.into())), bits,
"Unexpected value of size {} before casting", size);
let res = match src_layout.ty.sty {
Float(fty) => self.cast_from_float(bits, fty, dest_layout.ty)?,
_ => self.cast_from_int(bits, src_layout, dest_layout)?,
};
// Sanity check
match res {
Scalar::Ptr(_) => bug!("Fabricated a ptr value from an int...?"),
Scalar::Bits { bits, size } => {
debug_assert_eq!(size as u64, dest_layout.size.bytes());
debug_assert_eq!(truncate(bits, Size::from_bytes(size.into())), bits,
"Unexpected value of size {} after casting", size);
}
}
// Done
Ok(res)
}
}
}
fn cast_from_int(
&self,
v: u128,
src_layout: TyLayout<'tcx>,
dest_layout: TyLayout<'tcx>,
) -> EvalResult<'tcx, Scalar<M::PointerTag>> {
let signed = src_layout.abi.is_signed();
let v = if signed {
self.sign_extend(v, src_layout)
} else {
v
};
trace!("cast_from_int: {}, {}, {}", v, src_layout.ty, dest_layout.ty);
use rustc::ty::TyKind::*;
match dest_layout.ty.sty {
Int(_) | Uint(_) => {
let v = self.truncate(v, dest_layout);
Ok(Scalar::from_uint(v, dest_layout.size))
}
Float(FloatTy::F32) if signed => Ok(Scalar::from_uint(
Single::from_i128(v as i128).value.to_bits(),
Size::from_bits(32)
)),
Float(FloatTy::F64) if signed => Ok(Scalar::from_uint(
Double::from_i128(v as i128).value.to_bits(),
Size::from_bits(64)
)),
Float(FloatTy::F32) => Ok(Scalar::from_uint(
Single::from_u128(v).value.to_bits(),
Size::from_bits(32)
)),
Float(FloatTy::F64) => Ok(Scalar::from_uint(
Double::from_u128(v).value.to_bits(),
Size::from_bits(64)
)),
Char => {
// `u8` to `char` cast
debug_assert_eq!(v as u8 as u128, v);
Ok(Scalar::from_uint(v, Size::from_bytes(4)))
},
// No alignment check needed for raw pointers.
// But we have to truncate to target ptr size.
RawPtr(_) => {
Ok(Scalar::from_uint(
self.truncate_to_ptr(v).0,
self.pointer_size(),
))
},
// Casts to bool are not permitted by rustc, no need to handle them here.
_ => err!(Unimplemented(format!("int to {:?} cast", dest_layout.ty))),
}
}
fn cast_from_float(
&self,
bits: u128,
fty: FloatTy,
dest_ty: Ty<'tcx>
) -> EvalResult<'tcx, Scalar<M::PointerTag>> {
use rustc::ty::TyKind::*;
use rustc_apfloat::FloatConvert;
match dest_ty.sty {
// float -> uint
Uint(t) => {
let width = t.bit_width().unwrap_or_else(|| self.pointer_size().bits() as usize);
let v = match fty {
FloatTy::F32 => Single::from_bits(bits).to_u128(width).value,
FloatTy::F64 => Double::from_bits(bits).to_u128(width).value,
};
// This should already fit the bit width
Ok(Scalar::from_uint(v, Size::from_bits(width as u64)))
},
// float -> int
Int(t) => {
let width = t.bit_width().unwrap_or_else(|| self.pointer_size().bits() as usize);
let v = match fty {
FloatTy::F32 => Single::from_bits(bits).to_i128(width).value,
FloatTy::F64 => Double::from_bits(bits).to_i128(width).value,
};
Ok(Scalar::from_int(v, Size::from_bits(width as u64)))
},
// f64 -> f32
Float(FloatTy::F32) if fty == FloatTy::F64 => {
Ok(Scalar::from_uint(
Single::to_bits(Double::from_bits(bits).convert(&mut false).value),
Size::from_bits(32),
))
},
// f32 -> f64
Float(FloatTy::F64) if fty == FloatTy::F32 => {
Ok(Scalar::from_uint(
Double::to_bits(Single::from_bits(bits).convert(&mut false).value),
Size::from_bits(64),
))
},
// identity cast
Float(FloatTy:: F64) => Ok(Scalar::from_uint(bits, Size::from_bits(64))),
Float(FloatTy:: F32) => Ok(Scalar::from_uint(bits, Size::from_bits(32))),
_ => err!(Unimplemented(format!("float to {:?} cast", dest_ty))),
}
}
fn cast_from_ptr(
&self,
ptr: Pointer<M::PointerTag>,
ty: Ty<'tcx>
) -> EvalResult<'tcx, Scalar<M::PointerTag>> {
use rustc::ty::TyKind::*;
match ty.sty {
// Casting to a reference or fn pointer is not permitted by rustc,
// no need to support it here.
RawPtr(_) |
Int(IntTy::Isize) |
Uint(UintTy::Usize) => Ok(ptr.into()),
Int(_) | Uint(_) => err!(ReadPointerAsBytes),
_ => err!(Unimplemented(format!("ptr to {:?} cast", ty))),
}
}
fn unsize_into_ptr(
&mut self,
src: OpTy<'tcx, M::PointerTag>,
dest: PlaceTy<'tcx, M::PointerTag>,
// The pointee types
sty: Ty<'tcx>,
dty: Ty<'tcx>,
) -> EvalResult<'tcx> {
// A<Struct> -> A<Trait> conversion
let (src_pointee_ty, dest_pointee_ty) = self.tcx.struct_lockstep_tails(sty, dty);
match (&src_pointee_ty.sty, &dest_pointee_ty.sty) {
(&ty::Array(_, length), &ty::Slice(_)) => {
let ptr = self.read_immediate(src)?.to_scalar_ptr()?;
// u64 cast is from usize to u64, which is always good
let val = Immediate::new_slice(
ptr,
length.unwrap_usize(self.tcx.tcx),
self,
);
self.write_immediate(val, dest)
}
(&ty::Dynamic(..), &ty::Dynamic(..)) => {
// For now, upcasts are limited to changes in marker
// traits, and hence never actually require an actual
// change to the vtable.
let val = self.read_immediate(src)?;
self.write_immediate(*val, dest)
}
(_, &ty::Dynamic(ref data, _)) => {
// Initial cast from sized to dyn trait
let vtable = self.get_vtable(src_pointee_ty, data.principal())?;
let ptr = self.read_immediate(src)?.to_scalar_ptr()?;
let val = Immediate::new_dyn_trait(ptr, vtable);
self.write_immediate(val, dest)
}
_ => bug!("invalid unsizing {:?} -> {:?}", src.layout.ty, dest.layout.ty),
}
}
fn unsize_into(
&mut self,
src: OpTy<'tcx, M::PointerTag>,
dest: PlaceTy<'tcx, M::PointerTag>,
) -> EvalResult<'tcx> {
match (&src.layout.ty.sty, &dest.layout.ty.sty) {
(&ty::Ref(_, s, _), &ty::Ref(_, d, _)) |
(&ty::Ref(_, s, _), &ty::RawPtr(TypeAndMut { ty: d, .. })) |
(&ty::RawPtr(TypeAndMut { ty: s, .. }),
&ty::RawPtr(TypeAndMut { ty: d, .. })) => {
self.unsize_into_ptr(src, dest, s, d)
}
(&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
assert_eq!(def_a, def_b);
if def_a.is_box() || def_b.is_box() {
if !def_a.is_box() || !def_b.is_box() {
bug!("invalid unsizing between {:?} -> {:?}", src.layout, dest.layout);
}
return self.unsize_into_ptr(
src,
dest,
src.layout.ty.boxed_ty(),
dest.layout.ty.boxed_ty(),
);
}
// unsizing of generic struct with pointer fields
// Example: `Arc<T>` -> `Arc<Trait>`
// here we need to increase the size of every &T thin ptr field to a fat ptr
for i in 0..src.layout.fields.count() {
let dst_field = self.place_field(dest, i as u64)?;
if dst_field.layout.is_zst() {
continue;
}
let src_field = match src.try_as_mplace() {
Ok(mplace) => {
let src_field = self.mplace_field(mplace, i as u64)?;
src_field.into()
}
Err(..) => {
let src_field_layout = src.layout.field(self, i)?;
// this must be a field covering the entire thing
assert_eq!(src.layout.fields.offset(i).bytes(), 0);
assert_eq!(src_field_layout.size, src.layout.size);
// just sawp out the layout
OpTy::from(ImmTy { imm: src.to_immediate(), layout: src_field_layout })
}
};
if src_field.layout.ty == dst_field.layout.ty {
self.copy_op(src_field, dst_field)?;
} else {
self.unsize_into(src_field, dst_field)?;
}
}
Ok(())
}
_ => {
bug!(
"unsize_into: invalid conversion: {:?} -> {:?}",
src.layout,
dest.layout
)
}
}
}
}
| 41.058081 | 99 | 0.445907 |
08edc44fa7ec9e804453421d5ba86a4f3375d0ea | 632 | use std::error::Error;
use error::Error as AppscrapsError;
use error::ErrorKind as AppscrapsErrorKind;
use error::Result as AppscrapsResult;
pub trait WrapError {
fn wrap_error_to_err<TResult>(self) -> AppscrapsResult<TResult>;
fn wrap_error_to_error(self) -> AppscrapsError;
}
impl <TError> WrapError for TError
where TError: Error + Send + 'static {
fn wrap_error_to_err<TResult>(self) -> AppscrapsResult<TResult> {
Err(self.wrap_error_to_error())
}
fn wrap_error_to_error(self) -> AppscrapsError {
let err = Box::new(self);
AppscrapsErrorKind::ErrorWrapper(err).into()
}
}
| 27.478261 | 69 | 0.704114 |
de0b89f46ba3fbd8a643a2009af9dc28f08da45e | 1,464 | // revisions: mir thir
// [thir]compile-flags: -Z thir-unsafeck
// only-x86_64
#![feature(target_feature_11)]
#[target_feature(enable = "sse2")]
const fn sse2() {}
#[target_feature(enable = "avx")]
#[target_feature(enable = "bmi2")]
fn avx_bmi2() {}
struct Quux;
impl Quux {
#[target_feature(enable = "avx")]
#[target_feature(enable = "bmi2")]
fn avx_bmi2(&self) {}
}
fn foo() {
sse2(); //~ ERROR call to function with `#[target_feature]` is unsafe
avx_bmi2(); //~ ERROR call to function with `#[target_feature]` is unsafe
Quux.avx_bmi2(); //~ ERROR call to function with `#[target_feature]` is unsafe
}
#[target_feature(enable = "sse2")]
fn bar() {
avx_bmi2(); //~ ERROR call to function with `#[target_feature]` is unsafe
Quux.avx_bmi2(); //~ ERROR call to function with `#[target_feature]` is unsafe
}
#[target_feature(enable = "avx")]
fn baz() {
sse2(); //~ ERROR call to function with `#[target_feature]` is unsafe
avx_bmi2(); //~ ERROR call to function with `#[target_feature]` is unsafe
Quux.avx_bmi2(); //~ ERROR call to function with `#[target_feature]` is unsafe
}
#[target_feature(enable = "avx")]
#[target_feature(enable = "bmi2")]
fn qux() {
sse2(); //~ ERROR call to function with `#[target_feature]` is unsafe
}
const name: () = sse2(); //~ ERROR call to function with `#[target_feature]` is unsafe
fn main() {}
| 29.28 | 86 | 0.618169 |
1eb7c8039ddec7977477191d9cc8d4a790a5f1c4 | 1,098 | #[doc = "Reader of register US_LONPR"]
pub type R = crate::R<u32, super::US_LONPR>;
#[doc = "Writer for register US_LONPR"]
pub type W = crate::W<u32, super::US_LONPR>;
#[doc = "Register US_LONPR `reset()`'s with value 0"]
impl crate::ResetValue for super::US_LONPR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `LONPL`"]
pub type LONPL_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `LONPL`"]
pub struct LONPL_W<'a> {
w: &'a mut W,
}
impl<'a> LONPL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0x3fff) | ((value as u32) & 0x3fff);
self.w
}
}
impl R {
#[doc = "Bits 0:13 - LON Preamble Length"]
#[inline(always)]
pub fn lonpl(&self) -> LONPL_R {
LONPL_R::new((self.bits & 0x3fff) as u16)
}
}
impl W {
#[doc = "Bits 0:13 - LON Preamble Length"]
#[inline(always)]
pub fn lonpl(&mut self) -> LONPL_W {
LONPL_W { w: self }
}
}
| 26.780488 | 74 | 0.57286 |
d65860b9cf2f074780b2caeec0e93026780fe62c | 3,085 | #[doc = "Register `US_LINIR` reader"]
pub struct R(crate::R<US_LINIR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<US_LINIR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<US_LINIR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<US_LINIR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `US_LINIR` writer"]
pub struct W(crate::W<US_LINIR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<US_LINIR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<US_LINIR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<US_LINIR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `IDCHR` reader - Identifier Character"]
pub struct IDCHR_R(crate::FieldReader<u8, u8>);
impl IDCHR_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
IDCHR_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for IDCHR_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `IDCHR` writer - Identifier Character"]
pub struct IDCHR_W<'a> {
w: &'a mut W,
}
impl<'a> IDCHR_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) | (value as u32 & 0xff);
self.w
}
}
impl R {
#[doc = "Bits 0:7 - Identifier Character"]
#[inline(always)]
pub fn idchr(&self) -> IDCHR_R {
IDCHR_R::new((self.bits & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - Identifier Character"]
#[inline(always)]
pub fn idchr(&mut self) -> IDCHR_W {
IDCHR_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "LIN Identifier Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [us_linir](index.html) module"]
pub struct US_LINIR_SPEC;
impl crate::RegisterSpec for US_LINIR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [us_linir::R](R) reader structure"]
impl crate::Readable for US_LINIR_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [us_linir::W](W) writer structure"]
impl crate::Writable for US_LINIR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets US_LINIR to value 0"]
impl crate::Resettable for US_LINIR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 29.663462 | 412 | 0.60389 |
abea32802f5cf2222a73593ef052b2283e768eaf | 5,706 | #[doc = "Reader of register PSELP"]
pub type R = crate::R<u32, super::PSELP>;
#[doc = "Writer for register PSELP"]
pub type W = crate::W<u32, super::PSELP>;
#[doc = "Register PSELP `reset()`'s with value 0"]
impl crate::ResetValue for super::PSELP {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Analog positive input channel\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum PSELP_A {
#[doc = "0: Not connected"]
NC = 0,
#[doc = "1: AIN0"]
ANALOGINPUT0 = 1,
#[doc = "2: AIN1"]
ANALOGINPUT1 = 2,
#[doc = "3: AIN2"]
ANALOGINPUT2 = 3,
#[doc = "4: AIN3"]
ANALOGINPUT3 = 4,
#[doc = "5: AIN4"]
ANALOGINPUT4 = 5,
#[doc = "6: AIN5"]
ANALOGINPUT5 = 6,
#[doc = "7: AIN6"]
ANALOGINPUT6 = 7,
#[doc = "8: AIN7"]
ANALOGINPUT7 = 8,
#[doc = "9: VDD"]
VDD = 9,
}
impl From<PSELP_A> for u8 {
#[inline(always)]
fn from(variant: PSELP_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `PSELP`"]
pub type PSELP_R = crate::R<u8, PSELP_A>;
impl PSELP_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, PSELP_A> {
use crate::Variant::*;
match self.bits {
0 => Val(PSELP_A::NC),
1 => Val(PSELP_A::ANALOGINPUT0),
2 => Val(PSELP_A::ANALOGINPUT1),
3 => Val(PSELP_A::ANALOGINPUT2),
4 => Val(PSELP_A::ANALOGINPUT3),
5 => Val(PSELP_A::ANALOGINPUT4),
6 => Val(PSELP_A::ANALOGINPUT5),
7 => Val(PSELP_A::ANALOGINPUT6),
8 => Val(PSELP_A::ANALOGINPUT7),
9 => Val(PSELP_A::VDD),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `NC`"]
#[inline(always)]
pub fn is_nc(&self) -> bool {
*self == PSELP_A::NC
}
#[doc = "Checks if the value of the field is `ANALOGINPUT0`"]
#[inline(always)]
pub fn is_analog_input0(&self) -> bool {
*self == PSELP_A::ANALOGINPUT0
}
#[doc = "Checks if the value of the field is `ANALOGINPUT1`"]
#[inline(always)]
pub fn is_analog_input1(&self) -> bool {
*self == PSELP_A::ANALOGINPUT1
}
#[doc = "Checks if the value of the field is `ANALOGINPUT2`"]
#[inline(always)]
pub fn is_analog_input2(&self) -> bool {
*self == PSELP_A::ANALOGINPUT2
}
#[doc = "Checks if the value of the field is `ANALOGINPUT3`"]
#[inline(always)]
pub fn is_analog_input3(&self) -> bool {
*self == PSELP_A::ANALOGINPUT3
}
#[doc = "Checks if the value of the field is `ANALOGINPUT4`"]
#[inline(always)]
pub fn is_analog_input4(&self) -> bool {
*self == PSELP_A::ANALOGINPUT4
}
#[doc = "Checks if the value of the field is `ANALOGINPUT5`"]
#[inline(always)]
pub fn is_analog_input5(&self) -> bool {
*self == PSELP_A::ANALOGINPUT5
}
#[doc = "Checks if the value of the field is `ANALOGINPUT6`"]
#[inline(always)]
pub fn is_analog_input6(&self) -> bool {
*self == PSELP_A::ANALOGINPUT6
}
#[doc = "Checks if the value of the field is `ANALOGINPUT7`"]
#[inline(always)]
pub fn is_analog_input7(&self) -> bool {
*self == PSELP_A::ANALOGINPUT7
}
#[doc = "Checks if the value of the field is `VDD`"]
#[inline(always)]
pub fn is_vdd(&self) -> bool {
*self == PSELP_A::VDD
}
}
#[doc = "Write proxy for field `PSELP`"]
pub struct PSELP_W<'a> {
w: &'a mut W,
}
impl<'a> PSELP_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PSELP_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Not connected"]
#[inline(always)]
pub fn nc(self) -> &'a mut W {
self.variant(PSELP_A::NC)
}
#[doc = "AIN0"]
#[inline(always)]
pub fn analog_input0(self) -> &'a mut W {
self.variant(PSELP_A::ANALOGINPUT0)
}
#[doc = "AIN1"]
#[inline(always)]
pub fn analog_input1(self) -> &'a mut W {
self.variant(PSELP_A::ANALOGINPUT1)
}
#[doc = "AIN2"]
#[inline(always)]
pub fn analog_input2(self) -> &'a mut W {
self.variant(PSELP_A::ANALOGINPUT2)
}
#[doc = "AIN3"]
#[inline(always)]
pub fn analog_input3(self) -> &'a mut W {
self.variant(PSELP_A::ANALOGINPUT3)
}
#[doc = "AIN4"]
#[inline(always)]
pub fn analog_input4(self) -> &'a mut W {
self.variant(PSELP_A::ANALOGINPUT4)
}
#[doc = "AIN5"]
#[inline(always)]
pub fn analog_input5(self) -> &'a mut W {
self.variant(PSELP_A::ANALOGINPUT5)
}
#[doc = "AIN6"]
#[inline(always)]
pub fn analog_input6(self) -> &'a mut W {
self.variant(PSELP_A::ANALOGINPUT6)
}
#[doc = "AIN7"]
#[inline(always)]
pub fn analog_input7(self) -> &'a mut W {
self.variant(PSELP_A::ANALOGINPUT7)
}
#[doc = "VDD"]
#[inline(always)]
pub fn vdd(self) -> &'a mut W {
self.variant(PSELP_A::VDD)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x1f) | ((value as u32) & 0x1f);
self.w
}
}
impl R {
#[doc = "Bits 0:4 - Analog positive input channel"]
#[inline(always)]
pub fn pselp(&self) -> PSELP_R {
PSELP_R::new((self.bits & 0x1f) as u8)
}
}
impl W {
#[doc = "Bits 0:4 - Analog positive input channel"]
#[inline(always)]
pub fn pselp(&mut self) -> PSELP_W {
PSELP_W { w: self }
}
}
| 28.964467 | 70 | 0.55205 |
50ec592f5f389236b3e3e1baef62c6019faacc0b | 938 | /// Fallback mode after successful packet transmission or packet reception.
///
/// Argument of [`set_tx_rx_fallback_mode`].
///
/// [`set_tx_rx_fallback_mode`]: crate::subghz::SubGhz::set_tx_rx_fallback_mode.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum FallbackMode {
/// Standby mode entry.
Standby = 0x20,
/// Standby with HSE32 enabled.
StandbyHse = 0x30,
/// Frequency synthesizer entry.
Fs = 0x40,
}
impl From<FallbackMode> for u8 {
fn from(fm: FallbackMode) -> Self {
fm as u8
}
}
impl Default for FallbackMode {
/// Default fallback mode after power-on reset.
///
/// # Example
///
/// ```
/// use stm32wlxx_hal::subghz::FallbackMode;
///
/// assert_eq!(FallbackMode::default(), FallbackMode::Standby);
/// ```
fn default() -> Self {
FallbackMode::Standby
}
}
| 24.684211 | 80 | 0.621535 |
f4ccbb5cecd29575e1aaea6908036115aab6a92e | 2,303 | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
account_address::AccountAddress,
chain_id::ChainId,
transaction::{RawTransaction, SignedTransaction, TransactionPayload},
};
use anyhow::Result;
// use chrono::Utc;
use diem_crypto::{ed25519::*, test_utils::KeyPair, traits::SigningKey};
use std::string::String;
// TODO: chrono-sgx clock feature broken
// TODO: UNSAFE
use std::time::{SystemTime, UNIX_EPOCH};
use std::untrusted::time::SystemTimeEx;
pub fn create_unsigned_txn(
payload: TransactionPayload,
sender_address: AccountAddress,
sender_sequence_number: u64,
max_gas_amount: u64,
gas_unit_price: u64,
gas_currency_code: String,
txn_expiration_secs: i64, // for compatibility with UTC's timestamp.
chain_id: ChainId,
) -> RawTransaction {
//let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
RawTransaction::new(
sender_address,
sender_sequence_number,
payload,
max_gas_amount,
gas_unit_price,
gas_currency_code,
txn_expiration_secs as u64,
chain_id,
)
}
pub trait TransactionSigner {
fn sign_txn(&self, raw_txn: RawTransaction) -> Result<SignedTransaction>;
}
/// Craft a transaction request.
pub fn create_user_txn<T: TransactionSigner + ?Sized>(
signer: &T,
payload: TransactionPayload,
sender_address: AccountAddress,
sender_sequence_number: u64,
max_gas_amount: u64,
gas_unit_price: u64,
gas_currency_code: String,
txn_expiration_secs: i64, // for compatibility with UTC's timestamp.
chain_id: ChainId,
) -> Result<SignedTransaction> {
let raw_txn = create_unsigned_txn(
payload,
sender_address,
sender_sequence_number,
max_gas_amount,
gas_unit_price,
gas_currency_code,
txn_expiration_secs,
chain_id,
);
signer.sign_txn(raw_txn)
}
impl TransactionSigner for KeyPair<Ed25519PrivateKey, Ed25519PublicKey> {
fn sign_txn(&self, raw_txn: RawTransaction) -> Result<SignedTransaction> {
let signature = self.private_key.sign(&raw_txn);
Ok(SignedTransaction::new(
raw_txn,
self.public_key.clone(),
signature,
))
}
}
| 28.085366 | 80 | 0.685193 |
ff52b0e95699ce7180375ab5c7cad0b58ec51c27 | 685 | use crate::guild::Guild;
use discord_types::Message;
use std::future::Future;
pub trait CanEdit<'a> {
fn edit(&'a self, guild: &'a Guild) -> EditBuilder<'a>;
}
impl<'a> CanEdit<'a> for Message {
fn edit(&'a self, guild: &'a Guild) -> EditBuilder<'a> {
EditBuilder::new(self, guild)
}
}
pub struct EditBuilder<'a> {
message: &'a Message,
guild: &'a Guild,
}
impl<'a> EditBuilder<'a> {
fn new(message: &'a Message, guild: &'a Guild) -> Self {
EditBuilder { message, guild }
}
/*pub fn send(self) -> impl Future<Output = Result<(), Error>> {
let Self { message, guild } = self;
let client = guild.client();
async move {
// let mut res = client.edit
}
}*/
}
| 19.571429 | 65 | 0.616058 |
e556d22992f6b6571386b0331d4889b81a817a70 | 4,361 | use lock_api::{
RawMutex, RawRwLock, RawRwLockDowngrade, RawRwLockRecursive, RawRwLockUpgrade,
RawRwLockUpgradeDowngrade,
};
use std::cell::Cell;
pub struct RawCellMutex {
locked: Cell<bool>,
}
unsafe impl RawMutex for RawCellMutex {
const INIT: Self = RawCellMutex {
locked: Cell::new(false),
};
type GuardMarker = lock_api::GuardNoSend;
#[inline]
fn lock(&self) {
if self.is_locked() {
deadlock("", "Mutex")
}
self.locked.set(true)
}
#[inline]
fn try_lock(&self) -> bool {
if self.is_locked() {
false
} else {
self.locked.set(true);
true
}
}
unsafe fn unlock(&self) {
self.locked.set(false)
}
#[inline]
fn is_locked(&self) -> bool {
self.locked.get()
}
}
const WRITER_BIT: usize = 0b01;
const ONE_READER: usize = 0b10;
pub struct RawCellRwLock {
state: Cell<usize>,
}
impl RawCellRwLock {
#[inline]
fn is_exclusive(&self) -> bool {
self.state.get() & WRITER_BIT != 0
}
}
unsafe impl RawRwLock for RawCellRwLock {
const INIT: Self = Self {
state: Cell::new(0),
};
type GuardMarker = <RawCellMutex as RawMutex>::GuardMarker;
#[inline]
fn lock_shared(&self) {
if !self.try_lock_shared() {
deadlock("sharedly ", "RwLock")
}
}
#[inline]
fn try_lock_shared(&self) -> bool {
// TODO: figure out whether this is realistic; could maybe help
// debug deadlocks from 2+ read() in the same thread?
// if self.is_locked() {
// false
// } else {
// self.state.set(ONE_READER);
// true
// }
self.try_lock_shared_recursive()
}
#[inline]
unsafe fn unlock_shared(&self) {
self.state.set(self.state.get() - ONE_READER)
}
#[inline]
fn lock_exclusive(&self) {
if !self.try_lock_exclusive() {
deadlock("exclusively", "RwLock")
}
self.state.set(WRITER_BIT)
}
#[inline]
fn try_lock_exclusive(&self) -> bool {
if self.is_locked() {
false
} else {
self.state.set(WRITER_BIT);
true
}
}
unsafe fn unlock_exclusive(&self) {
self.state.set(0)
}
fn is_locked(&self) -> bool {
self.state.get() != 0
}
}
unsafe impl RawRwLockDowngrade for RawCellRwLock {
unsafe fn downgrade(&self) {
// no-op -- we're always exclusively locked for this thread
}
}
unsafe impl RawRwLockUpgrade for RawCellRwLock {
#[inline]
fn lock_upgradable(&self) {
if self.try_lock_upgradable() {
deadlock("upgradably+sharedly ", "RwLock")
}
}
#[inline]
fn try_lock_upgradable(&self) -> bool {
// defer to normal -- we can always try to upgrade
self.try_lock_shared()
}
#[inline]
unsafe fn unlock_upgradable(&self) {
self.unlock_shared()
}
#[inline]
unsafe fn upgrade(&self) {
if !self.try_upgrade() {
deadlock("upgrade ", "RwLock")
}
}
#[inline]
unsafe fn try_upgrade(&self) -> bool {
if self.state.get() == ONE_READER {
self.state.set(WRITER_BIT);
true
} else {
false
}
}
}
unsafe impl RawRwLockUpgradeDowngrade for RawCellRwLock {
#[inline]
unsafe fn downgrade_upgradable(&self) {
// no-op -- we're always upgradable
}
#[inline]
unsafe fn downgrade_to_upgradable(&self) {
// no-op -- we're always exclusively locked for this thread
}
}
unsafe impl RawRwLockRecursive for RawCellRwLock {
#[inline]
fn lock_shared_recursive(&self) {
if !self.try_lock_shared_recursive() {
deadlock("recursively+sharedly", "RwLock")
}
}
#[inline]
fn try_lock_shared_recursive(&self) -> bool {
if self.is_exclusive() {
false
} else if let Some(new) = self.state.get().checked_add(ONE_READER) {
self.state.set(new);
true
} else {
false
}
}
}
#[cold]
#[inline(never)]
fn deadlock(lockkind: &str, ty: &str) -> ! {
panic!("deadlock: tried to {}lock a Cell{} twice", lockkind, ty)
}
| 21.805 | 82 | 0.553084 |
6142892ea6f5e7848e0a2bf944445535cc9dcdc8 | 15,324 | //! A crate of fundamentals for audio PCM DSP.
//!
//! - Use the [**Sample** trait](./trait.Sample.html) to remain generic across bit-depth.
//! - Use the [**Frame** trait](./frame/trait.Frame.html) to remain generic over channel layout.
//! - Use the [**Signal** trait](./signal/trait.Signal.html) for working with **Iterators** that yield **Frames**.
//! - Use the [**slice** module](./slice/index.html) for working with slices of **Samples** and **Frames**.
//! - See the [**conv** module](./conv/index.html) for fast conversions between slices, frames and samples.
//! - See the [**types** module](./types/index.html) for provided custom sample types.
//! - See the [**interpolate** module](./interpolate/index.html) for sample rate conversion and scaling.
//! - See the [**ring_buffer** module](./ring_buffer/index.html) for fast FIFO queue options.
#![recursion_limit="512"]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(alloc, core_intrinsics))]
#[cfg(feature = "std")]
extern crate core;
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
type BTreeMap<K, V> = alloc::collections::btree_map::BTreeMap<K, V>;
#[cfg(feature = "std")]
type BTreeMap<K, V> = std::collections::BTreeMap<K, V>;
#[cfg(not(feature = "std"))]
type Vec<T> = alloc::vec::Vec<T>;
#[cfg(feature = "std")]
#[allow(dead_code)]
type Vec<T> = std::vec::Vec<T>;
#[cfg(not(feature = "std"))]
type VecDeque<T> = alloc::collections::vec_deque::VecDeque<T>;
#[cfg(feature = "std")]
type VecDeque<T> = std::collections::vec_deque::VecDeque<T>;
#[cfg(not(feature = "std"))]
pub type Box<T> = alloc::boxed::Box<T>;
#[cfg(feature = "std")]
pub type Box<T> = std::boxed::Box<T>;
#[cfg(not(feature = "std"))]
type Rc<T> = alloc::rc::Rc<T>;
#[cfg(feature = "std")]
type Rc<T> = std::rc::Rc<T>;
pub use conv::{FromSample, ToSample, Duplex, FromSampleSlice, ToSampleSlice, DuplexSampleSlice,
FromSampleSliceMut, ToSampleSliceMut, DuplexSampleSliceMut, FromBoxedSampleSlice,
ToBoxedSampleSlice, DuplexBoxedSampleSlice, FromFrameSlice, ToFrameSlice,
DuplexFrameSlice, FromFrameSliceMut, ToFrameSliceMut, DuplexFrameSliceMut,
FromBoxedFrameSlice, ToBoxedFrameSlice, DuplexBoxedFrameSlice, DuplexSlice,
DuplexSliceMut, DuplexBoxedSlice};
pub use frame::Frame;
pub use signal::Signal;
pub use types::{I24, U24, I48, U48};
pub mod slice;
pub mod conv;
pub mod envelope;
pub mod frame;
pub mod peak;
pub mod ring_buffer;
pub mod rms;
pub mod signal;
pub mod types;
pub mod window;
pub mod interpolate;
mod ops {
pub mod f32 {
#[allow(unused_imports)]
use core;
#[cfg(not(feature = "std"))]
pub fn sqrt(x: f32) -> f32 {
unsafe { core::intrinsics::sqrtf32(x) }
}
#[cfg(feature = "std")]
pub fn sqrt(x: f32) -> f32 {
x.sqrt()
}
#[cfg(feature = "std")]
pub fn powf32(a: f32, b: f32) -> f32 {
a.powf(b)
}
#[cfg(not(feature = "std"))]
pub fn powf32(a: f32, b: f32) -> f32 {
unsafe { core::intrinsics::powf32(a, b) }
}
}
pub mod f64 {
#[allow(unused_imports)]
use core;
#[cfg(not(feature = "std"))]
pub fn floor(x: f64) -> f64 {
unsafe { core::intrinsics::floorf64(x) }
}
#[cfg(feature = "std")]
pub fn floor(x: f64) -> f64 {
x.floor()
}
#[cfg(not(feature = "std"))]
#[allow(dead_code)]
pub fn ceil(x: f64) -> f64 {
unsafe { core::intrinsics::ceilf64(x) }
}
#[cfg(feature = "std")]
#[allow(dead_code)]
pub fn ceil(x: f64) -> f64 {
x.ceil()
}
#[cfg(not(feature = "std"))]
pub fn sin(x: f64) -> f64 {
unsafe { core::intrinsics::sinf64(x) }
}
#[cfg(feature = "std")]
pub fn sin(x: f64) -> f64 {
x.sin()
}
#[cfg(not(feature = "std"))]
pub fn cos(x: f64) -> f64 {
unsafe { core::intrinsics::cosf64(x) }
}
#[cfg(feature = "std")]
pub fn cos(x: f64) -> f64 {
x.cos()
}
#[cfg(not(feature = "std"))]
pub fn sqrt(x: f64) -> f64 {
unsafe { core::intrinsics::sqrtf64(x) }
}
#[cfg(feature = "std")]
pub fn sqrt(x: f64) -> f64 {
x.sqrt()
}
}
}
/// A trait for working generically across different **Sample** format types.
///
/// Provides methods for converting to and from any type that implements the
/// [`FromSample`](./trait.FromSample.html) trait and provides methods for performing signal
/// amplitude addition and multiplication.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::{I24, Sample};
///
/// fn main() {
/// assert_eq!((-1.0).to_sample::<u8>(), 0);
/// assert_eq!(0.0.to_sample::<u8>(), 128);
/// assert_eq!(0i32.to_sample::<u32>(), 2_147_483_648);
/// assert_eq!(I24::new(0).unwrap(), Sample::from_sample(0.0));
/// assert_eq!(0.0, Sample::equilibrium());
/// }
/// ```
pub trait Sample: Copy + Clone + PartialOrd + PartialEq {
/// When summing two samples of a signal together, it is necessary for both samples to be
/// represented in some signed format. This associated `Addition` type represents the format to
/// which `Self` should be converted for optimal `Addition` performance.
///
/// For example, u32's optimal `Addition` type would be i32, u8's would be i8, f32's would be
/// f32, etc.
///
/// Specifying this as an associated type allows us to automatically determine the optimal,
/// lossless Addition format type for summing any two unique `Sample` types together.
///
/// As a user of the `sample` crate, you will never need to be concerned with this type unless
/// you are defining your own unique `Sample` type(s).
type Signed: SignedSample + Duplex<Self>;
/// When multiplying two samples of a signal together, it is necessary for both samples to be
/// represented in some signed, floating-point format. This associated `Multiplication` type
/// represents the format to which `Self` should be converted for optimal `Multiplication`
/// performance.
///
/// For example, u32's optimal `Multiplication` type would be f32, u64's would be f64, i8's
/// would be f32, etc.
///
/// Specifying this as an associated type allows us to automatically determine the optimal,
/// lossless Multiplication format type for multiplying any two unique `Sample` types together.
///
/// As a user of the `sample` crate, you will never need to be concerned with this type unless
/// you are defining your own unique `Sample` type(s).
type Float: FloatSample + Duplex<Self>;
/// The equilibrium value for the wave that this `Sample` type represents. This is normally the
/// value that is equal distance from both the min and max ranges of the sample.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::Sample;
///
/// fn main() {
/// assert_eq!(0.0, f32::equilibrium());
/// assert_eq!(0, i32::equilibrium());
/// assert_eq!(128, u8::equilibrium());
/// assert_eq!(32_768_u16, Sample::equilibrium());
/// }
/// ```
///
/// **Note:** This will likely be changed to an "associated const" if the feature lands.
fn equilibrium() -> Self;
/// The multiplicative identity of the signal.
///
/// In other words: A value which when used to scale/multiply the amplitude or frequency of a
/// signal, returns the same signal.
///
/// This is useful as a default, non-affecting amplitude or frequency multiplier.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::{Sample, U48};
///
/// fn main() {
/// assert_eq!(1.0, f32::identity());
/// assert_eq!(1.0, i8::identity());
/// assert_eq!(1.0, u8::identity());
/// assert_eq!(1.0, U48::identity());
/// }
/// ```
#[inline]
fn identity() -> Self::Float {
<Self::Float as FloatSample>::identity()
}
/// Convert `self` to any type that implements `FromSample<Self>`.
///
/// Find more details on type-specific conversion ranges and caveats in the `conv` module.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::Sample;
///
/// fn main() {
/// assert_eq!(0.0.to_sample::<i32>(), 0);
/// assert_eq!(0.0.to_sample::<u8>(), 128);
/// assert_eq!((-1.0).to_sample::<u8>(), 0);
/// }
/// ```
#[inline]
fn to_sample<S>(self) -> S
where
Self: ToSample<S>,
{
self.to_sample_()
}
/// Create a `Self` from any type that implements `ToSample<Self>`.
///
/// Find more details on type-specific conversion ranges and caveats in the `conv` module.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::{Sample, I24};
///
/// fn main() {
/// assert_eq!(f32::from_sample(128_u8), 0.0);
/// assert_eq!(i8::from_sample(-1.0), -128);
/// assert_eq!(I24::from_sample(0.0), I24::new(0).unwrap());
/// }
/// ```
#[inline]
fn from_sample<S>(s: S) -> Self
where
Self: FromSample<S>,
{
FromSample::from_sample_(s)
}
/// Converts `self` to the equivalent `Sample` in the associated `Signed` format.
///
/// This is a simple wrapper around `Sample::to_sample` which may provide extra convenience in
/// some cases, particularly for assisting type inference.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::Sample;
///
/// fn main() {
/// assert_eq!(128_u8.to_signed_sample(), 0i8);
/// }
/// ```
fn to_signed_sample(self) -> Self::Signed {
self.to_sample()
}
/// Converts `self` to the equivalent `Sample` in the associated `Float` format.
///
/// This is a simple wrapper around `Sample::to_sample` which may provide extra convenience in
/// some cases, particularly for assisting type inference.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::Sample;
///
/// fn main() {
/// assert_eq!(128_u8.to_float_sample(), 0.0);
/// }
/// ```
fn to_float_sample(self) -> Self::Float {
self.to_sample()
}
/// Adds (or "offsets") the amplitude of the `Sample` by the given signed amplitude.
///
/// `Self` will be converted to `Self::Signed`, the addition will occur and then the result
/// will be converted back to `Self`. These conversions allow us to correctly handle the
/// addition of unsigned signal formats.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::Sample;
///
/// fn main() {
/// assert_eq!(0.25.add_amp(0.5), 0.75);
/// assert_eq!(192u8.add_amp(-128), 64);
/// }
/// ```
#[inline]
fn add_amp(self, amp: Self::Signed) -> Self {
let self_s = self.to_signed_sample();
(self_s + amp).to_sample()
}
/// Multiplies (or "scales") the amplitude of the `Sample` by the given float amplitude.
///
/// - `amp` > 1.0 amplifies the sample.
/// - `amp` < 1.0 attenuates the sample.
/// - `amp` == 1.0 yields the same sample.
/// - `amp` == 0.0 yields the `Sample::equilibrium`.
///
/// `Self` will be converted to `Self::Float`, the multiplication will occur and then the
/// result will be converted back to `Self`. These conversions allow us to correctly handle the
/// multiplication of integral signal formats.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::Sample;
///
/// fn main() {
/// assert_eq!(64_i8.mul_amp(0.5), 32);
/// assert_eq!(0.5.mul_amp(-2.0), -1.0);
/// assert_eq!(64_u8.mul_amp(0.0), 128);
/// }
/// ```
#[inline]
fn mul_amp(self, amp: Self::Float) -> Self {
let self_f = self.to_float_sample();
(self_f * amp).to_sample()
}
}
/// A macro used to simplify the implementation of `Sample`.
macro_rules! impl_sample {
($($T:ty:
Signed: $Addition:ty,
Float: $Modulation:ty,
equilibrium: $equilibrium:expr),*) =>
{
$(
impl Sample for $T {
type Signed = $Addition;
type Float = $Modulation;
#[inline]
fn equilibrium() -> Self {
$equilibrium
}
}
)*
}
}
// Expands to `Sample` implementations for all of the following types.
impl_sample!{
i8: Signed: i8, Float: f32, equilibrium: 0,
i16: Signed: i16, Float: f32, equilibrium: 0,
I24: Signed: I24, Float: f32, equilibrium: types::i24::EQUILIBRIUM,
i32: Signed: i32, Float: f32, equilibrium: 0,
I48: Signed: I48, Float: f64, equilibrium: types::i48::EQUILIBRIUM,
i64: Signed: i64, Float: f64, equilibrium: 0,
u8: Signed: i8, Float: f32, equilibrium: 128,
u16: Signed: i16, Float: f32, equilibrium: 32_768,
U24: Signed: i32, Float: f32, equilibrium: types::u24::EQUILIBRIUM,
u32: Signed: i32, Float: f32, equilibrium: 2_147_483_648,
U48: Signed: i64, Float: f64, equilibrium: types::u48::EQUILIBRIUM,
u64: Signed: i64, Float: f64, equilibrium: 9_223_372_036_854_775_808,
f32: Signed: f32, Float: f32, equilibrium: 0.0,
f64: Signed: f64, Float: f64, equilibrium: 0.0
}
/// Integral and floating-point **Sample** format types whose equilibrium is at 0.
///
/// **Sample**s often need to be converted to some mutual **SignedSample** type for signal
/// addition.
pub trait SignedSample
: Sample<Signed = Self>
+ core::ops::Add<Output = Self>
+ core::ops::Sub<Output = Self>
+ core::ops::Neg<Output = Self> {
}
macro_rules! impl_signed_sample { ($($T:ty)*) => { $( impl SignedSample for $T {} )* } }
impl_signed_sample!(i8 i16 I24 i32 I48 i64 f32 f64);
/// Sample format types represented as floating point numbers.
///
/// **Sample**s often need to be converted to some mutual **FloatSample** type for signal scaling
/// and modulation.
pub trait FloatSample
: Sample<Signed = Self, Float = Self>
+ SignedSample
+ core::ops::Mul<Output = Self>
+ core::ops::Div<Output = Self>
+ Duplex<f32>
+ Duplex<f64> {
/// Represents the multiplicative identity of the floating point signal.
fn identity() -> Self;
/// Calculate the square root of `Self`.
fn sample_sqrt(self) -> Self;
}
impl FloatSample for f32 {
#[inline]
fn identity() -> Self {
1.0
}
#[inline]
fn sample_sqrt(self) -> Self {
ops::f32::sqrt(self)
}
}
impl FloatSample for f64 {
#[inline]
fn identity() -> Self {
1.0
}
#[inline]
fn sample_sqrt(self) -> Self {
ops::f64::sqrt(self)
}
}
| 31.858628 | 114 | 0.576155 |
b9e4758b857fac1758832496b5ceac9c9299c307 | 415 | use snafu::prelude::*;
#[derive(Debug, Snafu)]
enum InnerError {
#[snafu(display("inner error"))]
AnExample,
}
#[derive(Debug, Snafu)]
enum Error {
NoDisplay { source: InnerError },
}
#[test]
fn default_error_display() {
let err: Error = AnExampleSnafu
.fail::<()>()
.context(NoDisplaySnafu)
.unwrap_err();
assert_eq!(format!("{}", err), "NoDisplay: inner error",);
}
| 18.863636 | 62 | 0.60241 |
16ae9605ec1c6d6aef9a0ba98c4fa48dc5c1aaf7 | 36,800 | // Copyright 2022 pyke.io
// 2019-2021 Tauri Programme within The Commons Conservancy
// [https://tauri.studio/]
//
// 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::{
collections::{hash_map::Entry, HashMap, HashSet},
ffi::OsString,
os::windows::ffi::OsStringExt
};
use lazy_static::lazy_static;
use parking_lot::Mutex;
use windows::Win32::{
System::SystemServices::{LANG_JAPANESE, LANG_KOREAN},
UI::{
Input::KeyboardAndMouse::{self as win32km, *},
TextServices::HKL,
WindowsAndMessaging::*
}
};
use super::keyboard::ExScancode;
use crate::{
keyboard::{Key, KeyCode, ModifiersState, NativeKeyCode},
platform_impl::platform::util
};
lazy_static! {
pub(crate) static ref LAYOUT_CACHE: Mutex<LayoutCache> = Mutex::new(LayoutCache::default());
}
fn key_pressed(vkey: VIRTUAL_KEY) -> bool {
unsafe { (GetKeyState(u32::from(vkey.0) as i32) & (1 << 15)) == (1 << 15) }
}
const NUMPAD_VKEYS: [VIRTUAL_KEY; 16] = [
VK_NUMPAD0,
VK_NUMPAD1,
VK_NUMPAD2,
VK_NUMPAD3,
VK_NUMPAD4,
VK_NUMPAD5,
VK_NUMPAD6,
VK_NUMPAD7,
VK_NUMPAD8,
VK_NUMPAD9,
VK_MULTIPLY,
VK_ADD,
VK_SEPARATOR,
VK_SUBTRACT,
VK_DECIMAL,
VK_DIVIDE
];
lazy_static! {
static ref NUMPAD_KEYCODES: HashSet<KeyCode> = {
let mut keycodes = HashSet::new();
keycodes.insert(KeyCode::Numpad0);
keycodes.insert(KeyCode::Numpad1);
keycodes.insert(KeyCode::Numpad2);
keycodes.insert(KeyCode::Numpad3);
keycodes.insert(KeyCode::Numpad4);
keycodes.insert(KeyCode::Numpad5);
keycodes.insert(KeyCode::Numpad6);
keycodes.insert(KeyCode::Numpad7);
keycodes.insert(KeyCode::Numpad8);
keycodes.insert(KeyCode::Numpad9);
keycodes.insert(KeyCode::NumpadMultiply);
keycodes.insert(KeyCode::NumpadAdd);
keycodes.insert(KeyCode::NumpadComma);
keycodes.insert(KeyCode::NumpadSubtract);
keycodes.insert(KeyCode::NumpadDecimal);
keycodes.insert(KeyCode::NumpadDivide);
keycodes
};
}
bitflags! {
pub struct WindowsModifiers : u8 {
const SHIFT = 1 << 0;
const CONTROL = 1 << 1;
const ALT = 1 << 2;
const CAPS_LOCK = 1 << 3;
const FLAGS_END = 1 << 4;
}
}
impl WindowsModifiers {
pub fn active_modifiers(key_state: &[u8; 256]) -> WindowsModifiers {
let shift = key_state[usize::from(VK_SHIFT.0)] & 0x80 != 0;
let lshift = key_state[usize::from(VK_LSHIFT.0)] & 0x80 != 0;
let rshift = key_state[usize::from(VK_RSHIFT.0)] & 0x80 != 0;
let control = key_state[usize::from(VK_CONTROL.0)] & 0x80 != 0;
let lcontrol = key_state[usize::from(VK_LCONTROL.0)] & 0x80 != 0;
let rcontrol = key_state[usize::from(VK_RCONTROL.0)] & 0x80 != 0;
let alt = key_state[usize::from(VK_MENU.0)] & 0x80 != 0;
let lalt = key_state[usize::from(VK_LMENU.0)] & 0x80 != 0;
let ralt = key_state[usize::from(VK_RMENU.0)] & 0x80 != 0;
let caps = key_state[usize::from(VK_CAPITAL.0)] & 0x01 != 0;
let mut result = WindowsModifiers::empty();
if shift || lshift || rshift {
result.insert(WindowsModifiers::SHIFT);
}
if control || lcontrol || rcontrol {
result.insert(WindowsModifiers::CONTROL);
}
if alt || lalt || ralt {
result.insert(WindowsModifiers::ALT);
}
if caps {
result.insert(WindowsModifiers::CAPS_LOCK);
}
result
}
pub fn apply_to_kbd_state(self, key_state: &mut [u8; 256]) {
if self.intersects(Self::SHIFT) {
key_state[usize::from(VK_SHIFT.0)] |= 0x80;
} else {
key_state[usize::from(VK_SHIFT.0)] &= !0x80;
key_state[usize::from(VK_LSHIFT.0)] &= !0x80;
key_state[usize::from(VK_RSHIFT.0)] &= !0x80;
}
if self.intersects(Self::CONTROL) {
key_state[usize::from(VK_CONTROL.0)] |= 0x80;
} else {
key_state[usize::from(VK_CONTROL.0)] &= !0x80;
key_state[usize::from(VK_LCONTROL.0)] &= !0x80;
key_state[usize::from(VK_RCONTROL.0)] &= !0x80;
}
if self.intersects(Self::ALT) {
key_state[usize::from(VK_MENU.0)] |= 0x80;
} else {
key_state[usize::from(VK_MENU.0)] &= !0x80;
key_state[usize::from(VK_LMENU.0)] &= !0x80;
key_state[usize::from(VK_RMENU.0)] &= !0x80;
}
if self.intersects(Self::CAPS_LOCK) {
key_state[usize::from(VK_CAPITAL.0)] |= 0x01;
} else {
key_state[usize::from(VK_CAPITAL.0)] &= !0x01;
}
}
/// Removes the control modifier if the alt modifier is not present.
/// This is useful because on Windows: (Control + Alt) == AltGr
/// but we don't want to interfere with the AltGr state.
pub fn remove_only_ctrl(mut self) -> WindowsModifiers {
if !self.contains(WindowsModifiers::ALT) {
self.remove(WindowsModifiers::CONTROL);
}
self
}
}
pub(crate) struct Layout {
pub hkl: HKL,
/// Maps numpad keys from Windows virtual key to a `Key`.
///
/// This is useful because some numpad keys generate different charcaters
/// based on the locale. For example `VK_DECIMAL` is sometimes "." and
/// sometimes ",". Note: numpad-specific virtual keys are only produced by
/// Windows when the NumLock is active.
///
/// Making this field separate from the `keys` field saves having to add
/// NumLock as a modifier to `WindowsModifiers`, which would double the
/// number of items in keys.
pub numlock_on_keys: HashMap<u16, Key<'static>>,
/// Like `numlock_on_keys` but this will map to the key that would be
/// produced if numlock was off. The keys of this map are identical to the
/// keys of `numlock_on_keys`.
pub numlock_off_keys: HashMap<u16, Key<'static>>,
/// Maps a modifier state to group of key strings
/// We're not using `ModifiersState` here because that object cannot express
/// caps lock, but we need to handle caps lock too.
///
/// This map shouldn't need to exist.
/// However currently this seems to be the only good way
/// of getting the label for the pressed key. Note that calling `ToUnicode`
/// just when the key is pressed/released would be enough if `ToUnicode`
/// wouldn't change the keyboard state (it clears the dead key). There is a
/// flag to prevent changing the state, but that flag requires Windows 10,
/// version 1607 or newer)
pub keys: HashMap<WindowsModifiers, HashMap<KeyCode, Key<'static>>>,
pub has_alt_graph: bool
}
impl Layout {
pub fn get_key(&self, mods: WindowsModifiers, num_lock_on: bool, vkey: VIRTUAL_KEY, scancode: ExScancode, keycode: KeyCode) -> Key<'static> {
let native_code = NativeKeyCode::Windows(scancode);
let unknown_alt = vkey == VK_MENU;
if !unknown_alt {
// Here we try using the virtual key directly but if the virtual key doesn't
// distinguish between left and right alt, we can't report AltGr. Therefore, we
// only do this if the key is not the "unknown alt" key.
//
// The reason for using the virtual key directly is that `MapVirtualKeyExW`
// (used when building the keys map) sometimes maps virtual keys to odd
// scancodes that don't match the scancode coming from the KEYDOWN message for
// the same key. For example: `VK_LEFT` is mapped to `0x004B`, but the scancode
// for the left arrow is `0xE04B`.
let key_from_vkey = vkey_to_non_char_key(vkey, native_code, self.hkl, self.has_alt_graph);
if !matches!(key_from_vkey, Key::Unidentified(_)) {
return key_from_vkey;
}
}
if num_lock_on {
if let Some(key) = self.numlock_on_keys.get(&vkey.0) {
return key.clone();
}
} else if let Some(key) = self.numlock_off_keys.get(&vkey.0) {
return key.clone();
}
if let Some(keys) = self.keys.get(&mods) {
if let Some(key) = keys.get(&keycode) {
return key.clone();
}
}
Key::Unidentified(native_code)
}
}
#[derive(Default)]
pub(crate) struct LayoutCache {
/// Maps locale identifiers (HKL) to layouts
pub layouts: HashMap<isize, Layout>,
pub strings: HashSet<&'static str>
}
impl LayoutCache {
/// Checks whether the current layout is already known and
/// prepares the layout if it isn't known.
/// The current layout is then returned.
pub fn get_current_layout<'a>(&'a mut self) -> (HKL, &'a Layout) {
let locale_id = unsafe { GetKeyboardLayout(0) };
match self.layouts.entry(locale_id.0) {
Entry::Occupied(entry) => (locale_id, entry.into_mut()),
Entry::Vacant(entry) => {
let layout = Self::prepare_layout(&mut self.strings, locale_id);
(locale_id, entry.insert(layout))
}
}
}
pub fn get_agnostic_mods(&mut self) -> ModifiersState {
let (_, layout) = self.get_current_layout();
let filter_out_altgr = layout.has_alt_graph && key_pressed(VK_RMENU);
let mut mods = ModifiersState::empty();
mods.set(ModifiersState::SHIFT, key_pressed(VK_SHIFT));
mods.set(ModifiersState::CONTROL, key_pressed(VK_CONTROL) && !filter_out_altgr);
mods.set(ModifiersState::ALT, key_pressed(VK_MENU) && !filter_out_altgr);
mods.set(ModifiersState::SUPER, key_pressed(VK_LWIN) || key_pressed(VK_RWIN));
mods
}
fn prepare_layout(strings: &mut HashSet<&'static str>, locale_id: HKL) -> Layout {
let mut layout = Layout {
hkl: locale_id,
numlock_on_keys: Default::default(),
numlock_off_keys: Default::default(),
keys: Default::default(),
has_alt_graph: false
};
// We initialize the keyboard state with all zeros to
// simulate a scenario when no modifier is active.
let mut key_state = [0u8; 256];
// `MapVirtualKeyExW` maps (non-numpad-specific) virtual keys to scancodes as if
// numlock was off. We rely on this behavior to find all virtual keys which are
// not numpad-specific but map to the numpad.
//
// src_vkey: VK ==> scancode: u16 (on the numpad)
//
// Then we convert the source virtual key into a `Key` and the scancode into a
// virtual key to get the reverse mapping.
//
// src_vkey: VK ==> scancode: u16 (on the numpad)
// || ||
// \/ \/
// map_value: Key <- map_vkey: VK
layout.numlock_off_keys.reserve(NUMPAD_KEYCODES.len());
for vk in 0_u16..256 {
let scancode = unsafe { MapVirtualKeyExW(u32::from(vk), MAPVK_VK_TO_VSC_EX, locale_id as HKL) };
if scancode == 0 {
continue;
}
let vk = VIRTUAL_KEY(vk);
let keycode = KeyCode::from_scancode(scancode);
if !is_numpad_specific(vk) && NUMPAD_KEYCODES.contains(&keycode) {
let native_code = NativeKeyCode::Windows(scancode as u16);
let map_vkey = keycode_to_vkey(keycode, locale_id);
if map_vkey == Default::default() {
continue;
}
let map_value = vkey_to_non_char_key(vk, native_code, locale_id, false);
if matches!(map_value, Key::Unidentified(_)) {
continue;
}
layout.numlock_off_keys.insert(map_vkey.0, map_value);
}
}
layout.numlock_on_keys.reserve(NUMPAD_VKEYS.len());
for vk in NUMPAD_VKEYS.iter() {
let scancode = unsafe { MapVirtualKeyExW(u32::from(vk.0), MAPVK_VK_TO_VSC_EX, locale_id as HKL) };
let unicode = Self::to_unicode_string(&key_state, *vk, scancode, locale_id);
if let ToUnicodeResult::Str(s) = unicode {
let static_str = get_or_insert_str(strings, s);
layout.numlock_on_keys.insert(vk.0, Key::Character(static_str));
}
}
// Iterate through every combination of modifiers
let mods_end = WindowsModifiers::FLAGS_END.bits;
for mod_state in 0..mods_end {
let mut keys_for_this_mod = HashMap::with_capacity(256);
let mod_state = unsafe { WindowsModifiers::from_bits_unchecked(mod_state) };
mod_state.apply_to_kbd_state(&mut key_state);
// Virtual key values are in the domain [0, 255].
// This is reinforced by the fact that the keyboard state array has 256
// elements. This array is allowed to be indexed by virtual key values
// giving the key state for the virtual key used for indexing.
for vk in 0_u16..256 {
let scancode = unsafe { MapVirtualKeyExW(u32::from(vk), MAPVK_VK_TO_VSC_EX, locale_id) };
if scancode == 0 {
continue;
}
let vk = VIRTUAL_KEY(vk);
let native_code = NativeKeyCode::Windows(scancode as ExScancode);
let key_code = KeyCode::from_scancode(scancode);
// Let's try to get the key from just the scancode and vk
// We don't necessarily know yet if AltGraph is present on this layout so we'll
// assume it isn't. Then we'll do a second pass where we set the "AltRight" keys
// to "AltGr" in case we find out that there's an AltGraph.
let preliminary_key = vkey_to_non_char_key(vk, native_code, locale_id, false);
match preliminary_key {
Key::Unidentified(_) => (),
_ => {
keys_for_this_mod.insert(key_code, preliminary_key);
continue;
}
}
let unicode = Self::to_unicode_string(&key_state, vk, scancode, locale_id);
let key = match unicode {
ToUnicodeResult::Str(str) => {
let static_str = get_or_insert_str(strings, str);
Key::Character(static_str)
}
ToUnicodeResult::Dead(dead_char) => {
//#[cfg(debug_assertions)] println!("{:?} - {:?} produced dead {:?}", key_code, mod_state, dead_char);
Key::Dead(dead_char)
}
ToUnicodeResult::None => {
let has_alt = mod_state.contains(WindowsModifiers::ALT);
let has_ctrl = mod_state.contains(WindowsModifiers::CONTROL);
// HACK: `ToUnicodeEx` seems to fail getting the string for the numpad
// divide key, so we handle that explicitly here
if !has_alt && !has_ctrl && key_code == KeyCode::NumpadDivide {
Key::Character("/")
} else {
// Just use the unidentified key, we got earlier
preliminary_key
}
}
};
// Check for alt graph.
// The logic is that if a key pressed with no modifier produces
// a different `Character` from when it's pressed with CTRL+ALT then the layout
// has AltGr.
let ctrl_alt: WindowsModifiers = WindowsModifiers::CONTROL | WindowsModifiers::ALT;
let is_in_ctrl_alt = mod_state == ctrl_alt;
if !layout.has_alt_graph && is_in_ctrl_alt {
// Unwrapping here because if we are in the ctrl+alt modifier state
// then the alt modifier state must have come before.
let simple_keys = layout.keys.get(&WindowsModifiers::empty()).unwrap();
if let Some(Key::Character(key_no_altgr)) = simple_keys.get(&key_code) {
if let Key::Character(key) = key.clone() {
layout.has_alt_graph = key != *key_no_altgr;
}
}
}
keys_for_this_mod.insert(key_code, key);
}
layout.keys.insert(mod_state, keys_for_this_mod);
}
// Second pass: replace right alt keys with AltGr if the layout has alt graph
if layout.has_alt_graph {
for mod_state in 0..mods_end {
let mod_state = unsafe { WindowsModifiers::from_bits_unchecked(mod_state) };
if let Some(keys) = layout.keys.get_mut(&mod_state) {
if let Some(key) = keys.get_mut(&KeyCode::AltRight) {
*key = Key::AltGraph;
}
}
}
}
layout
}
fn to_unicode_string(key_state: &[u8; 256], vkey: VIRTUAL_KEY, scancode: u32, locale_id: HKL) -> ToUnicodeResult {
unsafe {
let mut label_wide = [0u16; 8];
let mut wide_len = ToUnicodeEx(u32::from(vkey.0), scancode, key_state, &mut label_wide, 0, locale_id);
if wide_len < 0 {
// If it's dead, we run `ToUnicode` again to consume the dead-key
wide_len = ToUnicodeEx(u32::from(vkey.0), scancode, key_state, &mut label_wide, 0, locale_id);
if wide_len > 0 {
let os_string = OsString::from_wide(&label_wide[0..wide_len as usize]);
if let Ok(label_str) = os_string.into_string() {
if let Some(ch) = label_str.chars().next() {
return ToUnicodeResult::Dead(Some(ch));
}
}
}
return ToUnicodeResult::Dead(None);
}
if wide_len > 0 {
let os_string = OsString::from_wide(&label_wide[0..wide_len as usize]);
if let Ok(label_str) = os_string.into_string() {
return ToUnicodeResult::Str(label_str);
}
}
}
ToUnicodeResult::None
}
}
pub fn get_or_insert_str<T>(strings: &mut HashSet<&'static str>, string: T) -> &'static str
where
T: AsRef<str>,
String: From<T>
{
{
let str_ref = string.as_ref();
if let Some(&existing) = strings.get(str_ref) {
return existing;
}
}
let leaked = Box::leak(Box::from(String::from(string)));
strings.insert(leaked);
leaked
}
#[derive(Debug, Clone, Eq, PartialEq)]
enum ToUnicodeResult {
Str(String),
Dead(Option<char>),
None
}
fn is_numpad_specific(vk: VIRTUAL_KEY) -> bool {
matches!(
vk,
win32km::VK_NUMPAD0
| win32km::VK_NUMPAD1
| win32km::VK_NUMPAD2
| win32km::VK_NUMPAD3
| win32km::VK_NUMPAD4
| win32km::VK_NUMPAD5
| win32km::VK_NUMPAD6
| win32km::VK_NUMPAD7
| win32km::VK_NUMPAD8
| win32km::VK_NUMPAD9
| win32km::VK_ADD
| win32km::VK_SUBTRACT
| win32km::VK_DIVIDE
| win32km::VK_DECIMAL
| win32km::VK_SEPARATOR
)
}
fn keycode_to_vkey(keycode: KeyCode, hkl: HKL) -> VIRTUAL_KEY {
let primary_lang_id = util::PRIMARYLANGID(hkl);
let is_korean = primary_lang_id == LANG_KOREAN;
let is_japanese = primary_lang_id == LANG_JAPANESE;
match keycode {
KeyCode::Backquote => VIRTUAL_KEY::default(),
KeyCode::Backslash => VIRTUAL_KEY::default(),
KeyCode::BracketLeft => VIRTUAL_KEY::default(),
KeyCode::BracketRight => VIRTUAL_KEY::default(),
KeyCode::Comma => VIRTUAL_KEY::default(),
KeyCode::Digit0 => VIRTUAL_KEY::default(),
KeyCode::Digit1 => VIRTUAL_KEY::default(),
KeyCode::Digit2 => VIRTUAL_KEY::default(),
KeyCode::Digit3 => VIRTUAL_KEY::default(),
KeyCode::Digit4 => VIRTUAL_KEY::default(),
KeyCode::Digit5 => VIRTUAL_KEY::default(),
KeyCode::Digit6 => VIRTUAL_KEY::default(),
KeyCode::Digit7 => VIRTUAL_KEY::default(),
KeyCode::Digit8 => VIRTUAL_KEY::default(),
KeyCode::Digit9 => VIRTUAL_KEY::default(),
KeyCode::Equal => VIRTUAL_KEY::default(),
KeyCode::IntlBackslash => VIRTUAL_KEY::default(),
KeyCode::IntlRo => VIRTUAL_KEY::default(),
KeyCode::IntlYen => VIRTUAL_KEY::default(),
KeyCode::KeyA => VIRTUAL_KEY::default(),
KeyCode::KeyB => VIRTUAL_KEY::default(),
KeyCode::KeyC => VIRTUAL_KEY::default(),
KeyCode::KeyD => VIRTUAL_KEY::default(),
KeyCode::KeyE => VIRTUAL_KEY::default(),
KeyCode::KeyF => VIRTUAL_KEY::default(),
KeyCode::KeyG => VIRTUAL_KEY::default(),
KeyCode::KeyH => VIRTUAL_KEY::default(),
KeyCode::KeyI => VIRTUAL_KEY::default(),
KeyCode::KeyJ => VIRTUAL_KEY::default(),
KeyCode::KeyK => VIRTUAL_KEY::default(),
KeyCode::KeyL => VIRTUAL_KEY::default(),
KeyCode::KeyM => VIRTUAL_KEY::default(),
KeyCode::KeyN => VIRTUAL_KEY::default(),
KeyCode::KeyO => VIRTUAL_KEY::default(),
KeyCode::KeyP => VIRTUAL_KEY::default(),
KeyCode::KeyQ => VIRTUAL_KEY::default(),
KeyCode::KeyR => VIRTUAL_KEY::default(),
KeyCode::KeyS => VIRTUAL_KEY::default(),
KeyCode::KeyT => VIRTUAL_KEY::default(),
KeyCode::KeyU => VIRTUAL_KEY::default(),
KeyCode::KeyV => VIRTUAL_KEY::default(),
KeyCode::KeyW => VIRTUAL_KEY::default(),
KeyCode::KeyX => VIRTUAL_KEY::default(),
KeyCode::KeyY => VIRTUAL_KEY::default(),
KeyCode::KeyZ => VIRTUAL_KEY::default(),
KeyCode::Minus => VIRTUAL_KEY::default(),
KeyCode::Period => VIRTUAL_KEY::default(),
KeyCode::Quote => VIRTUAL_KEY::default(),
KeyCode::Semicolon => VIRTUAL_KEY::default(),
KeyCode::Slash => VIRTUAL_KEY::default(),
KeyCode::AltLeft => VK_LMENU,
KeyCode::AltRight => VK_RMENU,
KeyCode::Backspace => VK_BACK,
KeyCode::CapsLock => VK_CAPITAL,
KeyCode::ContextMenu => VK_APPS,
KeyCode::ControlLeft => VK_LCONTROL,
KeyCode::ControlRight => VK_RCONTROL,
KeyCode::Enter => VK_RETURN,
KeyCode::SuperLeft => VK_LWIN,
KeyCode::SuperRight => VK_RWIN,
KeyCode::ShiftLeft => VK_RSHIFT,
KeyCode::ShiftRight => VK_LSHIFT,
KeyCode::Space => VK_SPACE,
KeyCode::Tab => VK_TAB,
KeyCode::Convert => VK_CONVERT,
KeyCode::KanaMode => VK_KANA,
KeyCode::Lang1 if is_korean => VK_HANGUL,
KeyCode::Lang1 if is_japanese => VK_KANA,
KeyCode::Lang2 if is_korean => VK_HANJA,
KeyCode::Lang2 if is_japanese => VIRTUAL_KEY::default(),
KeyCode::Lang3 if is_japanese => VK_OEM_FINISH,
KeyCode::Lang4 if is_japanese => VIRTUAL_KEY::default(),
KeyCode::Lang5 if is_japanese => VIRTUAL_KEY::default(),
KeyCode::NonConvert => VK_NONCONVERT,
KeyCode::Delete => VK_DELETE,
KeyCode::End => VK_END,
KeyCode::Help => VK_HELP,
KeyCode::Home => VK_HOME,
KeyCode::Insert => VK_INSERT,
KeyCode::PageDown => VK_NEXT,
KeyCode::PageUp => VK_PRIOR,
KeyCode::ArrowDown => VK_DOWN,
KeyCode::ArrowLeft => VK_LEFT,
KeyCode::ArrowRight => VK_RIGHT,
KeyCode::ArrowUp => VK_UP,
KeyCode::NumLock => VK_NUMLOCK,
KeyCode::Numpad0 => VK_NUMPAD0,
KeyCode::Numpad1 => VK_NUMPAD1,
KeyCode::Numpad2 => VK_NUMPAD2,
KeyCode::Numpad3 => VK_NUMPAD3,
KeyCode::Numpad4 => VK_NUMPAD4,
KeyCode::Numpad5 => VK_NUMPAD5,
KeyCode::Numpad6 => VK_NUMPAD6,
KeyCode::Numpad7 => VK_NUMPAD7,
KeyCode::Numpad8 => VK_NUMPAD8,
KeyCode::Numpad9 => VK_NUMPAD9,
KeyCode::NumpadAdd => VK_ADD,
KeyCode::NumpadBackspace => VK_BACK,
KeyCode::NumpadClear => VK_CLEAR,
KeyCode::NumpadClearEntry => VIRTUAL_KEY::default(),
KeyCode::NumpadComma => VK_SEPARATOR,
KeyCode::NumpadDecimal => VK_DECIMAL,
KeyCode::NumpadDivide => VK_DIVIDE,
KeyCode::NumpadEnter => VK_RETURN,
KeyCode::NumpadEqual => VIRTUAL_KEY::default(),
KeyCode::NumpadHash => VIRTUAL_KEY::default(),
KeyCode::NumpadMemoryAdd => VIRTUAL_KEY::default(),
KeyCode::NumpadMemoryClear => VIRTUAL_KEY::default(),
KeyCode::NumpadMemoryRecall => VIRTUAL_KEY::default(),
KeyCode::NumpadMemoryStore => VIRTUAL_KEY::default(),
KeyCode::NumpadMemorySubtract => VIRTUAL_KEY::default(),
KeyCode::NumpadMultiply => VK_MULTIPLY,
KeyCode::NumpadParenLeft => VIRTUAL_KEY::default(),
KeyCode::NumpadParenRight => VIRTUAL_KEY::default(),
KeyCode::NumpadStar => VIRTUAL_KEY::default(),
KeyCode::NumpadSubtract => VK_SUBTRACT,
KeyCode::Escape => VK_ESCAPE,
KeyCode::Fn => VIRTUAL_KEY::default(),
KeyCode::FnLock => VIRTUAL_KEY::default(),
KeyCode::PrintScreen => VK_SNAPSHOT,
KeyCode::ScrollLock => VK_SCROLL,
KeyCode::Pause => VK_PAUSE,
KeyCode::BrowserBack => VK_BROWSER_BACK,
KeyCode::BrowserFavorites => VK_BROWSER_FAVORITES,
KeyCode::BrowserForward => VK_BROWSER_FORWARD,
KeyCode::BrowserHome => VK_BROWSER_HOME,
KeyCode::BrowserRefresh => VK_BROWSER_REFRESH,
KeyCode::BrowserSearch => VK_BROWSER_SEARCH,
KeyCode::BrowserStop => VK_BROWSER_STOP,
KeyCode::Eject => VIRTUAL_KEY::default(),
KeyCode::LaunchApp1 => VK_LAUNCH_APP1,
KeyCode::LaunchApp2 => VK_LAUNCH_APP2,
KeyCode::LaunchMail => VK_LAUNCH_MAIL,
KeyCode::MediaPlayPause => VK_MEDIA_PLAY_PAUSE,
KeyCode::MediaSelect => VK_LAUNCH_MEDIA_SELECT,
KeyCode::MediaStop => VK_MEDIA_STOP,
KeyCode::MediaTrackNext => VK_MEDIA_NEXT_TRACK,
KeyCode::MediaTrackPrevious => VK_MEDIA_PREV_TRACK,
KeyCode::Power => VIRTUAL_KEY::default(),
KeyCode::Sleep => VIRTUAL_KEY::default(),
KeyCode::AudioVolumeDown => VK_VOLUME_DOWN,
KeyCode::AudioVolumeMute => VK_VOLUME_MUTE,
KeyCode::AudioVolumeUp => VK_VOLUME_UP,
KeyCode::WakeUp => VIRTUAL_KEY::default(),
KeyCode::Hyper => VIRTUAL_KEY::default(),
KeyCode::Turbo => VIRTUAL_KEY::default(),
KeyCode::Abort => VIRTUAL_KEY::default(),
KeyCode::Resume => VIRTUAL_KEY::default(),
KeyCode::Suspend => VIRTUAL_KEY::default(),
KeyCode::Again => VIRTUAL_KEY::default(),
KeyCode::Copy => VIRTUAL_KEY::default(),
KeyCode::Cut => VIRTUAL_KEY::default(),
KeyCode::Find => VIRTUAL_KEY::default(),
KeyCode::Open => VIRTUAL_KEY::default(),
KeyCode::Paste => VIRTUAL_KEY::default(),
KeyCode::Props => VIRTUAL_KEY::default(),
KeyCode::Select => VK_SELECT,
KeyCode::Undo => VIRTUAL_KEY::default(),
KeyCode::Hiragana => VIRTUAL_KEY::default(),
KeyCode::Katakana => VIRTUAL_KEY::default(),
KeyCode::F1 => VK_F1,
KeyCode::F2 => VK_F2,
KeyCode::F3 => VK_F3,
KeyCode::F4 => VK_F4,
KeyCode::F5 => VK_F5,
KeyCode::F6 => VK_F6,
KeyCode::F7 => VK_F7,
KeyCode::F8 => VK_F8,
KeyCode::F9 => VK_F9,
KeyCode::F10 => VK_F10,
KeyCode::F11 => VK_F11,
KeyCode::F12 => VK_F12,
KeyCode::F13 => VK_F13,
KeyCode::F14 => VK_F14,
KeyCode::F15 => VK_F15,
KeyCode::F16 => VK_F16,
KeyCode::F17 => VK_F17,
KeyCode::F18 => VK_F18,
KeyCode::F19 => VK_F19,
KeyCode::F20 => VK_F20,
KeyCode::F21 => VK_F21,
KeyCode::F22 => VK_F22,
KeyCode::F23 => VK_F23,
KeyCode::F24 => VK_F24,
KeyCode::F25 => VIRTUAL_KEY::default(),
KeyCode::F26 => VIRTUAL_KEY::default(),
KeyCode::F27 => VIRTUAL_KEY::default(),
KeyCode::F28 => VIRTUAL_KEY::default(),
KeyCode::F29 => VIRTUAL_KEY::default(),
KeyCode::F30 => VIRTUAL_KEY::default(),
KeyCode::F31 => VIRTUAL_KEY::default(),
KeyCode::F32 => VIRTUAL_KEY::default(),
KeyCode::F33 => VIRTUAL_KEY::default(),
KeyCode::F34 => VIRTUAL_KEY::default(),
KeyCode::F35 => VIRTUAL_KEY::default(),
KeyCode::Unidentified(_) => VIRTUAL_KEY::default(),
_ => VIRTUAL_KEY::default()
}
}
/// This converts virtual keys to `Key`s. Only virtual keys which can be
/// unambiguously converted to a `Key`, with only the information passed in as
/// arguments, are converted.
///
/// In other words: this function does not need to "prepare" the current layout
/// in order to do the conversion, but as such it cannot convert certain keys,
/// like language-specific character keys.
///
/// The result includes all non-character keys defined within `Key` plus
/// characters from numpad keys. For example, backspace and tab are included.
fn vkey_to_non_char_key(vkey: VIRTUAL_KEY, native_code: NativeKeyCode, hkl: HKL, has_alt_graph: bool) -> Key<'static> {
// List of the Web key names and their corresponding platform-native key names:
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
let primary_lang_id = util::PRIMARYLANGID(hkl);
let is_korean = primary_lang_id == LANG_KOREAN;
let is_japanese = primary_lang_id == LANG_JAPANESE;
match vkey {
win32km::VK_LBUTTON => Key::Unidentified(NativeKeyCode::Unidentified), // Mouse
win32km::VK_RBUTTON => Key::Unidentified(NativeKeyCode::Unidentified), // Mouse
// I don't think this can be represented with a Key
win32km::VK_CANCEL => Key::Unidentified(native_code),
win32km::VK_MBUTTON => Key::Unidentified(NativeKeyCode::Unidentified), // Mouse
win32km::VK_XBUTTON1 => Key::Unidentified(NativeKeyCode::Unidentified), // Mouse
win32km::VK_XBUTTON2 => Key::Unidentified(NativeKeyCode::Unidentified), // Mouse
win32km::VK_BACK => Key::Backspace,
win32km::VK_TAB => Key::Tab,
win32km::VK_CLEAR => Key::Clear,
win32km::VK_RETURN => Key::Enter,
win32km::VK_SHIFT => Key::Shift,
win32km::VK_CONTROL => Key::Control,
win32km::VK_MENU => Key::Alt,
win32km::VK_PAUSE => Key::Pause,
win32km::VK_CAPITAL => Key::CapsLock,
// win32km::VK_HANGEUL => Key::HangulMode, // Deprecated in favour of VK_HANGUL
// VK_HANGUL and VK_KANA are defined as the same constant, therefore
// we use appropriate conditions to differentate between them
win32km::VK_HANGUL if is_korean => Key::HangulMode,
win32km::VK_KANA if is_japanese => Key::KanaMode,
win32km::VK_JUNJA => Key::JunjaMode,
win32km::VK_FINAL => Key::FinalMode,
// VK_HANJA and VK_KANJI are defined as the same constant, therefore
// we use appropriate conditions to differentate between them
win32km::VK_HANJA if is_korean => Key::HanjaMode,
win32km::VK_KANJI if is_japanese => Key::KanjiMode,
win32km::VK_ESCAPE => Key::Escape,
win32km::VK_CONVERT => Key::Convert,
win32km::VK_NONCONVERT => Key::NonConvert,
win32km::VK_ACCEPT => Key::Accept,
win32km::VK_MODECHANGE => Key::ModeChange,
win32km::VK_SPACE => Key::Space,
win32km::VK_PRIOR => Key::PageUp,
win32km::VK_NEXT => Key::PageDown,
win32km::VK_END => Key::End,
win32km::VK_HOME => Key::Home,
win32km::VK_LEFT => Key::ArrowLeft,
win32km::VK_UP => Key::ArrowUp,
win32km::VK_RIGHT => Key::ArrowRight,
win32km::VK_DOWN => Key::ArrowDown,
win32km::VK_SELECT => Key::Select,
win32km::VK_PRINT => Key::Print,
win32km::VK_EXECUTE => Key::Execute,
win32km::VK_SNAPSHOT => Key::PrintScreen,
win32km::VK_INSERT => Key::Insert,
win32km::VK_DELETE => Key::Delete,
win32km::VK_HELP => Key::Help,
win32km::VK_LWIN => Key::Super,
win32km::VK_RWIN => Key::Super,
win32km::VK_APPS => Key::ContextMenu,
win32km::VK_SLEEP => Key::Standby,
// Numpad keys produce characters
win32km::VK_NUMPAD0 => Key::Unidentified(native_code),
win32km::VK_NUMPAD1 => Key::Unidentified(native_code),
win32km::VK_NUMPAD2 => Key::Unidentified(native_code),
win32km::VK_NUMPAD3 => Key::Unidentified(native_code),
win32km::VK_NUMPAD4 => Key::Unidentified(native_code),
win32km::VK_NUMPAD5 => Key::Unidentified(native_code),
win32km::VK_NUMPAD6 => Key::Unidentified(native_code),
win32km::VK_NUMPAD7 => Key::Unidentified(native_code),
win32km::VK_NUMPAD8 => Key::Unidentified(native_code),
win32km::VK_NUMPAD9 => Key::Unidentified(native_code),
win32km::VK_MULTIPLY => Key::Unidentified(native_code),
win32km::VK_ADD => Key::Unidentified(native_code),
win32km::VK_SEPARATOR => Key::Unidentified(native_code),
win32km::VK_SUBTRACT => Key::Unidentified(native_code),
win32km::VK_DECIMAL => Key::Unidentified(native_code),
win32km::VK_DIVIDE => Key::Unidentified(native_code),
win32km::VK_F1 => Key::F1,
win32km::VK_F2 => Key::F2,
win32km::VK_F3 => Key::F3,
win32km::VK_F4 => Key::F4,
win32km::VK_F5 => Key::F5,
win32km::VK_F6 => Key::F6,
win32km::VK_F7 => Key::F7,
win32km::VK_F8 => Key::F8,
win32km::VK_F9 => Key::F9,
win32km::VK_F10 => Key::F10,
win32km::VK_F11 => Key::F11,
win32km::VK_F12 => Key::F12,
win32km::VK_F13 => Key::F13,
win32km::VK_F14 => Key::F14,
win32km::VK_F15 => Key::F15,
win32km::VK_F16 => Key::F16,
win32km::VK_F17 => Key::F17,
win32km::VK_F18 => Key::F18,
win32km::VK_F19 => Key::F19,
win32km::VK_F20 => Key::F20,
win32km::VK_F21 => Key::F21,
win32km::VK_F22 => Key::F22,
win32km::VK_F23 => Key::F23,
win32km::VK_F24 => Key::F24,
win32km::VK_NAVIGATION_VIEW => Key::Unidentified(native_code),
win32km::VK_NAVIGATION_MENU => Key::Unidentified(native_code),
win32km::VK_NAVIGATION_UP => Key::Unidentified(native_code),
win32km::VK_NAVIGATION_DOWN => Key::Unidentified(native_code),
win32km::VK_NAVIGATION_LEFT => Key::Unidentified(native_code),
win32km::VK_NAVIGATION_RIGHT => Key::Unidentified(native_code),
win32km::VK_NAVIGATION_ACCEPT => Key::Unidentified(native_code),
win32km::VK_NAVIGATION_CANCEL => Key::Unidentified(native_code),
win32km::VK_NUMLOCK => Key::NumLock,
win32km::VK_SCROLL => Key::ScrollLock,
win32km::VK_OEM_NEC_EQUAL => Key::Unidentified(native_code),
// win32km::VK_OEM_FJ_JISHO => Key::Unidentified(native_code), // Conflicts with `VK_OEM_NEC_EQUAL`
win32km::VK_OEM_FJ_MASSHOU => Key::Unidentified(native_code),
win32km::VK_OEM_FJ_TOUROKU => Key::Unidentified(native_code),
win32km::VK_OEM_FJ_LOYA => Key::Unidentified(native_code),
win32km::VK_OEM_FJ_ROYA => Key::Unidentified(native_code),
win32km::VK_LSHIFT => Key::Shift,
win32km::VK_RSHIFT => Key::Shift,
win32km::VK_LCONTROL => Key::Control,
win32km::VK_RCONTROL => Key::Control,
win32km::VK_LMENU => Key::Alt,
win32km::VK_RMENU => {
if has_alt_graph {
Key::AltGraph
} else {
Key::Alt
}
}
win32km::VK_BROWSER_BACK => Key::BrowserBack,
win32km::VK_BROWSER_FORWARD => Key::BrowserForward,
win32km::VK_BROWSER_REFRESH => Key::BrowserRefresh,
win32km::VK_BROWSER_STOP => Key::BrowserStop,
win32km::VK_BROWSER_SEARCH => Key::BrowserSearch,
win32km::VK_BROWSER_FAVORITES => Key::BrowserFavorites,
win32km::VK_BROWSER_HOME => Key::BrowserHome,
win32km::VK_VOLUME_MUTE => Key::AudioVolumeMute,
win32km::VK_VOLUME_DOWN => Key::AudioVolumeDown,
win32km::VK_VOLUME_UP => Key::AudioVolumeUp,
win32km::VK_MEDIA_NEXT_TRACK => Key::MediaTrackNext,
win32km::VK_MEDIA_PREV_TRACK => Key::MediaTrackPrevious,
win32km::VK_MEDIA_STOP => Key::MediaStop,
win32km::VK_MEDIA_PLAY_PAUSE => Key::MediaPlayPause,
win32km::VK_LAUNCH_MAIL => Key::LaunchMail,
win32km::VK_LAUNCH_MEDIA_SELECT => Key::LaunchMediaPlayer,
win32km::VK_LAUNCH_APP1 => Key::LaunchApplication1,
win32km::VK_LAUNCH_APP2 => Key::LaunchApplication2,
// This function only converts "non-printable"
win32km::VK_OEM_1 => Key::Unidentified(native_code),
win32km::VK_OEM_PLUS => Key::Unidentified(native_code),
win32km::VK_OEM_COMMA => Key::Unidentified(native_code),
win32km::VK_OEM_MINUS => Key::Unidentified(native_code),
win32km::VK_OEM_PERIOD => Key::Unidentified(native_code),
win32km::VK_OEM_2 => Key::Unidentified(native_code),
win32km::VK_OEM_3 => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_A => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_B => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_X => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_Y => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_RIGHT_SHOULDER => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_LEFT_SHOULDER => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_LEFT_TRIGGER => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_RIGHT_TRIGGER => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_DPAD_UP => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_DPAD_DOWN => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_DPAD_LEFT => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_DPAD_RIGHT => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_MENU => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_VIEW => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_LEFT_THUMBSTICK_BUTTON => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_RIGHT_THUMBSTICK_BUTTON => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_LEFT_THUMBSTICK_UP => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_LEFT_THUMBSTICK_DOWN => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_LEFT_THUMBSTICK_RIGHT => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_LEFT_THUMBSTICK_LEFT => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_RIGHT_THUMBSTICK_UP => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_RIGHT_THUMBSTICK_DOWN => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_RIGHT_THUMBSTICK_RIGHT => Key::Unidentified(native_code),
win32km::VK_GAMEPAD_RIGHT_THUMBSTICK_LEFT => Key::Unidentified(native_code),
// This function only converts "non-printable"
win32km::VK_OEM_4 => Key::Unidentified(native_code),
win32km::VK_OEM_5 => Key::Unidentified(native_code),
win32km::VK_OEM_6 => Key::Unidentified(native_code),
win32km::VK_OEM_7 => Key::Unidentified(native_code),
win32km::VK_OEM_8 => Key::Unidentified(native_code),
win32km::VK_OEM_AX => Key::Unidentified(native_code),
win32km::VK_OEM_102 => Key::Unidentified(native_code),
win32km::VK_ICO_HELP => Key::Unidentified(native_code),
win32km::VK_ICO_00 => Key::Unidentified(native_code),
win32km::VK_PROCESSKEY => Key::Process,
win32km::VK_ICO_CLEAR => Key::Unidentified(native_code),
win32km::VK_PACKET => Key::Unidentified(native_code),
win32km::VK_OEM_RESET => Key::Unidentified(native_code),
win32km::VK_OEM_JUMP => Key::Unidentified(native_code),
win32km::VK_OEM_PA1 => Key::Unidentified(native_code),
win32km::VK_OEM_PA2 => Key::Unidentified(native_code),
win32km::VK_OEM_PA3 => Key::Unidentified(native_code),
win32km::VK_OEM_WSCTRL => Key::Unidentified(native_code),
win32km::VK_OEM_CUSEL => Key::Unidentified(native_code),
win32km::VK_OEM_ATTN => Key::Attn,
win32km::VK_OEM_FINISH => {
if is_japanese {
Key::Katakana
} else {
// This matches IE and Firefox behaviour according to
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
// At the time of writing, there is no `Key::Finish` variant as
// Finish is not mentionned at https://w3c.github.io/uievents-key/
// Also see: https://github.com/pyfisch/keyboard-types/issues/9
Key::Unidentified(native_code)
}
}
win32km::VK_OEM_COPY => Key::Copy,
win32km::VK_OEM_AUTO => Key::Hankaku,
win32km::VK_OEM_ENLW => Key::Zenkaku,
win32km::VK_OEM_BACKTAB => Key::Romaji,
win32km::VK_ATTN => Key::KanaMode,
win32km::VK_CRSEL => Key::CrSel,
win32km::VK_EXSEL => Key::ExSel,
win32km::VK_EREOF => Key::EraseEof,
win32km::VK_PLAY => Key::Play,
win32km::VK_ZOOM => Key::ZoomToggle,
win32km::VK_NONAME => Key::Unidentified(native_code),
win32km::VK_PA1 => Key::Unidentified(native_code),
win32km::VK_OEM_CLEAR => Key::Clear,
_ => Key::Unidentified(native_code)
}
}
| 38.134715 | 142 | 0.703668 |
0a3767186960f21449da1a0aa3429435c4217dd7 | 5,021 | use crate::{error::Convert, object::Object, schema::Any};
use serde::{
de::{DeserializeSeed, Deserializer, EnumAccess, Error, MapAccess, SeqAccess, Visitor},
Deserialize,
};
use std::{borrow::Cow, fmt};
pub struct AnyVisitor;
impl<'de> Visitor<'de> for AnyVisitor {
type Value = Object;
fn expecting(&self, _: &mut fmt::Formatter) -> fmt::Result {
unreachable!()
}
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Object::new_bool(v))
}
fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_i64(v as i64)
}
fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_i64(v as i64)
}
fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_i64(v as i64)
}
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: Error,
{
Object::new_i64(v).de()
}
fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_u64(v as u64)
}
fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_u64(v as u64)
}
fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_u64(v as u64)
}
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where
E: Error,
{
Object::new_u64(v).de()
}
fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_f64(v as f64)
}
fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
where
E: Error,
{
Object::new_f64(v).de()
}
fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_borrowed_str(&v.to_string())
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_borrowed_str(v)
}
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where
E: Error,
{
Object::new_str(v).de()
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_borrowed_str(&v)
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_borrowed_bytes(v)
}
fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
where
E: Error,
{
Object::new_bytes(v).de()
}
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_borrowed_bytes(&v)
}
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Object::new_none())
}
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(AnyVisitor)
}
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: Error,
{
Ok(Object::new_none())
}
fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(AnyVisitor)
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut args: smallvec::SmallVec<[Object; 16]> = smallvec::SmallVec::new();
while let Some(arg) = seq.next_element()? {
let arg: Object = arg;
args.push(arg);
}
let mut list = Object::build_list(args.len()).de()?;
for (i, arg) in args.into_iter().enumerate() {
list.set(i, arg);
}
Ok(list.build())
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut dict = Object::build_dict().de()?;
while let Some(k) = map.next_key()? {
let k: Cow<str> = k;
let v = map.next_value()?;
dict.set(Object::new_str(&k).de()?, v).de()?;
}
Ok(dict.build())
}
fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
where
A: EnumAccess<'de>,
{
let (v, _) = data.variant()?;
Ok(v)
}
}
impl<'de> Deserialize<'de> for Object {
fn deserialize<D>(de: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
de.deserialize_any(AnyVisitor)
}
}
impl<'a, 'de> DeserializeSeed<'de> for &'a Any {
type Value = Object;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(AnyVisitor)
}
}
| 21.549356 | 90 | 0.523402 |
e256bae37ae2d0a1ea9d69585ee7dcb48583af37 | 7,814 | use std::collections::HashMap;
use std::path::{/*Path, */PathBuf};
use serde::{Deserialize, Serialize};
mod config;
use config::{ProjectSettings};
mod camera;
use edsdk::wrap;
//use edsdk::types;
#[derive(Serialize, Deserialize, Debug)]
struct RecieveInfo{
id: i32,
name: String,
value: String,
info: HashMap<String, String>
}
pub struct Application{
project: ProjectSettings,
edsdk: wrap::Library,
camera_device: Option<wrap::Camera>,
camera_session: Option<wrap::Session>,
}
impl Application{
pub fn new()->Self{
let edsdk = wrap::Library::initialize();
return Application{project: ProjectSettings::load().unwrap(), edsdk: edsdk.unwrap(), camera_device: None, camera_session: None};
}
// send error
pub fn send_error<T>(&self, webview: &mut web_view::WebView<T>, title: &str, message: &str){
let _ = webview.eval(&format!("error_msg(\"{}\", \"{}\")", title, message));
}
// send project data to webview
pub fn send_project_root<T>(&self, webview: &mut web_view::WebView<T>){
let root_path = str::replace(self.project.get_root_path(), "\\", "\\\\");
let _ = webview.eval(&format!("set_root(\"{}\")", root_path));
}
// change projects root path
pub fn change_project_root<T>(&mut self, webview: &mut web_view::WebView<T>){
// TODO:have to use current root path
let mut current_path = std::env::current_exe().unwrap();
current_path.pop();
let result = web_view::DialogBuilder::new(webview).choose_directory("select a project root directory", current_path);
if result.is_ok(){
let path = result.unwrap();
if path.is_some(){
let path = path.unwrap();
self.project.set_root_path(path.to_str().unwrap());
self.project.save();
self.send_project_root(webview);
}
}
}
// send image
pub fn send_image<T>(&self, webview: &mut web_view::WebView<T>, image_name: &str, func_name: &str)
{
let mut path = std::env::current_exe().unwrap();
path.pop();
path.push(image_name);
let jpg = std::fs::read(&path).unwrap();
let _ = webview.eval(&format!("{}(\"{}\")", func_name, base64::encode(&jpg)));
}
pub fn send_process_list<T>(&self, webview: &mut web_view::WebView<T>){
let pathes = self.project.calc_process_list();
let pathes: Vec<String> = pathes.iter().map(|p|format!("\"{}\"",p)).collect();
let path_string = pathes.join(",");
let _ = webview.eval(&format!("set_process_list(\"[{}]\")", path_string));
}
// receive iso changed
pub fn receive_iso(&mut self, iso_speed: &str){
self.project.set_iso(iso_speed);
if self.camera_session.is_some(){
let _ = self.camera_session.as_ref().map(|session|{
session.set_iso_speed(camera::convert_iso(self.project.get_iso()))
});
}
}
// receive av changed
pub fn receive_av(&mut self, aperture_value: &str){
self.project.set_aperture_value(aperture_value);
if self.camera_session.is_some(){
let _ = self.camera_session.as_ref().map(|session|{
session.set_av(camera::convert_av(self.project.get_aperture_value_as_str()))
});
}
}
// receive tv changed
pub fn receive_tv(&mut self, time_value: &str){
self.project.set_time_value(time_value);
if self.camera_session.is_some(){
let _ = self.camera_session.as_ref().map(|session|{
session.set_tv(camera::convert_tv(self.project.get_time_value_as_str()))
});
}
}
// connect and open session
pub fn connect_camera<T>(&mut self, webview: &mut web_view::WebView<T>){
let mut devices = self.edsdk.get_device_list();
if devices.len() > 0{
self.camera_device = std::mem::replace(&mut devices[0], None);
let session = self.camera_device.as_ref().map(|dev|{
let info = dev.get_device_info().unwrap();
let _ = webview.eval(&format!("set_connection(\"{}\")", info.description));
let fmt = format!("set_connection(\"{}\")", info.description);
let _ = webview.eval(&fmt);
let session = dev.open_session();
if session.is_ok(){
// TODO: set values from config
Some(session.unwrap())
}
else{
None
}
});
self.camera_session = session.unwrap();
}
else{
let _ = webview.eval(&format!("set_connection(\"disconnecting\")"));
}
}
pub fn create_process<T>(&mut self, webview: &mut web_view::WebView<T>, process_name: &str){
let result = self.project.create_process(process_name);
if result.is_some(){
self.select_process(webview, process_name);
}
else{
self.send_error(webview, "failed to create process", &format!("couldn't make a dir {} or a setting file on that.", process_name));
}
}
pub fn select_process<T>(&mut self, webview: &mut web_view::WebView<T>, process_name: &str){
if self.project.set_last_processing(process_name){
;
}
else{
self.send_error(webview, "failed to select process", &format!("process {} may not be valid.", process_name));
}
}
pub fn invoked<T>(&mut self, webview: &mut web_view::WebView<T>, arg: &str){
let deserialized : RecieveInfo = serde_json::from_str(arg).unwrap();
match deserialized.name.as_str(){
"button"=>{
eprint!("pressed")
}
"menu"=>{
let checked = deserialized.info.get("checked");
if checked.is_some(){
match &*(checked.unwrap().as_str()){
"true"=>{
eprint!("menu {:?}", deserialized.value)
},
_=>{
}
}
}
}
"request_img"=>{
self.send_image(webview, "rust_albedo.jpg", "set_albedo");
self.send_image(webview, "rust_normal.jpg", "set_normal");
self.send_image(webview, "rust_roughness.jpg", "set_roughness");
}
"request_root"=>{
self.send_project_root(webview);
}
"request_connecting"=>{
self.connect_camera(webview);
}
"change_root"=>{
self.change_project_root(webview);
}
"update_iso"=>{
self.receive_iso(deserialized.value.as_str());
}
"update_av"=>{
self.receive_av(deserialized.value.as_str());
}
"update_tv"=>{
self.receive_tv(deserialized.value.as_str());
}
"create_process"=>{
self.create_process(webview, deserialized.value.as_str());
}
"select_process"=>{
self.select_process(webview, deserialized.value.as_str());
}
"request_processes"=>{
self.send_process_list(webview);
}
"request_caribrations"=>{
}
_=>{
eprint!("unknown {:?}", arg)
}
}
}
}
| 38.492611 | 143 | 0.525979 |
d7a44877d1a22b6af3a7211e25b03312d8fb36bc | 1,426 | // Copyright 2017 Zachary Bush.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use {crate::loading::Transaction, budgetronlib::error::BResult};
pub mod config;
mod refunds;
mod regex;
mod transfers;
pub enum Collator {
Transfers(transfers::TransferCollator),
Refund(refunds::RefundCollator),
Config(config::ConfiguredProcessors),
}
pub use crate::processing::{
config::ConfiguredProcessors, refunds::RefundCollator, transfers::TransferCollator,
};
pub trait Collate {
fn collate(&self, transactions: Vec<Transaction>) -> BResult<Vec<Transaction>>;
}
impl Collate for Collator {
fn collate(&self, transactions: Vec<Transaction>) -> BResult<Vec<Transaction>> {
match *self {
Collator::Transfers(ref tc) => tc.collate(transactions),
Collator::Config(ref cfg) => cfg.collate(transactions),
Collator::Refund(ref rc) => rc.collate(transactions),
}
}
}
pub fn collate_all(
mut transactions: Vec<Transaction>,
collators: &[Collator],
) -> BResult<Vec<Transaction>> {
for collator in collators {
transactions = collator.collate(transactions)?
}
Ok(transactions)
}
| 29.102041 | 87 | 0.693548 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.