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
76d1df92e4fd955b04dc7aa97a799efdb0b568f8
4,705
// Copyright 2020 The Matrix.org Foundation C.I.C. // // 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 matrix_sdk_base::crypto::{AcceptSettings, ReadOnlyDevice, Sas as BaseSas}; use ruma::UserId; use crate::{error::Result, Client}; /// An object controlling the interactive verification flow. #[derive(Debug, Clone)] pub struct SasVerification { pub(crate) inner: BaseSas, pub(crate) client: Client, } impl SasVerification { /// Accept the interactive verification flow. pub async fn accept(&self) -> Result<()> { self.accept_with_settings(Default::default()).await } /// Accept the interactive verification flow with specific settings. /// /// # Arguments /// /// * `settings` - specific customizations to the verification flow. /// /// # Examples /// /// ```no_run /// # use matrix_sdk::Client; /// # use futures::executor::block_on; /// # use url::Url; /// # use ruma::user_id; /// use matrix_sdk::verification::SasVerification; /// use matrix_sdk_base::crypto::AcceptSettings; /// use matrix_sdk::ruma::events::key::verification::ShortAuthenticationString; /// # let homeserver = Url::parse("http://example.com").unwrap(); /// # let client = Client::new(homeserver).unwrap(); /// # let flow_id = "someID"; /// # let user_id = user_id!("@alice:example"); /// # block_on(async { /// let sas = client /// .get_verification(&user_id, flow_id) /// .await /// .unwrap() /// .sas() /// .unwrap(); /// /// let only_decimal = AcceptSettings::with_allowed_methods( /// vec![ShortAuthenticationString::Decimal] /// ); /// sas.accept_with_settings(only_decimal).await.unwrap(); /// # }); /// ``` pub async fn accept_with_settings(&self, settings: AcceptSettings) -> Result<()> { if let Some(request) = self.inner.accept_with_settings(settings) { self.client.send_verification_request(request).await?; } Ok(()) } /// Confirm that the short auth strings match on both sides. pub async fn confirm(&self) -> Result<()> { let (request, signature) = self.inner.confirm().await?; if let Some(request) = request { self.client.send_verification_request(request).await?; } if let Some(s) = signature { self.client.send(s, None).await?; } Ok(()) } /// Cancel the interactive verification flow. pub async fn cancel(&self) -> Result<()> { if let Some(request) = self.inner.cancel() { self.client.send_verification_request(request).await?; } Ok(()) } /// Get the emoji version of the short auth string. pub fn emoji(&self) -> Option<[(&'static str, &'static str); 7]> { self.inner.emoji() } /// Get the decimal version of the short auth string. pub fn decimals(&self) -> Option<(u16, u16, u16)> { self.inner.decimals() } /// Does this verification flow support emoji for the short authentication /// string. pub fn supports_emoji(&self) -> bool { self.inner.supports_emoji() } /// Is the verification process done. pub fn is_done(&self) -> bool { self.inner.is_done() } /// Are we in a state where we can show the short auth string. pub fn can_be_presented(&self) -> bool { self.inner.can_be_presented() } /// Is the verification process canceled. pub fn is_cancelled(&self) -> bool { self.inner.is_cancelled() } /// Get the other users device that we're verifying. pub fn other_device(&self) -> &ReadOnlyDevice { self.inner.other_device() } /// Did this verification flow start from a verification request. pub fn started_from_request(&self) -> bool { self.inner.started_from_request() } /// Is this a verification that is veryfying one of our own devices. pub fn is_self_verification(&self) -> bool { self.inner.is_self_verification() } /// Get our own user id. pub fn own_user_id(&self) -> &UserId { self.inner.user_id() } }
31.577181
86
0.621679
7180f5c6e3c26101cc35e81dd55d71ca39b21fa6
16,744
//! # Examples //! //! ```rust,no_run //! use ashpd::documents::{DocumentsProxy, Permission}; //! //! async fn run() -> ashpd::Result<()> { //! let connection = zbus::Connection::session().await?; //! let proxy = DocumentsProxy::new(&connection).await?; //! //! println!("{:#?}", proxy.mount_point().await?); //! //! for (doc_id, host_path) in proxy.list("org.mozilla.firefox").await? { //! if doc_id == "f2ee988d" { //! let info = proxy.info(&doc_id).await?; //! println!("{:#?}", info); //! } //! } //! //! proxy //! .grant_permissions( //! "f2ee988d", //! "org.mozilla.firefox", //! &[Permission::GrantPermissions], //! ) //! .await?; //! proxy //! .revoke_permissions("f2ee988d", "org.mozilla.firefox", &[Permission::Write]) //! .await?; //! //! proxy.delete("f2ee988d").await?; //! //! Ok(()) //! } //! ``` pub(crate) const DESTINATION: &str = "org.freedesktop.portal.Documents"; pub(crate) const PATH: &str = "/org/freedesktop/portal/documents"; use std::{ collections::HashMap, ffi::CString, os::unix::ffi::OsStrExt, os::unix::prelude::AsRawFd, }; use std::{ fmt::Debug, path::{Path, PathBuf}, str::FromStr, }; use enumflags2::BitFlags; use serde::{de::Deserializer, Deserialize, Serialize, Serializer}; use serde_repr::{Deserialize_repr, Serialize_repr}; use strum_macros::{AsRefStr, EnumString, IntoStaticStr, ToString}; use zvariant::{Fd, Signature}; use zvariant_derive::Type; use crate::{ helpers::{call_method, path_from_null_terminated}, Error, }; #[derive(Serialize_repr, Deserialize_repr, PartialEq, Copy, Clone, BitFlags, Debug, Type)] #[repr(u32)] /// pub enum Flags { /// Reuse the existing document store entry for the file. ReuseExisting = 1, /// Persistent file. Persistent = 2, /// Depends on the application needs. AsNeededByApp = 4, /// Export a directory. ExportDirectory = 8, } /// A [`HashMap`] mapping application IDs to the permissions for that /// application pub type Permissions = HashMap<String, Vec<Permission>>; #[derive(Debug, Clone, AsRefStr, EnumString, IntoStaticStr, ToString, PartialEq, Eq)] #[strum(serialize_all = "lowercase")] /// The possible permissions to grant to a specific application for a specific /// document. pub enum Permission { /// Read access. Read, /// Write access. Write, #[strum(serialize = "grant-permissions")] /// The possibility to grant new permissions to the file. GrantPermissions, /// Delete access. Delete, } impl zvariant::Type for Permission { fn signature() -> Signature<'static> { String::signature() } } impl Serialize for Permission { fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: Serializer, { String::serialize(&self.to_string(), serializer) } } impl<'de> Deserialize<'de> for Permission { fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error> where D: Deserializer<'de>, { Ok(Permission::from_str(&String::deserialize(deserializer)?).expect("invalid permission")) } } /// The interface lets sandboxed applications make files from the outside world /// available to sandboxed applications in a controlled way. /// /// Exported files will be made accessible to the application via a fuse /// filesystem that gets mounted at `/run/user/$UID/doc/`. The filesystem gets /// mounted both outside and inside the sandbox, but the view inside the sandbox /// is restricted to just those files that the application is allowed to access. /// /// Individual files will appear at `/run/user/$UID/doc/$DOC_ID/filename`, /// where `$DOC_ID` is the ID of the file in the document store. /// It is returned by the [`DocumentsProxy::add`] and /// [`DocumentsProxy::add_named`] calls. /// /// The permissions that the application has for a document store entry (see /// [`DocumentsProxy::grant_permissions`]) are reflected in the POSIX mode bits /// in the fuse filesystem. /// /// Wrapper of the DBus interface: [`org.freedesktop.portal.Documents`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-org.freedesktop.portal.Documents). #[derive(Debug)] #[doc(alias = "org.freedesktop.portal.Documents")] pub struct DocumentsProxy<'a>(zbus::Proxy<'a>); impl<'a> DocumentsProxy<'a> { /// Create a new instance of [`DocumentsProxy`]. pub async fn new(connection: &zbus::Connection) -> Result<DocumentsProxy<'a>, Error> { let proxy = zbus::ProxyBuilder::new_bare(connection) .interface("org.freedesktop.portal.Documents")? .path(PATH)? .destination(DESTINATION)? .build() .await?; Ok(Self(proxy)) } /// Get a reference to the underlying Proxy. pub fn inner(&self) -> &zbus::Proxy<'_> { &self.0 } /// Adds a file to the document store. /// The file is passed in the form of an open file descriptor /// to prove that the caller has access to the file. /// /// # Arguments /// /// * `o_path_fd` - Open file descriptor for the file to add. /// * `reuse_existing` - Whether to reuse an existing document store entry /// for the file. /// * `persistent` - Whether to add the file only for this session or /// permanently. /// /// # Returns /// /// The ID of the file in the document store. /// /// # Specifications /// /// See also [`Add`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.Add). #[doc(alias = "Add")] pub async fn add<F>( &self, o_path_fd: &F, reuse_existing: bool, persistent: bool, ) -> Result<String, Error> where F: AsRawFd + Debug, { call_method( &self.0, "Add", &(Fd::from(o_path_fd.as_raw_fd()), reuse_existing, persistent), ) .await } /// Adds multiple files to the document store. /// The files are passed in the form of an open file descriptor /// to prove that the caller has access to the file. /// /// # Arguments /// /// * `o_path_fds` - Open file descriptors for the files to export. /// * `flags` - A [`Flags`]. /// * `app_id` - An application ID, or empty string. /// * `permissions` - The permissions to grant. /// /// # Returns /// /// The IDs of the files in the document store along with other extra info. /// /// # Specifications /// /// See also [`AddFull`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.AddFull). #[doc(alias = "AddFull")] pub async fn add_full<F: AsRawFd>( &self, o_path_fds: &[&F], flags: BitFlags<Flags>, app_id: &str, permissions: &[Permission], ) -> Result<(Vec<String>, HashMap<String, zvariant::OwnedValue>), Error> { let o_path: Vec<Fd> = o_path_fds.iter().map(|f| Fd::from(f.as_raw_fd())).collect(); call_method(&self.0, "AddFull", &(o_path, flags, app_id, permissions)).await } /// Creates an entry in the document store for writing a new file. /// /// # Arguments /// /// * `o_path_parent_fd` - Open file descriptor for the parent directory. /// * `filename` - The basename for the file. /// * `reuse_existing` - Whether to reuse an existing document store entry /// for the file. /// * `persistent` - Whether to add the file only for this session or /// permanently. /// /// # Returns /// /// The ID of the file in the document store. /// /// # Specifications /// /// See also [`AddNamed`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.AddNamed). #[doc(alias = "AddNamed")] pub async fn add_named<F, P>( &self, o_path_parent_fd: &F, filename: P, reuse_existing: bool, persistent: bool, ) -> Result<String, Error> where F: AsRawFd + Debug, P: AsRef<Path> + Serialize + zvariant::Type + Debug, { let cstr = CString::new(filename.as_ref().as_os_str().as_bytes()) .expect("`filename` should not be null terminated"); call_method( &self.0, "AddNamed", &( Fd::from(o_path_parent_fd.as_raw_fd()), cstr.as_bytes_with_nul(), reuse_existing, persistent, ), ) .await } /// Adds multiple files to the document store. /// The files are passed in the form of an open file descriptor /// to prove that the caller has access to the file. /// /// # Arguments /// /// * `o_path_fd` - Open file descriptor for the parent directory. /// * `filename` - The basename for the file. /// * `flags` - A [`Flags`]. /// * `app_id` - An application ID, or empty string. /// * `permissions` - The permissions to grant. /// /// # Returns /// /// The ID of the file in the document store along with other extra info. /// /// # Specifications /// /// See also [`AddNamedFull`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.AddNamedFull). #[doc(alias = "AddNamedFull")] pub async fn add_named_full<F, P>( &self, o_path_fd: &F, filename: P, flags: BitFlags<Flags>, app_id: &str, permissions: &[Permission], ) -> Result<(String, HashMap<String, zvariant::OwnedValue>), Error> where F: AsRawFd + Debug, P: AsRef<Path> + Serialize + zvariant::Type + Debug, { let cstr = CString::new(filename.as_ref().as_os_str().as_bytes()) .expect("`filename` should not be null terminated"); call_method( &self.0, "AddNamedFull", &( Fd::from(o_path_fd.as_raw_fd()), cstr.as_bytes_with_nul(), flags, app_id, permissions, ), ) .await } /// Removes an entry from the document store. The file itself is not /// deleted. /// /// **Note** This call is available inside the sandbox if the /// application has the [`Permission::Delete`] for the document. /// /// # Arguments /// /// * `doc_id` - The ID of the file in the document store. /// /// # Specifications /// /// See also [`Delete`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.Delete). #[doc(alias = "Delete")] pub async fn delete(&self, doc_id: &str) -> Result<(), Error> { call_method(&self.0, "Delete", &(doc_id)).await } /// Returns the path at which the document store fuse filesystem is mounted. /// This will typically be `/run/user/$UID/doc/`. /// /// # Specifications /// /// See also [`GetMountPoint`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.GetMountPoint). #[doc(alias = "GetMountPoint")] #[doc(alias = "get_mount_point")] pub async fn mount_point(&self) -> Result<PathBuf, Error> { let bytes: Vec<u8> = call_method(&self.0, "GetMountPoint", &()).await?; Ok(path_from_null_terminated(bytes)) } /// Grants access permissions for a file in the document store to an /// application. /// /// **Note** This call is available inside the sandbox if the /// application has the [`Permission::GrantPermissions`] for the document. /// /// # Arguments /// /// * `doc_id` - The ID of the file in the document store. /// * `app_id` - The ID of the application to which permissions are granted. /// * `permissions` - The permissions to grant. /// /// # Specifications /// /// See also [`GrantPermissions`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.GrantPermissions). #[doc(alias = "GrantPermissions")] pub async fn grant_permissions( &self, doc_id: &str, app_id: &str, permissions: &[Permission], ) -> Result<(), Error> { call_method(&self.0, "GrantPermissions", &(doc_id, app_id, permissions)).await } /// Gets the filesystem path and application permissions for a document /// store entry. /// /// **Note** This call is not available inside the sandbox. /// /// # Arguments /// /// * `doc_id` - The ID of the file in the document store. /// /// # Returns /// /// The path of the file in the host filesystem along with the /// [`Permissions`]. /// /// # Specifications /// /// See also [`Info`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.Info). #[doc(alias = "Info")] pub async fn info(&self, doc_id: &str) -> Result<(PathBuf, Permissions), Error> { let (bytes, permissions): (Vec<u8>, Permissions) = call_method(&self.0, "Info", &(doc_id)).await?; Ok((path_from_null_terminated(bytes), permissions)) } /// Lists documents in the document store for an application (or for all /// applications). /// /// **Note** This call is not available inside the sandbox. /// /// # Arguments /// /// * `app-id` - The application ID, or '' to list all documents. /// /// # Returns /// /// [`HashMap`] mapping document IDs to their filesystem path on the host /// system. /// /// # Specifications /// /// See also [`List`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.List). #[doc(alias = "List")] pub async fn list(&self, app_id: &str) -> Result<HashMap<String, PathBuf>, Error> { let response: HashMap<String, Vec<u8>> = call_method(&self.0, "List", &(app_id)).await?; let mut new_response: HashMap<String, PathBuf> = HashMap::new(); for (key, bytes) in response { new_response.insert(key, path_from_null_terminated(bytes)); } Ok(new_response) } /// Looks up the document ID for a file. /// /// **Note** This call is not available inside the sandbox. /// /// # Arguments /// /// * `filename` - A path in the host filesystem. /// /// # Returns /// /// The ID of the file in the document store, or [`None`] if the file is not /// in the document store. /// /// # Specifications /// /// See also [`Lookup`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.Lookup). #[doc(alias = "Lookup")] pub async fn lookup<P: AsRef<Path> + Serialize + zvariant::Type + Debug>( &self, filename: P, ) -> Result<Option<String>, Error> { let cstr = CString::new(filename.as_ref().as_os_str().as_bytes()) .expect("`filename` should not be null terminated"); let doc_id: String = call_method(&self.0, "Lookup", &(cstr.as_bytes_with_nul())).await?; if doc_id.is_empty() { Ok(None) } else { Ok(Some(doc_id)) } } /// Revokes access permissions for a file in the document store from an /// application. /// /// **Note** This call is available inside the sandbox if the /// application has the [`Permission::GrantPermissions`] for the document. /// /// # Arguments /// /// * `doc_id` - The ID of the file in the document store. /// * `app_id` - The ID of the application from which the permissions are /// revoked. /// * `permissions` - The permissions to revoke. /// /// # Specifications /// /// See also [`RevokePermissions`](https://flatpak.github.io/xdg-desktop-portal/portal-docs.html#gdbus-method-org-freedesktop-portal-Documents.RevokePermissions). #[doc(alias = "RevokePermissions")] pub async fn revoke_permissions( &self, doc_id: &str, app_id: &str, permissions: &[Permission], ) -> Result<(), Error> { call_method(&self.0, "RevokePermissions", &(doc_id, app_id, permissions)).await } } /// Interact with `org.freedesktop.portal.FileTransfer` interface. mod file_transfer; pub use file_transfer::FileTransferProxy;
34.311475
174
0.60123
4ba3a710e1427b49727a20a6ec8627df68ba4671
9,967
use std::error::Error; use std::fs; use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use super::runtime::get_inline_snapshot_value; lazy_static! { static ref RUN_ID: String = { let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); format!("{}-{}", d.as_secs(), d.subsec_nanos()) }; } #[derive(Debug, Serialize, Deserialize)] pub struct PendingInlineSnapshot { pub run_id: String, pub line: u32, pub new: Option<Snapshot>, pub old: Option<Snapshot>, } impl PendingInlineSnapshot { pub fn new(new: Option<Snapshot>, old: Option<Snapshot>, line: u32) -> PendingInlineSnapshot { PendingInlineSnapshot { new, old, line, run_id: RUN_ID.clone(), } } pub fn load_batch<P: AsRef<Path>>(p: P) -> Result<Vec<PendingInlineSnapshot>, Box<dyn Error>> { let f = BufReader::new(fs::File::open(p)?); let iter = serde_json::Deserializer::from_reader(f).into_iter::<PendingInlineSnapshot>(); let mut rv = iter.collect::<Result<Vec<PendingInlineSnapshot>, _>>()?; // remove all but the last run if let Some(last_run_id) = rv.last().map(|x| x.run_id.clone()) { rv.retain(|x| x.run_id == last_run_id); } Ok(rv) } pub fn save_batch<P: AsRef<Path>>( p: P, batch: &[PendingInlineSnapshot], ) -> Result<(), Box<dyn Error>> { fs::remove_file(&p).ok(); for snap in batch { snap.save(&p)?; } Ok(()) } pub fn save<P: AsRef<Path>>(&self, p: P) -> Result<(), Box<dyn Error>> { let mut f = fs::OpenOptions::new().create(true).append(true).open(p)?; let mut s = serde_json::to_string(self)?; s.push('\n'); f.write_all(s.as_bytes())?; Ok(()) } } /// Snapshot metadata information. #[derive(Debug, Default, Serialize, Deserialize, Clone)] pub struct MetaData { /// The source file (relative to workspace root). #[serde(skip_serializing_if = "Option::is_none")] pub source: Option<String>, /// Optionally the expression that created the snapshot. #[serde(skip_serializing_if = "Option::is_none")] pub expression: Option<String>, } impl MetaData { pub fn get_relative_source(&self, base: &Path) -> Option<PathBuf> { self.source.as_ref().map(|source| { base.join(source) .canonicalize() .ok() .and_then(|s| s.strip_prefix(base).ok().map(|x| x.to_path_buf())) .unwrap_or_else(|| base.to_path_buf()) }) } } /// A helper to work with stored snapshots. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Snapshot { module_name: String, #[serde(skip_serializing_if = "Option::is_none")] snapshot_name: Option<String>, metadata: MetaData, snapshot: SnapshotContents, } impl Snapshot { /// Loads a snapshot from a file. pub fn from_file<P: AsRef<Path>>(p: P) -> Result<Snapshot, Box<dyn Error>> { let mut f = BufReader::new(fs::File::open(p.as_ref())?); let mut buf = String::new(); f.read_line(&mut buf)?; // yaml format let metadata = if buf.trim_end() == "---" { loop { let read = f.read_line(&mut buf)?; if read == 0 { break; } if buf[buf.len() - read..].trim_end() == "---" { buf.truncate(buf.len() - read); break; } } serde_yaml::from_str(&buf)? // legacy format } else { let mut rv = MetaData::default(); loop { buf.clear(); let read = f.read_line(&mut buf)?; if read == 0 || buf.trim_end().is_empty() { buf.truncate(buf.len() - read); break; } let mut iter = buf.splitn(2, ':'); if let Some(key) = iter.next() { if let Some(value) = iter.next() { let value = value.trim(); match key.to_lowercase().as_str() { "expression" => rv.expression = Some(value.to_string()), "source" => rv.source = Some(value.into()), _ => {} } } } } rv }; buf.clear(); for (idx, line) in f.lines().enumerate() { let line = line?; if idx > 0 { buf.push('\n'); } buf.push_str(&line); } let module_name = p .as_ref() .file_name() .unwrap() .to_str() .unwrap_or("") .split("__") .next() .unwrap_or("<unknown>") .to_string(); let snapshot_name = p .as_ref() .file_name() .unwrap() .to_str() .unwrap_or("") .split('.') .next() .unwrap_or("") .splitn(2, "__") .nth(1) .map(|x| x.to_string()); Ok(Snapshot::from_components( module_name, snapshot_name, metadata, buf.into(), )) } /// Creates an empty snapshot. pub(crate) fn from_components( module_name: String, snapshot_name: Option<String>, metadata: MetaData, snapshot: SnapshotContents, ) -> Snapshot { Snapshot { module_name, snapshot_name, metadata, snapshot, } } /// Returns the module name. pub fn module_name(&self) -> &str { &self.module_name } /// Returns the snapshot name. pub fn snapshot_name(&self) -> Option<&str> { self.snapshot_name.as_deref() } /// The metadata in the snapshot. pub fn metadata(&self) -> &MetaData { &self.metadata } /// The snapshot contents pub fn contents(&self) -> &SnapshotContents { &self.snapshot } /// The snapshot contents as a &str pub fn contents_str(&self) -> &str { &self.snapshot.0 } pub(crate) fn save<P: AsRef<Path>>(&self, path: P) -> Result<(), Box<dyn Error>> { let path = path.as_ref(); if let Some(folder) = path.parent() { fs::create_dir_all(&folder)?; } let mut f = fs::File::create(&path)?; serde_yaml::to_writer(&mut f, &self.metadata)?; f.write_all(b"\n---\n")?; f.write_all(self.contents_str().as_bytes())?; f.write_all(b"\n")?; Ok(()) } } /// The contents of a Snapshot // Could be Cow, but I think limited savings #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SnapshotContents(String); impl SnapshotContents { pub fn from_inline(value: &str) -> SnapshotContents { SnapshotContents(get_inline_snapshot_value(value)) } pub fn to_inline(&self, indentation: usize) -> String { let contents = &self.0; let mut out = String::new(); let is_escape = contents.lines().count() > 1 || contents.contains(&['\\', '"'][..]); out.push_str(if is_escape { "r###\"" } else { "\"" }); // if we have more than one line we want to change into the block // representation mode if contents.lines().count() > 1 { out.extend( contents .lines() // newline needs to be at the start, since we don't want the end // finishing with a newline - the closing suffix should be on the same line .map(|l| { format!( "\n{:width$}{l}", "", width = if l.is_empty() { 0 } else { indentation }, l = l ) }) // `lines` removes the final line ending - add back .chain(Some(format!("\n{:width$}", "", width = indentation)).into_iter()), ); } else { out.push_str(contents); } out.push_str(if is_escape { "\"###" } else { "\"" }); out } } impl From<&str> for SnapshotContents { fn from(value: &str) -> SnapshotContents { SnapshotContents(value.to_string()) } } impl From<String> for SnapshotContents { fn from(value: String) -> SnapshotContents { SnapshotContents(value) } } impl From<SnapshotContents> for String { fn from(value: SnapshotContents) -> String { value.0 } } impl PartialEq for SnapshotContents { fn eq(&self, other: &Self) -> bool { self.0.trim_end() == other.0.trim_end() } } #[test] fn test_snapshot_contents() { let snapshot_contents = SnapshotContents("testing".to_string()); assert_eq!(snapshot_contents.to_inline(0), r#""testing""#); let t = &" a b"[1..]; assert_eq!( SnapshotContents(t.to_string()).to_inline(0), "r###\" a b \"###" ); let t = &" a b"[1..]; assert_eq!( SnapshotContents(t.to_string()).to_inline(4), "r###\" a b \"###" ); let t = &" a b"[1..]; assert_eq!( SnapshotContents(t.to_string()).to_inline(0), "r###\" a b \"###" ); let t = &" a b"[1..]; assert_eq!( SnapshotContents(t.to_string()).to_inline(0), "r###\" a b \"###" ); let t = "ab"; assert_eq!(SnapshotContents(t.to_string()).to_inline(0), r##""ab""##); }
27.23224
99
0.500552
4bbfc83ffebc7291652c09bb5c61fed0fea6bf1a
20,543
use crate::error::{self, Result}; use bottlerocket_types::agent_config::{ ClusterType, CreationPolicy, Ec2Config, EksClusterConfig, K8sVersion, MigrationConfig, SonobuoyConfig, SonobuoyMode, TufRepoConfig, AWS_CREDENTIALS_SECRET_NAME, }; use kube::ResourceExt; use kube::{api::ObjectMeta, Client}; use maplit::btreemap; use model::clients::{CrdClient, ResourceClient, TestClient}; use model::constants::NAMESPACE; use model::{ Agent, Configuration, DestructionPolicy, Resource, ResourceSpec, SecretName, Test, TestSpec, }; use serde_json::Value; use snafu::ResultExt; use std::collections::BTreeMap; use structopt::StructOpt; /// Create an EKS resource, EC2 resource and run Sonobuoy. #[derive(Debug, StructOpt)] pub(crate) struct RunAwsK8s { /// Name of the sonobuoy test. #[structopt(long, short)] name: String, /// Location of the sonobuoy test agent image. // TODO - default to an ECR public repository image #[structopt(long, short)] test_agent_image: String, /// Name of the pull secret for the sonobuoy test image (if needed). #[structopt(long)] test_agent_pull_secret: Option<String>, /// Keep the test agent running after completion. #[structopt(long)] keep_running: bool, /// The plugin used for the sonobuoy test. Normally this is `e2e` (the default). #[structopt(long, default_value = "e2e")] sonobuoy_plugin: String, /// The mode used for the sonobuoy test. One of `non-disruptive-conformance`, /// `certified-conformance`, `quick`. Although the Sonobuoy binary defaults to /// `non-disruptive-conformance`, we default to `quick` to make a quick test the most ergonomic. #[structopt(long, default_value = "quick")] sonobuoy_mode: SonobuoyMode, /// The kubernetes conformance image used for the sonobuoy test. #[structopt(long)] kubernetes_conformance_image: Option<String>, /// The name of the secret containing aws credentials. #[structopt(long)] aws_secret: Option<SecretName>, /// The AWS region. #[structopt(long, default_value = "us-west-2")] region: String, /// The name of the EKS cluster that will be used (whether it is being created or already /// exists). #[structopt(long)] cluster_name: String, /// The name of the TestSys resource that will represent this cluster. If you do not specify a /// value, one will be created matching the `cluster-name`. Unless there is a name conflict or /// you desire a specific resource name, then you do not need to supply a resource name here. #[structopt(long)] cluster_resource_name: Option<String>, /// The version of the EKS cluster that is to be created (with or without the 'v', e.g. 1.20 or /// v1.21, etc.) *This only affects EKS cluster creation!* If the cluster already exists, this /// option will have no affect. #[structopt(long)] cluster_version: Option<K8sVersion>, /// Whether or not we want the EKS cluster to be created. The possible values are: /// - `create`: the cluster will be created, it is an error for the cluster to pre-exist /// - `ifNotExists`: the cluster will be created if it does not already exist /// - `never`: the cluster must pre-exist or else it is an error #[structopt(long, default_value = "ifNotExists")] cluster_creation_policy: CreationPolicy, /// Whether or not we want the EKS cluster to be destroyed. The possible values are: /// - `onDeletion`: the cluster will be destroyed when its TestSys resource is deleted. /// - `never`: the cluster will not be destroyed. #[structopt(long, default_value = "never")] cluster_destruction_policy: DestructionPolicy, /// The container image of the EKS resource provider. // TODO - provide a default on ECR Public #[structopt(long)] cluster_provider_image: String, /// Name of the pull secret for the cluster provider image. #[structopt(long)] cluster_provider_pull_secret: Option<String>, /// Keep the EKS provider agent running after cluster creation. #[structopt(long)] keep_cluster_provider_running: bool, /// The EC2 AMI ID to use for cluster nodes. #[structopt(long)] ami: String, /// The EC2 instance type to use for cluster nodes. For example `m5.large`. If you do not /// provide an instance type, an appropriate instance type will be used based on the AMI's /// architecture. #[structopt(long)] instance_type: Option<String>, /// The name of the TestSys resource that will represent EC2 instances serving as cluster nodes. /// Defaults to `cluster-name-instances`. #[structopt(long)] ec2_resource_name: Option<String>, /// The container image of the EC2 resource provider. // TODO - provide a default on ECR Public #[structopt(long)] ec2_provider_image: String, /// Name of the pull secret for the EC2 provider image. #[structopt(long)] ec2_provider_pull_secret: Option<String>, /// Keep the EC2 instance provider running after instances are created. #[structopt(long)] keep_instance_provider_running: bool, /// Allow the sonobuoy test agent to rerun failed test. #[structopt(long)] retry_failed_attempts: Option<u32>, /// Perform an upgrade downgrade test. #[structopt(long, requires_all(&["starting-version", "upgrade-version", "migration-agent-image"]))] upgrade_downgrade: bool, /// Starting version for an upgrade/downgrade test. #[structopt(long, requires("upgrade-downgrade"))] starting_version: Option<String>, /// Version the ec2 instances should be upgraded to in an upgrade/downgrade test. #[structopt(long, requires("upgrade-downgrade"))] upgrade_version: Option<String>, /// Location of the tuf repo metadata. #[structopt(long, requires_all(&["tuf-repo-targets-url", "upgrade-downgrade"]))] tuf_repo_metadata_url: Option<String>, /// Location of the tuf repo targets. #[structopt(long, requires_all(&["tuf-repo-metadata-url", "upgrade-downgrade"]))] tuf_repo_targets_url: Option<String>, /// Location of the migration agent image. // TODO - default to an ECR public repository image #[structopt(long, short)] migration_agent_image: Option<String>, /// Name of the pull secret for the eks migration image (if needed). #[structopt(long)] migration_agent_pull_secret: Option<String>, /// The arn for the role that should be assumed by the agents. #[structopt(long)] assume_role: Option<String>, } impl RunAwsK8s { pub(crate) async fn run(self, k8s_client: Client) -> Result<()> { let cluster_resource_name = self .cluster_resource_name .as_ref() .unwrap_or(&self.cluster_name); let ec2_resource_name = self .ec2_resource_name .clone() .unwrap_or(format!("{}-instances", self.cluster_name)); let aws_secret_map = self.aws_secret.as_ref().map(|secret_name| { btreemap! [ AWS_CREDENTIALS_SECRET_NAME.to_string() => secret_name.clone()] }); let eks_resource = self.eks_resource(cluster_resource_name, aws_secret_map.clone())?; let ec2_resource = self.ec2_resource( &ec2_resource_name, aws_secret_map.clone(), cluster_resource_name, )?; let tests = if self.upgrade_downgrade { if let (Some(starting_version), Some(upgrade_version), Some(migration_agent_image)) = ( self.starting_version.as_ref(), self.upgrade_version.as_ref(), self.migration_agent_image.as_ref(), ) { let tuf_repo = if let (Some(tuf_repo_metadata_url), Some(tuf_repo_targets_url)) = ( self.tuf_repo_metadata_url.as_ref(), self.tuf_repo_targets_url.as_ref(), ) { Some(TufRepoConfig { metadata_url: tuf_repo_metadata_url.to_string(), targets_url: tuf_repo_targets_url.to_string(), }) } else { None }; let init_test_name = format!("{}-1-initial", self.name); let upgrade_test_name = format!("{}-2-migrate", self.name); let upgraded_test_name = format!("{}-3-migrated", self.name); let downgrade_test_name = format!("{}-4-migrate", self.name); let final_test_name = format!("{}-5-final", self.name); let init_eks_test = self.sonobuoy_test( &init_test_name, aws_secret_map.clone(), &ec2_resource_name, cluster_resource_name, None, )?; let upgrade_test = self.migration_test( &upgrade_test_name, upgrade_version, tuf_repo.clone(), aws_secret_map.clone(), &ec2_resource_name, cluster_resource_name, Some(vec![init_test_name.clone()]), migration_agent_image, &self.migration_agent_pull_secret, )?; let upgraded_eks_test = self.sonobuoy_test( &upgraded_test_name, aws_secret_map.clone(), &ec2_resource_name, cluster_resource_name, Some(vec![init_test_name.clone(), upgrade_test_name.clone()]), )?; let downgrade_test = self.migration_test( &downgrade_test_name, starting_version, tuf_repo, aws_secret_map.clone(), &ec2_resource_name, cluster_resource_name, Some(vec![ init_test_name.clone(), upgrade_test_name.clone(), upgraded_test_name.clone(), ]), migration_agent_image, &self.migration_agent_pull_secret, )?; let final_eks_test = self.sonobuoy_test( &final_test_name, aws_secret_map.clone(), &ec2_resource_name, cluster_resource_name, Some(vec![ init_test_name, upgrade_test_name, upgraded_test_name, downgrade_test_name, ]), )?; vec![ init_eks_test, upgrade_test, upgraded_eks_test, downgrade_test, final_eks_test, ] } else { return Err(error::Error::InvalidArguments { why: "If performing an upgrade/downgrade test,\ `starting-version`, `upgrade-version` must be provided." .to_string(), }); } } else { vec![self.sonobuoy_test( &self.name, aws_secret_map.clone(), &ec2_resource_name, cluster_resource_name, None, )?] }; let resource_client = ResourceClient::new_from_k8s_client(k8s_client.clone()); let test_client = TestClient::new_from_k8s_client(k8s_client); let _ = resource_client .create(eks_resource) .await .context(error::ModelClientSnafu { message: "Unable to create EKS cluster resource object", })?; println!("Created resource object '{}'", cluster_resource_name); let _ = resource_client .create(ec2_resource) .await .context(error::ModelClientSnafu { message: "Unable to create EC2 instances resource object", })?; println!("Created resource object '{}'", ec2_resource_name); for test in tests { let name = test.name(); let _ = test_client .create(test) .await .context(error::ModelClientSnafu { message: "Unable to create test object", })?; println!("Created test object '{}'", name); } Ok(()) } fn eks_resource( &self, name: &str, secrets: Option<BTreeMap<String, SecretName>>, ) -> Result<Resource> { Ok(Resource { metadata: ObjectMeta { name: Some(name.to_string()), namespace: Some(NAMESPACE.into()), ..Default::default() }, spec: ResourceSpec { depends_on: None, agent: Agent { name: "eks-provider".to_string(), image: self.cluster_provider_image.clone(), pull_secret: self.cluster_provider_pull_secret.clone(), keep_running: self.keep_cluster_provider_running, timeout: None, configuration: Some( EksClusterConfig { cluster_name: self.cluster_name.clone(), creation_policy: Some(self.cluster_creation_policy), region: Some(self.region.clone()), zones: None, version: self.cluster_version, assume_role: self.assume_role.clone(), } .into_map() .context(error::ConfigMapSnafu)?, ), secrets, capabilities: None, }, destruction_policy: self.cluster_destruction_policy, }, status: None, }) } fn ec2_resource( &self, name: &str, secrets: Option<BTreeMap<String, SecretName>>, cluster_resource_name: &str, ) -> Result<Resource> { let mut ec2_config = Ec2Config { node_ami: self.ami.clone(), // TODO - configurable instance_count: Some(2), instance_type: self.instance_type.clone(), cluster_name: self.cluster_name.clone(), region: self.region.clone(), instance_profile_arn: format!("${{{}.iamInstanceProfileArn}}", cluster_resource_name), subnet_id: format!("${{{}.privateSubnetId}}", cluster_resource_name), cluster_type: ClusterType::Eks, endpoint: Some(format!("${{{}.endpoint}}", cluster_resource_name)), certificate: Some(format!("${{{}.certificate}}", cluster_resource_name)), cluster_dns_ip: Some(format!("${{{}.clusterDnsIp}}", cluster_resource_name)), security_groups: vec![], assume_role: self.assume_role.clone(), } .into_map() .context(error::ConfigMapSnafu)?; // TODO - we have change the raw map to reference/template a non string field. let previous_value = ec2_config.insert( "securityGroups".to_owned(), Value::String(format!("${{{}.securityGroups}}", cluster_resource_name)), ); if previous_value.is_none() { todo!("This is an error: fields in the Ec2Config struct have changed") } Ok(Resource { metadata: ObjectMeta { name: Some(name.to_string()), namespace: Some(NAMESPACE.into()), ..Default::default() }, spec: ResourceSpec { depends_on: Some(vec![cluster_resource_name.to_owned()]), agent: Agent { name: "ec2-provider".to_string(), image: self.ec2_provider_image.clone(), pull_secret: self.ec2_provider_pull_secret.clone(), keep_running: self.keep_instance_provider_running, timeout: None, configuration: Some(ec2_config), secrets, capabilities: None, }, destruction_policy: DestructionPolicy::OnDeletion, }, status: None, }) } fn sonobuoy_test( &self, name: &str, secrets: Option<BTreeMap<String, SecretName>>, ec2_resource_name: &str, cluster_resource_name: &str, depends_on: Option<Vec<String>>, ) -> Result<Test> { Ok(Test { metadata: ObjectMeta { name: Some(name.to_string()), namespace: Some(NAMESPACE.into()), ..Default::default() }, spec: TestSpec { resources: vec![ ec2_resource_name.to_string(), cluster_resource_name.to_string(), ], depends_on, retries: self.retry_failed_attempts, agent: Agent { name: "sonobuoy-test-agent".to_string(), image: self.test_agent_image.clone(), pull_secret: self.test_agent_pull_secret.clone(), keep_running: self.keep_running, timeout: None, configuration: Some( SonobuoyConfig { kubeconfig_base64: format!( "${{{}.encodedKubeconfig}}", cluster_resource_name ), plugin: self.sonobuoy_plugin.clone(), mode: self.sonobuoy_mode, kubernetes_version: None, kube_conformance_image: self.kubernetes_conformance_image.clone(), assume_role: self.assume_role.clone(), } .into_map() .context(error::ConfigMapSnafu)?, ), secrets, // FIXME: Add CLI option for setting this capabilities: None, }, }, status: None, }) } #[allow(clippy::too_many_arguments)] fn migration_test( &self, name: &str, version: &str, tuf_repo: Option<TufRepoConfig>, secrets: Option<BTreeMap<String, SecretName>>, ec2_resource_name: &str, cluster_resource_name: &str, depends_on: Option<Vec<String>>, migration_agent_image: &str, migration_agent_pull_secret: &Option<String>, ) -> Result<Test> { let mut migration_config = MigrationConfig { aws_region: format!("${{{}.region}}", cluster_resource_name), instance_ids: Default::default(), migrate_to_version: version.to_string(), tuf_repo, assume_role: self.assume_role.clone(), } .into_map() .context(error::ConfigMapSnafu)?; migration_config.insert( "instanceIds".to_string(), Value::String(format!("${{{}.ids}}", ec2_resource_name)), ); Ok(Test { metadata: ObjectMeta { name: Some(name.to_string()), namespace: Some(NAMESPACE.into()), ..Default::default() }, spec: TestSpec { resources: vec![ ec2_resource_name.to_owned(), cluster_resource_name.to_owned(), ], depends_on, retries: None, agent: Agent { name: "eks-test-agent".to_string(), image: migration_agent_image.to_string(), pull_secret: migration_agent_pull_secret.clone(), keep_running: self.keep_running, timeout: None, configuration: Some(migration_config), secrets, capabilities: None, }, }, status: None, }) } }
39.279159
103
0.551964
9b2b6a8487745a14ca1203d0d3b8988a917ab2a9
10,595
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CheckResourceNameResult { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<check_resource_name_result::Status>, } pub mod check_resource_name_result { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Allowed, Reserved, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudError { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorResponse>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorAdditionalInfo { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub info: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<ErrorResponse>, #[serde(rename = "additionalInfo", default, skip_serializing_if = "Vec::is_empty")] pub additional_info: Vec<ErrorAdditionalInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Location { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")] pub subscription_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<location::Type>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "regionalDisplayName", default, skip_serializing_if = "Option::is_none")] pub regional_display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option<LocationMetadata>, } pub mod location { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Region, EdgeZone, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LocationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Location>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LocationMetadata { #[serde(rename = "regionType", default, skip_serializing_if = "Option::is_none")] pub region_type: Option<location_metadata::RegionType>, #[serde(rename = "regionCategory", default, skip_serializing_if = "Option::is_none")] pub region_category: Option<location_metadata::RegionCategory>, #[serde(rename = "geographyGroup", default, skip_serializing_if = "Option::is_none")] pub geography_group: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub longitude: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub latitude: Option<String>, #[serde(rename = "physicalLocation", default, skip_serializing_if = "Option::is_none")] pub physical_location: Option<String>, #[serde(rename = "pairedRegion", default, skip_serializing_if = "Vec::is_empty")] pub paired_region: Vec<PairedRegion>, #[serde(rename = "homeLocation", default, skip_serializing_if = "Option::is_none")] pub home_location: Option<String>, } pub mod location_metadata { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RegionType { Physical, Logical, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RegionCategory { Recommended, Extended, Other, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedByTenant { #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<operation::Display>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Display { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PairedRegion { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")] pub subscription_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceName { pub name: String, #[serde(rename = "type")] pub type_: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Subscription { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")] pub subscription_id: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<subscription::State>, #[serde(rename = "subscriptionPolicies", default, skip_serializing_if = "Option::is_none")] pub subscription_policies: Option<SubscriptionPolicies>, #[serde(rename = "authorizationSource", default, skip_serializing_if = "Option::is_none")] pub authorization_source: Option<String>, #[serde(rename = "managedByTenants", default, skip_serializing_if = "Vec::is_empty")] pub managed_by_tenants: Vec<ManagedByTenant>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } pub mod subscription { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum State { Enabled, Warned, PastDue, Disabled, Deleted, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SubscriptionListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Subscription>, #[serde(rename = "nextLink")] pub next_link: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SubscriptionPolicies { #[serde(rename = "locationPlacementId", default, skip_serializing_if = "Option::is_none")] pub location_placement_id: Option<String>, #[serde(rename = "quotaId", default, skip_serializing_if = "Option::is_none")] pub quota_id: Option<String>, #[serde(rename = "spendingLimit", default, skip_serializing_if = "Option::is_none")] pub spending_limit: Option<subscription_policies::SpendingLimit>, } pub mod subscription_policies { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum SpendingLimit { On, Off, CurrentPeriodOff, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TenantIdDescription { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "tenantCategory", default, skip_serializing_if = "Option::is_none")] pub tenant_category: Option<tenant_id_description::TenantCategory>, #[serde(default, skip_serializing_if = "Option::is_none")] pub country: Option<String>, #[serde(rename = "countryCode", default, skip_serializing_if = "Option::is_none")] pub country_code: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub domains: Vec<String>, #[serde(rename = "defaultDomain", default, skip_serializing_if = "Option::is_none")] pub default_domain: Option<String>, #[serde(rename = "tenantType", default, skip_serializing_if = "Option::is_none")] pub tenant_type: Option<String>, #[serde(rename = "tenantBrandingLogoUrl", default, skip_serializing_if = "Option::is_none")] pub tenant_branding_logo_url: Option<String>, } pub mod tenant_id_description { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TenantCategory { Home, ProjectedBy, ManagedBy, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TenantListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<TenantIdDescription>, #[serde(rename = "nextLink")] pub next_link: String, }
41.712598
96
0.695611
61ccb74b61d4b5a4cc124a0eea140a243d6c64e5
13,276
use crate::{db::RootDatabase, FileId}; use hir::{HirDisplay, SourceAnalyzer, Ty}; use ra_syntax::{ algo::visit::{visitor, Visitor}, ast::{self, AstNode, TypeAscriptionOwner}, SmolStr, SourceFile, SyntaxKind, SyntaxNode, TextRange, }; #[derive(Debug, PartialEq, Eq)] pub enum InlayKind { TypeHint, } #[derive(Debug)] pub struct InlayHint { pub range: TextRange, pub kind: InlayKind, pub label: SmolStr, } pub(crate) fn inlay_hints(db: &RootDatabase, file_id: FileId, file: &SourceFile) -> Vec<InlayHint> { file.syntax() .descendants() .map(|node| get_inlay_hints(db, file_id, &node).unwrap_or_default()) .flatten() .collect() } fn get_inlay_hints( db: &RootDatabase, file_id: FileId, node: &SyntaxNode, ) -> Option<Vec<InlayHint>> { visitor() .visit(|let_statement: ast::LetStmt| { if let_statement.ascribed_type().is_some() { return None; } let pat = let_statement.pat()?; let analyzer = SourceAnalyzer::new(db, file_id, let_statement.syntax(), None); Some(get_pat_type_hints(db, &analyzer, pat, false)) }) .visit(|closure_parameter: ast::LambdaExpr| { let analyzer = SourceAnalyzer::new(db, file_id, closure_parameter.syntax(), None); closure_parameter.param_list().map(|param_list| { param_list .params() .filter(|closure_param| closure_param.ascribed_type().is_none()) .filter_map(|closure_param| closure_param.pat()) .map(|root_pat| get_pat_type_hints(db, &analyzer, root_pat, false)) .flatten() .collect() }) }) .visit(|for_expression: ast::ForExpr| { let pat = for_expression.pat()?; let analyzer = SourceAnalyzer::new(db, file_id, for_expression.syntax(), None); Some(get_pat_type_hints(db, &analyzer, pat, false)) }) .visit(|if_expr: ast::IfExpr| { let pat = if_expr.condition()?.pat()?; let analyzer = SourceAnalyzer::new(db, file_id, if_expr.syntax(), None); Some(get_pat_type_hints(db, &analyzer, pat, true)) }) .visit(|while_expr: ast::WhileExpr| { let pat = while_expr.condition()?.pat()?; let analyzer = SourceAnalyzer::new(db, file_id, while_expr.syntax(), None); Some(get_pat_type_hints(db, &analyzer, pat, true)) }) .visit(|match_arm_list: ast::MatchArmList| { let analyzer = SourceAnalyzer::new(db, file_id, match_arm_list.syntax(), None); Some( match_arm_list .arms() .map(|match_arm| match_arm.pats()) .flatten() .map(|root_pat| get_pat_type_hints(db, &analyzer, root_pat, true)) .flatten() .collect(), ) }) .accept(&node)? } fn get_pat_type_hints( db: &RootDatabase, analyzer: &SourceAnalyzer, root_pat: ast::Pat, skip_root_pat_hint: bool, ) -> Vec<InlayHint> { let original_pat = &root_pat.clone(); get_leaf_pats(root_pat) .into_iter() .filter(|pat| !skip_root_pat_hint || pat != original_pat) .filter_map(|pat| { get_node_displayable_type(db, &analyzer, &pat) .map(|pat_type| (pat.syntax().text_range(), pat_type)) }) .map(|(range, pat_type)| InlayHint { range, kind: InlayKind::TypeHint, label: pat_type.display(db).to_string().into(), }) .collect() } fn get_leaf_pats(root_pat: ast::Pat) -> Vec<ast::Pat> { let mut pats_to_process = std::collections::VecDeque::<ast::Pat>::new(); pats_to_process.push_back(root_pat); let mut leaf_pats = Vec::new(); while let Some(maybe_leaf_pat) = pats_to_process.pop_front() { match &maybe_leaf_pat { ast::Pat::BindPat(bind_pat) => { if let Some(pat) = bind_pat.pat() { pats_to_process.push_back(pat); } else { leaf_pats.push(maybe_leaf_pat); } } ast::Pat::TuplePat(tuple_pat) => { for arg_pat in tuple_pat.args() { pats_to_process.push_back(arg_pat); } } ast::Pat::RecordPat(record_pat) => { if let Some(pat_list) = record_pat.record_field_pat_list() { pats_to_process.extend( pat_list .record_field_pats() .filter_map(|record_field_pat| { record_field_pat .pat() .filter(|pat| pat.syntax().kind() != SyntaxKind::BIND_PAT) }) .chain(pat_list.bind_pats().map(|bind_pat| { bind_pat.pat().unwrap_or_else(|| ast::Pat::from(bind_pat)) })), ); } } ast::Pat::TupleStructPat(tuple_struct_pat) => { for arg_pat in tuple_struct_pat.args() { pats_to_process.push_back(arg_pat); } } _ => (), } } leaf_pats } fn get_node_displayable_type( db: &RootDatabase, analyzer: &SourceAnalyzer, node_pat: &ast::Pat, ) -> Option<Ty> { analyzer.type_of_pat(db, node_pat).and_then(|resolved_type| { if let Ty::Apply(_) = resolved_type { Some(resolved_type) } else { None } }) } #[cfg(test)] mod tests { use crate::mock_analysis::single_file; use insta::assert_debug_snapshot_matches; #[test] fn let_statement() { let (analysis, file_id) = single_file( r#" #[derive(PartialEq)] enum CustomOption<T> { None, Some(T), } #[derive(PartialEq)] struct Test { a: CustomOption<u32>, b: u8, } fn main() { struct InnerStruct {} let test = 54; let test: i32 = 33; let mut test = 33; let _ = 22; let test = "test"; let test = InnerStruct {}; let test = vec![222]; let test: Vec<_> = (0..3).collect(); let test = (0..3).collect::<Vec<i128>>(); let test = (0..3).collect::<Vec<_>>(); let mut test = Vec::new(); test.push(333); let test = (42, 'a'); let (a, (b, c, (d, e), f)) = (2, (3, 4, (6.6, 7.7), 5)); }"#, ); assert_debug_snapshot_matches!(analysis.inlay_hints(file_id).unwrap(), @r#"[ InlayHint { range: [193; 197), kind: TypeHint, label: "i32", }, InlayHint { range: [236; 244), kind: TypeHint, label: "i32", }, InlayHint { range: [275; 279), kind: TypeHint, label: "&str", }, InlayHint { range: [539; 543), kind: TypeHint, label: "(i32, char)", }, InlayHint { range: [566; 567), kind: TypeHint, label: "i32", }, InlayHint { range: [570; 571), kind: TypeHint, label: "i32", }, InlayHint { range: [573; 574), kind: TypeHint, label: "i32", }, InlayHint { range: [584; 585), kind: TypeHint, label: "i32", }, InlayHint { range: [577; 578), kind: TypeHint, label: "f64", }, InlayHint { range: [580; 581), kind: TypeHint, label: "f64", }, ]"# ); } #[test] fn closure_parameter() { let (analysis, file_id) = single_file( r#" fn main() { let mut start = 0; (0..2).for_each(|increment| { start += increment; }) }"#, ); assert_debug_snapshot_matches!(analysis.inlay_hints(file_id).unwrap(), @r#"[ InlayHint { range: [21; 30), kind: TypeHint, label: "i32", }, InlayHint { range: [57; 66), kind: TypeHint, label: "i32", }, ]"# ); } #[test] fn for_expression() { let (analysis, file_id) = single_file( r#" fn main() { let mut start = 0; for increment in 0..2 { start += increment; } }"#, ); assert_debug_snapshot_matches!(analysis.inlay_hints(file_id).unwrap(), @r#"[ InlayHint { range: [21; 30), kind: TypeHint, label: "i32", }, InlayHint { range: [44; 53), kind: TypeHint, label: "i32", }, ]"# ); } #[test] fn if_expr() { let (analysis, file_id) = single_file( r#" #[derive(PartialEq)] enum CustomOption<T> { None, Some(T), } #[derive(PartialEq)] struct Test { a: CustomOption<u32>, b: u8, } fn main() { let test = CustomOption::Some(Test { a: CustomOption::Some(3), b: 1 }); if let CustomOption::None = &test {}; if let test = &test {}; if let CustomOption::Some(test) = &test {}; if let CustomOption::Some(Test { a, b }) = &test {}; if let CustomOption::Some(Test { a: x, b: y }) = &test {}; if let CustomOption::Some(Test { a: CustomOption::Some(x), b: y }) = &test {}; if let CustomOption::Some(Test { a: CustomOption::None, b: y }) = &test {}; if let CustomOption::Some(Test { b: y, .. }) = &test {}; if test == CustomOption::None {} }"#, ); assert_debug_snapshot_matches!(analysis.inlay_hints(file_id).unwrap(), @r#"[ InlayHint { range: [166; 170), kind: TypeHint, label: "CustomOption<Test>", }, InlayHint { range: [334; 338), kind: TypeHint, label: "&Test", }, InlayHint { range: [389; 390), kind: TypeHint, label: "&CustomOption<u32>", }, InlayHint { range: [392; 393), kind: TypeHint, label: "&u8", }, InlayHint { range: [531; 532), kind: TypeHint, label: "&u32", }, ]"# ); } #[test] fn while_expr() { let (analysis, file_id) = single_file( r#" #[derive(PartialEq)] enum CustomOption<T> { None, Some(T), } #[derive(PartialEq)] struct Test { a: CustomOption<u32>, b: u8, } fn main() { let test = CustomOption::Some(Test { a: CustomOption::Some(3), b: 1 }); while let CustomOption::None = &test {}; while let test = &test {}; while let CustomOption::Some(test) = &test {}; while let CustomOption::Some(Test { a, b }) = &test {}; while let CustomOption::Some(Test { a: x, b: y }) = &test {}; while let CustomOption::Some(Test { a: CustomOption::Some(x), b: y }) = &test {}; while let CustomOption::Some(Test { a: CustomOption::None, b: y }) = &test {}; while let CustomOption::Some(Test { b: y, .. }) = &test {}; while test == CustomOption::None {} }"#, ); assert_debug_snapshot_matches!(analysis.inlay_hints(file_id).unwrap(), @r###" ⋮[ ⋮ InlayHint { ⋮ range: [166; 170), ⋮ kind: TypeHint, ⋮ label: "CustomOption<Test>", ⋮ }, ⋮ InlayHint { ⋮ range: [343; 347), ⋮ kind: TypeHint, ⋮ label: "&Test", ⋮ }, ⋮ InlayHint { ⋮ range: [401; 402), ⋮ kind: TypeHint, ⋮ label: "&CustomOption<u32>", ⋮ }, ⋮ InlayHint { ⋮ range: [404; 405), ⋮ kind: TypeHint, ⋮ label: "&u8", ⋮ }, ⋮ InlayHint { ⋮ range: [549; 550), ⋮ kind: TypeHint, ⋮ label: "&u32", ⋮ }, ⋮] "### ); } #[test] fn match_arm_list() { let (analysis, file_id) = single_file( r#" #[derive(PartialEq)] enum CustomOption<T> { None, Some(T), } #[derive(PartialEq)] struct Test { a: CustomOption<u32>, b: u8, } fn main() { match CustomOption::Some(Test { a: CustomOption::Some(3), b: 1 }) { CustomOption::None => (), test => (), CustomOption::Some(test) => (), CustomOption::Some(Test { a, b }) => (), CustomOption::Some(Test { a: x, b: y }) => (), CustomOption::Some(Test { a: CustomOption::Some(x), b: y }) => (), CustomOption::Some(Test { a: CustomOption::None, b: y }) => (), CustomOption::Some(Test { b: y, .. }) => (), _ => {} } }"#, ); assert_debug_snapshot_matches!(analysis.inlay_hints(file_id).unwrap(), @r#"[ InlayHint { range: [311; 315), kind: TypeHint, label: "Test", }, InlayHint { range: [358; 359), kind: TypeHint, label: "CustomOption<u32>", }, InlayHint { range: [361; 362), kind: TypeHint, label: "u8", }, InlayHint { range: [484; 485), kind: TypeHint, label: "u32", }, ]"# ); } }
26.446215
100
0.496234
e8f270b2262414c114906a67639a53c4c3881f87
16,366
//! Structural Similarity index. //! //! The SSIM index is a full reference metric; in other words, the measurement //! or prediction of image quality is based on an initial uncompressed or //! distortion-free image as reference. SSIM is designed to improve on //! traditional methods such as peak signal-to-noise ratio (PSNR) and mean //! squared error (MSE). //! //! See https://en.wikipedia.org/wiki/Structural_similarity for more details. use crate::video::decode::Decoder; use crate::video::pixel::CastFromPrimitive; use crate::video::pixel::Pixel; use crate::video::ChromaWeight; use crate::video::{FrameInfo, PlanarMetrics, VideoMetric}; use std::cmp; use std::error::Error; use std::f64::consts::{E, PI}; use v_frame::plane::Plane; /// Calculates the SSIM score between two videos. Higher is better. #[inline] pub fn calculate_video_ssim<D: Decoder, F: Fn(usize) + Send>( decoder1: &mut D, decoder2: &mut D, frame_limit: Option<usize>, progress_callback: F, ) -> Result<PlanarMetrics, Box<dyn Error>> { let cweight = Some( decoder1 .get_video_details() .chroma_sampling .get_chroma_weight(), ); Ssim { cweight }.process_video(decoder1, decoder2, frame_limit, progress_callback) } /// Calculates the SSIM score between two video frames. Higher is better. #[inline] pub fn calculate_frame_ssim<T: Pixel>( frame1: &FrameInfo<T>, frame2: &FrameInfo<T>, ) -> Result<PlanarMetrics, Box<dyn Error>> { let processor = Ssim::default(); let result = processor.process_frame(frame1, frame2)?; let cweight = frame1.chroma_sampling.get_chroma_weight(); Ok(PlanarMetrics { y: log10_convert(result.y, 1.0), u: log10_convert(result.u, 1.0), v: log10_convert(result.v, 1.0), avg: log10_convert( result.y + cweight * (result.u + result.v), 1.0 + 2.0 * cweight, ), }) } #[derive(Default)] struct Ssim { pub cweight: Option<f64>, } impl VideoMetric for Ssim { type FrameResult = PlanarMetrics; type VideoResult = PlanarMetrics; /// Returns the *unweighted* scores. Depending on whether we output per-frame /// or per-video, these will be weighted at different points. fn process_frame<T: Pixel>( &self, frame1: &FrameInfo<T>, frame2: &FrameInfo<T>, ) -> Result<Self::FrameResult, Box<dyn Error>> { frame1.can_compare(frame2)?; const KERNEL_SHIFT: usize = 8; const KERNEL_WEIGHT: usize = 1 << KERNEL_SHIFT; let sample_max = (1 << frame1.bit_depth) - 1; let mut y = 0.0; let mut u = 0.0; let mut v = 0.0; rayon::scope(|s| { s.spawn(|_| { let y_kernel = build_gaussian_kernel( frame1.planes[0].cfg.height as f64 * 1.5 / 256.0, cmp::min(frame1.planes[0].cfg.width, frame1.planes[0].cfg.height), KERNEL_WEIGHT, ); y = calculate_plane_ssim( &frame1.planes[0], &frame2.planes[0], sample_max, &y_kernel, &y_kernel, ) }); s.spawn(|_| { let u_kernel = build_gaussian_kernel( frame1.planes[1].cfg.height as f64 * 1.5 / 256.0, cmp::min(frame1.planes[1].cfg.width, frame1.planes[1].cfg.height), KERNEL_WEIGHT, ); u = calculate_plane_ssim( &frame1.planes[1], &frame2.planes[1], sample_max, &u_kernel, &u_kernel, ) }); s.spawn(|_| { let v_kernel = build_gaussian_kernel( frame1.planes[2].cfg.height as f64 * 1.5 / 256.0, cmp::min(frame1.planes[2].cfg.width, frame1.planes[2].cfg.height), KERNEL_WEIGHT, ); v = calculate_plane_ssim( &frame1.planes[2], &frame2.planes[2], sample_max, &v_kernel, &v_kernel, ) }); }); Ok(PlanarMetrics { y, u, v, // Not used here avg: 0., }) } fn aggregate_frame_results( &self, metrics: &[Self::FrameResult], ) -> Result<Self::VideoResult, Box<dyn Error>> { let cweight = self.cweight.unwrap_or(1.0); let y_sum = metrics.iter().map(|m| m.y).sum::<f64>(); let u_sum = metrics.iter().map(|m| m.u).sum::<f64>(); let v_sum = metrics.iter().map(|m| m.v).sum::<f64>(); Ok(PlanarMetrics { y: log10_convert(y_sum, metrics.len() as f64), u: log10_convert(u_sum, metrics.len() as f64), v: log10_convert(v_sum, metrics.len() as f64), avg: log10_convert( y_sum + cweight * (u_sum + v_sum), (1. + 2. * cweight) * metrics.len() as f64, ), }) } } /// Calculates the MSSSIM score between two videos. Higher is better. /// /// MSSSIM is a variant of SSIM computed over subsampled versions /// of an image. It is designed to be a more accurate metric /// than SSIM. #[inline] pub fn calculate_video_msssim<D: Decoder, F: Fn(usize) + Send>( decoder1: &mut D, decoder2: &mut D, frame_limit: Option<usize>, progress_callback: F, ) -> Result<PlanarMetrics, Box<dyn Error>> { let cweight = Some( decoder1 .get_video_details() .chroma_sampling .get_chroma_weight(), ); MsSsim { cweight }.process_video(decoder1, decoder2, frame_limit, progress_callback) } /// Calculates the MSSSIM score between two video frames. Higher is better. /// /// MSSSIM is a variant of SSIM computed over subsampled versions /// of an image. It is designed to be a more accurate metric /// than SSIM. #[inline] pub fn calculate_frame_msssim<T: Pixel>( frame1: &FrameInfo<T>, frame2: &FrameInfo<T>, ) -> Result<PlanarMetrics, Box<dyn Error>> { let processor = MsSsim::default(); let result = processor.process_frame(frame1, frame2)?; let cweight = frame1.chroma_sampling.get_chroma_weight(); Ok(PlanarMetrics { y: log10_convert(result.y, 1.0), u: log10_convert(result.u, 1.0), v: log10_convert(result.v, 1.0), avg: log10_convert( result.y + cweight * (result.u + result.v), 1.0 + 2.0 * cweight, ), }) } #[derive(Default)] struct MsSsim { pub cweight: Option<f64>, } impl VideoMetric for MsSsim { type FrameResult = PlanarMetrics; type VideoResult = PlanarMetrics; /// Returns the *unweighted* scores. Depending on whether we output per-frame /// or per-video, these will be weighted at different points. fn process_frame<T: Pixel>( &self, frame1: &FrameInfo<T>, frame2: &FrameInfo<T>, ) -> Result<Self::FrameResult, Box<dyn Error>> { frame1.can_compare(frame2)?; let bit_depth = frame1.bit_depth; let mut y = 0.0; let mut u = 0.0; let mut v = 0.0; rayon::scope(|s| { s.spawn(|_| { y = calculate_plane_msssim(&frame1.planes[0], &frame2.planes[0], bit_depth) }); s.spawn(|_| { u = calculate_plane_msssim(&frame1.planes[1], &frame2.planes[1], bit_depth) }); s.spawn(|_| { v = calculate_plane_msssim(&frame1.planes[2], &frame2.planes[2], bit_depth) }); }); Ok(PlanarMetrics { y, u, v, // Not used here avg: 0., }) } fn aggregate_frame_results( &self, metrics: &[Self::FrameResult], ) -> Result<Self::VideoResult, Box<dyn Error>> { let cweight = self.cweight.unwrap(); let y_sum = metrics.iter().map(|m| m.y).sum::<f64>(); let u_sum = metrics.iter().map(|m| m.u).sum::<f64>(); let v_sum = metrics.iter().map(|m| m.v).sum::<f64>(); Ok(PlanarMetrics { y: log10_convert(y_sum, metrics.len() as f64), u: log10_convert(u_sum, metrics.len() as f64), v: log10_convert(v_sum, metrics.len() as f64), avg: log10_convert( y_sum + cweight * (u_sum + v_sum), (1. + 2. * cweight) * metrics.len() as f64, ), }) } } #[derive(Debug, Clone, Copy, Default)] struct SsimMoments { mux: i64, muy: i64, x2: i64, xy: i64, y2: i64, w: i64, } const SSIM_K1: f64 = 0.01 * 0.01; const SSIM_K2: f64 = 0.03 * 0.03; fn calculate_plane_ssim<T: Pixel>( plane1: &Plane<T>, plane2: &Plane<T>, sample_max: u64, vert_kernel: &[i64], horiz_kernel: &[i64], ) -> f64 { let vec1 = plane_to_vec(plane1); let vec2 = plane_to_vec(plane2); calculate_plane_ssim_internal( &vec1, &vec2, plane1.cfg.width, plane1.cfg.height, sample_max, vert_kernel, horiz_kernel, ) .0 } fn calculate_plane_ssim_internal( plane1: &[u32], plane2: &[u32], width: usize, height: usize, sample_max: u64, vert_kernel: &[i64], horiz_kernel: &[i64], ) -> (f64, f64) { let vert_offset = vert_kernel.len() >> 1; let line_size = vert_kernel.len().next_power_of_two(); let line_mask = line_size - 1; let mut lines = vec![vec![SsimMoments::default(); width]; line_size]; let horiz_offset = horiz_kernel.len() >> 1; let mut ssim = 0.0; let mut ssimw = 0.0; let mut cs = 0.0; for y in 0..(height + vert_offset) { if y < height { let buf = &mut lines[y & line_mask]; let line1 = &plane1[(y * width)..]; let line2 = &plane2[(y * width)..]; for x in 0..width { let mut moments = SsimMoments::default(); let k_min = horiz_offset.saturating_sub(x); let tmp_offset = (x + horiz_offset + 1).saturating_sub(width); let k_max = horiz_kernel.len() - tmp_offset; for k in k_min..k_max { let window = horiz_kernel[k]; let target_x = (x + k).saturating_sub(horiz_offset); let pix1 = line1[target_x] as i64; let pix2 = line2[target_x] as i64; moments.mux += window * pix1; moments.muy += window * pix2; moments.x2 += window * pix1 * pix1; moments.xy += window * pix1 * pix2; moments.y2 += window * pix2 * pix2; moments.w += window; } buf[x] = moments; } } if y >= vert_offset { let k_min = vert_kernel.len().saturating_sub(y + 1); let tmp_offset = (y + 1).saturating_sub(height); let k_max = vert_kernel.len() - tmp_offset; for x in 0..width { let mut moments = SsimMoments::default(); for k in k_min..k_max { let buf = lines[(y + 1 + k - vert_kernel.len()) & line_mask][x]; let window = vert_kernel[k]; moments.mux += window * buf.mux; moments.muy += window * buf.muy; moments.x2 += window * buf.x2; moments.xy += window * buf.xy; moments.y2 += window * buf.y2; moments.w += window * buf.w; } let w = moments.w as f64; let c1 = sample_max.pow(2) as f64 * SSIM_K1 * w.powi(2); let c2 = sample_max.pow(2) as f64 * SSIM_K2 * w.powi(2); let mx2 = (moments.mux as f64).powi(2); let mxy = moments.mux as f64 * moments.muy as f64; let my2 = (moments.muy as f64).powi(2); let cs_tmp = w * (c2 + 2.0 * (moments.xy as f64 * w - mxy)) / (moments.x2 as f64 * w - mx2 + moments.y2 as f64 * w - my2 + c2); cs += cs_tmp; ssim += cs_tmp * (2.0 * mxy + c1) / (mx2 + my2 + c1); ssimw += w; } } } (ssim / ssimw, cs / ssimw) } fn calculate_plane_msssim<T: Pixel>(plane1: &Plane<T>, plane2: &Plane<T>, bit_depth: usize) -> f64 { const KERNEL_SHIFT: usize = 10; const KERNEL_WEIGHT: usize = 1 << KERNEL_SHIFT; // These come from the original MS-SSIM implementation paper: // https://ece.uwaterloo.ca/~z70wang/publications/msssim.pdf // They don't add up to 1 due to rounding done in the paper. const MS_WEIGHT: [f64; 5] = [0.0448, 0.2856, 0.3001, 0.2363, 0.1333]; let mut sample_max = (1 << bit_depth) - 1; let mut ssim = [0.0; 5]; let mut cs = [0.0; 5]; let mut width = plane1.cfg.width; let mut height = plane1.cfg.height; let mut plane1 = plane_to_vec(plane1); let mut plane2 = plane_to_vec(plane2); let kernel = build_gaussian_kernel(1.5, 5, KERNEL_WEIGHT); let res = calculate_plane_ssim_internal( &plane1, &plane2, width, height, sample_max, &kernel, &kernel, ); ssim[0] = res.0; cs[0] = res.1; for i in 1..5 { plane1 = msssim_downscale(&plane1, width, height); plane2 = msssim_downscale(&plane2, width, height); width /= 2; height /= 2; sample_max *= 4; let res = calculate_plane_ssim_internal( &plane1, &plane2, width, height, sample_max, &kernel, &kernel, ); ssim[i] = res.0; cs[i] = res.1; } cs.iter() .zip(MS_WEIGHT.iter()) .take(4) .map(|(cs, weight)| cs.powf(*weight)) .fold(1.0, |acc, val| acc * val) * ssim[4].powf(MS_WEIGHT[4]) } fn build_gaussian_kernel(sigma: f64, max_len: usize, kernel_weight: usize) -> Vec<i64> { let scale = 1.0 / ((2.0 * PI).sqrt() * sigma); let nhisigma2 = -0.5 / sigma.powi(2); // Compute the kernel size so that the error in the first truncated // coefficient is no larger than 0.5*KERNEL_WEIGHT. // There is no point in going beyond this given our working precision. let s = (0.5 * PI).sqrt() * sigma * (1.0 / kernel_weight as f64); let len = if s >= 1.0 { 0 } else { (sigma * (-2.0 * s.log(E)).sqrt()).floor() as usize }; let kernel_len = if len >= max_len { max_len - 1 } else { len }; let kernel_size = (kernel_len << 1) | 1; let mut kernel = vec![0; kernel_size]; let mut sum = 0; for ci in 1..=kernel_len { let val = kernel_weight as f64 * scale * E.powf(nhisigma2 * ci.pow(2) as f64) + 0.5; let val = val as i64; kernel[kernel_len - ci] = val; kernel[kernel_len + ci] = val; sum += val; } kernel[kernel_len] = kernel_weight as i64 - (sum << 1); kernel } fn plane_to_vec<T: Pixel>(input: &Plane<T>) -> Vec<u32> { input.data.iter().map(|pix| u32::cast_from(*pix)).collect() } // This acts differently from downscaling a plane, and is what // requires us to pass around slices of bytes, instead of `Plane`s. // Instead of averaging the four pixels, it sums them. // In effect, this gives us much more precision when we downscale. fn msssim_downscale(input: &[u32], input_width: usize, input_height: usize) -> Vec<u32> { let output_width = input_width / 2; let output_height = input_height / 2; let mut output = vec![0; output_width * output_height]; for j in 0..output_height { let j0 = 2 * j; let j1 = cmp::min(j0 + 1, input_height - 1); for i in 0..output_width { let i0 = 2 * i; let i1 = cmp::min(i0 + 1, input_width - 1); output[j * output_width + i] = input[j0 * input_width + i0] + input[j0 * input_width + i1] + input[j1 * input_width + i0] + input[j1 * input_width + i1]; } } output } fn log10_convert(score: f64, weight: f64) -> f64 { 10.0 * (weight.log10() - (weight - score).log10()) }
34.238494
100
0.543566
39da68307aab10f42d96d1259297867a82605fdc
3,300
#[doc = "Register `frame_byte_cnt0_5` reader"] pub struct R(crate::R<FRAME_BYTE_CNT0_5_SPEC>); impl core::ops::Deref for R { type Target = crate::R<FRAME_BYTE_CNT0_5_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<FRAME_BYTE_CNT0_5_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<FRAME_BYTE_CNT0_5_SPEC>) -> Self { R(reader) } } #[doc = "Register `frame_byte_cnt0_5` writer"] pub struct W(crate::W<FRAME_BYTE_CNT0_5_SPEC>); impl core::ops::Deref for W { type Target = crate::W<FRAME_BYTE_CNT0_5_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<FRAME_BYTE_CNT0_5_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<FRAME_BYTE_CNT0_5_SPEC>) -> Self { W(writer) } } #[doc = "Field `frame_byte_cnt_0_5` reader - "] pub struct FRAME_BYTE_CNT_0_5_R(crate::FieldReader<u32, u32>); impl FRAME_BYTE_CNT_0_5_R { #[inline(always)] pub(crate) fn new(bits: u32) -> Self { FRAME_BYTE_CNT_0_5_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for FRAME_BYTE_CNT_0_5_R { type Target = crate::FieldReader<u32, u32>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `frame_byte_cnt_0_5` writer - "] pub struct FRAME_BYTE_CNT_0_5_W<'a> { w: &'a mut W, } impl<'a> FRAME_BYTE_CNT_0_5_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = value; self.w } } impl R { #[doc = "Bits 0:31"] #[inline(always)] pub fn frame_byte_cnt_0_5(&self) -> FRAME_BYTE_CNT_0_5_R { FRAME_BYTE_CNT_0_5_R::new(self.bits) } } impl W { #[doc = "Bits 0:31"] #[inline(always)] pub fn frame_byte_cnt_0_5(&mut self) -> FRAME_BYTE_CNT_0_5_W { FRAME_BYTE_CNT_0_5_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 = "frame_byte_cnt0_5.\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 [frame_byte_cnt0_5](index.html) module"] pub struct FRAME_BYTE_CNT0_5_SPEC; impl crate::RegisterSpec for FRAME_BYTE_CNT0_5_SPEC { type Ux = u32; } #[doc = "`read()` method returns [frame_byte_cnt0_5::R](R) reader structure"] impl crate::Readable for FRAME_BYTE_CNT0_5_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [frame_byte_cnt0_5::W](W) writer structure"] impl crate::Writable for FRAME_BYTE_CNT0_5_SPEC { type Writer = W; } #[doc = "`reset()` method sets frame_byte_cnt0_5 to value 0"] impl crate::Resettable for FRAME_BYTE_CNT0_5_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
31.730769
416
0.640606
0a86a9df6f7728d9129f862be4790305ef2ec412
391
use serde_json::{json, Value}; use super::{logic, Data, Expression}; pub fn compute(args: &[Expression], data: &Data) -> Value { let a = args .get(0) .map(|arg| arg.compute(data)) .unwrap_or(json!(null)); let b = args .get(1) .map(|arg| arg.compute(data)) .unwrap_or(json!(null)); Value::Bool(!logic::is_strict_equal(&a, &b)) }
23
59
0.554987
239ac3786e7932749dac5733cd4af9e3cc2e7af7
60,179
//! Methods for lowering the HIR to types. There are two main cases here: //! //! - Lowering a type reference like `&usize` or `Option<foo::bar::Baz>` to a //! type: The entry point for this is `Ty::from_hir`. //! - Building the type for an item: This happens through the `type_for_def` query. //! //! This usually involves resolving names, collecting generic arguments etc. use std::cell::{Cell, RefCell}; use std::{iter, sync::Arc}; use base_db::CrateId; use chalk_ir::{cast::Cast, fold::Shift, interner::HasInterner, Mutability, Safety}; use hir_def::intern::Interned; use hir_def::{ adt::StructKind, body::{Expander, LowerCtx}, builtin_type::BuiltinType, generics::{TypeParamProvenance, WherePredicate, WherePredicateTypeTarget}, path::{GenericArg, Path, PathSegment, PathSegments}, resolver::{HasResolver, Resolver, TypeNs}, type_ref::{TraitRef as HirTraitRef, TypeBound, TypeRef}, AdtId, AssocContainerId, AssocItemId, ConstId, ConstParamId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule, ImplId, LocalFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId, TypeParamId, UnionId, VariantId, }; use hir_expand::{name::Name, ExpandResult}; use la_arena::ArenaMap; use smallvec::SmallVec; use stdx::impl_from; use syntax::ast; use crate::{ consteval, db::HirDatabase, mapping::ToChalk, static_lifetime, to_assoc_type_id, to_chalk_trait_id, to_placeholder_idx, utils::{ all_super_trait_refs, associated_type_by_name_including_super_traits, generics, Generics, }, AliasEq, AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, DynTy, FnPointer, FnSig, FnSubst, ImplTraitId, Interner, OpaqueTy, PolyFnSig, ProjectionTy, QuantifiedWhereClause, QuantifiedWhereClauses, ReturnTypeImplTrait, ReturnTypeImplTraits, Substitution, TraitEnvironment, TraitRef, TraitRefExt, Ty, TyBuilder, TyKind, WhereClause, }; #[derive(Debug)] pub struct TyLoweringContext<'a> { pub db: &'a dyn HirDatabase, pub resolver: &'a Resolver, in_binders: DebruijnIndex, /// Note: Conceptually, it's thinkable that we could be in a location where /// some type params should be represented as placeholders, and others /// should be converted to variables. I think in practice, this isn't /// possible currently, so this should be fine for now. pub type_param_mode: TypeParamLoweringMode, pub impl_trait_mode: ImplTraitLoweringMode, impl_trait_counter: Cell<u16>, /// When turning `impl Trait` into opaque types, we have to collect the /// bounds at the same time to get the IDs correct (without becoming too /// complicated). I don't like using interior mutability (as for the /// counter), but I've tried and failed to make the lifetimes work for /// passing around a `&mut TyLoweringContext`. The core problem is that /// we're grouping the mutable data (the counter and this field) together /// with the immutable context (the references to the DB and resolver). /// Splitting this up would be a possible fix. opaque_type_data: RefCell<Vec<ReturnTypeImplTrait>>, expander: RefCell<Option<Expander>>, } impl<'a> TyLoweringContext<'a> { pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self { let impl_trait_counter = Cell::new(0); let impl_trait_mode = ImplTraitLoweringMode::Disallowed; let type_param_mode = TypeParamLoweringMode::Placeholder; let in_binders = DebruijnIndex::INNERMOST; let opaque_type_data = RefCell::new(Vec::new()); Self { db, resolver, in_binders, impl_trait_mode, impl_trait_counter, type_param_mode, opaque_type_data, expander: RefCell::new(None), } } pub fn with_debruijn<T>( &self, debruijn: DebruijnIndex, f: impl FnOnce(&TyLoweringContext) -> T, ) -> T { let opaque_ty_data_vec = self.opaque_type_data.replace(Vec::new()); let expander = self.expander.replace(None); let new_ctx = Self { in_binders: debruijn, impl_trait_counter: Cell::new(self.impl_trait_counter.get()), opaque_type_data: RefCell::new(opaque_ty_data_vec), expander: RefCell::new(expander), ..*self }; let result = f(&new_ctx); self.impl_trait_counter.set(new_ctx.impl_trait_counter.get()); self.opaque_type_data.replace(new_ctx.opaque_type_data.into_inner()); self.expander.replace(new_ctx.expander.into_inner()); result } pub fn with_shifted_in<T>( &self, debruijn: DebruijnIndex, f: impl FnOnce(&TyLoweringContext) -> T, ) -> T { self.with_debruijn(self.in_binders.shifted_in_from(debruijn), f) } pub fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Self { Self { impl_trait_mode, ..self } } pub fn with_type_param_mode(self, type_param_mode: TypeParamLoweringMode) -> Self { Self { type_param_mode, ..self } } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum ImplTraitLoweringMode { /// `impl Trait` gets lowered into an opaque type that doesn't unify with /// anything except itself. This is used in places where values flow 'out', /// i.e. for arguments of the function we're currently checking, and return /// types of functions we're calling. Opaque, /// `impl Trait` gets lowered into a type variable. Used for argument /// position impl Trait when inside the respective function, since it allows /// us to support that without Chalk. Param, /// `impl Trait` gets lowered into a variable that can unify with some /// type. This is used in places where values flow 'in', i.e. for arguments /// of functions we're calling, and the return type of the function we're /// currently checking. Variable, /// `impl Trait` is disallowed and will be an error. Disallowed, } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum TypeParamLoweringMode { Placeholder, Variable, } impl<'a> TyLoweringContext<'a> { pub fn lower_ty(&self, type_ref: &TypeRef) -> Ty { self.lower_ty_ext(type_ref).0 } pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option<TypeNs>) { let mut res = None; let ty = match type_ref { TypeRef::Never => TyKind::Never.intern(&Interner), TypeRef::Tuple(inner) => { let inner_tys = inner.iter().map(|tr| self.lower_ty(tr)); TyKind::Tuple(inner_tys.len(), Substitution::from_iter(&Interner, inner_tys)) .intern(&Interner) } TypeRef::Path(path) => { let (ty, res_) = self.lower_path(path); res = res_; ty } TypeRef::RawPtr(inner, mutability) => { let inner_ty = self.lower_ty(inner); TyKind::Raw(lower_to_chalk_mutability(*mutability), inner_ty).intern(&Interner) } TypeRef::Array(inner, len) => { let inner_ty = self.lower_ty(inner); let const_len = consteval::usize_const(len.as_usize()); TyKind::Array(inner_ty, const_len).intern(&Interner) } TypeRef::Slice(inner) => { let inner_ty = self.lower_ty(inner); TyKind::Slice(inner_ty).intern(&Interner) } TypeRef::Reference(inner, _, mutability) => { let inner_ty = self.lower_ty(inner); let lifetime = static_lifetime(); TyKind::Ref(lower_to_chalk_mutability(*mutability), lifetime, inner_ty) .intern(&Interner) } TypeRef::Placeholder => TyKind::Error.intern(&Interner), TypeRef::Fn(params, is_varargs) => { let substs = self.with_shifted_in(DebruijnIndex::ONE, |ctx| { Substitution::from_iter(&Interner, params.iter().map(|tr| ctx.lower_ty(tr))) }); TyKind::Function(FnPointer { num_binders: 0, // FIXME lower `for<'a> fn()` correctly sig: FnSig { abi: (), safety: Safety::Safe, variadic: *is_varargs }, substitution: FnSubst(substs), }) .intern(&Interner) } TypeRef::DynTrait(bounds) => { let self_ty = TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner); let bounds = self.with_shifted_in(DebruijnIndex::ONE, |ctx| { QuantifiedWhereClauses::from_iter( &Interner, bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)), ) }); let bounds = crate::make_only_type_binders(1, bounds); TyKind::Dyn(DynTy { bounds, lifetime: static_lifetime() }).intern(&Interner) } TypeRef::ImplTrait(bounds) => { match self.impl_trait_mode { ImplTraitLoweringMode::Opaque => { let idx = self.impl_trait_counter.get(); self.impl_trait_counter.set(idx + 1); assert!(idx as usize == self.opaque_type_data.borrow().len()); // this dance is to make sure the data is in the right // place even if we encounter more opaque types while // lowering the bounds self.opaque_type_data.borrow_mut().push(ReturnTypeImplTrait { bounds: crate::make_only_type_binders(1, Vec::new()), }); // We don't want to lower the bounds inside the binders // we're currently in, because they don't end up inside // those binders. E.g. when we have `impl Trait<impl // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer // to the self parameter from `impl Trait`, and the // bounds aren't actually stored nested within each // other, but separately. So if the `T` refers to a type // parameter of the outer function, it's just one binder // away instead of two. let actual_opaque_type_data = self .with_debruijn(DebruijnIndex::INNERMOST, |ctx| { ctx.lower_impl_trait(bounds) }); self.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data; let func = match self.resolver.generic_def() { Some(GenericDefId::FunctionId(f)) => f, _ => panic!("opaque impl trait lowering in non-function"), }; let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx); let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into(); let generics = generics(self.db.upcast(), func.into()); let parameters = generics.bound_vars_subst(self.in_binders); TyKind::Alias(AliasTy::Opaque(OpaqueTy { opaque_ty_id, substitution: parameters, })) .intern(&Interner) } ImplTraitLoweringMode::Param => { let idx = self.impl_trait_counter.get(); // FIXME we're probably doing something wrong here self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16); if let Some(def) = self.resolver.generic_def() { let generics = generics(self.db.upcast(), def); let param = generics .iter() .filter(|(_, data)| { data.provenance == TypeParamProvenance::ArgumentImplTrait }) .nth(idx as usize) .map_or(TyKind::Error, |(id, _)| { TyKind::Placeholder(to_placeholder_idx(self.db, id)) }); param.intern(&Interner) } else { TyKind::Error.intern(&Interner) } } ImplTraitLoweringMode::Variable => { let idx = self.impl_trait_counter.get(); // FIXME we're probably doing something wrong here self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16); let (parent_params, self_params, list_params, _impl_trait_params) = if let Some(def) = self.resolver.generic_def() { let generics = generics(self.db.upcast(), def); generics.provenance_split() } else { (0, 0, 0, 0) }; TyKind::BoundVar(BoundVar::new( self.in_binders, idx as usize + parent_params + self_params + list_params, )) .intern(&Interner) } ImplTraitLoweringMode::Disallowed => { // FIXME: report error TyKind::Error.intern(&Interner) } } } TypeRef::Macro(macro_call) => { let (expander, recursion_start) = { let mut expander = self.expander.borrow_mut(); if expander.is_some() { (Some(expander), false) } else { if let Some(module_id) = self.resolver.module() { *expander = Some(Expander::new( self.db.upcast(), macro_call.file_id, module_id, )); (Some(expander), true) } else { (None, false) } } }; let ty = if let Some(mut expander) = expander { let expander_mut = expander.as_mut().unwrap(); let macro_call = macro_call.to_node(self.db.upcast()); match expander_mut.enter_expand::<ast::Type>(self.db.upcast(), macro_call) { Ok(ExpandResult { value: Some((mark, expanded)), .. }) => { let ctx = LowerCtx::new(self.db.upcast(), expander_mut.current_file_id()); let type_ref = TypeRef::from_ast(&ctx, expanded); drop(expander); let ty = self.lower_ty(&type_ref); self.expander .borrow_mut() .as_mut() .unwrap() .exit(self.db.upcast(), mark); Some(ty) } _ => None, } } else { None }; if recursion_start { *self.expander.borrow_mut() = None; } ty.unwrap_or_else(|| TyKind::Error.intern(&Interner)) } TypeRef::Error => TyKind::Error.intern(&Interner), }; (ty, res) } /// This is only for `generic_predicates_for_param`, where we can't just /// lower the self types of the predicates since that could lead to cycles. /// So we just check here if the `type_ref` resolves to a generic param, and which. fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeParamId> { let path = match type_ref { TypeRef::Path(path) => path, _ => return None, }; if path.type_anchor().is_some() { return None; } if path.segments().len() > 1 { return None; } let resolution = match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) { Some((it, None)) => it, _ => return None, }; if let TypeNs::GenericParam(param_id) = resolution { Some(param_id) } else { None } } pub(crate) fn lower_ty_relative_path( &self, ty: Ty, // We need the original resolution to lower `Self::AssocTy` correctly res: Option<TypeNs>, remaining_segments: PathSegments<'_>, ) -> (Ty, Option<TypeNs>) { if remaining_segments.len() == 1 { // resolve unselected assoc types let segment = remaining_segments.first().unwrap(); (self.select_associated_type(res, segment), None) } else if remaining_segments.len() > 1 { // FIXME report error (ambiguous associated type) (TyKind::Error.intern(&Interner), None) } else { (ty, res) } } pub(crate) fn lower_partly_resolved_path( &self, resolution: TypeNs, resolved_segment: PathSegment<'_>, remaining_segments: PathSegments<'_>, infer_args: bool, ) -> (Ty, Option<TypeNs>) { let ty = match resolution { TypeNs::TraitId(trait_) => { // if this is a bare dyn Trait, we'll directly put the required ^0 for the self type in there let self_ty = if remaining_segments.len() == 0 { Some( TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)) .intern(&Interner), ) } else { None }; let trait_ref = self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty); let ty = if remaining_segments.len() == 1 { let segment = remaining_segments.first().unwrap(); let found = self .db .trait_data(trait_ref.hir_trait_id()) .associated_type_by_name(segment.name); match found { Some(associated_ty) => { // FIXME handle type parameters on the segment TyKind::Alias(AliasTy::Projection(ProjectionTy { associated_ty_id: to_assoc_type_id(associated_ty), substitution: trait_ref.substitution, })) .intern(&Interner) } None => { // FIXME: report error (associated type not found) TyKind::Error.intern(&Interner) } } } else if remaining_segments.len() > 1 { // FIXME report error (ambiguous associated type) TyKind::Error.intern(&Interner) } else { let dyn_ty = DynTy { bounds: crate::make_only_type_binders( 1, QuantifiedWhereClauses::from_iter( &Interner, Some(crate::wrap_empty_binders(WhereClause::Implemented( trait_ref, ))), ), ), lifetime: static_lifetime(), }; TyKind::Dyn(dyn_ty).intern(&Interner) }; return (ty, None); } TypeNs::GenericParam(param_id) => { let generics = generics( self.db.upcast(), self.resolver.generic_def().expect("generics in scope"), ); match self.type_param_mode { TypeParamLoweringMode::Placeholder => { TyKind::Placeholder(to_placeholder_idx(self.db, param_id)) } TypeParamLoweringMode::Variable => { let idx = generics.param_idx(param_id).expect("matching generics"); TyKind::BoundVar(BoundVar::new(self.in_binders, idx)) } } .intern(&Interner) } TypeNs::SelfType(impl_id) => { let generics = generics(self.db.upcast(), impl_id.into()); let substs = match self.type_param_mode { TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db), TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders), }; self.db.impl_self_ty(impl_id).substitute(&Interner, &substs) } TypeNs::AdtSelfType(adt) => { let generics = generics(self.db.upcast(), adt.into()); let substs = match self.type_param_mode { TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db), TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders), }; self.db.ty(adt.into()).substitute(&Interner, &substs) } TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args), TypeNs::BuiltinType(it) => { self.lower_path_inner(resolved_segment, it.into(), infer_args) } TypeNs::TypeAliasId(it) => { self.lower_path_inner(resolved_segment, it.into(), infer_args) } // FIXME: report error TypeNs::EnumVariantId(_) => return (TyKind::Error.intern(&Interner), None), }; self.lower_ty_relative_path(ty, Some(resolution), remaining_segments) } pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option<TypeNs>) { // Resolve the path (in type namespace) if let Some(type_ref) = path.type_anchor() { let (ty, res) = self.lower_ty_ext(type_ref); return self.lower_ty_relative_path(ty, res, path.segments()); } let (resolution, remaining_index) = match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) { Some(it) => it, None => return (TyKind::Error.intern(&Interner), None), }; let (resolved_segment, remaining_segments) = match remaining_index { None => ( path.segments().last().expect("resolved path has at least one element"), PathSegments::EMPTY, ), Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)), }; self.lower_partly_resolved_path(resolution, resolved_segment, remaining_segments, false) } fn select_associated_type(&self, res: Option<TypeNs>, segment: PathSegment<'_>) -> Ty { if let Some(res) = res { let ty = associated_type_shorthand_candidates( self.db, res, move |name, t, associated_ty| { if name == segment.name { let substs = match self.type_param_mode { TypeParamLoweringMode::Placeholder => { // if we're lowering to placeholders, we have to put // them in now let generics = generics( self.db.upcast(), self.resolver.generic_def().expect( "there should be generics if there's a generic param", ), ); let s = generics.type_params_subst(self.db); s.apply(t.substitution.clone(), &Interner) } TypeParamLoweringMode::Variable => t.substitution.clone(), }; // We need to shift in the bound vars, since // associated_type_shorthand_candidates does not do that let substs = substs.shifted_in_from(&Interner, self.in_binders); // FIXME handle type parameters on the segment return Some( TyKind::Alias(AliasTy::Projection(ProjectionTy { associated_ty_id: to_assoc_type_id(associated_ty), substitution: substs, })) .intern(&Interner), ); } None }, ); ty.unwrap_or_else(|| TyKind::Error.intern(&Interner)) } else { TyKind::Error.intern(&Interner) } } fn lower_path_inner( &self, segment: PathSegment<'_>, typeable: TyDefId, infer_args: bool, ) -> Ty { let generic_def = match typeable { TyDefId::BuiltinType(_) => None, TyDefId::AdtId(it) => Some(it.into()), TyDefId::TypeAliasId(it) => Some(it.into()), }; let substs = self.substs_from_path_segment(segment, generic_def, infer_args, None); self.db.ty(typeable).substitute(&Interner, &substs) } /// Collect generic arguments from a path into a `Substs`. See also /// `create_substs_for_ast_path` and `def_to_ty` in rustc. pub(super) fn substs_from_path( &self, path: &Path, // Note that we don't call `db.value_type(resolved)` here, // `ValueTyDefId` is just a convenient way to pass generics and // special-case enum variants resolved: ValueTyDefId, infer_args: bool, ) -> Substitution { let last = path.segments().last().expect("path should have at least one segment"); let (segment, generic_def) = match resolved { ValueTyDefId::FunctionId(it) => (last, Some(it.into())), ValueTyDefId::StructId(it) => (last, Some(it.into())), ValueTyDefId::UnionId(it) => (last, Some(it.into())), ValueTyDefId::ConstId(it) => (last, Some(it.into())), ValueTyDefId::StaticId(_) => (last, None), ValueTyDefId::EnumVariantId(var) => { // the generic args for an enum variant may be either specified // on the segment referring to the enum, or on the segment // referring to the variant. So `Option::<T>::None` and // `Option::None::<T>` are both allowed (though the former is // preferred). See also `def_ids_for_path_segments` in rustc. let len = path.segments().len(); let penultimate = if len >= 2 { path.segments().get(len - 2) } else { None }; let segment = match penultimate { Some(segment) if segment.args_and_bindings.is_some() => segment, _ => last, }; (segment, Some(var.parent.into())) } }; self.substs_from_path_segment(segment, generic_def, infer_args, None) } fn substs_from_path_segment( &self, segment: PathSegment<'_>, def_generic: Option<GenericDefId>, infer_args: bool, explicit_self_ty: Option<Ty>, ) -> Substitution { let mut substs = Vec::new(); let def_generics = def_generic.map(|def| generics(self.db.upcast(), def)); let (parent_params, self_params, type_params, impl_trait_params) = def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split()); let total_len = parent_params + self_params + type_params + impl_trait_params; substs.extend(iter::repeat(TyKind::Error.intern(&Interner)).take(parent_params)); let fill_self_params = || { substs.extend( explicit_self_ty .into_iter() .chain(iter::repeat(TyKind::Error.intern(&Interner))) .take(self_params), ) }; let mut had_explicit_type_args = false; if let Some(generic_args) = &segment.args_and_bindings { if !generic_args.has_self_type { fill_self_params(); } let expected_num = if generic_args.has_self_type { self_params + type_params } else { type_params }; let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 }; // if args are provided, it should be all of them, but we can't rely on that for arg in generic_args .args .iter() .filter(|arg| matches!(arg, GenericArg::Type(_))) .skip(skip) .take(expected_num) { match arg { GenericArg::Type(type_ref) => { had_explicit_type_args = true; let ty = self.lower_ty(type_ref); substs.push(ty); } GenericArg::Lifetime(_) => {} } } } else { fill_self_params(); } // handle defaults. In expression or pattern path segments without // explicitly specified type arguments, missing type arguments are inferred // (i.e. defaults aren't used). if !infer_args || had_explicit_type_args { if let Some(def_generic) = def_generic { let defaults = self.db.generic_defaults(def_generic); assert_eq!(total_len, defaults.len()); for default_ty in defaults.iter().skip(substs.len()) { // each default can depend on the previous parameters let substs_so_far = Substitution::from_iter(&Interner, substs.clone()); substs.push(default_ty.clone().substitute(&Interner, &substs_so_far)); } } } // add placeholders for args that were not provided // FIXME: emit diagnostics in contexts where this is not allowed for _ in substs.len()..total_len { substs.push(TyKind::Error.intern(&Interner)); } assert_eq!(substs.len(), total_len); Substitution::from_iter(&Interner, substs) } fn lower_trait_ref_from_path( &self, path: &Path, explicit_self_ty: Option<Ty>, ) -> Option<TraitRef> { let resolved = match self.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), path.mod_path())? { TypeNs::TraitId(tr) => tr, _ => return None, }; let segment = path.segments().last().expect("path should have at least one segment"); Some(self.lower_trait_ref_from_resolved_path(resolved, segment, explicit_self_ty)) } pub(crate) fn lower_trait_ref_from_resolved_path( &self, resolved: TraitId, segment: PathSegment<'_>, explicit_self_ty: Option<Ty>, ) -> TraitRef { let substs = self.trait_ref_substs_from_path(segment, resolved, explicit_self_ty); TraitRef { trait_id: to_chalk_trait_id(resolved), substitution: substs } } fn lower_trait_ref( &self, trait_ref: &HirTraitRef, explicit_self_ty: Option<Ty>, ) -> Option<TraitRef> { self.lower_trait_ref_from_path(&trait_ref.path, explicit_self_ty) } fn trait_ref_substs_from_path( &self, segment: PathSegment<'_>, resolved: TraitId, explicit_self_ty: Option<Ty>, ) -> Substitution { self.substs_from_path_segment(segment, Some(resolved.into()), false, explicit_self_ty) } pub(crate) fn lower_where_predicate( &'a self, where_predicate: &'a WherePredicate, ignore_bindings: bool, ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a { match where_predicate { WherePredicate::ForLifetime { target, bound, .. } | WherePredicate::TypeBound { target, bound } => { let self_ty = match target { WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref), WherePredicateTypeTarget::TypeParam(param_id) => { let generic_def = self.resolver.generic_def().expect("generics in scope"); let generics = generics(self.db.upcast(), generic_def); let param_id = hir_def::TypeParamId { parent: generic_def, local_id: *param_id }; let placeholder = to_placeholder_idx(self.db, param_id); match self.type_param_mode { TypeParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder), TypeParamLoweringMode::Variable => { let idx = generics.param_idx(param_id).expect("matching generics"); TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx)) } } .intern(&Interner) } }; self.lower_type_bound(bound, self_ty, ignore_bindings) .collect::<Vec<_>>() .into_iter() } WherePredicate::Lifetime { .. } => vec![].into_iter(), } } pub(crate) fn lower_type_bound( &'a self, bound: &'a TypeBound, self_ty: Ty, ignore_bindings: bool, ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a { let mut bindings = None; let trait_ref = match bound { TypeBound::Path(path) => { bindings = self.lower_trait_ref_from_path(path, Some(self_ty)); bindings.clone().map(WhereClause::Implemented).map(crate::wrap_empty_binders) } TypeBound::ForLifetime(_, path) => { // FIXME Don't silently drop the hrtb lifetimes here bindings = self.lower_trait_ref_from_path(path, Some(self_ty)); bindings.clone().map(WhereClause::Implemented).map(crate::wrap_empty_binders) } TypeBound::Lifetime(_) => None, TypeBound::Error => None, }; trait_ref.into_iter().chain( bindings .into_iter() .filter(move |_| !ignore_bindings) .flat_map(move |tr| self.assoc_type_bindings_from_type_bound(bound, tr)), ) } fn assoc_type_bindings_from_type_bound( &'a self, bound: &'a TypeBound, trait_ref: TraitRef, ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a { let last_segment = match bound { TypeBound::Path(path) | TypeBound::ForLifetime(_, path) => path.segments().last(), TypeBound::Error | TypeBound::Lifetime(_) => None, }; last_segment .into_iter() .flat_map(|segment| segment.args_and_bindings.into_iter()) .flat_map(|args_and_bindings| args_and_bindings.bindings.iter()) .flat_map(move |binding| { let found = associated_type_by_name_including_super_traits( self.db, trait_ref.clone(), &binding.name, ); let (super_trait_ref, associated_ty) = match found { None => return SmallVec::<[QuantifiedWhereClause; 1]>::new(), Some(t) => t, }; let projection_ty = ProjectionTy { associated_ty_id: to_assoc_type_id(associated_ty), substitution: super_trait_ref.substitution, }; let mut preds = SmallVec::with_capacity( binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(), ); if let Some(type_ref) = &binding.type_ref { let ty = self.lower_ty(type_ref); let alias_eq = AliasEq { alias: AliasTy::Projection(projection_ty.clone()), ty }; preds.push(crate::wrap_empty_binders(WhereClause::AliasEq(alias_eq))); } for bound in &binding.bounds { preds.extend(self.lower_type_bound( bound, TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(&Interner), false, )); } preds }) } fn lower_impl_trait(&self, bounds: &[Interned<TypeBound>]) -> ReturnTypeImplTrait { cov_mark::hit!(lower_rpit); let self_ty = TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner); let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| { bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)).collect() }); ReturnTypeImplTrait { bounds: crate::make_only_type_binders(1, predicates) } } } fn count_impl_traits(type_ref: &TypeRef) -> usize { let mut count = 0; type_ref.walk(&mut |type_ref| { if matches!(type_ref, TypeRef::ImplTrait(_)) { count += 1; } }); count } /// Build the signature of a callable item (function, struct or enum variant). pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig { match def { CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f), CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s), CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e), } } pub fn associated_type_shorthand_candidates<R>( db: &dyn HirDatabase, res: TypeNs, mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>, ) -> Option<R> { let mut search = |t| { for t in all_super_trait_refs(db, t) { let data = db.trait_data(t.hir_trait_id()); for (name, assoc_id) in &data.items { if let AssocItemId::TypeAliasId(alias) = assoc_id { if let Some(result) = cb(name, &t, *alias) { return Some(result); } } } } None }; match res { TypeNs::SelfType(impl_id) => search( // we're _in_ the impl -- the binders get added back later. Correct, // but it would be nice to make this more explicit db.impl_trait(impl_id)?.into_value_and_skipped_binders().0, ), TypeNs::GenericParam(param_id) => { let predicates = db.generic_predicates_for_param(param_id); let res = predicates.iter().find_map(|pred| match pred.skip_binders().skip_binders() { // FIXME: how to correctly handle higher-ranked bounds here? WhereClause::Implemented(tr) => search( tr.clone() .shifted_out_to(&Interner, DebruijnIndex::ONE) .expect("FIXME unexpected higher-ranked trait bound"), ), _ => None, }); if let res @ Some(_) = res { return res; } // Handle `Self::Type` referring to own associated type in trait definitions if let GenericDefId::TraitId(trait_id) = param_id.parent { let generics = generics(db.upcast(), trait_id.into()); if generics.params.types[param_id.local_id].provenance == TypeParamProvenance::TraitSelf { let trait_ref = TyBuilder::trait_ref(db, trait_id) .fill_with_bound_vars(DebruijnIndex::INNERMOST, 0) .build(); return search(trait_ref); } } None } _ => None, } } /// Build the type of all specific fields of a struct or enum variant. pub(crate) fn field_types_query( db: &dyn HirDatabase, variant_id: VariantId, ) -> Arc<ArenaMap<LocalFieldId, Binders<Ty>>> { let var_data = variant_id.variant_data(db.upcast()); let (resolver, def): (_, GenericDefId) = match variant_id { VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()), VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()), VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()), }; let generics = generics(db.upcast(), def); let mut res = ArenaMap::default(); let ctx = TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); for (field_id, field_data) in var_data.fields().iter() { res.insert(field_id, make_binders(&generics, ctx.lower_ty(&field_data.type_ref))) } Arc::new(res) } /// This query exists only to be used when resolving short-hand associated types /// like `T::Item`. /// /// See the analogous query in rustc and its comment: /// <https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46> /// This is a query mostly to handle cycles somewhat gracefully; e.g. the /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but /// these are fine: `T: Foo<U::Item>, U: Foo<()>`. pub(crate) fn generic_predicates_for_param_query( db: &dyn HirDatabase, param_id: TypeParamId, ) -> Arc<[Binders<QuantifiedWhereClause>]> { let resolver = param_id.parent.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); let generics = generics(db.upcast(), param_id.parent); resolver .where_predicates_in_scope() // we have to filter out all other predicates *first*, before attempting to lower them .filter(|pred| match pred { WherePredicate::ForLifetime { target, .. } | WherePredicate::TypeBound { target, .. } => match target { WherePredicateTypeTarget::TypeRef(type_ref) => { ctx.lower_ty_only_param(type_ref) == Some(param_id) } WherePredicateTypeTarget::TypeParam(local_id) => *local_id == param_id.local_id, }, WherePredicate::Lifetime { .. } => false, }) .flat_map(|pred| ctx.lower_where_predicate(pred, true).map(|p| make_binders(&generics, p))) .collect() } pub(crate) fn generic_predicates_for_param_recover( _db: &dyn HirDatabase, _cycle: &[String], _param_id: &TypeParamId, ) -> Arc<[Binders<QuantifiedWhereClause>]> { Arc::new([]) } pub(crate) fn trait_environment_query( db: &dyn HirDatabase, def: GenericDefId, ) -> Arc<TraitEnvironment> { let resolver = def.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver) .with_type_param_mode(TypeParamLoweringMode::Placeholder); let mut traits_in_scope = Vec::new(); let mut clauses = Vec::new(); for pred in resolver.where_predicates_in_scope() { for pred in ctx.lower_where_predicate(pred, false) { if let WhereClause::Implemented(tr) = &pred.skip_binders() { traits_in_scope .push((tr.self_type_parameter(&Interner).clone(), tr.hir_trait_id())); } let program_clause: chalk_ir::ProgramClause<Interner> = pred.clone().cast(&Interner); clauses.push(program_clause.into_from_env_clause(&Interner)); } } let container: Option<AssocContainerId> = match def { // FIXME: is there a function for this? GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container), GenericDefId::AdtId(_) => None, GenericDefId::TraitId(_) => None, GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container), GenericDefId::ImplId(_) => None, GenericDefId::EnumVariantId(_) => None, GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container), }; if let Some(AssocContainerId::TraitId(trait_id)) = container { // add `Self: Trait<T1, T2, ...>` to the environment in trait // function default implementations (and speculative code // inside consts or type aliases) cov_mark::hit!(trait_self_implements_self); let substs = TyBuilder::type_params_subst(db, trait_id); let trait_ref = TraitRef { trait_id: to_chalk_trait_id(trait_id), substitution: substs }; let pred = WhereClause::Implemented(trait_ref); let program_clause: chalk_ir::ProgramClause<Interner> = pred.cast(&Interner); clauses.push(program_clause.into_from_env_clause(&Interner)); } let krate = def.module(db.upcast()).krate(); let env = chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses); Arc::new(TraitEnvironment { krate, traits_from_clauses: traits_in_scope, env }) } /// Resolve the where clause(s) of an item with generics. pub(crate) fn generic_predicates_query( db: &dyn HirDatabase, def: GenericDefId, ) -> Arc<[Binders<QuantifiedWhereClause>]> { let resolver = def.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); let generics = generics(db.upcast(), def); resolver .where_predicates_in_scope() .flat_map(|pred| ctx.lower_where_predicate(pred, false).map(|p| make_binders(&generics, p))) .collect() } /// Resolve the default type params from generics pub(crate) fn generic_defaults_query( db: &dyn HirDatabase, def: GenericDefId, ) -> Arc<[Binders<Ty>]> { let resolver = def.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); let generic_params = generics(db.upcast(), def); let defaults = generic_params .iter() .enumerate() .map(|(idx, (_, p))| { let mut ty = p.default.as_ref().map_or(TyKind::Error.intern(&Interner), |t| ctx.lower_ty(t)); // Each default can only refer to previous parameters. ty = crate::fold_free_vars(ty, |bound, binders| { if bound.index >= idx && bound.debruijn == DebruijnIndex::INNERMOST { // type variable default referring to parameter coming // after it. This is forbidden (FIXME: report // diagnostic) TyKind::Error.intern(&Interner) } else { bound.shifted_in_from(binders).to_ty(&Interner) } }); crate::make_only_type_binders(idx, ty) }) .collect(); defaults } pub(crate) fn generic_defaults_recover( db: &dyn HirDatabase, _cycle: &[String], def: &GenericDefId, ) -> Arc<[Binders<Ty>]> { let generic_params = generics(db.upcast(), *def); // we still need one default per parameter let defaults = generic_params .iter() .enumerate() .map(|(idx, _)| { let ty = TyKind::Error.intern(&Interner); crate::make_only_type_binders(idx, ty) }) .collect(); defaults } fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig { let data = db.function_data(def); let resolver = def.resolver(db.upcast()); let ctx_params = TyLoweringContext::new(db, &resolver) .with_impl_trait_mode(ImplTraitLoweringMode::Variable) .with_type_param_mode(TypeParamLoweringMode::Variable); let params = data.params.iter().map(|tr| ctx_params.lower_ty(tr)).collect::<Vec<_>>(); let ctx_ret = TyLoweringContext::new(db, &resolver) .with_impl_trait_mode(ImplTraitLoweringMode::Opaque) .with_type_param_mode(TypeParamLoweringMode::Variable); let ret = ctx_ret.lower_ty(&data.ret_type); let generics = generics(db.upcast(), def.into()); make_binders(&generics, CallableSig::from_params_and_return(params, ret, data.is_varargs())) } /// Build the declared type of a function. This should not need to look at the /// function body. fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> { let generics = generics(db.upcast(), def.into()); let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST); make_binders( &generics, TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner), ) } /// Build the declared type of a const. fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> { let data = db.const_data(def); let generics = generics(db.upcast(), def.into()); let resolver = def.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); make_binders(&generics, ctx.lower_ty(&data.type_ref)) } /// Build the declared type of a static. fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> { let data = db.static_data(def); let resolver = def.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver); Binders::empty(&Interner, ctx.lower_ty(&data.type_ref)) } fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig { let struct_data = db.struct_data(def); let fields = struct_data.variant_data.fields(); let resolver = def.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>(); let (ret, binders) = type_for_adt(db, def.into()).into_value_and_skipped_binders(); Binders::new(binders, CallableSig::from_params_and_return(params, ret, false)) } /// Build the type of a tuple struct constructor. fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> { let struct_data = db.struct_data(def); if let StructKind::Unit = struct_data.variant_data.kind() { return type_for_adt(db, def.into()); } let generics = generics(db.upcast(), def.into()); let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST); make_binders( &generics, TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner), ) } fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig { let enum_data = db.enum_data(def.parent); let var_data = &enum_data.variants[def.local_id]; let fields = var_data.variant_data.fields(); let resolver = def.parent.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>(); let (ret, binders) = type_for_adt(db, def.parent.into()).into_value_and_skipped_binders(); Binders::new(binders, CallableSig::from_params_and_return(params, ret, false)) } /// Build the type of a tuple enum variant constructor. fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> { let enum_data = db.enum_data(def.parent); let var_data = &enum_data.variants[def.local_id].variant_data; if let StructKind::Unit = var_data.kind() { return type_for_adt(db, def.parent.into()); } let generics = generics(db.upcast(), def.parent.into()); let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST); make_binders( &generics, TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner), ) } fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> { let generics = generics(db.upcast(), adt.into()); let b = TyBuilder::adt(db, adt); let ty = b.fill_with_bound_vars(DebruijnIndex::INNERMOST, 0).build(); make_binders(&generics, ty) } fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> { let generics = generics(db.upcast(), t.into()); let resolver = t.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); if db.type_alias_data(t).is_extern { Binders::empty(&Interner, TyKind::Foreign(crate::to_foreign_def_id(t)).intern(&Interner)) } else { let type_ref = &db.type_alias_data(t).type_ref; let inner = ctx.lower_ty(type_ref.as_deref().unwrap_or(&TypeRef::Error)); make_binders(&generics, inner) } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum CallableDefId { FunctionId(FunctionId), StructId(StructId), EnumVariantId(EnumVariantId), } impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId); impl CallableDefId { pub fn krate(self, db: &dyn HirDatabase) -> CrateId { let db = db.upcast(); match self { CallableDefId::FunctionId(f) => f.lookup(db).module(db), CallableDefId::StructId(s) => s.lookup(db).container, CallableDefId::EnumVariantId(e) => e.parent.lookup(db).container, } .krate() } } impl From<CallableDefId> for GenericDefId { fn from(def: CallableDefId) -> GenericDefId { match def { CallableDefId::FunctionId(f) => f.into(), CallableDefId::StructId(s) => s.into(), CallableDefId::EnumVariantId(e) => e.into(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum TyDefId { BuiltinType(BuiltinType), AdtId(AdtId), TypeAliasId(TypeAliasId), } impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId); #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ValueTyDefId { FunctionId(FunctionId), StructId(StructId), UnionId(UnionId), EnumVariantId(EnumVariantId), ConstId(ConstId), StaticId(StaticId), } impl_from!(FunctionId, StructId, UnionId, EnumVariantId, ConstId, StaticId for ValueTyDefId); /// Build the declared type of an item. This depends on the namespace; e.g. for /// `struct Foo(usize)`, we have two types: The type of the struct itself, and /// the constructor function `(usize) -> Foo` which lives in the values /// namespace. pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> { match def { TyDefId::BuiltinType(it) => Binders::empty(&Interner, TyBuilder::builtin(it)), TyDefId::AdtId(it) => type_for_adt(db, it), TyDefId::TypeAliasId(it) => type_for_type_alias(db, it), } } pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> { let generics = match *def { TyDefId::BuiltinType(_) => { return Binders::empty(&Interner, TyKind::Error.intern(&Interner)) } TyDefId::AdtId(it) => generics(db.upcast(), it.into()), TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()), }; make_binders(&generics, TyKind::Error.intern(&Interner)) } pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> { match def { ValueTyDefId::FunctionId(it) => type_for_fn(db, it), ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it), ValueTyDefId::UnionId(it) => type_for_adt(db, it.into()), ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it), ValueTyDefId::ConstId(it) => type_for_const(db, it), ValueTyDefId::StaticId(it) => type_for_static(db, it), } } pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> { let impl_data = db.impl_data(impl_id); let resolver = impl_id.resolver(db.upcast()); let generics = generics(db.upcast(), impl_id.into()); let ctx = TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); make_binders(&generics, ctx.lower_ty(&impl_data.self_ty)) } pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty { let parent_data = db.generic_params(def.parent); let data = &parent_data.consts[def.local_id]; let resolver = def.parent.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver); ctx.lower_ty(&data.ty) } pub(crate) fn impl_self_ty_recover( db: &dyn HirDatabase, _cycle: &[String], impl_id: &ImplId, ) -> Binders<Ty> { let generics = generics(db.upcast(), (*impl_id).into()); make_binders(&generics, TyKind::Error.intern(&Interner)) } pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> { let impl_data = db.impl_data(impl_id); let resolver = impl_id.resolver(db.upcast()); let ctx = TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); let (self_ty, binders) = db.impl_self_ty(impl_id).into_value_and_skipped_binders(); let target_trait = impl_data.target_trait.as_ref()?; Some(Binders::new(binders, ctx.lower_trait_ref(target_trait, Some(self_ty))?)) } pub(crate) fn return_type_impl_traits( db: &dyn HirDatabase, def: hir_def::FunctionId, ) -> Option<Arc<Binders<ReturnTypeImplTraits>>> { // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe let data = db.function_data(def); let resolver = def.resolver(db.upcast()); let ctx_ret = TyLoweringContext::new(db, &resolver) .with_impl_trait_mode(ImplTraitLoweringMode::Opaque) .with_type_param_mode(TypeParamLoweringMode::Variable); let _ret = (&ctx_ret).lower_ty(&data.ret_type); let generics = generics(db.upcast(), def.into()); let return_type_impl_traits = ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() }; if return_type_impl_traits.impl_traits.is_empty() { None } else { Some(Arc::new(make_binders(&generics, return_type_impl_traits))) } } pub(crate) fn lower_to_chalk_mutability(m: hir_def::type_ref::Mutability) -> Mutability { match m { hir_def::type_ref::Mutability::Shared => Mutability::Not, hir_def::type_ref::Mutability::Mut => Mutability::Mut, } } fn make_binders<T: HasInterner<Interner = Interner>>(generics: &Generics, value: T) -> Binders<T> { crate::make_only_type_binders(generics.len(), value) }
43.201005
120
0.568305
160fc66e59681e54239b101aa32ea547bef444c6
9,147
// Copyright 2020 The Matrix.org Foundation C.I.C. // // 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. //! Collection of small in-memory stores that can be used to cache Olm objects. //! //! Note: You'll only be interested in these if you are implementing a custom //! `CryptoStore`. use std::{collections::HashMap, sync::Arc}; use dashmap::DashMap; use matrix_sdk_common::locks::Mutex; use ruma::{DeviceId, RoomId, UserId}; use crate::{ identities::ReadOnlyDevice, olm::{InboundGroupSession, Session}, }; /// In-memory store for Olm Sessions. #[derive(Debug, Default, Clone)] pub struct SessionStore { entries: Arc<DashMap<String, Arc<Mutex<Vec<Session>>>>>, } impl SessionStore { /// Create a new empty Session store. pub fn new() -> Self { Self::default() } /// Add a session to the store. /// /// Returns true if the session was added, false if the session was /// already in the store. pub async fn add(&self, session: Session) -> bool { let sessions_lock = self .entries .entry(session.sender_key.to_string()) .or_insert_with(|| Arc::new(Mutex::new(Vec::new()))); let mut sessions = sessions_lock.lock().await; if !sessions.contains(&session) { sessions.push(session); true } else { false } } /// Get all the sessions that belong to the given sender key. pub fn get(&self, sender_key: &str) -> Option<Arc<Mutex<Vec<Session>>>> { self.entries.get(sender_key).map(|s| s.clone()) } /// Add a list of sessions belonging to the sender key. pub fn set_for_sender(&self, sender_key: &str, sessions: Vec<Session>) { self.entries.insert(sender_key.to_owned(), Arc::new(Mutex::new(sessions))); } } #[derive(Debug, Default, Clone)] /// In-memory store that holds inbound group sessions. pub struct GroupSessionStore { #[allow(clippy::type_complexity)] entries: Arc<DashMap<Box<RoomId>, HashMap<String, HashMap<String, InboundGroupSession>>>>, } impl GroupSessionStore { /// Create a new empty store. pub fn new() -> Self { Self::default() } /// Add an inbound group session to the store. /// /// Returns true if the session was added, false if the session was /// already in the store. pub fn add(&self, session: InboundGroupSession) -> bool { self.entries .entry((*session.room_id).to_owned()) .or_insert_with(HashMap::new) .entry(session.sender_key.to_string()) .or_insert_with(HashMap::new) .insert(session.session_id().to_owned(), session) .is_none() } /// Get all the group sessions the store knows about. pub fn get_all(&self) -> Vec<InboundGroupSession> { self.entries .iter() .flat_map(|d| { d.value() .values() .flat_map(|t| t.values().cloned().collect::<Vec<InboundGroupSession>>()) .collect::<Vec<InboundGroupSession>>() }) .collect() } /// Get the number of `InboundGroupSession`s we have. pub fn count(&self) -> usize { self.entries.iter().map(|d| d.value().values().map(|t| t.len()).sum::<usize>()).sum() } /// Get a inbound group session from our store. /// /// # Arguments /// * `room_id` - The room id of the room that the session belongs to. /// /// * `sender_key` - The sender key that sent us the session. /// /// * `session_id` - The unique id of the session. pub fn get( &self, room_id: &RoomId, sender_key: &str, session_id: &str, ) -> Option<InboundGroupSession> { self.entries .get(room_id) .and_then(|m| m.get(sender_key).and_then(|m| m.get(session_id).cloned())) } } /// In-memory store holding the devices of users. #[derive(Clone, Debug, Default)] pub struct DeviceStore { #[allow(clippy::type_complexity)] entries: Arc<DashMap<Box<UserId>, DashMap<Box<DeviceId>, ReadOnlyDevice>>>, } impl DeviceStore { /// Create a new empty device store. pub fn new() -> Self { Self::default() } /// Add a device to the store. /// /// Returns true if the device was already in the store, false otherwise. pub fn add(&self, device: ReadOnlyDevice) -> bool { let user_id = device.user_id(); self.entries .entry(user_id.to_owned()) .or_insert_with(DashMap::new) .insert(device.device_id().into(), device) .is_none() } /// Get the device with the given device_id and belonging to the given user. pub fn get(&self, user_id: &UserId, device_id: &DeviceId) -> Option<ReadOnlyDevice> { self.entries.get(user_id).and_then(|m| m.get(device_id).map(|d| d.value().clone())) } /// Remove the device with the given device_id and belonging to the given /// user. /// /// Returns the device if it was removed, None if it wasn't in the store. pub fn remove(&self, user_id: &UserId, device_id: &DeviceId) -> Option<ReadOnlyDevice> { self.entries.get(user_id).and_then(|m| m.remove(device_id)).map(|(_, d)| d) } /// Get a read-only view over all devices of the given user. pub fn user_devices(&self, user_id: &UserId) -> HashMap<Box<DeviceId>, ReadOnlyDevice> { self.entries .entry(user_id.to_owned()) .or_insert_with(DashMap::new) .iter() .map(|i| (i.key().to_owned(), i.value().clone())) .collect() } } #[cfg(test)] mod test { use matrix_sdk_test::async_test; use ruma::room_id; use crate::{ identities::device::testing::get_device, olm::{test::get_account_and_session, InboundGroupSession}, store::caches::{DeviceStore, GroupSessionStore, SessionStore}, }; #[async_test] async fn test_session_store() { let (_, session) = get_account_and_session().await; let store = SessionStore::new(); assert!(store.add(session.clone()).await); assert!(!store.add(session.clone()).await); let sessions = store.get(&session.sender_key).unwrap(); let sessions = sessions.lock().await; let loaded_session = &sessions[0]; assert_eq!(&session, loaded_session); } #[async_test] async fn test_session_store_bulk_storing() { let (_, session) = get_account_and_session().await; let store = SessionStore::new(); store.set_for_sender(&session.sender_key, vec![session.clone()]); let sessions = store.get(&session.sender_key).unwrap(); let sessions = sessions.lock().await; let loaded_session = &sessions[0]; assert_eq!(&session, loaded_session); } #[async_test] async fn test_group_session_store() { let (account, _) = get_account_and_session().await; let room_id = room_id!("!test:localhost"); let (outbound, _) = account.create_group_session_pair_with_defaults(room_id).await.unwrap(); assert_eq!(0, outbound.message_index().await); assert!(!outbound.shared()); outbound.mark_as_shared(); assert!(outbound.shared()); let inbound = InboundGroupSession::new( "test_key", "test_key", room_id, outbound.session_key().await, None, ) .unwrap(); let store = GroupSessionStore::new(); store.add(inbound.clone()); let loaded_session = store.get(room_id, "test_key", outbound.session_id()).unwrap(); assert_eq!(inbound, loaded_session); } #[async_test] async fn test_device_store() { let device = get_device(); let store = DeviceStore::new(); assert!(store.add(device.clone())); assert!(!store.add(device.clone())); let loaded_device = store.get(device.user_id(), device.device_id()).unwrap(); assert_eq!(device, loaded_device); let user_devices = store.user_devices(device.user_id()); assert_eq!(&**user_devices.keys().next().unwrap(), device.device_id()); assert_eq!(user_devices.values().next().unwrap(), &device); let loaded_device = user_devices.get(device.device_id()).unwrap(); assert_eq!(&device, loaded_device); store.remove(device.user_id(), device.device_id()); let loaded_device = store.get(device.user_id(), device.device_id()); assert!(loaded_device.is_none()); } }
31.982517
100
0.612551
8a9d3ebf1a25cdcb6155f8195d8b7a25a74fc7e4
3,377
use huber_common::model::package::{Package, PackageManagement, PackageSource, PackageTargetType}; #[allow(dead_code)] pub fn release() -> Package { Package { name: "navi".to_string(), source: PackageSource::Github { owner: "denisidoro".to_string(), repo: "navi".to_string(), }, detail: None, targets: vec![ PackageTargetType::LinuxAmd64(PackageManagement { artifact_templates: vec![ "navi-v{version}-x86_64-unknown-linux-musl.tar.gz".to_string() ], executable_templates: None, executable_mappings: None, install_commands: None, uninstall_commands: None, upgrade_commands: None, tag_version_regex_template: None, scan_dirs: None, }), PackageTargetType::LinuxAmd64(PackageManagement { artifact_templates: vec!["navi-v{version}-aarch64-linux-android.tar.gz".to_string()], executable_templates: None, executable_mappings: None, install_commands: None, uninstall_commands: None, upgrade_commands: None, tag_version_regex_template: None, scan_dirs: None, }), PackageTargetType::LinuxArm32(PackageManagement { artifact_templates: vec![ "navi-v{version}-armv7-unknown-linux-musleabihf.tar.gz".to_string() ], executable_templates: None, executable_mappings: None, install_commands: None, uninstall_commands: None, upgrade_commands: None, tag_version_regex_template: None, scan_dirs: None, }), PackageTargetType::MacOS(PackageManagement { artifact_templates: vec!["navi-v{version}-x86_64-apple-darwin.tar.gz".to_string()], executable_templates: None, executable_mappings: None, install_commands: None, uninstall_commands: None, upgrade_commands: None, tag_version_regex_template: None, scan_dirs: None, }), PackageTargetType::MacOSArm64(PackageManagement { artifact_templates: vec!["navi-v{version}-aarch64-apple-ios.tar.gz".to_string()], executable_templates: None, executable_mappings: None, install_commands: None, uninstall_commands: None, upgrade_commands: None, tag_version_regex_template: None, scan_dirs: None, }), PackageTargetType::Windows(PackageManagement { artifact_templates: vec!["navi-v{version}-x86_64-pc-windows-gnu.zip".to_string()], executable_templates: None, executable_mappings: None, install_commands: None, uninstall_commands: None, upgrade_commands: None, tag_version_regex_template: None, scan_dirs: None, }), ], version: None, description: None, release_kind: None, } }
40.686747
101
0.542493
3800398fe90a7a0a4ece7b22db3fbcf89f10a9e0
9,909
//! A crate for using libcurl as a backend for HTTP git requests with git2-rs. //! //! This crate provides one public function, `register`, which will register //! a custom HTTP transport with libcurl for any HTTP requests made by libgit2. //! At this time the `register` function is unsafe for the same reasons that //! `git2::transport::register` is also unsafe. //! //! It is not recommended to use this crate wherever possible. The current //! libcurl backend used, `curl-rust`, only supports executing a request in one //! method call implying no streaming support. This consequently means that //! when a repository is cloned the entire contents of the repo are downloaded //! into memory, and *then* written off to disk by libgit2 afterwards. It //! should be possible to alleviate this problem in the future. //! //! > **NOTE**: At this time this crate likely does not support a `git push` //! > operation, only clones. #![doc(html_root_url = "https://docs.rs/git2-curl/0.10")] #![deny(missing_docs)] #![warn(rust_2018_idioms)] #![cfg_attr(test, deny(warnings))] use std::error; use std::io::prelude::*; use std::io::{self, Cursor}; use std::str; use std::sync::{Arc, Mutex, Once, ONCE_INIT}; use curl::easy::{Easy, List}; use git2::transport::SmartSubtransportStream; use git2::transport::{Service, SmartSubtransport, Transport}; use git2::Error; use log::{debug, info}; use url::Url; struct CurlTransport { handle: Arc<Mutex<Easy>>, /// The URL of the remote server, e.g. "https://github.com/user/repo" /// /// This is an empty string until the first action is performed. /// If there is an HTTP redirect, this will be updated with the new URL. base_url: Arc<Mutex<String>>, } struct CurlSubtransport { handle: Arc<Mutex<Easy>>, service: &'static str, url_path: &'static str, base_url: Arc<Mutex<String>>, method: &'static str, reader: Option<Cursor<Vec<u8>>>, sent_request: bool, } /// Register the libcurl backend for HTTP requests made by libgit2. /// /// This function takes one parameter, a `handle`, which is used to perform all /// future HTTP requests. The handle can be previously configured with /// information such as proxies, SSL information, etc. /// /// This function is unsafe largely for the same reasons as /// `git2::transport::register`: /// /// * The function needs to be synchronized against all other creations of /// transport (any API calls to libgit2). /// * The function will leak `handle` as once registered it is not currently /// possible to unregister the backend. /// /// This function may be called concurrently, but only the first `handle` will /// be used. All others will be discarded. pub unsafe fn register(handle: Easy) { static INIT: Once = ONCE_INIT; let handle = Arc::new(Mutex::new(handle)); let handle2 = handle.clone(); INIT.call_once(move || { git2::transport::register("http", move |remote| factory(remote, handle.clone())).unwrap(); git2::transport::register("https", move |remote| factory(remote, handle2.clone())).unwrap(); }); } fn factory(remote: &git2::Remote<'_>, handle: Arc<Mutex<Easy>>) -> Result<Transport, Error> { Transport::smart( remote, true, CurlTransport { handle: handle, base_url: Arc::new(Mutex::new(String::new())), }, ) } impl SmartSubtransport for CurlTransport { fn action( &self, url: &str, action: Service, ) -> Result<Box<dyn SmartSubtransportStream>, Error> { let mut base_url = self.base_url.lock().unwrap(); if base_url.len() == 0 { *base_url = url.to_string(); } let (service, path, method) = match action { Service::UploadPackLs => ("upload-pack", "/info/refs?service=git-upload-pack", "GET"), Service::UploadPack => ("upload-pack", "/git-upload-pack", "POST"), Service::ReceivePackLs => { ("receive-pack", "/info/refs?service=git-receive-pack", "GET") } Service::ReceivePack => ("receive-pack", "/git-receive-pack", "POST"), }; info!("action {} {}", service, path); Ok(Box::new(CurlSubtransport { handle: self.handle.clone(), service: service, url_path: path, base_url: self.base_url.clone(), method: method, reader: None, sent_request: false, })) } fn close(&self) -> Result<(), Error> { Ok(()) // ... } } impl CurlSubtransport { fn err<E: Into<Box<dyn error::Error + Send + Sync>>>(&self, err: E) -> io::Error { io::Error::new(io::ErrorKind::Other, err) } fn execute(&mut self, data: &[u8]) -> io::Result<()> { if self.sent_request { return Err(self.err("already sent HTTP request")); } let agent = format!("git/1.0 (git2-curl {})", env!("CARGO_PKG_VERSION")); // Parse our input URL to figure out the host let url = format!("{}{}", self.base_url.lock().unwrap(), self.url_path); let parsed = Url::parse(&url).map_err(|_| self.err("invalid url, failed to parse"))?; let host = match parsed.host_str() { Some(host) => host, None => return Err(self.err("invalid url, did not have a host")), }; // Prep the request debug!("request to {}", url); let mut h = self.handle.lock().unwrap(); h.url(&url)?; h.useragent(&agent)?; h.follow_location(true)?; match self.method { "GET" => h.get(true)?, "PUT" => h.put(true)?, "POST" => h.post(true)?, other => h.custom_request(other)?, } let mut headers = List::new(); headers.append(&format!("Host: {}", host))?; if data.len() > 0 { h.post_fields_copy(data)?; headers.append(&format!( "Accept: application/x-git-{}-result", self.service ))?; headers.append(&format!( "Content-Type: \ application/x-git-{}-request", self.service ))?; } else { headers.append("Accept: */*")?; } headers.append("Expect:")?; h.http_headers(headers)?; let mut content_type = None; let mut data = Vec::new(); { let mut h = h.transfer(); // Look for the Content-Type header h.header_function(|header| { let header = match str::from_utf8(header) { Ok(s) => s, Err(..) => return true, }; let mut parts = header.splitn(2, ": "); let name = parts.next().unwrap(); let value = match parts.next() { Some(value) => value, None => return true, }; if name.eq_ignore_ascii_case("Content-Type") { content_type = Some(value.trim().to_string()); } true })?; // Collect the request's response in-memory h.write_function(|buf| { data.extend_from_slice(buf); Ok(buf.len()) })?; // Send the request h.perform()?; } let code = h.response_code()?; if code != 200 { return Err(self.err( &format!( "failed to receive HTTP 200 response: \ got {}", code )[..], )); } // Check returned headers let expected = match self.method { "GET" => format!("application/x-git-{}-advertisement", self.service), _ => format!("application/x-git-{}-result", self.service), }; match content_type { Some(ref content_type) if *content_type != expected => { return Err(self.err( &format!( "expected a Content-Type header \ with `{}` but found `{}`", expected, content_type )[..], )) } Some(..) => {} None => { return Err(self.err( &format!( "expected a Content-Type header \ with `{}` but didn't find one", expected )[..], )) } } // Ok, time to read off some data. let rdr = Cursor::new(data); self.reader = Some(rdr); // If there was a redirect, update the `CurlTransport` with the new base. if let Ok(Some(effective_url)) = h.effective_url() { let new_base = if effective_url.ends_with(self.url_path) { // Strip the action from the end. &effective_url[..effective_url.len() - self.url_path.len()] } else { // I'm not sure if this code path makes sense, but it's what // libgit does. effective_url }; *self.base_url.lock().unwrap() = new_base.to_string(); } Ok(()) } } impl Read for CurlSubtransport { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if self.reader.is_none() { self.execute(&[])?; } self.reader.as_mut().unwrap().read(buf) } } impl Write for CurlSubtransport { fn write(&mut self, data: &[u8]) -> io::Result<usize> { if self.reader.is_none() { self.execute(data)?; } Ok(data.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }
33.934932
100
0.533858
d6b17f3a73d7163b3da6be370b031d6aff39d216
4,349
use super::prelude::*; use std::collections::BTreeMap; pub trait CategoricalType: Eq + Hash + Clone + FromStr + Ord + PartialOrd {} impl<T> CategoricalType for T where T: Eq + Hash + Clone + FromStr + Ord + PartialOrd {} #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, Hash)] #[serde(from = "CategoricalShadow<T>")] pub struct Categorical<T: CategoricalType> { #[serde(flatten)] pub(crate) seen: BTreeMap<T, u64>, #[serde(skip_serializing)] pub(crate) total: u64, } fn categorical_map_de<'de, D, T>(deserializer: D) -> Result<BTreeMap<T, u64>, D::Error> where T: CategoricalType, D: Deserializer<'de>, { let hm_string_keys: BTreeMap<String, u64> = BTreeMap::deserialize(deserializer)?; let mut hm_final: BTreeMap<T, u64> = BTreeMap::new(); for (k, v) in hm_string_keys { hm_final.insert( k.parse() .map_err(|_| serde::de::Error::custom(format!("could not deserialize {}", k)))?, v, ); } if hm_final.is_empty() { return Err(serde::de::Error::custom( "Could not create categorical. Categorical must be non-empty (i.e. have at least one value in 'seen').", )); } Ok(hm_final) } impl<T: CategoricalType> Categorical<T> { pub fn push(&mut self, t: T) { match self.seen.get_mut(&t) { Some(occurrences) => { *occurrences += 1; } None => { self.seen.insert(t, 1); } }; self.total += 1; } } /// This struct purely serves as an intermediary to check invariants in the /// Categorical struct #[derive(Deserialize)] struct CategoricalShadow<T: CategoricalType> { #[serde(deserialize_with = "categorical_map_de")] #[serde(flatten)] seen: BTreeMap<T, u64>, } impl<T: CategoricalType> From<CategoricalShadow<T>> for Categorical<T> { fn from(shadow: CategoricalShadow<T>) -> Self { let total: u64 = shadow.seen.values().sum(); Categorical { seen: shadow.seen, total, } } } impl<T: CategoricalType> Distribution<T> for Categorical<T> { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T { if self.seen.len() == 1 { // unwrap() is always OK here because len == 1 return self.seen.keys().next().unwrap().clone(); } let f = rng.gen_range(0.0..1.0); let mut index = (f * self.total as f64).floor() as i64; for (k, v) in self.seen.iter() { index -= *v as i64; if index < 0 { return k.clone(); } } unreachable!() } } #[cfg(test)] pub mod tests { use super::*; #[test] fn test_push() { let categorical_json = json!( { "a" : 5, "b" : 10, } ); let mut categorical: Categorical<String> = serde_json::from_value(categorical_json).unwrap(); categorical.push("a".to_string()); categorical.push("b".to_string()); assert_eq!(categorical.seen.get("a").unwrap(), &6); assert_eq!(categorical.seen.get("b").unwrap(), &11); assert_eq!(categorical.total, 17); } #[test] fn test_sample() { use rand::distributions::Distribution; let categorical_json = json!( { "a" : 5, "b" : 10, } ); let categorical: Categorical<String> = serde_json::from_value(categorical_json).unwrap(); let mut rng = rand::thread_rng(); for _ in 1..100 { match categorical.sample(&mut rng).as_ref() { "a" => {} "b" => {} _ => panic!("Should only get 'a's and 'b's"), } } } #[test] fn test_categorical_empty_invariant() { let categorical_json = json!({}); assert!(serde_json::from_value::<Categorical<String>>(categorical_json).is_err()) } #[test] fn test_weightless_single_invariant() { let categorical_json = json!({ "foo": 0 }); assert_eq!( "foo", serde_json::from_value::<Categorical<String>>(categorical_json) .unwrap() .sample(&mut rand::thread_rng()) ) } }
29.385135
116
0.539434
2196af6010949472533594afff78721b7560059c
34,588
use crate::{ border::BorderBuilder, brush::{Brush, GradientPoint}, button::ButtonBuilder, core::{algebra::Vector2, color::Color, math::Rect, pool::Handle}, decorator::DecoratorBuilder, grid::{Column, GridBuilder, Row}, message::{ ButtonMessage, CursorIcon, MessageData, MessageDirection, TextMessage, UiMessage, UiMessageData, WidgetMessage, WindowMessage, }, text::TextBuilder, vector_image::{Primitive, VectorImageBuilder}, widget::{Widget, WidgetBuilder}, BuildContext, Control, HorizontalAlignment, NodeHandleMapping, RestrictionEntry, Thickness, UINode, UserInterface, VerticalAlignment, BRUSH_BRIGHT, BRUSH_LIGHT, BRUSH_LIGHTER, BRUSH_LIGHTEST, COLOR_DARK, COLOR_DARKEST, }; use std::{ cell::RefCell, ops::{Deref, DerefMut}, }; /// Represents a widget looking as window in Windows - with title, minimize and close buttons. /// It has scrollable region for content, content can be any desired node or even other window. /// Window can be dragged by its title. #[derive(Clone)] pub struct Window<M: MessageData, C: Control<M, C>> { widget: Widget<M, C>, mouse_click_pos: Vector2<f32>, initial_position: Vector2<f32>, initial_size: Vector2<f32>, is_dragging: bool, minimized: bool, can_minimize: bool, can_close: bool, can_resize: bool, header: Handle<UINode<M, C>>, minimize_button: Handle<UINode<M, C>>, close_button: Handle<UINode<M, C>>, drag_delta: Vector2<f32>, content: Handle<UINode<M, C>>, grips: RefCell<[Grip; 8]>, title: Handle<UINode<M, C>>, title_grid: Handle<UINode<M, C>>, } const GRIP_SIZE: f32 = 6.0; const CORNER_GRIP_SIZE: f32 = GRIP_SIZE * 2.0; #[derive(Copy, Clone, Debug)] enum GripKind { LeftTopCorner = 0, RightTopCorner = 1, RightBottomCorner = 2, LeftBottomCorner = 3, Left = 4, Top = 5, Right = 6, Bottom = 7, } #[derive(Clone)] struct Grip { kind: GripKind, bounds: Rect<f32>, is_dragging: bool, cursor: CursorIcon, } impl Grip { fn new(kind: GripKind, cursor: CursorIcon) -> Self { Self { kind, bounds: Default::default(), is_dragging: false, cursor, } } } crate::define_widget_deref!(Window<M, C>); impl<M: MessageData, C: Control<M, C>> Control<M, C> for Window<M, C> { fn resolve(&mut self, node_map: &NodeHandleMapping<M, C>) { node_map.resolve(&mut self.header); node_map.resolve(&mut self.minimize_button); node_map.resolve(&mut self.close_button); node_map.resolve(&mut self.title); node_map.resolve(&mut self.title_grid); node_map.resolve(&mut self.content); } fn arrange_override(&self, ui: &UserInterface<M, C>, final_size: Vector2<f32>) -> Vector2<f32> { let size = self.widget.arrange_override(ui, final_size); let mut grips = self.grips.borrow_mut(); // Adjust grips. grips[GripKind::Left as usize].bounds = Rect::new(0.0, GRIP_SIZE, GRIP_SIZE, final_size.y - GRIP_SIZE * 2.0); grips[GripKind::Top as usize].bounds = Rect::new(GRIP_SIZE, 0.0, final_size.x - GRIP_SIZE * 2.0, GRIP_SIZE); grips[GripKind::Right as usize].bounds = Rect::new( final_size.x - GRIP_SIZE, GRIP_SIZE, GRIP_SIZE, final_size.y - GRIP_SIZE * 2.0, ); grips[GripKind::Bottom as usize].bounds = Rect::new( GRIP_SIZE, final_size.y - GRIP_SIZE, final_size.x - GRIP_SIZE * 2.0, GRIP_SIZE, ); // Corners have different size to improve usability. grips[GripKind::LeftTopCorner as usize].bounds = Rect::new(0.0, 0.0, CORNER_GRIP_SIZE, CORNER_GRIP_SIZE); grips[GripKind::RightTopCorner as usize].bounds = Rect::new( final_size.x - GRIP_SIZE, 0.0, CORNER_GRIP_SIZE, CORNER_GRIP_SIZE, ); grips[GripKind::RightBottomCorner as usize].bounds = Rect::new( final_size.x - CORNER_GRIP_SIZE, final_size.y - CORNER_GRIP_SIZE, CORNER_GRIP_SIZE, CORNER_GRIP_SIZE, ); grips[GripKind::LeftBottomCorner as usize].bounds = Rect::new( 0.0, final_size.y - CORNER_GRIP_SIZE, CORNER_GRIP_SIZE, CORNER_GRIP_SIZE, ); size } fn handle_routed_message( &mut self, ui: &mut UserInterface<M, C>, message: &mut UiMessage<M, C>, ) { self.widget.handle_routed_message(ui, message); match &message.data() { UiMessageData::Widget(msg) => { // Grip interaction have higher priority than other actions. if self.can_resize { match msg { &WidgetMessage::MouseDown { pos, .. } => { ui.send_message(WidgetMessage::topmost( self.handle(), MessageDirection::ToWidget, )); // Check grips. for grip in self.grips.borrow_mut().iter_mut() { let offset = self.screen_position; let screen_bounds = grip.bounds.translate(offset); if screen_bounds.contains(pos) { grip.is_dragging = true; self.initial_position = self.actual_local_position(); self.initial_size = self.actual_size(); self.mouse_click_pos = pos; ui.capture_mouse(self.handle()); break; } } } WidgetMessage::MouseUp { .. } => { for grip in self.grips.borrow_mut().iter_mut() { if grip.is_dragging { ui.release_mouse_capture(); grip.is_dragging = false; break; } } } &WidgetMessage::MouseMove { pos, .. } => { let mut new_cursor = None; for grip in self.grips.borrow().iter() { let offset = self.screen_position; let screen_bounds = grip.bounds.translate(offset); if screen_bounds.contains(pos) { new_cursor = Some(grip.cursor); } if grip.is_dragging { let delta = self.mouse_click_pos - pos; let (dx, dy, dw, dh) = match grip.kind { GripKind::Left => (-1.0, 0.0, 1.0, 0.0), GripKind::Top => (0.0, -1.0, 0.0, 1.0), GripKind::Right => (0.0, 0.0, -1.0, 0.0), GripKind::Bottom => (0.0, 0.0, 0.0, -1.0), GripKind::LeftTopCorner => (-1.0, -1.0, 1.0, 1.0), GripKind::RightTopCorner => (0.0, -1.0, -1.0, 1.0), GripKind::RightBottomCorner => (0.0, 0.0, -1.0, -1.0), GripKind::LeftBottomCorner => (-1.0, 0.0, 1.0, -1.0), }; let new_pos = self.initial_position + Vector2::new(delta.x * dx, delta.y * dy); let new_size = self.initial_size + Vector2::new(delta.x * dw, delta.y * dh); if new_size.x > self.min_width() && new_size.x < self.max_width() && new_size.y > self.min_height() && new_size.y < self.max_height() { ui.send_message(WidgetMessage::desired_position( self.handle(), MessageDirection::ToWidget, new_pos, )); ui.send_message(WidgetMessage::width( self.handle(), MessageDirection::ToWidget, new_size.x, )); ui.send_message(WidgetMessage::height( self.handle(), MessageDirection::ToWidget, new_size.y, )); } break; } } self.set_cursor(new_cursor); } _ => {} } } if (message.destination() == self.header || ui .node(self.header) .has_descendant(message.destination(), ui)) && !message.handled() && !self.has_active_grip() { match msg { WidgetMessage::MouseDown { pos, .. } => { self.mouse_click_pos = *pos; ui.send_message(WindowMessage::move_start( self.handle, MessageDirection::ToWidget, )); message.set_handled(true); } WidgetMessage::MouseUp { .. } => { ui.send_message(WindowMessage::move_end( self.handle, MessageDirection::ToWidget, )); message.set_handled(true); } WidgetMessage::MouseMove { pos, .. } => { if self.is_dragging { self.drag_delta = *pos - self.mouse_click_pos; let new_pos = self.initial_position + self.drag_delta; ui.send_message(WindowMessage::move_to( self.handle(), MessageDirection::ToWidget, new_pos, )); } message.set_handled(true); } _ => (), } } if let WidgetMessage::Unlink = msg { if message.destination() == self.handle() { self.initial_position = self.screen_position; } } } UiMessageData::Button(ButtonMessage::Click) => { if message.destination() == self.minimize_button { ui.send_message(WindowMessage::minimize( self.handle(), MessageDirection::ToWidget, !self.minimized, )); } else if message.destination() == self.close_button { ui.send_message(WindowMessage::close( self.handle(), MessageDirection::ToWidget, )); } } UiMessageData::Window(msg) => { if message.destination() == self.handle() && message.direction() == MessageDirection::ToWidget { match msg { &WindowMessage::Open { center } => { if !self.visibility() { ui.send_message(WidgetMessage::visibility( self.handle(), MessageDirection::ToWidget, true, )); ui.send_message(WidgetMessage::topmost( self.handle(), MessageDirection::ToWidget, )); if center { ui.send_message(WidgetMessage::center( self.handle(), MessageDirection::ToWidget, )); } } } &WindowMessage::OpenModal { center } => { if !self.visibility() { ui.send_message(WidgetMessage::visibility( self.handle(), MessageDirection::ToWidget, true, )); ui.send_message(WidgetMessage::topmost( self.handle(), MessageDirection::ToWidget, )); if center { ui.send_message(WidgetMessage::center( self.handle(), MessageDirection::ToWidget, )); } ui.push_picking_restriction(RestrictionEntry { handle: self.handle(), stop: true, }); } } WindowMessage::Close => { if self.visibility() { ui.send_message(WidgetMessage::visibility( self.handle(), MessageDirection::ToWidget, false, )); ui.remove_picking_restriction(self.handle()); } } &WindowMessage::Minimize(minimized) => { if self.minimized != minimized { self.minimized = minimized; if self.content.is_some() { ui.send_message(WidgetMessage::visibility( self.content, MessageDirection::ToWidget, !minimized, )); } } } &WindowMessage::CanMinimize(value) => { if self.can_minimize != value { self.can_minimize = value; if self.minimize_button.is_some() { ui.send_message(WidgetMessage::visibility( self.minimize_button, MessageDirection::ToWidget, value, )); } } } &WindowMessage::CanClose(value) => { if self.can_close != value { self.can_close = value; if self.close_button.is_some() { ui.send_message(WidgetMessage::visibility( self.close_button, MessageDirection::ToWidget, value, )); } } } &WindowMessage::CanResize(value) => { if self.can_resize != value { self.can_resize = value; ui.send_message(message.reverse()); } } &WindowMessage::Move(new_pos) => { if self.desired_local_position() != new_pos { ui.send_message(WidgetMessage::desired_position( self.handle(), MessageDirection::ToWidget, new_pos, )); ui.send_message(message.reverse()); } } WindowMessage::MoveStart => { if !self.is_dragging { ui.capture_mouse(self.header); let initial_position = self.actual_local_position(); self.initial_position = initial_position; self.is_dragging = true; ui.send_message(message.reverse()); } } WindowMessage::MoveEnd => { if self.is_dragging { ui.release_mouse_capture(); self.is_dragging = false; ui.send_message(message.reverse()); } } WindowMessage::Title(title) => { match title { WindowTitle::Text(text) => { if let UINode::Text(_) = ui.node(self.title) { // Just modify existing text, this is much faster than // re-create text everytime. ui.send_message(TextMessage::text( self.title, MessageDirection::ToWidget, text.clone(), )); } else { ui.send_message(WidgetMessage::remove( self.title, MessageDirection::ToWidget, )); self.title = make_text_title(&mut ui.build_ctx(), text); } } WindowTitle::Node(node) => { if self.title.is_some() { // Remove old title. ui.send_message(WidgetMessage::remove( self.title, MessageDirection::ToWidget, )); } if node.is_some() { self.title = *node; // Attach new one. ui.send_message(WidgetMessage::link( self.title, MessageDirection::ToWidget, self.title_grid, )); } } } } } } } _ => (), } } fn remove_ref(&mut self, handle: Handle<UINode<M, C>>) { if self.header == handle { self.header = Handle::NONE; } if self.content == handle { self.content = Handle::NONE; } if self.close_button == handle { self.close_button = Handle::NONE; } if self.minimize_button == handle { self.minimize_button = Handle::NONE; } if self.title == handle { self.title = Handle::NONE; } if self.title_grid == handle { self.title_grid = Handle::NONE; } } } impl<M: MessageData, C: Control<M, C>> Window<M, C> { pub fn is_dragging(&self) -> bool { self.is_dragging } pub fn drag_delta(&self) -> Vector2<f32> { self.drag_delta } pub fn has_active_grip(&self) -> bool { for grip in self.grips.borrow().iter() { if grip.is_dragging { return true; } } false } pub fn set_can_resize(&mut self, value: bool) { self.can_resize = value; } pub fn can_resize(&self) -> bool { self.can_resize } } pub struct WindowBuilder<M: MessageData, C: Control<M, C>> { pub widget_builder: WidgetBuilder<M, C>, pub content: Handle<UINode<M, C>>, pub title: Option<WindowTitle<M, C>>, pub can_close: bool, pub can_minimize: bool, pub open: bool, pub close_button: Option<Handle<UINode<M, C>>>, pub minimize_button: Option<Handle<UINode<M, C>>>, // Warning: Any dependant builders must take this into account! pub modal: bool, pub can_resize: bool, } /// Window title can be either text or node. /// /// If `Text` is used, then builder will automatically create Text node with specified text, /// but with default font. /// /// If you need more flexibility (i.e. put a picture near text) then `Node` option is for you: /// it allows to put any UI node hierarchy you want to. #[derive(Debug, Clone, PartialEq)] pub enum WindowTitle<M: MessageData, C: Control<M, C>> { Text(String), Node(Handle<UINode<M, C>>), } impl<M: MessageData, C: Control<M, C>> WindowTitle<M, C> { pub fn text<P: AsRef<str>>(text: P) -> Self { WindowTitle::Text(text.as_ref().to_owned()) } pub fn node(node: Handle<UINode<M, C>>) -> Self { Self::Node(node) } } fn make_text_title<M: MessageData, C: Control<M, C>>( ctx: &mut BuildContext<M, C>, text: &str, ) -> Handle<UINode<M, C>> { TextBuilder::new( WidgetBuilder::new() .with_margin(Thickness::uniform(5.0)) .on_row(0) .on_column(0), ) .with_text(text) .build(ctx) } enum HeaderButton { Close, Minimize, } fn make_mark<M: MessageData, C: Control<M, C>>( ctx: &mut BuildContext<M, C>, button: HeaderButton, ) -> Handle<UINode<M, C>> { VectorImageBuilder::new( WidgetBuilder::new() .with_horizontal_alignment(HorizontalAlignment::Center) .with_vertical_alignment(match button { HeaderButton::Close => VerticalAlignment::Center, HeaderButton::Minimize => VerticalAlignment::Bottom, }) .with_margin(match button { HeaderButton::Close => Thickness::uniform(0.0), HeaderButton::Minimize => Thickness::bottom(3.0), }) .with_foreground(BRUSH_BRIGHT), ) .with_primitives(match button { HeaderButton::Close => { vec![ Primitive::Line { begin: Vector2::new(0.0, 0.0), end: Vector2::new(12.0, 12.0), thickness: 3.0, }, Primitive::Line { begin: Vector2::new(12.0, 0.0), end: Vector2::new(0.0, 12.0), thickness: 3.0, }, ] } HeaderButton::Minimize => { vec![Primitive::Line { begin: Vector2::new(0.0, 0.0), end: Vector2::new(12.0, 0.0), thickness: 3.0, }] } }) .build(ctx) } fn make_header_button<M: MessageData, C: Control<M, C>>( ctx: &mut BuildContext<M, C>, button: HeaderButton, ) -> Handle<UINode<M, C>> { ButtonBuilder::new(WidgetBuilder::new().with_margin(Thickness::uniform(2.0))) .with_back( DecoratorBuilder::new( BorderBuilder::new(WidgetBuilder::new()) .with_stroke_thickness(Thickness::uniform(0.0)), ) .with_normal_brush(Brush::Solid(Color::TRANSPARENT)) .with_hover_brush(BRUSH_LIGHT) .with_pressed_brush(BRUSH_LIGHTEST) .build(ctx), ) .with_content(make_mark(ctx, button)) .build(ctx) } impl<'a, M: MessageData, C: Control<M, C>> WindowBuilder<M, C> { pub fn new(widget_builder: WidgetBuilder<M, C>) -> Self { Self { widget_builder, content: Handle::NONE, title: None, can_close: true, can_minimize: true, open: true, close_button: None, minimize_button: None, modal: false, can_resize: true, } } pub fn with_content(mut self, content: Handle<UINode<M, C>>) -> Self { self.content = content; self } pub fn with_title(mut self, title: WindowTitle<M, C>) -> Self { self.title = Some(title); self } pub fn with_minimize_button(mut self, button: Handle<UINode<M, C>>) -> Self { self.minimize_button = Some(button); self } pub fn with_close_button(mut self, button: Handle<UINode<M, C>>) -> Self { self.close_button = Some(button); self } pub fn can_close(mut self, can_close: bool) -> Self { self.can_close = can_close; self } pub fn can_minimize(mut self, can_minimize: bool) -> Self { self.can_minimize = can_minimize; self } pub fn open(mut self, open: bool) -> Self { self.open = open; self } pub fn modal(mut self, modal: bool) -> Self { self.modal = modal; self } pub fn can_resize(mut self, can_resize: bool) -> Self { self.can_resize = can_resize; self } pub fn build_window(self, ctx: &mut BuildContext<M, C>) -> Window<M, C> { let minimize_button; let close_button; let title; let title_grid; let header = BorderBuilder::new( WidgetBuilder::new() .with_horizontal_alignment(HorizontalAlignment::Stretch) .with_height(30.0) .with_background(Brush::LinearGradient { from: Vector2::new(0.5, 0.0), to: Vector2::new(0.5, 1.0), stops: vec![ GradientPoint { stop: 0.0, color: COLOR_DARK, }, GradientPoint { stop: 0.85, color: COLOR_DARK, }, GradientPoint { stop: 1.0, color: COLOR_DARKEST, }, ], }) .with_child({ title_grid = GridBuilder::new( WidgetBuilder::new() .with_child({ title = match self.title { None => Handle::NONE, Some(window_title) => match window_title { WindowTitle::Node(node) => node, WindowTitle::Text(text) => make_text_title(ctx, &text), }, }; title }) .with_child({ minimize_button = self.minimize_button.unwrap_or_else(|| { make_header_button(ctx, HeaderButton::Minimize) }); ctx[minimize_button] .set_visibility(self.can_minimize) .set_width(30.0) .set_row(0) .set_column(1); minimize_button }) .with_child({ close_button = self.close_button.unwrap_or_else(|| { make_header_button(ctx, HeaderButton::Close) }); ctx[close_button] .set_width(30.0) .set_visibility(self.can_close) .set_row(0) .set_column(2); close_button }), ) .add_column(Column::stretch()) .add_column(Column::auto()) .add_column(Column::auto()) .add_row(Row::stretch()) .build(ctx); title_grid }) .on_row(0), ) .build(ctx); if self.content.is_some() { ctx[self.content].set_row(1); } Window { widget: self .widget_builder .with_visibility(self.open) .with_child( BorderBuilder::new( WidgetBuilder::new() .with_foreground(BRUSH_LIGHTER) .with_child( GridBuilder::new( WidgetBuilder::new() .with_child(self.content) .with_child(header), ) .add_column(Column::stretch()) .add_row(Row::auto()) .add_row(Row::stretch()) .build(ctx), ), ) .with_stroke_thickness(Thickness::uniform(1.0)) .build(ctx), ) .build(), mouse_click_pos: Vector2::default(), initial_position: Vector2::default(), initial_size: Default::default(), is_dragging: false, minimized: false, can_minimize: self.can_minimize, can_close: self.can_close, can_resize: self.can_resize, header, minimize_button, close_button, drag_delta: Default::default(), content: self.content, grips: RefCell::new([ // Corners have priority Grip::new(GripKind::LeftTopCorner, CursorIcon::NwResize), Grip::new(GripKind::RightTopCorner, CursorIcon::NeResize), Grip::new(GripKind::RightBottomCorner, CursorIcon::SeResize), Grip::new(GripKind::LeftBottomCorner, CursorIcon::SwResize), Grip::new(GripKind::Left, CursorIcon::WResize), Grip::new(GripKind::Top, CursorIcon::NResize), Grip::new(GripKind::Right, CursorIcon::EResize), Grip::new(GripKind::Bottom, CursorIcon::SResize), ]), title, title_grid, } } pub fn build(self, ctx: &mut BuildContext<M, C>) -> Handle<UINode<M, C>> { let modal = self.modal; let open = self.open; let node = self.build_window(ctx); let handle = ctx.add_node(UINode::Window(node)); if modal && open { ctx.ui .push_picking_restriction(RestrictionEntry { handle, stop: true }); } handle } }
40.643948
101
0.395282
fc3fb6c07bb149ca20fc78a47d6121d83504879b
3,748
use cairo; use gdk::ContextExt; use gdk_pixbuf; use gtk; use gtk::ContainerExt; use gtk::CssProviderExt; use gtk::StyleContextExt; use gtk::WidgetExt; use unicode_segmentation::UnicodeSegmentation; use std::collections::hash_map::DefaultHasher; use std::f64; use std::hash::{Hash, Hasher}; use crate::res; const KR: f64 = 0.299; const KG: f64 = 0.587; const KB: f64 = 0.114; const Y: f64 = 0.731; const BLEND_FACTOR: f64 = 0.4; pub fn avatar<'a, P: Into<Option<&'a gdk_pixbuf::Pixbuf>>>(name: &str, avatar: P) -> gtk::Box { let vbox = gtk::Box::new(gtk::Orientation::Vertical, 12); if let Some(style_context) = vbox.get_style_context() { style_context.add_class("avatar"); let provider = gtk::CssProvider::new(); match provider.load_from_data(res::STYLE_AVATAR) { Ok(_) => { style_context.add_provider(&provider, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION) } Err(err) => eprintln!("error loading style provider for list: {}", err), } } let mut hasher = DefaultHasher::new(); name.hash(&mut hasher); let h = hasher.finish(); let angle = ((h & (0xffff << 48)) >> 48) as f64 / 65536.0 * 2.0 * f64::consts::PI; let (cb, cr) = angle.sin_cos(); let factor = cr.abs().max(cb.abs()); let (cb, cr) = (cb * factor, cr * factor); let r = 2.0 * (1.0 - KR) * cr + Y; let b = 2.0 * (1.0 - KB) * cb + Y; let g = (Y - KR * r - KB * b) / KG; let drawing = gtk::DrawingArea::new(); drawing.set_size_request(128, 128); if let Some(pic) = avatar.into() { drawing.connect_draw(clone!( pic => move |_, ctx| { ctx.set_source_pixbuf(&pic, 0.0, 0.0); ctx.paint(); gtk::Inhibit(true) })); } else { let first = UnicodeSegmentation::graphemes(name, true) .nth(0) .unwrap_or_default() .to_owned(); drawing.connect_draw(move |widget, ctx| { // If we can get a style_context, blend the color with the background color. let (width, height) = (widget.get_allocated_width(), widget.get_allocated_height()); let size = f64::from(width.min(height)); let half = size / 2.0; match widget.get_style_context() { Some(style_context) => gtk::render_background( &style_context, &ctx, f64::from(width) / 2.0 - half, f64::from(height) / 2.0 - half, size, size, ), None => {} }; ctx.set_source_rgba(r, g, b, 1.0 - BLEND_FACTOR); ctx.rectangle( f64::from(width) / 2.0 - half, f64::from(height) / 2.0 - half, size, size, ); ctx.fill(); if !first.is_empty() { ctx.select_font_face("Sans", cairo::FontSlant::Normal, cairo::FontWeight::Normal); ctx.set_font_size(48.0); let extents = ctx.text_extents(&first[..]); let x = f64::from(width) / 2.0 - (extents.width / 2.0 + extents.x_bearing); let y = f64::from(height) / 2.0 - (extents.height / 2.0 + extents.y_bearing); ctx.move_to(x, y); ctx.set_source_rgb(1.0, 1.0, 1.0); // TODO: Use pango for this, otherwise complex graphemes likely won't be shown // correctly. ctx.show_text(&first[..]); } gtk::Inhibit(true) }); } let name_label = gtk::Label::new(name); vbox.add(&drawing); vbox.add(&name_label); vbox }
34.703704
98
0.526948
5da65df54302728d896ffea33d1b159a2692638d
1,846
use crate::model::chart::{ChartSpan, NetworkChart}; use serde::Serialize; use typed_builder::TypedBuilder; #[derive(Serialize, Debug, Clone, TypedBuilder)] #[serde(rename_all = "camelCase")] #[builder(doc)] pub struct Request { pub span: ChartSpan, /// 1 .. 500 #[serde(skip_serializing_if = "Option::is_none")] #[builder(default, setter(strip_option))] pub limit: Option<u64>, #[builder(default, setter(strip_option))] pub offset: Option<u64>, } impl misskey_core::Request for Request { type Response = NetworkChart; const ENDPOINT: &'static str = "charts/network"; } #[cfg(test)] mod tests { use super::Request; use crate::test::{ClientExt, TestClient}; #[tokio::test] async fn request() { use crate::model::chart::ChartSpan; let client = TestClient::new(); client .test(Request { span: ChartSpan::Day, limit: None, offset: None, }) .await; client .test(Request { span: ChartSpan::Hour, limit: None, offset: None, }) .await; } #[tokio::test] async fn request_with_limit() { use crate::model::chart::ChartSpan; let client = TestClient::new(); client .test(Request { span: ChartSpan::Day, limit: Some(500), offset: None, }) .await; } #[tokio::test] async fn request_with_offset() { use crate::model::chart::ChartSpan; let client = TestClient::new(); client .test(Request { span: ChartSpan::Day, limit: None, offset: Some(5), }) .await; } }
23.666667
53
0.51571
f50c5cc81f22916be5602178548d3bc1b809fbf9
2,857
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License.. #![crate_name = "serializesampleenclave"] #![crate_type = "staticlib"] #![cfg_attr(not(target_env = "sgx"), no_std)] #![cfg_attr(target_env = "sgx", feature(rustc_private))] //#![feature(untagged_unions)] /// Must use these extern for auto deriving #[cfg(not(target_env = "sgx"))] #[macro_use] extern crate sgx_tstd as std; extern crate sgx_serialize; use sgx_serialize::{SerializeHelper, DeSerializeHelper}; #[macro_use] extern crate sgx_serialize_derive; #[derive(Serializable, DeSerializable)] struct TestStructUnit; #[derive(Serializable, DeSerializable)] struct TestStructNewType(i32); #[derive(Serializable, DeSerializable)] struct TestStructTuple(i32, i32); #[derive(Serializable, DeSerializable)] struct TestSturct { a1: u32, a2: u32, } #[derive(Serializable, DeSerializable)] enum TestEnum { EnumUnit, EnumNewType(u32), EnumTuple(u32, u32), EnumStruct{a1:i32, a2:i32}, EnumSubStruct(TestSturct), } #[no_mangle] pub extern "C" fn serialize() { //let a = TestSturct {a1: 2017u32, a2: 829u32}; //let a = TestEnum::EnumSubStruct(a); //let a = TestEnum::EnumTuple(2017, 829); //let a = TestEnum::EnumNewType(2017); let a = TestEnum::EnumStruct {a1: 2017, a2:829}; // new a SerializeHelper let helper = SerializeHelper::new(); // encode data let data = helper.encode(a).unwrap(); // decode data let helper = DeSerializeHelper::<TestEnum>::new(data); let c = helper.decode().unwrap(); // // for TestSturct // // println!("decode data: {}, {}", c.a1, c.a2); // // for TestEnum match c { TestEnum::EnumStruct {ref a1, ref a2} => { println!("decode data: {}, {}", a1, a2); }, TestEnum::EnumNewType(ref a) => { println!("decode data: {}", a); }, TestEnum::EnumTuple(ref a1, ref a2) => { println!("decode data: {}, {}", a1, a2); }, TestEnum::EnumSubStruct(ref a) => { println!("decode data: {}, {}", a.a1, a.a2); }, _ => {} } }
29.760417
63
0.654183
e2463b0ef6de1c09b9a01953e9e73ca5c27d00c2
1,565
#[macro_use] extern crate easy_xml_derive; use easy_xml::{de, se}; #[allow(unused_variables)] #[test] fn test() { // struct { #[derive(Debug, XmlDeserialize, XmlSerialize)] #[easy_xml(root)] struct Node { #[easy_xml(attribute)] attr1: String, #[easy_xml(attribute)] attr2: String, } let node: Node = de::from_str("<Node attr1=\"value1\" attr2=\"value2\"></Node>").unwrap(); assert_eq!(node.attr1.as_str(), "value1"); assert_eq!(node.attr2.as_str(), "value2"); let xml = se::to_string(&node).unwrap(); assert_eq!( xml.as_str(), r#"<?xml version="1.0" encoding="UTF-8"?><Node attr1="value1" attr2="value2" />"# ); } //enum { #[derive(Debug, XmlDeserialize, XmlSerialize)] enum Node { Node { #[easy_xml(attribute)] attr1: String, #[easy_xml(attribute)] attr2: String, }, } let node: Node = de::from_str("<Node attr1=\"value1\" attr2=\"value2\"></Node>").unwrap(); match &node { Node::Node { attr1, attr2 } => { assert_eq!(attr1.as_str(), "value1"); assert_eq!(attr2.as_str(), "value2"); } } let xml = se::to_string(&node).unwrap(); assert_eq!( xml.as_str(), r#"<?xml version="1.0" encoding="UTF-8"?><Node attr1="value1" attr2="value2" />"# ); } }
27.946429
98
0.483067
db358cc9f53345f9b9d10c9a26e8086113385fe4
6,238
// Copyright 2019 The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use std::sync::Arc; use log::*; use tari_crypto::tari_utilities::hex::Hex; use ttl_cache::TtlCache; use tari_common_types::types::Signature; use crate::{ blocks::Block, mempool::reorg_pool::reorg_pool::ReorgPoolConfig, transactions::transaction_entities::transaction::Transaction, }; pub const LOG_TARGET: &str = "c::mp::reorg_pool::reorg_pool_storage"; /// Reorg makes use of ReorgPoolStorage to provide thread save access to its TtlCache. /// The ReorgPoolStorage consists of all transactions that have recently been added to blocks. /// When a potential blockchain reorganization occurs the transactions can be recovered from the ReorgPool and can be /// added back into the UnconfirmedPool. Transactions in the ReOrg pool have a limited Time-to-live and will be removed /// from the pool when the Time-to-live thresholds is reached. Also, when the capacity of the pool has been reached, the /// oldest transactions will be removed to make space for incoming transactions. pub struct ReorgPoolStorage { config: ReorgPoolConfig, txs_by_signature: TtlCache<Signature, Arc<Transaction>>, } impl ReorgPoolStorage { /// Create a new ReorgPoolStorage with the specified configuration pub fn new(config: ReorgPoolConfig) -> Self { Self { config, txs_by_signature: TtlCache::new(config.storage_capacity), } } /// Insert a new transaction into the ReorgPoolStorage. Published transactions will have a limited Time-to-live in /// the ReorgPoolStorage and will be discarded once the Time-to-live threshold has been reached. pub fn insert(&mut self, tx: Arc<Transaction>) { let tx_key = tx.body.kernels()[0].excess_sig.clone(); let _ = self .txs_by_signature .insert(tx_key.clone(), tx.clone(), self.config.tx_ttl); debug!( target: LOG_TARGET, "Inserted transaction with signature {} into reorg pool:", tx_key.get_signature().to_hex() ); trace!(target: LOG_TARGET, "{}", tx); } /// Insert a set of new transactions into the ReorgPoolStorage pub fn insert_txs(&mut self, txs: Vec<Arc<Transaction>>) { for tx in txs.into_iter() { self.insert(tx); } } /// Check if a transaction is stored in the ReorgPoolStorage pub fn has_tx_with_excess_sig(&self, excess_sig: &Signature) -> bool { self.txs_by_signature.contains_key(excess_sig) } /// Remove double-spends from the ReorgPool. These transactions were orphaned by the provided published /// block. Check if any of the transactions in the ReorgPool has inputs that was spent by the provided /// published block. fn discard_double_spends(&mut self, published_block: &Block) { let mut removed_tx_keys: Vec<Signature> = Vec::new(); for (tx_key, ptx) in self.txs_by_signature.iter() { for input in ptx.body.inputs() { if published_block.body.inputs().contains(input) { removed_tx_keys.push(tx_key.clone()); } } } for tx_key in &removed_tx_keys { self.txs_by_signature.remove(tx_key); trace!( target: LOG_TARGET, "Removed double spend tx from reorg pool: {}", tx_key.get_signature().to_hex() ); } } /// Remove the transactions from the ReorgPoolStorage that were used in provided removed blocks. The transactions /// can be resubmitted to the Unconfirmed Pool. pub fn remove_reorged_txs_and_discard_double_spends( &mut self, removed_blocks: Vec<Arc<Block>>, new_blocks: &[Arc<Block>], ) -> Vec<Arc<Transaction>> { for block in new_blocks { self.discard_double_spends(block); } let mut removed_txs: Vec<Arc<Transaction>> = Vec::new(); for block in &removed_blocks { for kernel in block.body.kernels() { if let Some(removed_tx) = self.txs_by_signature.remove(&kernel.excess_sig) { trace!(target: LOG_TARGET, "Removed tx from reorg pool: {:?}", removed_tx); removed_txs.push(removed_tx); } } } removed_txs } /// Returns the total number of published transactions stored in the ReorgPoolStorage pub fn len(&mut self) -> usize { self.txs_by_signature.iter().count() } /// Returns all transaction stored in the ReorgPoolStorage. pub fn snapshot(&mut self) -> Vec<Arc<Transaction>> { self.txs_by_signature.iter().map(|(_, tx)| tx).cloned().collect() } }
43.929577
120
0.679064
deef166b565e4d1fb2b7e9254bb5365d8b36ed28
6,968
use itertools::Itertools; use std::fmt::Write; use hir::{db::HirDatabase, AdtDef, FieldSource, HasSource}; use ra_syntax::ast::{self, AstNode}; use crate::{Assist, AssistCtx, AssistId}; fn is_trivial_arm(arm: &ast::MatchArm) -> bool { fn single_pattern(arm: &ast::MatchArm) -> Option<ast::PatKind> { let (pat,) = arm.pats().collect_tuple()?; Some(pat.kind()) } match single_pattern(arm) { Some(ast::PatKind::PlaceholderPat(..)) => true, _ => false, } } pub(crate) fn fill_match_arms(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> { let match_expr = ctx.node_at_offset::<ast::MatchExpr>()?; // We already have some match arms, so we don't provide any assists. // Unless if there is only one trivial match arm possibly created // by match postfix complete. Trivial match arm is the catch all arm. if let Some(arm_list) = match_expr.match_arm_list() { let mut arm_iter = arm_list.arms(); let first = arm_iter.next(); match first { // If there arm list is empty or there is only one trivial arm, then proceed. Some(arm) if is_trivial_arm(arm) => { if arm_iter.next() != None { return None; } } None => {} _ => { return None; } } }; let expr = match_expr.expr()?; let analyzer = hir::SourceAnalyzer::new(ctx.db, ctx.frange.file_id, expr.syntax(), None); let match_expr_ty = analyzer.type_of(ctx.db, expr)?; let enum_def = analyzer.autoderef(ctx.db, match_expr_ty).find_map(|ty| match ty.as_adt() { Some((AdtDef::Enum(e), _)) => Some(e), _ => None, })?; let enum_name = enum_def.name(ctx.db)?; let db = ctx.db; ctx.add_action(AssistId("fill_match_arms"), "fill match arms", |edit| { let mut buf = format!("match {} {{\n", expr.syntax().text().to_string()); let variants = enum_def.variants(db); for variant in variants { let name = match variant.name(db) { Some(it) => it, None => continue, }; write!(&mut buf, " {}::{}", enum_name, name.to_string()).unwrap(); let pat = variant .fields(db) .into_iter() .map(|field| { let name = field.name(db).to_string(); let src = field.source(db); match src.ast { FieldSource::Named(_) => name, FieldSource::Pos(_) => "_".to_string(), } }) .collect::<Vec<_>>(); match pat.first().map(|s| s.as_str()) { Some("_") => write!(&mut buf, "({})", pat.join(", ")).unwrap(), Some(_) => write!(&mut buf, "{{{}}}", pat.join(", ")).unwrap(), None => (), }; buf.push_str(" => (),\n"); } buf.push_str("}"); edit.target(match_expr.syntax().range()); edit.set_cursor(expr.syntax().range().start()); edit.replace_node_and_indent(match_expr.syntax(), buf); }); ctx.build() } #[cfg(test)] mod tests { use crate::helpers::{check_assist, check_assist_target}; use super::fill_match_arms; #[test] fn fill_match_arms_empty_body() { check_assist( fill_match_arms, r#" enum A { As, Bs, Cs(String), Ds(String, String), Es{x: usize, y: usize} } fn main() { let a = A::As; match a<|> {} } "#, r#" enum A { As, Bs, Cs(String), Ds(String, String), Es{x: usize, y: usize} } fn main() { let a = A::As; match <|>a { A::As => (), A::Bs => (), A::Cs(_) => (), A::Ds(_, _) => (), A::Es{x, y} => (), } } "#, ); } #[test] fn test_fill_match_arm_refs() { check_assist( fill_match_arms, r#" enum A { As, } fn foo(a: &A) { match a<|> { } } "#, r#" enum A { As, } fn foo(a: &A) { match <|>a { A::As => (), } } "#, ); check_assist( fill_match_arms, r#" enum A { Es{x: usize, y: usize} } fn foo(a: &mut A) { match a<|> { } } "#, r#" enum A { Es{x: usize, y: usize} } fn foo(a: &mut A) { match <|>a { A::Es{x, y} => (), } } "#, ); check_assist( fill_match_arms, r#" enum E { X, Y} fn main() { match &E::X<|> } "#, r#" enum E { X, Y} fn main() { match <|>&E::X { E::X => (), E::Y => (), } } "#, ); } #[test] fn fill_match_arms_no_body() { check_assist( fill_match_arms, r#" enum E { X, Y} fn main() { match E::X<|> } "#, r#" enum E { X, Y} fn main() { match <|>E::X { E::X => (), E::Y => (), } } "#, ); } #[test] fn fill_match_arms_target() { check_assist_target( fill_match_arms, r#" enum E { X, Y} fn main() { match E::X<|> {} } "#, "match E::X {}", ); } #[test] fn fill_match_arms_trivial_arm() { check_assist( fill_match_arms, r#" enum E { X, Y } fn main() { match E::X { <|>_ => {}, } } "#, r#" enum E { X, Y } fn main() { match <|>E::X { E::X => (), E::Y => (), } } "#, ); } }
24.797153
94
0.365241
feb4455bec224a75e9d7d827e66ef794cdbf870c
5,467
// Copyright (c) SimpleStaking, Viable Systems and Tezedge Contributors // SPDX-License-Identifier: MIT use derive_builder::Builder; use getset::{CopyGetters, Getters}; use serde::{Deserialize, Serialize}; use crypto::hash::{BlockHash, ContextHash, OperationListListHash}; use tezos_encoding::enc::BinWriter; use tezos_encoding::encoding::HasEncoding; use tezos_encoding::nom::NomReader; use super::limits::{ BLOCK_HEADER_FITNESS_MAX_SIZE, BLOCK_HEADER_MAX_SIZE, BLOCK_HEADER_PROTOCOL_DATA_MAX_SIZE, GET_BLOCK_HEADERS_MAX_LENGTH, }; pub type Fitness = Vec<Vec<u8>>; pub type Level = i32; pub fn display_fitness(fitness: &Fitness) -> String { fitness .iter() .map(hex::encode) .collect::<Vec<String>>() .join("::") } #[derive( Serialize, Deserialize, Debug, Getters, Clone, HasEncoding, NomReader, BinWriter, tezos_encoding::generator::Generated, )] pub struct BlockHeaderMessage { #[get = "pub"] block_header: BlockHeader, } impl From<BlockHeader> for BlockHeaderMessage { fn from(block_header: BlockHeader) -> Self { BlockHeaderMessage { block_header } } } impl From<BlockHeaderMessage> for BlockHeader { fn from(msg: BlockHeaderMessage) -> Self { msg.block_header } } // ----------------------------------------------------------------------------------------------- #[derive( Serialize, Deserialize, Debug, Getters, Clone, HasEncoding, NomReader, BinWriter, tezos_encoding::generator::Generated, )] pub struct GetBlockHeadersMessage { #[get = "pub"] #[encoding(dynamic, list = "GET_BLOCK_HEADERS_MAX_LENGTH")] get_block_headers: Vec<BlockHash>, } impl GetBlockHeadersMessage { pub fn new(get_block_headers: Vec<BlockHash>) -> Self { GetBlockHeadersMessage { get_block_headers } } } // ----------------------------------------------------------------------------------------------- #[derive( Serialize, Deserialize, PartialEq, Debug, Clone, Builder, Getters, CopyGetters, HasEncoding, NomReader, BinWriter, tezos_encoding::generator::Generated, )] #[encoding(bounded = "BLOCK_HEADER_MAX_SIZE")] pub struct BlockHeader { #[get_copy = "pub"] #[encoding(builtin = "Int32")] level: Level, #[get_copy = "pub"] proto: u8, #[get = "pub"] predecessor: BlockHash, #[get_copy = "pub"] #[encoding(timestamp)] timestamp: i64, #[get_copy = "pub"] validation_pass: u8, #[get = "pub"] operations_hash: OperationListListHash, #[get = "pub"] #[encoding(composite( dynamic = "BLOCK_HEADER_FITNESS_MAX_SIZE", list, dynamic, list, builtin = "Uint8" ))] fitness: Fitness, #[get = "pub"] context: ContextHash, #[get = "pub"] #[encoding( bounded = "BLOCK_HEADER_PROTOCOL_DATA_MAX_SIZE", list, builtin = "Uint8" )] protocol_data: Vec<u8>, #[get = "pub"] #[serde(skip)] #[builder(default)] #[encoding(hash)] hash: EncodingHash, } /// Optional 256-bit digest of encoded data /// TODO https://viablesystems.atlassian.net/browse/TE-675 #[derive(Clone, Debug)] pub struct EncodingHash(pub Option<Vec<u8>>); impl PartialEq for EncodingHash { fn eq(&self, other: &Self) -> bool { match (self.0.as_ref(), other.0.as_ref()) { (Some(v1), Some(v2)) => v1 == v2, _ => true, } } } impl EncodingHash { pub fn as_ref(&self) -> Option<&Vec<u8>> { self.0.as_ref() } } impl Default for EncodingHash { fn default() -> Self { Self(None) } } impl From<Vec<u8>> for EncodingHash { fn from(hash: Vec<u8>) -> Self { Self(Some(hash)) } } #[cfg(test)] mod test { use crypto::blake2b; use crate::p2p::binary_message::{BinaryRead, BinaryWrite}; use super::*; #[test] fn test_decode_block_header_message_nom() { let data = hex::decode("00094F1F048D51777EF01C0106A09F747615CC72271A46EA75E097B48C7200CA2F1EAE6617000000005D7F495004C8626895CC82299089F495F7AD8864D1D3B0F364D497F1D175296B5F4A901EC80000001100000001000000000800000000012631B27A9F0E1DA2D2CA10202938298CFB1133D5F9A642F81E6697342263B6ECB621F10000000000032DB85C0E00961D14664ECBDF10CBE4DE7DD71096A4E1A177DB0890B13F0AB85999EB0D715E807BCA0438D3CEAA5C58560D60767F28A9E16326657FBE7FC8414FDE3C54A504").unwrap(); let _message = BlockHeaderMessage::from_bytes(data).unwrap(); } #[test] fn test_decode_block_header_message_hash() { let data = hex::decode("00094F1F048D51777EF01C0106A09F747615CC72271A46EA75E097B48C7200CA2F1EAE6617000000005D7F495004C8626895CC82299089F495F7AD8864D1D3B0F364D497F1D175296B5F4A901EC80000001100000001000000000800000000012631B27A9F0E1DA2D2CA10202938298CFB1133D5F9A642F81E6697342263B6ECB621F10000000000032DB85C0E00961D14664ECBDF10CBE4DE7DD71096A4E1A177DB0890B13F0AB85999EB0D715E807BCA0438D3CEAA5C58560D60767F28A9E16326657FBE7FC8414FDE3C54A504").unwrap(); let hash = blake2b::digest_256(&data).unwrap(); let message = BlockHeaderMessage::from_bytes(data).unwrap(); let decode_hash = message.block_header().hash().as_ref().unwrap(); assert_eq!(&hash, decode_hash); let encoded = message.as_bytes().unwrap(); let encode_hash = blake2b::digest_256(&encoded).unwrap(); assert_eq!(hash, encode_hash); } }
27.751269
456
0.659777
08f545283da532f9290cf418ec2c30858d198028
304
// FIXME: Make me compile! Diff budget: 2 lines. // Do not change this module. mod a { pub trait MyTrait { fn foo(&self) { } } pub struct MyType; impl MyTrait for MyType { } } // Do not modify this function. use a::MyTrait; fn main() { let x = a::MyType; x.foo(); }
15.2
48
0.569079
4b5e8e24485be07b6e76278529e2e102453f0cf2
5,875
//! Decrypting of Ansible vault 1.1 files and streams. //! //! This crate provides the `read_vault` function which will decrypt an //! ansible vault and yield a byte buffer of the plaintext. //! It detects incorrect vault secrets and incorrectly formatted vaults, //! and yields the appropriate errors. /// The error type for decrypting Ansible vaults. /// /// Errors either originate from failing I/O operations, or from /// passing incorrect (formatted) files, streams or secrets. #[derive(Debug)] pub enum Error { IoError(std::io::Error), NotAVault, InvalidFormat, IncorrectSecret, } /// A specialized `Result` type for decrypting Ansible vaults. pub type Result<T> = std::result::Result<T, Error>; impl std::cmp::PartialEq for Error { fn eq(&self, other: &Error) -> bool { match (self, other) { (Error::IoError(_), Error::IoError(_)) => true, (Error::NotAVault, Error::NotAVault) => true, (Error::InvalidFormat, Error::InvalidFormat) => true, (Error::IncorrectSecret, Error::IncorrectSecret) => true, _ => false, } } } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Error::IoError(err) => err.fmt(f), _ => { use std::error::Error; write!(f, "{}", self.description()) } } } } impl std::error::Error for Error { fn description(&self) -> &str { match self { Error::IoError(err) => err.description(), Error::NotAVault => "file is not an ansible vault", Error::InvalidFormat => "file is a broken ansible vault", Error::IncorrectSecret => "incorrect secret for ansible vault", } } fn cause(&self) -> Option<&std::error::Error> { match self { Error::IoError(err) => Some(err), _ => None, } } } impl From<std::io::Error> for Error { fn from(error: std::io::Error) -> Self { Error::IoError(error) } } impl From<std::string::FromUtf8Error> for Error { fn from(_error: std::string::FromUtf8Error) -> Self { Error::InvalidFormat } } impl From<base16::DecodeError> for Error { fn from(_error: base16::DecodeError) -> Self { Error::InvalidFormat } } impl From<hmac::crypto_mac::InvalidKeyLength> for Error { fn from(_error: hmac::crypto_mac::InvalidKeyLength) -> Self { Error::InvalidFormat } } fn read_hex_lines<T: std::io::BufRead>(lines: std::io::Lines<T>) -> Result<Vec<u8>> { let mut buffer: Vec<u8> = vec![]; let mut i = 0; for line in lines { let line = line?; let part_len = line.len() / 2; buffer.resize(i + part_len, 0); let (_, dest) = buffer.as_mut_slice().split_at_mut(i); i += part_len; base16::decode_slice(line.as_bytes(), dest)?; } Ok(buffer) } /// See https://github.com/ansible/ansible/blob/devel/lib/ansible/parsing/vault/__init__.py#L1286. fn verify_vault(key: &[u8], ciphertext: &[u8], crypted_hmac: &[u8]) -> Result<bool> { use hmac::Mac; let mut hmac = hmac::Hmac::<sha2::Sha256>::new_varkey(key)?; hmac.input(&ciphertext); Ok(hmac.result().code().as_slice().eq(crypted_hmac)) // Constant time equivalence is not required for this use case. } /// Decrypt an ansible vault stream using a key. /// /// When succesful, yields a plaintext byte buffer. pub fn read_vault<T: std::io::Read>(input: T, key: &str) -> Result<Vec<u8>> { use block_padding::{Padding, Pkcs7}; use std::io::BufRead; let mut lines = std::io::BufReader::new(input).lines(); let first: String = lines.next().ok_or(Error::NotAVault)??; if first != "$ANSIBLE_VAULT;1.1;AES256" { return Err(Error::NotAVault); } let inner = String::from_utf8(read_hex_lines(lines)?)?; let mut lines = inner.lines(); let salt = base16::decode(&lines.next().ok_or(Error::InvalidFormat)?)?; let hmac_verify = base16::decode(&lines.next().ok_or(Error::InvalidFormat)?)?; let mut ciphertext = base16::decode(&lines.next().ok_or(Error::InvalidFormat)?)?; let mut hmac_buffer = [0; 80]; pbkdf2::pbkdf2::<hmac::Hmac<sha2::Sha256>>(key.as_bytes(), &salt, 10000, &mut hmac_buffer); let key1 = &hmac_buffer[0..32]; let key2 = &hmac_buffer[32..64]; let iv = &hmac_buffer[64..80]; if !verify_vault(key2, &ciphertext, &hmac_verify)? { return Err(Error::IncorrectSecret); } use aes_ctr::stream_cipher::{NewStreamCipher, SyncStreamCipher}; let mut cipher = aes_ctr::Aes256Ctr::new_var(key1, iv).map_err(|_err| Error::InvalidFormat)?; cipher.apply_keystream(&mut ciphertext); let n = Pkcs7::unpad(&ciphertext) .map_err(|_| Error::InvalidFormat)? .len(); ciphertext.truncate(n); Ok(ciphertext) } /// Decrypt an ansible vault file using a key. /// /// When succesful, yields a plaintext byte buffer. pub fn read_vault_from_file(path: &std::path::Path, key: &str) -> Result<Vec<u8>> { let f = std::fs::File::open(path)?; read_vault(f, key) } #[cfg(test)] mod tests { fn lipsum_path() -> std::path::PathBuf { use std::str::FromStr; std::path::PathBuf::from_str("./test/lipsum.vault").unwrap() } #[test] fn wrong_password() { let result = crate::read_vault_from_file(&lipsum_path(), "not shibboleet").unwrap_err(); std::assert_eq!(result, crate::Error::IncorrectSecret); } #[test] fn contents() { let buf = crate::read_vault_from_file(&lipsum_path(), "shibboleet").unwrap(); let lipsum = std::string::String::from_utf8(buf).unwrap(); let reference = std::fs::read_to_string("./test/lipsum.txt").unwrap(); std::assert_eq!(lipsum, reference); } }
30.759162
120
0.614809
099d60606ec5bcde89c35dd11b96528a6e5e7f83
2,437
// Silence some warnings so they don't distract from the exercise. #![allow(dead_code, unused_mut, unused_variables)] fn main() { // This collects any command-line arguments into a vector of Strings. // For example: // // cargo run -- apple banana // // ...produces the equivalent of // // vec!["apple".to_string(), "banana".to_string()] let args: Vec<String> = std::env::args().skip(1).collect(); // This consumes the `args` vector to iterate through each String for arg in args { // 1a. Your task: handle the command-line arguments! // // - If arg is "sum", then call the sum() function // - If arg is "double", then call the double() function // - If arg is anything else, then call the count() function, passing "arg" to it. if arg == "sum" { sum(); } else if arg == "double" { double() } else { count(arg); } // 1b. Now try passing "sum", "double" and "bananas" to the program by adding your argument // after "cargo run". For example "cargo run sum" } } fn sum() { let mut sum = 0; // 2. Use a "for loop" to iterate through integers from 7 to 23 *inclusive* using a range // and add them all together (increment the `sum` variable). Hint: You should get 255 // Run it with `cargo run sum` for n in 7..=23 { sum += n; } println!("The sum is {}", sum); } fn double() { let mut count = 0; let mut x = 1; // 3. Use a "while loop" to count how many times you can double the value of `x` (multiply `x` // by 2) until `x` is larger than 500. Increment `count` each time through the loop. Run it // with `cargo run double` Hint: The answer is 9 times. while x < 500 { count += 1; x *= 2; } println!("You can double x {} times until x is larger than 500", count); } fn count(arg: String) { // Challenge: Use an unconditional loop (`loop`) to print `arg` 8 times, and then break. // You will need to count your loops, somehow. Run it with `cargo run bananas` let mut cnt = 0; loop { cnt = cnt +1; print!("{} ", arg); // Execute this line 8 times, and then break. `print!` doesn't add a newline. if cnt == 8 { break; } } println!(); // This will output just a newline at the end for cleanliness. }
33.383562
105
0.572015
7929f2f04f57aebad6c1db88df1fc29e45e316fd
7,425
use crate::tests::{fail_test, run_test, TestResult}; // TODO: Test the use/hide tests also as separate lines in REPL (i.e., with merging the delta in between) #[test] fn hides_def() -> TestResult { fail_test( r#"def foo [] { "foo" }; hide foo; foo"#, "", // we just care if it errors ) } #[test] fn hides_env() -> TestResult { fail_test(r#"let-env foo = "foo"; hide foo; $env.foo"#, "did you mean") } #[test] fn hides_def_then_redefines() -> TestResult { // this one should fail because of predecl -- cannot have more defs with the same name in a // block fail_test( r#"def foo [] { "foo" }; hide foo; def foo [] { "bar" }; foo"#, "defined more than once", ) } #[test] fn hides_env_then_redefines() -> TestResult { run_test( r#"let-env foo = "foo"; hide foo; let-env foo = "bar"; $env.foo"#, "bar", ) } #[test] fn hides_def_in_scope_1() -> TestResult { fail_test( r#"def foo [] { "foo" }; do { hide foo; foo }"#, "", // we just care if it errors ) } #[test] fn hides_def_in_scope_2() -> TestResult { run_test( r#"def foo [] { "foo" }; do { def foo [] { "bar" }; hide foo; foo }"#, "foo", ) } #[test] fn hides_def_in_scope_3() -> TestResult { fail_test( r#"def foo [] { "foo" }; do { hide foo; def foo [] { "bar" }; hide foo; foo }"#, "", // we just care if it errors ) } #[test] fn hides_def_in_scope_4() -> TestResult { fail_test( r#"def foo [] { "foo" }; do { def foo [] { "bar" }; hide foo; hide foo; foo }"#, "", // we just care if it errors ) } #[test] fn hides_env_in_scope_1() -> TestResult { fail_test( r#"let-env foo = "foo"; do { hide foo; $env.foo }"#, "did you mean", ) } #[test] fn hides_env_in_scope_2() -> TestResult { run_test( r#"let-env foo = "foo"; do { let-env foo = "bar"; hide foo; $env.foo }"#, "foo", ) } #[test] fn hides_env_in_scope_3() -> TestResult { fail_test( r#"let-env foo = "foo"; do { hide foo; let-env foo = "bar"; hide foo; $env.foo }"#, "did you mean", ) } #[test] fn hides_env_in_scope_4() -> TestResult { fail_test( r#"let-env foo = "foo"; do { let-env foo = "bar"; hide foo; hide foo; $env.foo }"#, "did you mean", ) } #[test] fn hide_def_twice_not_allowed() -> TestResult { fail_test( r#"def foo [] { "foo" }; hide foo; hide foo"#, "did not find", ) } #[test] fn hide_env_twice_not_allowed() -> TestResult { fail_test(r#"let-env foo = "foo"; hide foo; hide foo"#, "did not find") } #[test] fn hides_def_runs_env_1() -> TestResult { run_test( r#"let-env foo = "bar"; def foo [] { "foo" }; hide foo; $env.foo"#, "bar", ) } #[test] fn hides_def_runs_env_2() -> TestResult { run_test( r#"def foo [] { "foo" }; let-env foo = "bar"; hide foo; $env.foo"#, "bar", ) } #[test] fn hides_def_and_env() -> TestResult { fail_test( r#"let-env foo = "bar"; def foo [] { "foo" }; hide foo; hide foo; $env.foo"#, "did you mean", ) } #[test] fn hides_def_import_1() -> TestResult { fail_test( r#"module spam { export def foo [] { "foo" } }; use spam; hide spam foo; spam foo"#, "", // we just care if it errors ) } #[test] fn hides_def_import_2() -> TestResult { fail_test( r#"module spam { export def foo [] { "foo" } }; use spam; hide spam; spam foo"#, "", // we just care if it errors ) } #[test] fn hides_def_import_3() -> TestResult { fail_test( r#"module spam { export def foo [] { "foo" } }; use spam; hide spam [foo]; spam foo"#, "", // we just care if it errors ) } #[test] fn hides_def_import_4() -> TestResult { fail_test( r#"module spam { export def foo [] { "foo" } }; use spam foo; hide foo; foo"#, "", // we just care if it errors ) } #[test] fn hides_def_import_5() -> TestResult { fail_test( r#"module spam { export def foo [] { "foo" } }; use spam *; hide foo; foo"#, "", // we just care if it errors ) } #[test] fn hides_def_import_6() -> TestResult { fail_test( r#"module spam { export def foo [] { "foo" } }; use spam *; hide spam *; foo"#, "", // we just care if it errors ) } #[test] fn hides_env_import_1() -> TestResult { fail_test( r#"module spam { export env foo { "foo" } }; use spam; hide spam foo; $env.'spam foo'"#, "did you mean", ) } #[test] fn hides_env_import_2() -> TestResult { fail_test( r#"module spam { export env foo { "foo" } }; use spam; hide spam; $env.'spam foo'"#, "did you mean", ) } #[test] fn hides_env_import_3() -> TestResult { fail_test( r#"module spam { export env foo { "foo" } }; use spam; hide spam [foo]; $env.'spam foo'"#, "did you mean", ) } #[test] fn hides_env_import_4() -> TestResult { fail_test( r#"module spam { export env foo { "foo" } }; use spam foo; hide foo; $env.foo"#, "did you mean", ) } #[test] fn hides_env_import_5() -> TestResult { fail_test( r#"module spam { export env foo { "foo" } }; use spam *; hide foo; $env.foo"#, "did you mean", ) } #[test] fn hides_env_import_6() -> TestResult { fail_test( r#"module spam { export env foo { "foo" } }; use spam *; hide spam *; $env.foo"#, "did you mean", ) } #[test] fn hides_def_runs_env_import() -> TestResult { run_test( r#"module spam { export env foo { "foo" }; export def foo [] { "bar" } }; use spam foo; hide foo; $env.foo"#, "foo", ) } #[test] fn hides_def_and_env_import_1() -> TestResult { fail_test( r#"module spam { export env foo { "foo" }; export def foo [] { "bar" } }; use spam foo; hide foo; hide foo; $env.foo"#, "did you mean", ) } #[test] fn hides_def_and_env_import_2() -> TestResult { fail_test( r#"module spam { export env foo { "foo" }; export def foo [] { "bar" } }; use spam foo; hide foo; hide foo; foo"#, "", // we just care if it errors ) } #[test] fn use_def_import_after_hide() -> TestResult { run_test( r#"module spam { export def foo [] { "foo" } }; use spam foo; hide foo; use spam foo; foo"#, "foo", ) } #[test] fn use_env_import_after_hide() -> TestResult { run_test( r#"module spam { export env foo { "foo" } }; use spam foo; hide foo; use spam foo; $env.foo"#, "foo", ) } #[test] fn hide_shadowed_decl() -> TestResult { run_test( r#"module spam { export def foo [] { "bar" } }; def foo [] { "foo" }; do { use spam foo; hide foo; foo }"#, "foo", ) } #[test] fn hide_shadowed_env() -> TestResult { run_test( r#"module spam { export env foo { "bar" } }; let-env foo = "foo"; do { use spam foo; hide foo; $env.foo }"#, "foo", ) } #[test] fn hides_all_decls_within_scope() -> TestResult { fail_test( r#"module spam { export def foo [] { "bar" } }; def foo [] { "foo" }; use spam foo; hide foo; foo"#, "", // we just care if it errors ) } #[test] fn hides_all_envs_within_scope() -> TestResult { fail_test( r#"module spam { export env foo { "bar" } }; let-env foo = "foo"; use spam foo; hide foo; $env.foo"#, "did you mean", ) }
24.50495
127
0.544646
c16cfacb387467d0b6f9b9923e07db6acf48f11f
993
mod allow_ro_impl; mod allow_rw_impl; mod command_impl; mod raw_syscalls_impl; mod subscribe_impl; mod yield_impl; /// `fake::Syscalls` implements `libtock_platform::Syscalls` by forwarding the /// system calls to the thread's `fake::Kernel` instance. It is used by unit /// tests to provide the code under test access to Tock's system calls. pub struct Syscalls; #[cfg(test)] mod allow_ro_impl_tests; #[cfg(test)] mod allow_rw_impl_tests; #[cfg(test)] mod command_impl_tests; #[cfg(test)] mod raw_syscalls_impl_tests; #[cfg(test)] mod subscribe_impl_tests; #[cfg(test)] mod yield_impl_tests; // Miri does not always check that values are valid (see `doc/MiriTips.md` in // the root of this repository). This function uses a hack to verify a value is // valid. If the value is invalid, Miri will detect undefined behavior when it // executes this. It is used by submodules of fake::syscalls. fn assert_valid<T: core::fmt::Debug>(_value: T) { #[cfg(miri)] format!("{:?}", _value); }
29.205882
79
0.742195
907578dce854ba891b216a05e49f1fbaf6ab6c88
3,987
use bit_field::BitArray; use embedded_hal::digital::v2::{InputPin, OutputPin}; use hal::gpio::gpioa::*; use hal::gpio::gpiob::*; use hal::gpio::{Input, Output}; use stm32l1::stm32l151::SYST; pub const ROWS: usize = 5; pub const COLUMNS: usize = 14; type RowPins = (PB9<Input>, PB8<Input>, PB7<Input>, PB6<Input>, PA0<Input>); type ColumnPins = ( PA5<Output>, PA6<Output>, PA7<Output>, PB0<Output>, PB1<Output>, PB12<Output>, PB13<Output>, PB14<Output>, PA8<Output>, PA9<Output>, PA15<Output>, PB3<Output>, PB4<Output>, PB5<Output>, ); /// State of the scan matrix /// /// A 72-bit array whose most-significant 2 bits are unused. Each /// key's state is stored as 1 (pressed) or 0 (released) at the bit /// indexed by the corresponding [`keycodes::KeyIndex`], namely /// `Escape` is at bit 0 (least-significant bit), and `RCtrl` is at /// bit 69. /// /// This packed format is sent as-is to stock LED firmware for theme /// activation. pub type KeyState = [u8; (ROWS * COLUMNS + 2) / 8]; // [u8; 9] pub struct KeyMatrix { /// Stores the currently pressed down keys from last sample. pub state: KeyState, row_pins: RowPins, column_pins: ColumnPins, } impl KeyMatrix { pub fn new(row_pins: RowPins, column_pins: ColumnPins) -> Self { Self { state: [0; 9], row_pins, column_pins, } } pub fn sample(&mut self, syst: &SYST) { for column in 0..COLUMNS { self.enable_column(column); // Busy wait a short while before sampling the keys // to let the pins settle let current_tick = syst.cvr.read(); let wait_until_tick = current_tick - 100; while syst.cvr.read() > wait_until_tick {} self.state .set_bit(column, self.row_pins.0.is_high().unwrap()); self.state .set_bit(column + COLUMNS, self.row_pins.1.is_high().unwrap()); self.state .set_bit(column + 2 * COLUMNS, self.row_pins.2.is_high().unwrap()); self.state .set_bit(column + 3 * COLUMNS, self.row_pins.3.is_high().unwrap()); self.state .set_bit(column + 4 * COLUMNS, self.row_pins.4.is_high().unwrap()); self.disable_column(column); } } fn enable_column(&mut self, column: usize) { match column { 0 => self.column_pins.0.set_high(), 1 => self.column_pins.1.set_high(), 2 => self.column_pins.2.set_high(), 3 => self.column_pins.3.set_high(), 4 => self.column_pins.4.set_high(), 5 => self.column_pins.5.set_high(), 6 => self.column_pins.6.set_high(), 7 => self.column_pins.7.set_high(), 8 => self.column_pins.8.set_high(), 9 => self.column_pins.9.set_high(), 10 => self.column_pins.10.set_high(), 11 => self.column_pins.11.set_high(), 12 => self.column_pins.12.set_high(), 13 => self.column_pins.13.set_high(), _ => Ok(()), } .unwrap() } fn disable_column(&mut self, column: usize) { match column { 0 => self.column_pins.0.set_low(), 1 => self.column_pins.1.set_low(), 2 => self.column_pins.2.set_low(), 3 => self.column_pins.3.set_low(), 4 => self.column_pins.4.set_low(), 5 => self.column_pins.5.set_low(), 6 => self.column_pins.6.set_low(), 7 => self.column_pins.7.set_low(), 8 => self.column_pins.8.set_low(), 9 => self.column_pins.9.set_low(), 10 => self.column_pins.10.set_low(), 11 => self.column_pins.11.set_low(), 12 => self.column_pins.12.set_low(), 13 => self.column_pins.13.set_low(), _ => Ok(()), } .unwrap() } }
32.153226
83
0.553047
110d341102748281c04f81c74f7b1a508ef1776f
16,350
use std::borrow::Cow; use super::{ModelWalker, RelationFieldWalker, RelationName, ScalarFieldWalker}; use crate::{ ast, transform::ast_to_dml::db::{relations::*, ParserDatabase, ScalarFieldType}, }; use datamodel_connector::ConnectorCapability; use dml::relation_info::ReferentialAction; /// A relation that has the minimal amount of information for us to create one. Useful for /// validation purposes. Holds all possible relation types. #[derive(Copy, Clone)] pub(crate) struct RelationWalker<'ast, 'db> { pub(super) relation_id: usize, pub(super) db: &'db ParserDatabase<'ast>, } impl<'ast, 'db> RelationWalker<'ast, 'db> { /// Converts the walker to either an implicit many to many, or a inline relation walker /// gathering 1:1 and 1:n relations. pub(crate) fn refine(self) -> RefinedRelationWalker<'ast, 'db> { if self.get().is_many_to_many() { RefinedRelationWalker::ImplicitManyToMany(ImplicitManyToManyRelationWalker { db: self.db, relation_id: self.relation_id, }) } else { RefinedRelationWalker::Inline(InlineRelationWalker { relation_id: self.relation_id, db: self.db, }) } } /// The relation attributes parsed from the AST. pub(crate) fn get(self) -> &'db Relation<'ast> { &self.db.relations.relations_storage[self.relation_id] } } /// Splits the relation to different types. pub(crate) enum RefinedRelationWalker<'ast, 'db> { /// 1:1 and 1:n relations, where one side defines the relation arguments. Inline(InlineRelationWalker<'ast, 'db>), /// Implicit m:n relation. The arguments are inferred by Prisma. ImplicitManyToMany(ImplicitManyToManyRelationWalker<'ast, 'db>), } /// A scalar inferred by loose/magic reformatting pub(crate) struct InferredField<'ast, 'db> { pub(crate) name: String, pub(crate) arity: ast::FieldArity, pub(crate) tpe: ScalarFieldType, pub(crate) blueprint: ScalarFieldWalker<'ast, 'db>, } pub(crate) enum ReferencingFields<'ast, 'db> { Concrete(Box<dyn Iterator<Item = ScalarFieldWalker<'ast, 'db>> + 'db>), Inferred(Vec<InferredField<'ast, 'db>>), NA, } /// An explicitly defined 1:1 or 1:n relation. The walker has the referencing side defined, but /// might miss the back relation in the AST. #[derive(Copy, Clone)] pub(crate) struct InlineRelationWalker<'ast, 'db> { relation_id: usize, db: &'db ParserDatabase<'ast>, } impl<'ast, 'db> InlineRelationWalker<'ast, 'db> { /// Get the relation attributes defined in the AST. fn get(self) -> &'db Relation<'ast> { &self.db.relations.relations_storage[self.relation_id] } /// The relation is 1:1, having at most one record on both sides of the relation. pub(crate) fn is_one_to_one(self) -> bool { matches!(self.get().attributes, RelationAttributes::OneToOne(_)) } /// The model which holds the relation arguments. pub(crate) fn referencing_model(self) -> ModelWalker<'ast, 'db> { self.db.walk_model(self.get().model_a) } /// The model referenced and which hold the back-relation field. pub(crate) fn referenced_model(self) -> ModelWalker<'ast, 'db> { self.db.walk_model(self.get().model_b) } /// If the relation is defined from both sides, convert to an explicit relation /// walker. pub(crate) fn as_complete(self) -> Option<CompleteInlineRelationWalker<'ast, 'db>> { match (self.forward_relation_field(), self.back_relation_field()) { (Some(field_a), Some(field_b)) => { let walker = CompleteInlineRelationWalker { side_a: (self.referencing_model().model_id, field_a.field_id), side_b: (self.referenced_model().model_id, field_b.field_id), relation: &self.db.relations.relations_storage[self.relation_id], db: self.db, }; Some(walker) } _ => None, } } // Should only be used for lifting pub(crate) fn referencing_fields(self) -> ReferencingFields<'ast, 'db> { use crate::common::NameNormalizer; self.forward_relation_field() .and_then(|rf| rf.fields()) .map(|fields| ReferencingFields::Concrete(Box::new(fields))) .unwrap_or_else(|| match self.referenced_model().unique_criterias().next() { Some(first_unique_criteria) => ReferencingFields::Inferred( first_unique_criteria .fields() .map(|field| { let name = format!( "{}{}", self.referenced_model().name().camel_case(), field.name().pascal_case() ); if let Some(existing_field) = self.referencing_model().scalar_fields().find(|sf| sf.name() == name) { InferredField { name, arity: existing_field.ast_field().arity, tpe: existing_field.attributes().r#type, blueprint: field, } } else { InferredField { name, arity: ast::FieldArity::Optional, tpe: field.attributes().r#type, blueprint: field, } } }) .collect(), ), None => ReferencingFields::NA, }) } // Should only be used for lifting pub(crate) fn referenced_fields(self) -> Box<dyn Iterator<Item = ScalarFieldWalker<'ast, 'db>> + 'db> { self.forward_relation_field() .and_then( |field: RelationFieldWalker<'ast, 'db>| -> Option<Box<dyn Iterator<Item = ScalarFieldWalker<'ast, 'db>>>> { field.referenced_fields().map(|fields| Box::new(fields) as Box<dyn Iterator<Item = ScalarFieldWalker<'ast, 'db>>>) }, ) .unwrap_or_else(move || { Box::new( self.referenced_model() .unique_criterias() .find(|c| c.is_strict_criteria()) .into_iter() .flat_map(|c| c.fields()), ) }) } pub(crate) fn forward_relation_field(self) -> Option<RelationFieldWalker<'ast, 'db>> { let model = self.referencing_model(); match self.get().attributes { RelationAttributes::OneToOne(OneToOneRelationFields::Forward(a)) | RelationAttributes::OneToOne(OneToOneRelationFields::Both(a, _)) | RelationAttributes::OneToMany(OneToManyRelationFields::Both(a, _)) | RelationAttributes::OneToMany(OneToManyRelationFields::Forward(a)) => Some(model.relation_field(a)), RelationAttributes::OneToMany(OneToManyRelationFields::Back(_)) => None, RelationAttributes::ImplicitManyToMany { field_a: _, field_b: _ } => unreachable!(), } } pub(crate) fn forward_relation_field_arity(self) -> ast::FieldArity { self.forward_relation_field() .map(|rf| rf.ast_field().arity) .unwrap_or_else(|| { let is_required = match self.referencing_fields() { ReferencingFields::Concrete(mut fields) => fields.all(|f| f.ast_field().arity.is_required()), ReferencingFields::Inferred(fields) => fields.iter().all(|f| f.arity.is_required()), ReferencingFields::NA => todo!(), }; if is_required { ast::FieldArity::Required } else { ast::FieldArity::Optional } }) } pub(crate) fn back_relation_field(self) -> Option<RelationFieldWalker<'ast, 'db>> { let model = self.referenced_model(); match self.get().attributes { RelationAttributes::OneToOne(OneToOneRelationFields::Both(_, b)) | RelationAttributes::OneToMany(OneToManyRelationFields::Both(_, b)) | RelationAttributes::OneToMany(OneToManyRelationFields::Back(b)) => Some(model.relation_field(b)), RelationAttributes::OneToMany(OneToManyRelationFields::Forward(_)) | RelationAttributes::OneToOne(OneToOneRelationFields::Forward(_)) => None, RelationAttributes::ImplicitManyToMany { field_a: _, field_b: _ } => unreachable!(), } } /// The name of the relation. Either uses the `name` (or default) argument, /// or generates an implicit name. pub(crate) fn relation_name(self) -> RelationName<'ast> { self.get() .relation_name .map(RelationName::Explicit) .unwrap_or_else(|| RelationName::generated(self.referencing_model().name(), self.referenced_model().name())) } } /// Describes an implicit m:n relation between two models. Neither side defines fields, attributes /// or referential actions, which are all inferred by Prisma. #[derive(Copy, Clone)] pub(crate) struct ImplicitManyToManyRelationWalker<'ast, 'db> { relation_id: usize, db: &'db ParserDatabase<'ast>, } impl<'ast, 'db> ImplicitManyToManyRelationWalker<'ast, 'db> { /// Gets the relation attributes from the AST. fn get(&self) -> &'db Relation<'ast> { &self.db.relations.relations_storage[self.relation_id] } /// The model which comes first in the alphabetical order. pub(crate) fn model_a(self) -> ModelWalker<'ast, 'db> { self.db.walk_model(self.get().model_a) } /// The model which comes after model a in the alphabetical order. pub(crate) fn model_b(self) -> ModelWalker<'ast, 'db> { self.db.walk_model(self.get().model_b) } /// The field that defines the relation in model a. pub(crate) fn field_a(self) -> RelationFieldWalker<'ast, 'db> { match self.get().attributes { RelationAttributes::ImplicitManyToMany { field_a, field_b: _ } => self.model_a().relation_field(field_a), _ => unreachable!(), } } /// The field that defines the relation in model b. pub(crate) fn field_b(self) -> RelationFieldWalker<'ast, 'db> { match self.get().attributes { RelationAttributes::ImplicitManyToMany { field_a: _, field_b } => self.model_b().relation_field(field_b), _ => unreachable!(), } } } /// Represents a relation that has fields and references defined in one of the /// relation fields. Includes 1:1 and 1:n relations that are defined from both sides. #[derive(Copy, Clone)] pub(crate) struct CompleteInlineRelationWalker<'ast, 'db> { pub(crate) side_a: (ast::ModelId, ast::FieldId), pub(crate) side_b: (ast::ModelId, ast::FieldId), pub(crate) relation: &'db Relation<'ast>, pub(crate) db: &'db ParserDatabase<'ast>, } impl<'ast, 'db> CompleteInlineRelationWalker<'ast, 'db> { /// The model that defines the relation fields and actions. pub(crate) fn referencing_model(self) -> ModelWalker<'ast, 'db> { ModelWalker { model_id: self.side_a.0, db: self.db, model_attributes: &self.db.types.model_attributes[&self.side_a.0], } } /// The implicit relation side. pub(crate) fn referenced_model(self) -> ModelWalker<'ast, 'db> { ModelWalker { model_id: self.side_b.0, db: self.db, model_attributes: &self.db.types.model_attributes[&self.side_b.0], } } pub(crate) fn referencing_field(self) -> RelationFieldWalker<'ast, 'db> { RelationFieldWalker { model_id: self.side_a.0, field_id: self.side_a.1, db: self.db, relation_field: &self.db.types.relation_fields[&(self.side_a.0, self.side_a.1)], } } pub(crate) fn referenced_field(self) -> RelationFieldWalker<'ast, 'db> { RelationFieldWalker { model_id: self.side_b.0, field_id: self.side_b.1, db: self.db, relation_field: &self.db.types.relation_fields[&(self.side_b.0, self.side_b.1)], } } /// The name of the foreign key. Either taken from the `map` attribute, or generated following /// the Prisma defaults. pub(crate) fn foreign_key_name(self) -> Option<Cow<'ast, str>> { let from_forward = self.referencing_field().final_foreign_key_name(); let from_back = self.referenced_field().final_foreign_key_name(); from_forward.or(from_back) } /// The scalar fields defining the relation on the referenced model. pub(crate) fn referenced_fields(self) -> impl ExactSizeIterator<Item = ScalarFieldWalker<'ast, 'db>> + 'db { let f = move |field_id: &ast::FieldId| { let model_id = self.referenced_model().model_id; ScalarFieldWalker { model_id, field_id: *field_id, db: self.db, scalar_field: &self.db.types.scalar_fields[&(model_id, *field_id)], } }; match self.referencing_field().relation_field.references.as_ref() { Some(references) => references.iter().map(f), None => [].iter().map(f), } } /// The scalar fields on the defining the relation on the referencing model. pub(crate) fn referencing_fields(self) -> impl ExactSizeIterator<Item = ScalarFieldWalker<'ast, 'db>> + 'db { let f = move |field_id: &ast::FieldId| { let model_id = self.referencing_model().model_id; ScalarFieldWalker { model_id, field_id: *field_id, db: self.db, scalar_field: &self.db.types.scalar_fields[&(model_id, *field_id)], } }; match self.referencing_field().relation_field.fields.as_ref() { Some(references) => references.iter().map(f), None => [].iter().map(f), } } /// Gives the onUpdate referential action of the relation. If not defined /// explicitly, returns the default value. pub(crate) fn on_update(self) -> ReferentialAction { use ReferentialAction::*; self.referencing_field().attributes().on_update.unwrap_or_else(|| { let uses_foreign_keys = self .db .active_connector() .has_capability(ConnectorCapability::ForeignKeys); match self.referential_arity() { _ if uses_foreign_keys => Cascade, ast::FieldArity::Required => NoAction, _ => SetNull, } }) } /// Gives the onDelete referential action of the relation. If not defined /// explicitly, returns the default value. pub(crate) fn on_delete(self) -> ReferentialAction { use ReferentialAction::*; self.referencing_field().attributes().on_delete.unwrap_or_else(|| { let supports_restrict = self.db.active_connector().supports_referential_action(Restrict); match self.referential_arity() { ast::FieldArity::Required if supports_restrict => Restrict, ast::FieldArity::Required => NoAction, _ => SetNull, } }) } /// Prisma allows setting the relation field as optional, even if one of the /// underlying scalar fields is required. For the purpose of referential /// actions, we count the relation field required if any of the underlying /// fields is required. pub(crate) fn referential_arity(self) -> ast::FieldArity { self.referencing_field().referential_arity() } /// 1:1, 1:n or m:n pub(crate) fn relation_type(self) -> RelationType { self.relation.r#type() } }
40.270936
134
0.585994
bf72cb0bbe98c25f82ebbb7436bccfb922ebb20e
20,967
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use crate::Align; use crate::Bin; use crate::Buildable; use crate::Container; use crate::Frame; use crate::ResizeMode; use crate::ShadowType; use crate::Widget; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::StaticType; use glib::ToValue; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib::wrapper! { #[doc(alias = "GtkAspectFrame")] pub struct AspectFrame(Object<ffi::GtkAspectFrame, ffi::GtkAspectFrameClass>) @extends Frame, Bin, Container, Widget, @implements Buildable; match fn { type_ => || ffi::gtk_aspect_frame_get_type(), } } impl AspectFrame { #[doc(alias = "gtk_aspect_frame_new")] pub fn new( label: Option<&str>, xalign: f32, yalign: f32, ratio: f32, obey_child: bool, ) -> AspectFrame { assert_initialized_main_thread!(); unsafe { Widget::from_glib_none(ffi::gtk_aspect_frame_new( label.to_glib_none().0, xalign, yalign, ratio, obey_child.into_glib(), )) .unsafe_cast() } } // rustdoc-stripper-ignore-next /// Creates a new builder-pattern struct instance to construct [`AspectFrame`] objects. /// /// This method returns an instance of [`AspectFrameBuilder`] which can be used to create [`AspectFrame`] objects. pub fn builder() -> AspectFrameBuilder { AspectFrameBuilder::default() } } impl Default for AspectFrame { fn default() -> Self { glib::object::Object::new::<Self>(&[]) .expect("Can't construct AspectFrame object with default parameters") } } #[derive(Clone, Default)] // rustdoc-stripper-ignore-next /// A [builder-pattern] type to construct [`AspectFrame`] objects. /// /// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html pub struct AspectFrameBuilder { obey_child: Option<bool>, ratio: Option<f32>, xalign: Option<f32>, yalign: Option<f32>, label: Option<String>, label_widget: Option<Widget>, label_xalign: Option<f32>, label_yalign: Option<f32>, shadow_type: Option<ShadowType>, border_width: Option<u32>, child: Option<Widget>, resize_mode: Option<ResizeMode>, app_paintable: Option<bool>, can_default: Option<bool>, can_focus: Option<bool>, events: Option<gdk::EventMask>, expand: Option<bool>, #[cfg(any(feature = "v3_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v3_20")))] focus_on_click: Option<bool>, halign: Option<Align>, has_default: Option<bool>, has_focus: Option<bool>, has_tooltip: Option<bool>, height_request: Option<i32>, hexpand: Option<bool>, hexpand_set: Option<bool>, is_focus: Option<bool>, margin: Option<i32>, margin_bottom: Option<i32>, margin_end: Option<i32>, margin_start: Option<i32>, margin_top: Option<i32>, name: Option<String>, no_show_all: Option<bool>, opacity: Option<f64>, parent: Option<Container>, receives_default: Option<bool>, sensitive: Option<bool>, tooltip_markup: Option<String>, tooltip_text: Option<String>, valign: Option<Align>, vexpand: Option<bool>, vexpand_set: Option<bool>, visible: Option<bool>, width_request: Option<i32>, } impl AspectFrameBuilder { // rustdoc-stripper-ignore-next /// Create a new [`AspectFrameBuilder`]. pub fn new() -> Self { Self::default() } // rustdoc-stripper-ignore-next /// Build the [`AspectFrame`]. pub fn build(self) -> AspectFrame { let mut properties: Vec<(&str, &dyn ToValue)> = vec![]; if let Some(ref obey_child) = self.obey_child { properties.push(("obey-child", obey_child)); } if let Some(ref ratio) = self.ratio { properties.push(("ratio", ratio)); } if let Some(ref xalign) = self.xalign { properties.push(("xalign", xalign)); } if let Some(ref yalign) = self.yalign { properties.push(("yalign", yalign)); } if let Some(ref label) = self.label { properties.push(("label", label)); } if let Some(ref label_widget) = self.label_widget { properties.push(("label-widget", label_widget)); } if let Some(ref label_xalign) = self.label_xalign { properties.push(("label-xalign", label_xalign)); } if let Some(ref label_yalign) = self.label_yalign { properties.push(("label-yalign", label_yalign)); } if let Some(ref shadow_type) = self.shadow_type { properties.push(("shadow-type", shadow_type)); } if let Some(ref border_width) = self.border_width { properties.push(("border-width", border_width)); } if let Some(ref child) = self.child { properties.push(("child", child)); } if let Some(ref resize_mode) = self.resize_mode { properties.push(("resize-mode", resize_mode)); } if let Some(ref app_paintable) = self.app_paintable { properties.push(("app-paintable", app_paintable)); } if let Some(ref can_default) = self.can_default { properties.push(("can-default", can_default)); } if let Some(ref can_focus) = self.can_focus { properties.push(("can-focus", can_focus)); } if let Some(ref events) = self.events { properties.push(("events", events)); } if let Some(ref expand) = self.expand { properties.push(("expand", expand)); } #[cfg(any(feature = "v3_20", feature = "dox"))] if let Some(ref focus_on_click) = self.focus_on_click { properties.push(("focus-on-click", focus_on_click)); } if let Some(ref halign) = self.halign { properties.push(("halign", halign)); } if let Some(ref has_default) = self.has_default { properties.push(("has-default", has_default)); } if let Some(ref has_focus) = self.has_focus { properties.push(("has-focus", has_focus)); } if let Some(ref has_tooltip) = self.has_tooltip { properties.push(("has-tooltip", has_tooltip)); } if let Some(ref height_request) = self.height_request { properties.push(("height-request", height_request)); } if let Some(ref hexpand) = self.hexpand { properties.push(("hexpand", hexpand)); } if let Some(ref hexpand_set) = self.hexpand_set { properties.push(("hexpand-set", hexpand_set)); } if let Some(ref is_focus) = self.is_focus { properties.push(("is-focus", is_focus)); } if let Some(ref margin) = self.margin { properties.push(("margin", margin)); } if let Some(ref margin_bottom) = self.margin_bottom { properties.push(("margin-bottom", margin_bottom)); } if let Some(ref margin_end) = self.margin_end { properties.push(("margin-end", margin_end)); } if let Some(ref margin_start) = self.margin_start { properties.push(("margin-start", margin_start)); } if let Some(ref margin_top) = self.margin_top { properties.push(("margin-top", margin_top)); } if let Some(ref name) = self.name { properties.push(("name", name)); } if let Some(ref no_show_all) = self.no_show_all { properties.push(("no-show-all", no_show_all)); } if let Some(ref opacity) = self.opacity { properties.push(("opacity", opacity)); } if let Some(ref parent) = self.parent { properties.push(("parent", parent)); } if let Some(ref receives_default) = self.receives_default { properties.push(("receives-default", receives_default)); } if let Some(ref sensitive) = self.sensitive { properties.push(("sensitive", sensitive)); } if let Some(ref tooltip_markup) = self.tooltip_markup { properties.push(("tooltip-markup", tooltip_markup)); } if let Some(ref tooltip_text) = self.tooltip_text { properties.push(("tooltip-text", tooltip_text)); } if let Some(ref valign) = self.valign { properties.push(("valign", valign)); } if let Some(ref vexpand) = self.vexpand { properties.push(("vexpand", vexpand)); } if let Some(ref vexpand_set) = self.vexpand_set { properties.push(("vexpand-set", vexpand_set)); } if let Some(ref visible) = self.visible { properties.push(("visible", visible)); } if let Some(ref width_request) = self.width_request { properties.push(("width-request", width_request)); } glib::Object::new::<AspectFrame>(&properties) .expect("Failed to create an instance of AspectFrame") } pub fn obey_child(mut self, obey_child: bool) -> Self { self.obey_child = Some(obey_child); self } pub fn ratio(mut self, ratio: f32) -> Self { self.ratio = Some(ratio); self } pub fn xalign(mut self, xalign: f32) -> Self { self.xalign = Some(xalign); self } pub fn yalign(mut self, yalign: f32) -> Self { self.yalign = Some(yalign); self } pub fn label(mut self, label: &str) -> Self { self.label = Some(label.to_string()); self } pub fn label_widget(mut self, label_widget: &impl IsA<Widget>) -> Self { self.label_widget = Some(label_widget.clone().upcast()); self } pub fn label_xalign(mut self, label_xalign: f32) -> Self { self.label_xalign = Some(label_xalign); self } pub fn label_yalign(mut self, label_yalign: f32) -> Self { self.label_yalign = Some(label_yalign); self } pub fn shadow_type(mut self, shadow_type: ShadowType) -> Self { self.shadow_type = Some(shadow_type); self } pub fn border_width(mut self, border_width: u32) -> Self { self.border_width = Some(border_width); self } pub fn child(mut self, child: &impl IsA<Widget>) -> Self { self.child = Some(child.clone().upcast()); self } pub fn resize_mode(mut self, resize_mode: ResizeMode) -> Self { self.resize_mode = Some(resize_mode); self } pub fn app_paintable(mut self, app_paintable: bool) -> Self { self.app_paintable = Some(app_paintable); self } pub fn can_default(mut self, can_default: bool) -> Self { self.can_default = Some(can_default); self } pub fn can_focus(mut self, can_focus: bool) -> Self { self.can_focus = Some(can_focus); self } pub fn events(mut self, events: gdk::EventMask) -> Self { self.events = Some(events); self } pub fn expand(mut self, expand: bool) -> Self { self.expand = Some(expand); self } #[cfg(any(feature = "v3_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v3_20")))] pub fn focus_on_click(mut self, focus_on_click: bool) -> Self { self.focus_on_click = Some(focus_on_click); self } pub fn halign(mut self, halign: Align) -> Self { self.halign = Some(halign); self } pub fn has_default(mut self, has_default: bool) -> Self { self.has_default = Some(has_default); self } pub fn has_focus(mut self, has_focus: bool) -> Self { self.has_focus = Some(has_focus); self } pub fn has_tooltip(mut self, has_tooltip: bool) -> Self { self.has_tooltip = Some(has_tooltip); self } pub fn height_request(mut self, height_request: i32) -> Self { self.height_request = Some(height_request); self } pub fn hexpand(mut self, hexpand: bool) -> Self { self.hexpand = Some(hexpand); self } pub fn hexpand_set(mut self, hexpand_set: bool) -> Self { self.hexpand_set = Some(hexpand_set); self } pub fn is_focus(mut self, is_focus: bool) -> Self { self.is_focus = Some(is_focus); self } pub fn margin(mut self, margin: i32) -> Self { self.margin = Some(margin); self } pub fn margin_bottom(mut self, margin_bottom: i32) -> Self { self.margin_bottom = Some(margin_bottom); self } pub fn margin_end(mut self, margin_end: i32) -> Self { self.margin_end = Some(margin_end); self } pub fn margin_start(mut self, margin_start: i32) -> Self { self.margin_start = Some(margin_start); self } pub fn margin_top(mut self, margin_top: i32) -> Self { self.margin_top = Some(margin_top); self } pub fn name(mut self, name: &str) -> Self { self.name = Some(name.to_string()); self } pub fn no_show_all(mut self, no_show_all: bool) -> Self { self.no_show_all = Some(no_show_all); self } pub fn opacity(mut self, opacity: f64) -> Self { self.opacity = Some(opacity); self } pub fn parent(mut self, parent: &impl IsA<Container>) -> Self { self.parent = Some(parent.clone().upcast()); self } pub fn receives_default(mut self, receives_default: bool) -> Self { self.receives_default = Some(receives_default); self } pub fn sensitive(mut self, sensitive: bool) -> Self { self.sensitive = Some(sensitive); self } pub fn tooltip_markup(mut self, tooltip_markup: &str) -> Self { self.tooltip_markup = Some(tooltip_markup.to_string()); self } pub fn tooltip_text(mut self, tooltip_text: &str) -> Self { self.tooltip_text = Some(tooltip_text.to_string()); self } pub fn valign(mut self, valign: Align) -> Self { self.valign = Some(valign); self } pub fn vexpand(mut self, vexpand: bool) -> Self { self.vexpand = Some(vexpand); self } pub fn vexpand_set(mut self, vexpand_set: bool) -> Self { self.vexpand_set = Some(vexpand_set); self } pub fn visible(mut self, visible: bool) -> Self { self.visible = Some(visible); self } pub fn width_request(mut self, width_request: i32) -> Self { self.width_request = Some(width_request); self } } impl AspectFrame { pub const NONE: Option<&'static AspectFrame> = None; } pub trait AspectFrameExt: 'static { #[doc(alias = "gtk_aspect_frame_set")] fn set(&self, xalign: f32, yalign: f32, ratio: f32, obey_child: bool); #[doc(alias = "obey-child")] fn is_obey_child(&self) -> bool; #[doc(alias = "obey-child")] fn set_obey_child(&self, obey_child: bool); fn ratio(&self) -> f32; fn set_ratio(&self, ratio: f32); fn xalign(&self) -> f32; fn set_xalign(&self, xalign: f32); fn yalign(&self) -> f32; fn set_yalign(&self, yalign: f32); #[doc(alias = "obey-child")] fn connect_obey_child_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; #[doc(alias = "ratio")] fn connect_ratio_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; #[doc(alias = "xalign")] fn connect_xalign_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; #[doc(alias = "yalign")] fn connect_yalign_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<AspectFrame>> AspectFrameExt for O { fn set(&self, xalign: f32, yalign: f32, ratio: f32, obey_child: bool) { unsafe { ffi::gtk_aspect_frame_set( self.as_ref().to_glib_none().0, xalign, yalign, ratio, obey_child.into_glib(), ); } } fn is_obey_child(&self) -> bool { glib::ObjectExt::property(self.as_ref(), "obey-child") } fn set_obey_child(&self, obey_child: bool) { glib::ObjectExt::set_property(self.as_ref(), "obey-child", &obey_child) } fn ratio(&self) -> f32 { glib::ObjectExt::property(self.as_ref(), "ratio") } fn set_ratio(&self, ratio: f32) { glib::ObjectExt::set_property(self.as_ref(), "ratio", &ratio) } fn xalign(&self) -> f32 { glib::ObjectExt::property(self.as_ref(), "xalign") } fn set_xalign(&self, xalign: f32) { glib::ObjectExt::set_property(self.as_ref(), "xalign", &xalign) } fn yalign(&self) -> f32 { glib::ObjectExt::property(self.as_ref(), "yalign") } fn set_yalign(&self, yalign: f32) { glib::ObjectExt::set_property(self.as_ref(), "yalign", &yalign) } fn connect_obey_child_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_obey_child_trampoline< P: IsA<AspectFrame>, F: Fn(&P) + 'static, >( this: *mut ffi::GtkAspectFrame, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(AspectFrame::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::obey-child\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_obey_child_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_ratio_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_ratio_trampoline<P: IsA<AspectFrame>, F: Fn(&P) + 'static>( this: *mut ffi::GtkAspectFrame, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(AspectFrame::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::ratio\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_ratio_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_xalign_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_xalign_trampoline<P: IsA<AspectFrame>, F: Fn(&P) + 'static>( this: *mut ffi::GtkAspectFrame, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(AspectFrame::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::xalign\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_xalign_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } fn connect_yalign_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_yalign_trampoline<P: IsA<AspectFrame>, F: Fn(&P) + 'static>( this: *mut ffi::GtkAspectFrame, _param_spec: glib::ffi::gpointer, f: glib::ffi::gpointer, ) { let f: &F = &*(f as *const F); f(AspectFrame::from_glib_borrow(this).unsafe_cast_ref()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::yalign\0".as_ptr() as *const _, Some(transmute::<_, unsafe extern "C" fn()>( notify_yalign_trampoline::<Self, F> as *const (), )), Box_::into_raw(f), ) } } } impl fmt::Display for AspectFrame { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("AspectFrame") } }
30.970458
144
0.566939
ed18453f65bfce7e9b4e95d2b0dcf9fd2e6a0dcb
2,472
pub mod logging; pub mod sandbox_manager; pub mod sandbox_server; pub mod system_state_accessor_rpc; use ic_canister_sandbox_common::{controller_client_stub, protocol, rpc, transport}; use std::sync::Arc; /// Runs the canister sandbox service in the calling thread. The service /// will use the given unix domain socket as its only means of /// communication. It expects execution IPC commands to passed as /// inputs on this communication channel, and will communicate /// completions as well as auxiliary requests back on this channel. pub fn run_canister_sandbox(socket: std::os::unix::net::UnixStream) { let socket = Arc::new(socket); let out_stream = transport::UnixStreamMuxWriter::<protocol::transport::SandboxToController>::new( Arc::clone(&socket), ); let request_out_stream = out_stream.make_sink::<protocol::ctlsvc::Request>(); let reply_out_stream = out_stream.make_sink::<protocol::sbxsvc::Reply>(); // Construct RPC channel client to controller. let reply_handler = Arc::new(rpc::ReplyManager::<protocol::ctlsvc::Reply>::new()); let controller = Arc::new(controller_client_stub::ControllerClientStub::new(Arc::new( rpc::Channel::new(request_out_stream, reply_handler.clone()), ))); // Construct RPC server for the service offered by this binary, // namely access to the sandboxed canister runner functions. let svc = Arc::new(sandbox_server::SandboxServer::new( sandbox_manager::SandboxManager::new(controller), )); // Wrap it all up to handle frames received on socket -- either // replies to our outgoing requests, or incoming requests to the // RPC service offered by this binary. let frame_handler = transport::Demux::<_, _, protocol::transport::ControllerToSandbox>::new( Arc::new(rpc::ServerStub::new(svc, reply_out_stream)), reply_handler, ); // It is fine if we fail to spawn this thread. Used for fault // injection only. std::thread::spawn(move || { let inject_failure = std::env::var("SANDBOX_TESTING_ON_MALICIOUS_SHUTDOWN_MANUAL").is_ok(); if inject_failure { std::thread::sleep(std::time::Duration::from_millis(10)); std::process::exit(1); } }); // Run RPC operations on the stream socket. transport::socket_read_messages::<_, _>( move |message| { frame_handler.handle(message); }, socket, ); }
39.238095
99
0.68568
28de91a12b63a977890687224641d6a627a72ba3
29,858
use std::collections::HashMap; use std::cell::RefCell; use std::default::Default; use std::collections::BTreeMap; use serde_json as json; use std::io; use std::fs; use std::mem; use std::thread::sleep; use crate::client; // ############## // UTILITIES ### // ############ // ######## // HUB ### // ###### /// Central instance to access all AdExperienceReport related resource activities /// /// # Examples /// /// Instantiate a new hub /// /// ```test_harness,no_run /// extern crate hyper; /// extern crate hyper_rustls; /// extern crate yup_oauth2 as oauth2; /// extern crate google_adexperiencereport1 as adexperiencereport1; /// use adexperiencereport1::{Result, Error}; /// # async fn dox() { /// use std::default::Default; /// use oauth2; /// use adexperiencereport1::AdExperienceReport; /// /// // Get an ApplicationSecret instance by some means. It contains the `client_id` and /// // `client_secret`, among other things. /// let secret: oauth2::ApplicationSecret = Default::default(); /// // Instantiate the authenticator. It will choose a suitable authentication flow for you, /// // unless you replace `None` with the desired Flow. /// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about /// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and /// // retrieve them from storage. /// let auth = yup_oauth2::InstalledFlowAuthenticator::builder( /// secret, /// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect, /// ).build().await.unwrap(); /// let mut hub = AdExperienceReport::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth); /// // You can configure optional parameters by calling the respective setters at will, and /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.sites().get("name") /// .doit().await; /// /// match result { /// Err(e) => match e { /// // The Error enum provides details about what exactly happened. /// // You can also just use its `Debug`, `Display` or `Error` traits /// Error::HttpError(_) /// |Error::Io(_) /// |Error::MissingAPIKey /// |Error::MissingToken(_) /// |Error::Cancelled /// |Error::UploadSizeLimitExceeded(_, _) /// |Error::Failure(_) /// |Error::BadRequest(_) /// |Error::FieldClash(_) /// |Error::JsonDecodeError(_, _) => println!("{}", e), /// }, /// Ok(res) => println!("Success: {:?}", res), /// } /// # } /// ``` pub struct AdExperienceReport<> { client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>, auth: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>, _user_agent: String, _base_url: String, _root_url: String, } impl<'a, > client::Hub for AdExperienceReport<> {} impl<'a, > AdExperienceReport<> { pub fn new(client: hyper::Client<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>, hyper::body::Body>, authenticator: oauth2::authenticator::Authenticator<hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>>) -> AdExperienceReport<> { AdExperienceReport { client, auth: authenticator, _user_agent: "google-api-rust-client/2.0.4".to_string(), _base_url: "https://adexperiencereport.googleapis.com/".to_string(), _root_url: "https://adexperiencereport.googleapis.com/".to_string(), } } pub fn sites(&'a self) -> SiteMethods<'a> { SiteMethods { hub: &self } } pub fn violating_sites(&'a self) -> ViolatingSiteMethods<'a> { ViolatingSiteMethods { hub: &self } } /// Set the user-agent header field to use in all requests to the server. /// It defaults to `google-api-rust-client/2.0.4`. /// /// Returns the previously set user-agent. pub fn user_agent(&mut self, agent_name: String) -> String { mem::replace(&mut self._user_agent, agent_name) } /// Set the base url to use in all requests to the server. /// It defaults to `https://adexperiencereport.googleapis.com/`. /// /// Returns the previously set base url. pub fn base_url(&mut self, new_base_url: String) -> String { mem::replace(&mut self._base_url, new_base_url) } /// Set the root url to use in all requests to the server. /// It defaults to `https://adexperiencereport.googleapis.com/`. /// /// Returns the previously set root url. pub fn root_url(&mut self, new_root_url: String) -> String { mem::replace(&mut self._root_url, new_root_url) } } // ############ // SCHEMAS ### // ########## /// A site's Ad Experience Report summary on a single platform. /// /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct PlatformSummary { /// The site's Ad Experience Report status on this platform. #[serde(rename="betterAdsStatus")] pub better_ads_status: Option<String>, /// The time at which [enforcement](https://support.google.com/webtools/answer/7308033) against the site began or will begin on this platform. Not set when the filter_status is OFF. #[serde(rename="enforcementTime")] pub enforcement_time: Option<String>, /// The site's [enforcement status](https://support.google.com/webtools/answer/7308033) on this platform. #[serde(rename="filterStatus")] pub filter_status: Option<String>, /// The time at which the site's status last changed on this platform. #[serde(rename="lastChangeTime")] pub last_change_time: Option<String>, /// The site's regions on this platform. No longer populated, because there is no longer any semantic difference between sites in different regions. pub region: Option<Vec<String>>, /// A link to the full Ad Experience Report for the site on this platform.. Not set in ViolatingSitesResponse. Note that you must complete the [Search Console verification process](https://support.google.com/webmasters/answer/9008080) for the site before you can access the full report. #[serde(rename="reportUrl")] pub report_url: Option<String>, /// Whether the site is currently under review on this platform. #[serde(rename="underReview")] pub under_review: Option<bool>, } impl client::Part for PlatformSummary {} /// Response message for GetSiteSummary. /// /// # Activities /// /// This type is used in activities, which are methods you may call on this type or where this type is involved in. /// The list links the activity name, along with information about where it is used (one of *request* and *response*). /// /// * [get sites](SiteGetCall) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct SiteSummaryResponse { /// The site's Ad Experience Report summary on desktop. #[serde(rename="desktopSummary")] pub desktop_summary: Option<PlatformSummary>, /// The site's Ad Experience Report summary on mobile. #[serde(rename="mobileSummary")] pub mobile_summary: Option<PlatformSummary>, /// The name of the reviewed site, e.g. `google.com`. #[serde(rename="reviewedSite")] pub reviewed_site: Option<String>, } impl client::ResponseResult for SiteSummaryResponse {} /// Response message for ListViolatingSites. /// /// # Activities /// /// This type is used in activities, which are methods you may call on this type or where this type is involved in. /// The list links the activity name, along with information about where it is used (one of *request* and *response*). /// /// * [list violating sites](ViolatingSiteListCall) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ViolatingSitesResponse { /// The list of violating sites. #[serde(rename="violatingSites")] pub violating_sites: Option<Vec<SiteSummaryResponse>>, } impl client::ResponseResult for ViolatingSitesResponse {} // ################### // MethodBuilders ### // ################# /// A builder providing access to all methods supported on *site* resources. /// It is not used directly, but through the `AdExperienceReport` hub. /// /// # Example /// /// Instantiate a resource builder /// /// ```test_harness,no_run /// extern crate hyper; /// extern crate hyper_rustls; /// extern crate yup_oauth2 as oauth2; /// extern crate google_adexperiencereport1 as adexperiencereport1; /// /// # async fn dox() { /// use std::default::Default; /// use oauth2; /// use adexperiencereport1::AdExperienceReport; /// /// let secret: oauth2::ApplicationSecret = Default::default(); /// let auth = yup_oauth2::InstalledFlowAuthenticator::builder( /// secret, /// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect, /// ).build().await.unwrap(); /// let mut hub = AdExperienceReport::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* /// // like `get(...)` /// // to build up your call. /// let rb = hub.sites(); /// # } /// ``` pub struct SiteMethods<'a> where { hub: &'a AdExperienceReport<>, } impl<'a> client::MethodsBuilder for SiteMethods<'a> {} impl<'a> SiteMethods<'a> { /// Create a builder to help you perform the following task: /// /// Gets a site's Ad Experience Report summary. /// /// # Arguments /// /// * `name` - Required. The name of the site whose summary to get, e.g. `sites/http%3A%2F%2Fwww.google.com%2F`. Format: `sites/{site}` pub fn get(&self, name: &str) -> SiteGetCall<'a> { SiteGetCall { hub: self.hub, _name: name.to_string(), _delegate: Default::default(), _additional_params: Default::default(), } } } /// A builder providing access to all methods supported on *violatingSite* resources. /// It is not used directly, but through the `AdExperienceReport` hub. /// /// # Example /// /// Instantiate a resource builder /// /// ```test_harness,no_run /// extern crate hyper; /// extern crate hyper_rustls; /// extern crate yup_oauth2 as oauth2; /// extern crate google_adexperiencereport1 as adexperiencereport1; /// /// # async fn dox() { /// use std::default::Default; /// use oauth2; /// use adexperiencereport1::AdExperienceReport; /// /// let secret: oauth2::ApplicationSecret = Default::default(); /// let auth = yup_oauth2::InstalledFlowAuthenticator::builder( /// secret, /// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect, /// ).build().await.unwrap(); /// let mut hub = AdExperienceReport::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* /// // like `list(...)` /// // to build up your call. /// let rb = hub.violating_sites(); /// # } /// ``` pub struct ViolatingSiteMethods<'a> where { hub: &'a AdExperienceReport<>, } impl<'a> client::MethodsBuilder for ViolatingSiteMethods<'a> {} impl<'a> ViolatingSiteMethods<'a> { /// Create a builder to help you perform the following task: /// /// Lists sites that are failing in the Ad Experience Report on at least one platform. pub fn list(&self) -> ViolatingSiteListCall<'a> { ViolatingSiteListCall { hub: self.hub, _delegate: Default::default(), _additional_params: Default::default(), } } } // ################### // CallBuilders ### // ################# /// Gets a site's Ad Experience Report summary. /// /// A builder for the *get* method supported by a *site* resource. /// It is not used directly, but through a `SiteMethods` instance. /// /// # Example /// /// Instantiate a resource method builder /// /// ```test_harness,no_run /// # extern crate hyper; /// # extern crate hyper_rustls; /// # extern crate yup_oauth2 as oauth2; /// # extern crate google_adexperiencereport1 as adexperiencereport1; /// # async fn dox() { /// # use std::default::Default; /// # use oauth2; /// # use adexperiencereport1::AdExperienceReport; /// /// # let secret: oauth2::ApplicationSecret = Default::default(); /// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder( /// # secret, /// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect, /// # ).build().await.unwrap(); /// # let mut hub = AdExperienceReport::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth); /// // You can configure optional parameters by calling the respective setters at will, and /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.sites().get("name") /// .doit().await; /// # } /// ``` pub struct SiteGetCall<'a> where { hub: &'a AdExperienceReport<>, _name: String, _delegate: Option<&'a mut dyn client::Delegate>, _additional_params: HashMap<String, String>, } impl<'a> client::CallBuilder for SiteGetCall<'a> {} impl<'a> SiteGetCall<'a> { /// Perform the operation you have build so far. pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, SiteSummaryResponse)> { use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET}; use std::io::{Read, Seek}; use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION}; use client::ToParts; let mut dd = client::DefaultDelegate; let mut dlg: &mut dyn client::Delegate = match self._delegate { Some(d) => d, None => &mut dd }; dlg.begin(client::MethodInfo { id: "adexperiencereport.sites.get", http_method: hyper::Method::GET }); let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len()); params.push(("name", self._name.to_string())); for &field in ["alt", "name"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(client::Error::FieldClash(field)); } } for (name, value) in self._additional_params.iter() { params.push((&name, value.clone())); } params.push(("alt", "json".to_string())); let mut url = self.hub._base_url.clone() + "v1/{+name}"; let key = dlg.api_key(); match key { Some(value) => params.push(("key", value)), None => { dlg.finished(false); return Err(client::Error::MissingAPIKey) } } for &(find_this, param_name) in [("{+name}", "name")].iter() { let mut replace_with = String::new(); for &(name, ref value) in params.iter() { if name == param_name { replace_with = value.to_string(); break; } } if find_this.as_bytes()[1] == '+' as u8 { replace_with = percent_encode(replace_with.as_bytes(), DEFAULT_ENCODE_SET).to_string(); } url = url.replace(find_this, &replace_with); } { let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1); for param_name in ["name"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } } for &index in indices_for_removal.iter() { params.remove(index); } } let url = url::Url::parse_with_params(&url, params).unwrap(); loop { let mut req_result = { let client = &self.hub.client; dlg.pre_request(); let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string()) .header(USER_AGENT, self.hub._user_agent.clone()); let request = req_builder .body(hyper::body::Body::empty()); client.request(request.unwrap()).await }; match req_result { Err(err) => { if let client::Retry::After(d) = dlg.http_error(&err) { sleep(d); continue; } dlg.finished(false); return Err(client::Error::HttpError(err)) } Ok(mut res) => { if !res.status().is_success() { let res_body_string = client::get_body_as_string(res.body_mut()).await; let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok(); let server_error = json::from_str::<client::ServerError>(&res_body_string) .or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error)) .ok(); if let client::Retry::After(d) = dlg.http_failure(&res, json_server_error, server_error) { sleep(d); continue; } dlg.finished(false); return match json::from_str::<client::ErrorResponse>(&res_body_string){ Err(_) => Err(client::Error::Failure(res)), Ok(serr) => Err(client::Error::BadRequest(serr)) } } let result_value = { let res_body_string = client::get_body_as_string(res.body_mut()).await; match json::from_str(&res_body_string) { Ok(decoded) => (res, decoded), Err(err) => { dlg.response_json_decode_error(&res_body_string, &err); return Err(client::Error::JsonDecodeError(res_body_string, err)); } } }; dlg.finished(true); return Ok(result_value) } } } } /// Required. The name of the site whose summary to get, e.g. `sites/http%3A%2F%2Fwww.google.com%2F`. Format: `sites/{site}` /// /// Sets the *name* path property to the given value. /// /// Even though the property as already been set when instantiating this call, /// we provide this method for API completeness. pub fn name(mut self, new_value: &str) -> SiteGetCall<'a> { self._name = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> SiteGetCall<'a> { self._delegate = Some(new_value); self } /// Set any additional parameter of the query string used in the request. /// It should be used to set parameters which are not yet available through their own /// setters. /// /// Please note that this method must not be used to set any of the known parameters /// which have their own setter method. If done anyway, the request will fail. /// /// # Additional Parameters /// /// * *$.xgafv* (query-string) - V1 error format. /// * *access_token* (query-string) - OAuth access token. /// * *alt* (query-string) - Data format for response. /// * *callback* (query-string) - JSONP /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). pub fn param<T>(mut self, name: T, value: T) -> SiteGetCall<'a> where T: AsRef<str> { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self } } /// Lists sites that are failing in the Ad Experience Report on at least one platform. /// /// A builder for the *list* method supported by a *violatingSite* resource. /// It is not used directly, but through a `ViolatingSiteMethods` instance. /// /// # Example /// /// Instantiate a resource method builder /// /// ```test_harness,no_run /// # extern crate hyper; /// # extern crate hyper_rustls; /// # extern crate yup_oauth2 as oauth2; /// # extern crate google_adexperiencereport1 as adexperiencereport1; /// # async fn dox() { /// # use std::default::Default; /// # use oauth2; /// # use adexperiencereport1::AdExperienceReport; /// /// # let secret: oauth2::ApplicationSecret = Default::default(); /// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder( /// # secret, /// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect, /// # ).build().await.unwrap(); /// # let mut hub = AdExperienceReport::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots()), auth); /// // You can configure optional parameters by calling the respective setters at will, and /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.violating_sites().list() /// .doit().await; /// # } /// ``` pub struct ViolatingSiteListCall<'a> where { hub: &'a AdExperienceReport<>, _delegate: Option<&'a mut dyn client::Delegate>, _additional_params: HashMap<String, String>, } impl<'a> client::CallBuilder for ViolatingSiteListCall<'a> {} impl<'a> ViolatingSiteListCall<'a> { /// Perform the operation you have build so far. pub async fn doit(mut self) -> client::Result<(hyper::Response<hyper::body::Body>, ViolatingSitesResponse)> { use std::io::{Read, Seek}; use hyper::header::{CONTENT_TYPE, CONTENT_LENGTH, AUTHORIZATION, USER_AGENT, LOCATION}; use client::ToParts; let mut dd = client::DefaultDelegate; let mut dlg: &mut dyn client::Delegate = match self._delegate { Some(d) => d, None => &mut dd }; dlg.begin(client::MethodInfo { id: "adexperiencereport.violatingSites.list", http_method: hyper::Method::GET }); let mut params: Vec<(&str, String)> = Vec::with_capacity(2 + self._additional_params.len()); for &field in ["alt"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(client::Error::FieldClash(field)); } } for (name, value) in self._additional_params.iter() { params.push((&name, value.clone())); } params.push(("alt", "json".to_string())); let mut url = self.hub._base_url.clone() + "v1/violatingSites"; let key = dlg.api_key(); match key { Some(value) => params.push(("key", value)), None => { dlg.finished(false); return Err(client::Error::MissingAPIKey) } } let url = url::Url::parse_with_params(&url, params).unwrap(); loop { let mut req_result = { let client = &self.hub.client; dlg.pre_request(); let mut req_builder = hyper::Request::builder().method(hyper::Method::GET).uri(url.clone().into_string()) .header(USER_AGENT, self.hub._user_agent.clone()); let request = req_builder .body(hyper::body::Body::empty()); client.request(request.unwrap()).await }; match req_result { Err(err) => { if let client::Retry::After(d) = dlg.http_error(&err) { sleep(d); continue; } dlg.finished(false); return Err(client::Error::HttpError(err)) } Ok(mut res) => { if !res.status().is_success() { let res_body_string = client::get_body_as_string(res.body_mut()).await; let json_server_error = json::from_str::<client::JsonServerError>(&res_body_string).ok(); let server_error = json::from_str::<client::ServerError>(&res_body_string) .or_else(|_| json::from_str::<client::ErrorResponse>(&res_body_string).map(|r| r.error)) .ok(); if let client::Retry::After(d) = dlg.http_failure(&res, json_server_error, server_error) { sleep(d); continue; } dlg.finished(false); return match json::from_str::<client::ErrorResponse>(&res_body_string){ Err(_) => Err(client::Error::Failure(res)), Ok(serr) => Err(client::Error::BadRequest(serr)) } } let result_value = { let res_body_string = client::get_body_as_string(res.body_mut()).await; match json::from_str(&res_body_string) { Ok(decoded) => (res, decoded), Err(err) => { dlg.response_json_decode_error(&res_body_string, &err); return Err(client::Error::JsonDecodeError(res_body_string, err)); } } }; dlg.finished(true); return Ok(result_value) } } } } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. pub fn delegate(mut self, new_value: &'a mut dyn client::Delegate) -> ViolatingSiteListCall<'a> { self._delegate = Some(new_value); self } /// Set any additional parameter of the query string used in the request. /// It should be used to set parameters which are not yet available through their own /// setters. /// /// Please note that this method must not be used to set any of the known parameters /// which have their own setter method. If done anyway, the request will fail. /// /// # Additional Parameters /// /// * *$.xgafv* (query-string) - V1 error format. /// * *access_token* (query-string) - OAuth access token. /// * *alt* (query-string) - Data format for response. /// * *callback* (query-string) - JSONP /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). pub fn param<T>(mut self, name: T, value: T) -> ViolatingSiteListCall<'a> where T: AsRef<str> { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self } }
39.54702
290
0.592505
6235deb0e7fc74daa90e6b0432fbe841c179c13b
4,617
use std::{collections::HashSet, time::Duration}; use pretty_assertions::assert_eq; use super::{LookupHosts, SrvPollingMonitor}; use crate::{ error::Result, options::{ClientOptions, ServerAddress}, sdam::Topology, RUNTIME, }; fn localhost_test_build_10gen(port: u16) -> ServerAddress { ServerAddress::Tcp { host: "localhost.test.build.10gen.cc".into(), port: Some(port), } } lazy_static::lazy_static! { static ref DEFAULT_HOSTS: Vec<ServerAddress> = vec![ localhost_test_build_10gen(27017), localhost_test_build_10gen(27108), ]; } async fn run_test(new_hosts: Result<Vec<ServerAddress>>, expected_hosts: HashSet<ServerAddress>) { let mut options = ClientOptions::new_srv(); options.hosts = DEFAULT_HOSTS.clone(); options.test_options_mut().disable_monitoring_threads = true; let topology = Topology::new(options).unwrap(); let mut monitor = SrvPollingMonitor::new(topology.downgrade()).unwrap(); monitor .update_hosts(new_hosts.and_then(make_lookup_hosts), topology.clone()) .await; assert_eq!(expected_hosts, topology.servers().await); } fn make_lookup_hosts(hosts: Vec<ServerAddress>) -> Result<LookupHosts> { Ok(LookupHosts { hosts: hosts.into_iter().map(Result::Ok).collect(), min_ttl: Duration::from_secs(60), }) } // If a new DNS record is returned, it should be reflected in the topology. #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn add_new_dns_record() { let hosts = vec![ localhost_test_build_10gen(27017), localhost_test_build_10gen(27018), localhost_test_build_10gen(27019), ]; run_test(Ok(hosts.clone()), hosts.into_iter().collect()).await; } // If a DNS record is no longer returned, it should be reflected in the topology. #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn remove_dns_record() { let hosts = vec![localhost_test_build_10gen(27017)]; run_test(Ok(hosts.clone()), hosts.into_iter().collect()).await; } // If a single DNS record is replaced, it should be reflected in the topology. #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn replace_single_dns_record() { let hosts = vec![ localhost_test_build_10gen(27017), localhost_test_build_10gen(27019), ]; run_test(Ok(hosts.clone()), hosts.into_iter().collect()).await; } // If all DNS records are replaced, it should be reflected in the topology. #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn replace_all_dns_records() { let hosts = vec![localhost_test_build_10gen(27019)]; run_test(Ok(hosts.clone()), hosts.into_iter().collect()).await; } // If a timeout error occurs, the topology should be unchanged. #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn timeout_error() { run_test( Err(std::io::ErrorKind::TimedOut.into()), DEFAULT_HOSTS.iter().cloned().collect(), ) .await; } // If no results are returned, the topology should be unchanged. #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn no_results() { run_test(Ok(Vec::new()), DEFAULT_HOSTS.iter().cloned().collect()).await; } // SRV polling is not done for load-balanced clusters (as per spec at // https://github.com/mongodb/specifications/blob/master/source/polling-srv-records-for-mongos-discovery/tests/README.rst#test-that-srv-polling-is-not-done-for-load-balalanced-clusters). #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn load_balanced_no_srv_polling() { let hosts = vec![localhost_test_build_10gen(27017)]; let mut options = ClientOptions::new_srv(); let rescan_interval = options.original_srv_info.as_ref().cloned().unwrap().min_ttl; options.hosts = hosts.clone(); options.load_balanced = Some(true); options.test_options_mut().mock_lookup_hosts = Some(make_lookup_hosts(vec![ localhost_test_build_10gen(27017), localhost_test_build_10gen(27018), ])); let topology = Topology::new(options).unwrap(); RUNTIME.delay_for(rescan_interval * 2).await; assert_eq!( hosts.into_iter().collect::<HashSet<_>>(), topology.servers().await ); }
35.790698
186
0.700238
d7574da0726a2d9470394bf2d54244ee8451f890
3,045
//! A [Font Variations Table]( //! https://docs.microsoft.com/en-us/typography/opentype/spec/fvar) implementation. use core::num::NonZeroU16; use crate::{Tag, NormalizedCoordinate}; use crate::parser::{Stream, FromData, Fixed, Offset16, Offset, LazyArray16, f32_bound}; /// A [variation axis](https://docs.microsoft.com/en-us/typography/opentype/spec/fvar#variationaxisrecord). #[repr(C)] #[allow(missing_docs)] #[derive(Clone, Copy, PartialEq, Debug)] pub struct VariationAxis { pub tag: Tag, pub min_value: f32, pub def_value: f32, pub max_value: f32, /// An axis name in the `name` table. pub name_id: u16, pub hidden: bool, } impl FromData for VariationAxis { const SIZE: usize = 20; fn parse(data: &[u8]) -> Option<Self> { let mut s = Stream::new(data); let tag = s.read::<Tag>()?; let min_value = s.read::<Fixed>()?; let def_value = s.read::<Fixed>()?; let max_value = s.read::<Fixed>()?; let flags = s.read::<u16>()?; let name_id = s.read::<u16>()?; Some(VariationAxis { tag, min_value: def_value.0.min(min_value.0), def_value: def_value.0, max_value: def_value.0.max(max_value.0), name_id, hidden: (flags >> 3) & 1 == 1, }) } } impl VariationAxis { /// Returns a normalized variation coordinate for this axis. pub(crate) fn normalized_value(&self, mut v: f32) -> NormalizedCoordinate { // Based on // https://docs.microsoft.com/en-us/typography/opentype/spec/avar#overview v = f32_bound(self.min_value, v, self.max_value); if v == self.def_value { v = 0.0; } else if v < self.def_value { v = (v - self.def_value) / (self.def_value - self.min_value); } else { v = (v - self.def_value) / (self.max_value - self.def_value); } NormalizedCoordinate::from(v) } } /// A [Font Variations Table]( /// https://docs.microsoft.com/en-us/typography/opentype/spec/fvar). #[derive(Clone, Copy, Debug)] pub struct Table<'a> { /// A list of variation axes. pub axes: LazyArray16<'a, VariationAxis>, } impl<'a> Table<'a> { /// Parses a table from raw data. pub fn parse(data: &'a [u8]) -> Option<Self> { let mut s = Stream::new(data); let version = s.read::<u32>()?; if version != 0x00010000 { return None; } let axes_array_offset = s.read::<Offset16>()?; s.skip::<u16>(); // reserved let axis_count = s.read::<u16>()?; // 'If axisCount is zero, then the font is not functional as a variable font, // and must be treated as a non-variable font; // any variation-specific tables or data is ignored.' let axis_count = NonZeroU16::new(axis_count)?; let mut s = Stream::new_at(data, axes_array_offset.to_usize())?; let axes = s.read_array16::<VariationAxis>(axis_count.get())?; Some(Table { axes }) } }
31.071429
107
0.589819
0a3ba7610d38b684276872479ac4d8399a56b01d
1,024
//! Provides a generic decription of basic blocks. use ir; use std; /// Provides a unique identifer for a basic block. #[derive( Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, )] #[repr(C)] pub enum StmtId { /// cbindgen:field-names=[id] Inst(ir::InstId), /// cbindgen:field-names=[id] Dim(ir::DimId), } impl From<ir::InstId> for StmtId { fn from(id: ir::InstId) -> Self { StmtId::Inst(id) } } impl From<ir::DimId> for StmtId { fn from(id: ir::DimId) -> Self { StmtId::Dim(id) } } /// Represents a basic block in an Exhaust function. pub trait Statement<'a, L = ir::LoweringMap>: std::fmt::Debug { /// Returns the unique identifier of the `Statement`. fn stmt_id(&self) -> StmtId; /// Returns 'self' if it is an instruction. fn as_inst(&self) -> Option<&ir::Instruction<'a, L>> { None } /// Returns 'self' if it is a dimension fn as_dim(&self) -> Option<&ir::Dimension<'a>> { None } }
24.380952
85
0.603516
69392d8648f7adeafb61280cccb8d6ab0bec1165
8,940
//! Utilities for manipulating the char type // NB: transitionary, de-mode-ing. #[forbid(deprecated_mode)]; #[forbid(deprecated_pattern)]; use cmp::Eq; /* Lu Uppercase_Letter an uppercase letter Ll Lowercase_Letter a lowercase letter Lt Titlecase_Letter a digraphic character, with first part uppercase Lm Modifier_Letter a modifier letter Lo Other_Letter other letters, including syllables and ideographs Mn Nonspacing_Mark a nonspacing combining mark (zero advance width) Mc Spacing_Mark a spacing combining mark (positive advance width) Me Enclosing_Mark an enclosing combining mark Nd Decimal_Number a decimal digit Nl Letter_Number a letterlike numeric character No Other_Number a numeric character of other type Pc Connector_Punctuation a connecting punctuation mark, like a tie Pd Dash_Punctuation a dash or hyphen punctuation mark Ps Open_Punctuation an opening punctuation mark (of a pair) Pe Close_Punctuation a closing punctuation mark (of a pair) Pi Initial_Punctuation an initial quotation mark Pf Final_Punctuation a final quotation mark Po Other_Punctuation a punctuation mark of other type Sm Math_Symbol a symbol of primarily mathematical use Sc Currency_Symbol a currency sign Sk Modifier_Symbol a non-letterlike modifier symbol So Other_Symbol a symbol of other type Zs Space_Separator a space character (of various non-zero widths) Zl Line_Separator U+2028 LINE SEPARATOR only Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only Cc Control a C0 or C1 control code Cf Format a format control character Cs Surrogate a surrogate code point Co Private_Use a private-use character Cn Unassigned a reserved unassigned code point or a noncharacter */ export is_alphabetic, is_XID_start, is_XID_continue, is_lowercase, is_uppercase, is_whitespace, is_alphanumeric, is_ascii, is_digit, to_digit, cmp, escape_default, escape_unicode; use is_alphabetic = unicode::derived_property::Alphabetic; use is_XID_start = unicode::derived_property::XID_Start; use is_XID_continue = unicode::derived_property::XID_Continue; /** * Indicates whether a character is in lower case, defined * in terms of the Unicode General Category 'Ll' */ pure fn is_lowercase(c: char) -> bool { return unicode::general_category::Ll(c); } /** * Indicates whether a character is in upper case, defined * in terms of the Unicode General Category 'Lu'. */ pure fn is_uppercase(c: char) -> bool { return unicode::general_category::Lu(c); } /** * Indicates whether a character is whitespace, defined in * terms of the Unicode General Categories 'Zs', 'Zl', 'Zp' * additional 'Cc'-category control codes in the range [0x09, 0x0d] */ pure fn is_whitespace(c: char) -> bool { return ('\x09' <= c && c <= '\x0d') || unicode::general_category::Zs(c) || unicode::general_category::Zl(c) || unicode::general_category::Zp(c); } /** * Indicates whether a character is alphanumeric, defined * in terms of the Unicode General Categories 'Nd', * 'Nl', 'No' and the Derived Core Property 'Alphabetic'. */ pure fn is_alphanumeric(c: char) -> bool { return unicode::derived_property::Alphabetic(c) || unicode::general_category::Nd(c) || unicode::general_category::Nl(c) || unicode::general_category::No(c); } /// Indicates whether the character is an ASCII character pure fn is_ascii(c: char) -> bool { c - ('\x7F' & c) == '\x00' } /// Indicates whether the character is numeric (Nd, Nl, or No) pure fn is_digit(c: char) -> bool { return unicode::general_category::Nd(c) || unicode::general_category::Nl(c) || unicode::general_category::No(c); } /** * Convert a char to the corresponding digit. * * # Safety note * * This function returns none if `c` is not a valid char * * # Return value * * If `c` is between '0' and '9', the corresponding value * between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is * 'b' or 'B', 11, etc. Returns none if the char does not * refer to a digit in the given radix. */ pure fn to_digit(c: char, radix: uint) -> Option<uint> { let val = match c { '0' .. '9' => c as uint - ('0' as uint), 'a' .. 'z' => c as uint + 10u - ('a' as uint), 'A' .. 'Z' => c as uint + 10u - ('A' as uint), _ => return None }; if val < radix { Some(val) } else { None } } /** * Return the hexadecimal unicode escape of a char. * * The rules are as follows: * * - chars in [0,0xff] get 2-digit escapes: `\\xNN` * - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN` * - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN` */ fn escape_unicode(c: char) -> ~str { let s = u32::to_str(c as u32, 16u); let (c, pad) = (if c <= '\xff' { ('x', 2u) } else if c <= '\uffff' { ('u', 4u) } else { ('U', 8u) }); assert str::len(s) <= pad; let mut out = ~"\\"; str::push_str(out, str::from_char(c)); for uint::range(str::len(s), pad) |_i| { str::push_str(out, ~"0"); } str::push_str(out, s); move out } /** * Return a 'default' ASCII and C++11-like char-literal escape of a char. * * The default is chosen with a bias toward producing literals that are * legal in a variety of languages, including C++11 and similar C-family * languages. The exact rules are: * * - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. * - Single-quote, double-quote and backslash chars are backslash-escaped. * - Any other chars in the range [0x20,0x7e] are not escaped. * - Any other chars are given hex unicode escapes; see `escape_unicode`. */ fn escape_default(c: char) -> ~str { match c { '\t' => ~"\\t", '\r' => ~"\\r", '\n' => ~"\\n", '\\' => ~"\\\\", '\'' => ~"\\'", '"' => ~"\\\"", '\x20' .. '\x7e' => str::from_char(c), _ => escape_unicode(c) } } /** * Compare two chars * * # Return value * * -1 if a < b, 0 if a == b, +1 if a > b */ pure fn cmp(a: char, b: char) -> int { return if b > a { -1 } else if b < a { 1 } else { 0 } } impl char: Eq { pure fn eq(&&other: char) -> bool { self == other } pure fn ne(&&other: char) -> bool { self != other } } #[test] fn test_is_lowercase() { assert is_lowercase('a'); assert is_lowercase('ö'); assert is_lowercase('ß'); assert !is_lowercase('Ü'); assert !is_lowercase('P'); } #[test] fn test_is_uppercase() { assert !is_uppercase('h'); assert !is_uppercase('ä'); assert !is_uppercase('ß'); assert is_uppercase('Ö'); assert is_uppercase('T'); } #[test] fn test_is_whitespace() { assert is_whitespace(' '); assert is_whitespace('\u2007'); assert is_whitespace('\t'); assert is_whitespace('\n'); assert !is_whitespace('a'); assert !is_whitespace('_'); assert !is_whitespace('\u0000'); } #[test] fn test_to_digit() { assert to_digit('0', 10u) == Some(0u); assert to_digit('1', 2u) == Some(1u); assert to_digit('2', 3u) == Some(2u); assert to_digit('9', 10u) == Some(9u); assert to_digit('a', 16u) == Some(10u); assert to_digit('A', 16u) == Some(10u); assert to_digit('b', 16u) == Some(11u); assert to_digit('B', 16u) == Some(11u); assert to_digit('z', 36u) == Some(35u); assert to_digit('Z', 36u) == Some(35u); assert to_digit(' ', 10u).is_none(); assert to_digit('$', 36u).is_none(); } #[test] fn test_is_ascii() { assert str::all(~"banana", char::is_ascii); assert ! str::all(~"ประเทศไทย中华Việt Nam", char::is_ascii); } #[test] fn test_is_digit() { assert is_digit('2'); assert is_digit('7'); assert ! is_digit('c'); assert ! is_digit('i'); assert ! is_digit('z'); assert ! is_digit('Q'); } #[test] fn test_escape_default() { assert escape_default('\n') == ~"\\n"; assert escape_default('\r') == ~"\\r"; assert escape_default('\'') == ~"\\'"; assert escape_default('"') == ~"\\\""; assert escape_default(' ') == ~" "; assert escape_default('a') == ~"a"; assert escape_default('~') == ~"~"; assert escape_default('\x00') == ~"\\x00"; assert escape_default('\x1f') == ~"\\x1f"; assert escape_default('\x7f') == ~"\\x7f"; assert escape_default('\xff') == ~"\\xff"; assert escape_default('\u011b') == ~"\\u011b"; assert escape_default('\U0001d4b6') == ~"\\U0001d4b6"; } #[test] fn test_escape_unicode() { assert escape_unicode('\x00') == ~"\\x00"; assert escape_unicode('\n') == ~"\\x0a"; assert escape_unicode(' ') == ~"\\x20"; assert escape_unicode('a') == ~"\\x61"; assert escape_unicode('\u011b') == ~"\\u011b"; assert escape_unicode('\U0001d4b6') == ~"\\U0001d4b6"; }
31.149826
76
0.619239
1ed1fb6443e1a009f90510a493dcdf5952694580
3,648
// write methods use crate::enums::Direction; use crate::terminal::Terminal; use tuikit::attr::{Attr, Color}; impl Terminal { pub fn write(&mut self, message: &str, color: Color) { let attr = Attr { fg: color, ..Attr::default() }; self.correct_blinking_cursor_row(); self.term .print_with_attr(self.cursor.0, self.cursor.1, message, attr) .unwrap(); self.term.present().unwrap(); } pub fn writeln(&mut self, message: &str) { self.cursor.0 += 1; self.write(message, Color::LIGHT_RED); } pub fn write_output(&mut self, out: String) { out.split('\n').enumerate().for_each(|(idx, chunk)| { if idx != 0 { self.writeln(&format!(" {}", chunk)); } else { self.writeln(&format!(" Out[{}]: {}", self.history.last_idx() - 1, chunk)); } }); self.scroll_down(); self.empty_new_line(1); self.buffer.clear(); self.write_input(); } pub fn write_input(&mut self) { self.write( &format!(" In[{}]: {}", self.history.last_idx(), self.buffer), Color::YELLOW, ); } pub fn write_screen(&mut self) { self.clear(); self.reset_cursors(); self.empty_new_line(1); for (val, color) in self.terminal_screen[self.screen_cursor.0..].to_owned() { let space = if color == Color::LIGHT_RED { 2 } else { 1 }; let attr = Attr { fg: color, ..Attr::default() }; self.term .print_with_attr(self.cursor.0, self.cursor.1, &val, attr) .unwrap(); self.cursor.0 += space; } if self.terminal_screen.last().unwrap().1 == Color::YELLOW { self.cursor.0 -= 1; } self.correct_blinking_cursor_row(); self.term.present().unwrap(); self.write_input(); } pub fn back_space(&mut self) { self.move_blinking_cursor_auto(Direction::Left); if !self.buffer.is_empty() { self.buffer.remove(self.blinking_cursor_col_pos()); } self.empty_input_line(); self.write_input(); } // cursor + blinking cursor pub fn blinking_cursor_col_pos(&self) -> usize { self.blinking_cursor.1 - self.left_margin } pub fn move_blinking_cursor_manuel(&mut self, direction: Direction) { self.move_blinking_cursor_auto(direction); self.correct_blinking_cursor_row(); self.term.present().unwrap(); } pub fn move_blinking_cursor_auto(&mut self, direction: Direction) { match direction { Direction::Right => self.blinking_cursor.1 += 1, Direction::Left => self.blinking_cursor.1 -= 1, } if self.blinking_cursor.1 < self.left_margin { self.blinking_cursor.1 = self.left_margin; } if self.blinking_cursor.1 > self.left_margin + self.buffer.len() { self.blinking_cursor.1 = self.left_margin + self.buffer.len(); } } pub fn correct_blinking_cursor_row(&mut self) { self.blinking_cursor.0 = self.cursor.0; self.term .set_cursor(self.blinking_cursor.0, self.blinking_cursor.1) .unwrap(); } pub fn reset_blinking_cursor_col(&mut self) { self.blinking_cursor.1 = self.buffer.len() + self.left_margin; } pub fn reset_cursors(&mut self) { self.cursor = (0, 0); //self.blinking_cursor = (0, self.left_margin); } }
33.46789
91
0.55318
5093a77b571e9b711124d66c77d9c7f7cfc2ca00
4,542
use sp_core::{Pair, Public, sr25519}; use node_template_runtime::{ AccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig, SudoConfig, SystemConfig, WASM_BINARY, Signature }; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_finality_grandpa::AuthorityId as GrandpaId; use sp_runtime::traits::{Verify, IdentifyAccount}; use sc_service::ChainType; // The URL for the telemetry server. // const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; /// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type. pub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>; /// Generate a crypto pair from seed. pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public { TPublic::Pair::from_string(&format!("//{}", seed), None) .expect("static values are valid; qed") .public() } type AccountPublic = <Signature as Verify>::Signer; /// Generate an account ID from seed. pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId where AccountPublic: From<<TPublic::Pair as Pair>::Public> { AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account() } /// Generate an Aura authority key. pub fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) { ( get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s), ) } pub fn development_config() -> Result<ChainSpec, String> { let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; Ok(ChainSpec::from_genesis( // Name "Development", // ID "dev", ChainType::Development, move || testnet_genesis( wasm_binary, // Initial PoA authorities vec![ authority_keys_from_seed("Alice"), ], // Sudo account get_account_id_from_seed::<sr25519::Public>("Alice"), // Pre-funded accounts vec![ get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Bob"), get_account_id_from_seed::<sr25519::Public>("Alice//stash"), get_account_id_from_seed::<sr25519::Public>("Bob//stash"), ], true, ), // Bootnodes vec![], // Telemetry None, // Protocol ID None, // Properties None, // Extensions None, )) } pub fn local_testnet_config() -> Result<ChainSpec, String> { let wasm_binary = WASM_BINARY.ok_or_else(|| "Development wasm not available".to_string())?; Ok(ChainSpec::from_genesis( // Name "Local Testnet", // ID "local_testnet", ChainType::Local, move || testnet_genesis( wasm_binary, // Initial PoA authorities vec![ authority_keys_from_seed("Alice"), authority_keys_from_seed("Bob"), ], // Sudo account get_account_id_from_seed::<sr25519::Public>("Alice"), // Pre-funded accounts vec![ get_account_id_from_seed::<sr25519::Public>("Alice"), get_account_id_from_seed::<sr25519::Public>("Bob"), get_account_id_from_seed::<sr25519::Public>("Charlie"), get_account_id_from_seed::<sr25519::Public>("Dave"), get_account_id_from_seed::<sr25519::Public>("Eve"), get_account_id_from_seed::<sr25519::Public>("Ferdie"), get_account_id_from_seed::<sr25519::Public>("Alice//stash"), get_account_id_from_seed::<sr25519::Public>("Bob//stash"), get_account_id_from_seed::<sr25519::Public>("Charlie//stash"), get_account_id_from_seed::<sr25519::Public>("Dave//stash"), get_account_id_from_seed::<sr25519::Public>("Eve//stash"), get_account_id_from_seed::<sr25519::Public>("Ferdie//stash"), ], true, ), // Bootnodes vec![], // Telemetry None, // Protocol ID None, // Properties None, // Extensions None, )) } /// Configure initial storage state for FRAME modules. fn testnet_genesis( wasm_binary: &[u8], initial_authorities: Vec<(AuraId, GrandpaId)>, root_key: AccountId, endowed_accounts: Vec<AccountId>, _enable_println: bool, ) -> GenesisConfig { GenesisConfig { system: SystemConfig { // Add Wasm runtime to storage. code: wasm_binary.to_vec(), changes_trie_config: Default::default(), }, balances: BalancesConfig { // Configure endowed accounts with initial balance of 1 << 60. balances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(), }, aura: AuraConfig { authorities: initial_authorities.iter().map(|x| (x.0.clone())).collect(), }, grandpa: GrandpaConfig { authorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), }, sudo: SudoConfig { // Assign network admin rights. key: root_key, }, } }
28.746835
94
0.69705
79e8ce4a53937b6282da191cb92906f3d5d5b762
309
pub(crate) mod barrel_migration_executor; mod quaint_result_set_ext; pub use super::assertions::*; pub use super::command_helpers::*; pub use super::misc_helpers::*; pub use super::step_helpers::*; pub use super::test_api::*; pub use quaint_result_set_ext::*; pub use test_macros::*; pub use test_setup::*;
23.769231
41
0.750809
1c8e1100689add569d43e316ec6f2dbbe49bc828
2,500
use crate::macros::MacroQueueWriter; use crate::parser::filter::{Filter, FilterIgnore}; use regex::Regex; use std::collections::VecDeque; use std::fmt::Debug; pub trait FilterMetadata { type Metadata: Debug + Clone + MacroQueueWriter; fn metadata_iter(&self) -> std::collections::vec_deque::IntoIter<Self::Metadata>; fn filter_path(&self, filter: Filter) -> VecDeque<Self::Metadata> where Self: Sized, { let iter = self.metadata_iter(); match filter { Filter::PathStartsWith(filter) => iter .filter(|metadata| metadata.path().starts_with(filter.as_str())) .collect(), Filter::PathStartsWithMulti(vec) => iter .filter(|metadata| vec.iter().any(|s| metadata.path().starts_with(s))) .collect(), Filter::None => iter.collect(), Filter::PathEquals(filter) => iter .filter(|metadata| metadata.path().eq(filter.as_str())) .collect(), Filter::PathContains(filter) => iter .filter(|metadata| metadata.path().contains(filter.as_str())) .collect(), Filter::Regex(s) => { let regex = Regex::new(s.as_str()).unwrap(); iter.filter(|metadata| regex.is_match(metadata.path().as_ref())) .collect() } Filter::IgnoreIf(filter_ignore) => match filter_ignore { FilterIgnore::PathContains(s) => iter .filter(|metadata| !metadata.path().contains(s.as_str())) .collect(), FilterIgnore::PathStartsWith(s) => iter .filter(|metadata| !metadata.path().starts_with(s.as_str())) .collect(), FilterIgnore::PathContainsMulti(vec) => iter .filter(|metadata| !vec.iter().any(|s| metadata.path().contains(s))) .collect(), FilterIgnore::PathEquals(s) => iter .filter(|metadata| metadata.path().eq(s.as_str())) .collect(), }, Filter::MultiFilter(vec) => { let mut vec_dequeue: VecDeque<Self::Metadata> = VecDeque::new(); for filter in vec { let temp_queue = self.filter_path(filter); vec_dequeue.extend(temp_queue); } vec_dequeue } } } }
40.983607
88
0.5208
1d7164896717a79247d27b98feaf5e875db8f9a7
6,542
//! Virtio network device driver. use alloc::boxed::Box; use intrusive_collections::LinkedList; use kernel::device::{Device, DeviceOps}; use kernel::mmu; use kernel::print; use pci::{PCIDriver, PCIDevice, DeviceID, PCI_VENDOR_ID_REDHAT, PCI_CAPABILITY_VENDOR}; use virtqueue; const PCI_DEVICE_ID_VIRTIO_NET: u16 = 0x1041; #[allow(dead_code)] const DEVICE_FEATURE_SELECT: usize = 0x00; #[allow(dead_code)] const DEVICE_FEATURE: usize = 0x04; #[allow(dead_code)] const DRIVER_FEATURE_SELECT: usize = 0x08; #[allow(dead_code)] const DRIVER_FEATURE: usize = 0x0c; #[allow(dead_code)] const MSIX_CONFIG: usize = 0x10; #[allow(dead_code)] const NUM_QUEUES: usize = 0x12; #[allow(dead_code)] const DEVICE_STATUS: usize = 0x14; #[allow(dead_code)] const CONFIG_GENERATION: usize = 0x15; #[allow(dead_code)] const QUEUE_SELECT: usize = 0x16; #[allow(dead_code)] const QUEUE_SIZE: usize = 0x18; #[allow(dead_code)] const QUEUE_MSIX_VECTOR: usize = 0x1a; #[allow(dead_code)] const QUEUE_ENABLE: usize = 0x1c; #[allow(dead_code)] const QUEUE_NOTIFY_OFF: usize = 0x1e; #[allow(dead_code)] const QUEUE_DESC: usize = 0x20; #[allow(dead_code)] const QUEUE_AVAIL: usize = 0x28; #[allow(dead_code)] const QUEUE_USED: usize = 0x30; #[allow(dead_code)] const VIRTIO_ACKNOWLEDGE: u8 = 1; #[allow(dead_code)] const VIRTIO_DRIVER: u8 = 2; #[allow(dead_code)] const VIRTIO_FAILED: u8 = 128; #[allow(dead_code)] const VIRTIO_FEATURES_OK: u8 = 8; #[allow(dead_code)] const VIRTIO_DRIVER_OK: u8 = 4; #[allow(dead_code)] const DEVICE_NEEDS_RESET: u8 = 64; bitflags! { pub struct Features: u32 { const VIRTIO_NET_F_CSUM = 1<<0; const VIRTIO_NET_F_GUEST_CSUM = 1<<1; const VIRTIO_NET_F_CTRL_GUEST_OFFLOADS = 1<<2; const VIRTIO_NET_F_MAC = 1<<5; const VIRTIO_NET_F_GUEST_TSO4 = 1<<7; const VIRTIO_NET_F_GUEST_TSO6 = 1<<8; const VIRTIO_NET_F_GUEST_ECN = 1<<9; const VIRTIO_NET_F_GUEST_UFO = 1<<10; const VIRTIO_NET_F_HOST_TSO4 = 1<<11; const VIRTIO_NET_F_HOST_TSO6 = 1<<12; const VIRTIO_NET_F_HOST_ECN = 1<<13; const VIRTIO_NET_F_HOST_UFO = 1<<14; const VIRTIO_NET_F_MRG_RXBUF = 1<<15; const VIRTIO_NET_F_STATUS = 1<<16; const VIRTIO_NET_F_CTRL_VQ = 1<<17; const VIRTIO_NET_F_CTRL_RX = 1<<18; const VIRTIO_NET_F_CTRL_VLAN = 1<<19; const VIRTIO_NET_F_GUEST_ANNOUNCE = 1<<21; const VIRTIO_NET_F_MQ = 1<<22; const VIRTIO_NET_F_CTRL_MAC_ADDR = 1<<23; } } #[allow(dead_code)] const VIRTIO_PCI_CAP_COMMON_CFG: u8 = 1; #[allow(dead_code)] const VIRTIO_PCI_CAP_NOTIFY_CFG: u8 = 2; #[allow(dead_code)] const VIRTIO_PCI_CAP_ISR_CFG: u8 = 3; #[allow(dead_code)] const VIRTIO_PCI_CAP_DEVICE_CFG: u8 = 4; #[allow(dead_code)] const VIRTIO_PCI_CAP_PCI_CFG: u8 = 5; const VIRTIO_PCI_CAP_CFG_TYPE: u8 = 3; const VIRTIO_PCI_CAP_BAR: u8 = 4; struct VirtioNetDevice { vqs: LinkedList<virtqueue::VirtqueueAdapter>, } impl VirtioNetDevice { fn probe(pci_dev: &PCIDevice) -> Device { pci_dev.set_bus_master(true); let mut dev = VirtioNetDevice::new(); let bar_idx = VirtioNetDevice::find_capability(pci_dev, VIRTIO_PCI_CAP_DEVICE_CFG); let bar = &pci_dev.bars[bar_idx.unwrap()].clone().unwrap(); let ioport = unsafe { bar.remap() }; // // 1. Reset device // let mut status: u8 = 0; unsafe { ioport.write8(status, DEVICE_STATUS) }; // // 2. Set ACKNOWLEDGE status bit // status |= VIRTIO_ACKNOWLEDGE; unsafe { ioport.write8(status, DEVICE_STATUS) }; // // 3. Set DRIVER status bit // status |= VIRTIO_DRIVER; unsafe { ioport.write8(status, DEVICE_STATUS) }; // // 4. Negotiate features // unsafe { ioport.write32(VIRTIO_NET_F_MRG_RXBUF.bits(), DRIVER_FEATURE) }; // // 5. Set the FEATURES_OK status bit // status |= VIRTIO_FEATURES_OK; unsafe { ioport.write8(status, DEVICE_STATUS) }; // // 6. Re-read device status to ensure the FEATURES_OK bit is still set // if unsafe { ioport.read8(DEVICE_STATUS) } & VIRTIO_FEATURES_OK != VIRTIO_FEATURES_OK { panic!("Device does not support our subset of features"); } // // 7. Perform device-specific setup // let num_queues = unsafe { ioport.read16(NUM_QUEUES) }; println!("virtio-net: {} virtqueues found.", num_queues); for queue in 0..num_queues { unsafe { ioport.write16(queue as u16, QUEUE_SELECT) }; let size = unsafe { ioport.read16(QUEUE_SIZE) }; let vq = virtqueue::Virtqueue::new(size as usize); unsafe { ioport.write64( mmu::virt_to_phys(vq.raw_descriptor_table_ptr) as u64, QUEUE_DESC, ); ioport.write64( mmu::virt_to_phys(vq.raw_available_ring_ptr) as u64, QUEUE_AVAIL, ); ioport.write64(mmu::virt_to_phys(vq.raw_used_ring_ptr) as u64, QUEUE_USED); ioport.write16(1 as u16, QUEUE_ENABLE); } dev.add_vq(vq); } // // 8. Set DRIVER_OK status bit // status |= VIRTIO_DRIVER_OK; unsafe { ioport.write8(status, DEVICE_STATUS); } Device::new(Box::new(dev)) } fn find_capability(pci_dev: &PCIDevice, cfg_type: u8) -> Option<usize> { let mut capability = pci_dev.func.find_capability(PCI_CAPABILITY_VENDOR); while let Some(offset) = capability { let ty = pci_dev.func.read_config_u8(offset + VIRTIO_PCI_CAP_CFG_TYPE); let bar = pci_dev.func.read_config_u8(offset + VIRTIO_PCI_CAP_BAR); if ty == cfg_type && bar < 0x05 { return Some(bar as usize); } capability = pci_dev.func.find_next_capability(PCI_CAPABILITY_VENDOR, offset); } None } fn new() -> Self { VirtioNetDevice { vqs: LinkedList::new(virtqueue::VirtqueueAdapter::new()) } } fn add_vq(&mut self, vq: virtqueue::Virtqueue) { self.vqs.push_back(Box::new(vq)); } } impl DeviceOps for VirtioNetDevice {} pub static mut VIRTIO_NET_DRIVER: PCIDriver = PCIDriver::new( DeviceID::new(PCI_VENDOR_ID_REDHAT, PCI_DEVICE_ID_VIRTIO_NET), VirtioNetDevice::probe, );
29.872146
94
0.633751
1ede3967b3e6e2f30bdc826a55c5107f88c72fd9
14,209
use crate::{DrivingGoal, IndividTrip, PersonID, PersonSpec, Scenario, SidewalkSpot, SpawnTrip}; use abstutil::Timer; use geom::{Duration, Time}; use map_model::{BuildingID, DirectedRoadID, Map, PathConstraints}; use rand::seq::SliceRandom; use rand::Rng; use rand_xorshift::XorShiftRng; use serde::{Deserialize, Serialize}; use std::collections::BTreeSet; // A way to generate Scenarios #[derive(Clone, Serialize, Deserialize, Debug)] pub struct ScenarioGenerator { pub scenario_name: String, pub only_seed_buses: Option<BTreeSet<String>>, pub spawn_over_time: Vec<SpawnOverTime>, pub border_spawn_over_time: Vec<BorderSpawnOverTime>, } // SpawnOverTime and BorderSpawnOverTime should be kept separate. Agents in SpawnOverTime pick // their mode (use a car, walk, bus) based on the situation. When spawning directly a border, // agents have to start as a car or pedestrian already. #[derive(Clone, Serialize, Deserialize, Debug)] pub struct SpawnOverTime { pub num_agents: usize, // TODO use https://docs.rs/rand/0.5.5/rand/distributions/struct.Normal.html pub start_time: Time, pub stop_time: Time, pub goal: OriginDestination, pub percent_driving: f64, pub percent_biking: f64, pub percent_use_transit: f64, } #[derive(Clone, Serialize, Deserialize, Debug)] pub struct BorderSpawnOverTime { pub num_peds: usize, pub num_cars: usize, pub num_bikes: usize, pub percent_use_transit: f64, // TODO use https://docs.rs/rand/0.5.5/rand/distributions/struct.Normal.html pub start_time: Time, pub stop_time: Time, pub start_from_border: DirectedRoadID, pub goal: OriginDestination, } impl ScenarioGenerator { // TODO may need to fork the RNG a bit more pub fn generate(&self, map: &Map, rng: &mut XorShiftRng, timer: &mut Timer) -> Scenario { let mut scenario = Scenario::empty(map, &self.scenario_name); scenario.only_seed_buses = self.only_seed_buses.clone(); timer.start(format!("Generating scenario {}", self.scenario_name)); for s in &self.spawn_over_time { timer.start_iter("SpawnOverTime each agent", s.num_agents); for _ in 0..s.num_agents { timer.next(); s.spawn_agent(rng, &mut scenario, map, timer); } } timer.start_iter("BorderSpawnOverTime", self.border_spawn_over_time.len()); for s in &self.border_spawn_over_time { timer.next(); s.spawn_peds(rng, &mut scenario, map, timer); s.spawn_vehicles( s.num_cars, PathConstraints::Car, rng, &mut scenario, map, timer, ); s.spawn_vehicles( s.num_bikes, PathConstraints::Bike, rng, &mut scenario, map, timer, ); } timer.stop(format!("Generating scenario {}", self.scenario_name)); scenario } pub fn small_run(map: &Map) -> ScenarioGenerator { let mut s = ScenarioGenerator { scenario_name: "small_run".to_string(), only_seed_buses: None, spawn_over_time: vec![SpawnOverTime { num_agents: 100, start_time: Time::START_OF_DAY, stop_time: Time::START_OF_DAY + Duration::seconds(5.0), goal: OriginDestination::Anywhere, percent_driving: 0.5, percent_biking: 0.5, percent_use_transit: 0.5, }], // If there are no sidewalks/driving lanes at a border, scenario instantiation will // just warn and skip them. border_spawn_over_time: map .all_incoming_borders() .into_iter() .map(|i| BorderSpawnOverTime { num_peds: 10, num_cars: 10, num_bikes: 10, start_time: Time::START_OF_DAY, stop_time: Time::START_OF_DAY + Duration::seconds(5.0), start_from_border: i.some_outgoing_road(map).unwrap(), goal: OriginDestination::Anywhere, percent_use_transit: 0.5, }) .collect(), }; for i in map.all_outgoing_borders() { s.spawn_over_time.push(SpawnOverTime { num_agents: 10, start_time: Time::START_OF_DAY, stop_time: Time::START_OF_DAY + Duration::seconds(5.0), goal: OriginDestination::EndOfRoad(i.some_incoming_road(map).unwrap()), percent_driving: 0.5, percent_biking: 0.5, percent_use_transit: 0.5, }); } s } pub fn empty(name: &str) -> ScenarioGenerator { ScenarioGenerator { scenario_name: name.to_string(), only_seed_buses: Some(BTreeSet::new()), spawn_over_time: Vec::new(), border_spawn_over_time: Vec::new(), } } // No border agents here, because making the count work is hard. pub fn scaled_run(num_agents: usize) -> ScenarioGenerator { ScenarioGenerator { scenario_name: "scaled_run".to_string(), only_seed_buses: Some(BTreeSet::new()), spawn_over_time: vec![SpawnOverTime { num_agents: num_agents, start_time: Time::START_OF_DAY, stop_time: Time::START_OF_DAY + Duration::seconds(5.0), goal: OriginDestination::Anywhere, percent_driving: 0.5, percent_biking: 0.5, percent_use_transit: 0.5, }], border_spawn_over_time: Vec::new(), } } } impl SpawnOverTime { fn spawn_agent( &self, rng: &mut XorShiftRng, scenario: &mut Scenario, map: &Map, timer: &mut Timer, ) { let depart = rand_time(rng, self.start_time, self.stop_time); // Note that it's fine for agents to start/end at the same building. Later we might // want a better assignment of people per household, or workers per office building. let from_bldg = map.all_buildings().choose(rng).unwrap().id; let id = PersonID(scenario.people.len()); if rng.gen_bool(self.percent_driving) { if let Some(goal) = self .goal .pick_driving_goal(PathConstraints::Car, map, rng, timer) { scenario.people.push(PersonSpec { id, orig_id: None, trips: vec![IndividTrip { depart, trip: SpawnTrip::UsingParkedCar(from_bldg, goal), }], }); return; } } let start_spot = SidewalkSpot::building(from_bldg, map); if rng.gen_bool(self.percent_biking) { if let Some(goal) = self .goal .pick_driving_goal(PathConstraints::Bike, map, rng, timer) { scenario.people.push(PersonSpec { id, orig_id: None, trips: vec![IndividTrip { depart, trip: SpawnTrip::UsingBike(start_spot, goal), }], }); return; } } if let Some(goal) = self.goal.pick_walking_goal(map, rng, timer) { if start_spot == goal { timer.warn("Skipping walking trip between same two buildings".to_string()); return; } if rng.gen_bool(self.percent_use_transit) { // TODO This throws away some work. It also sequentially does expensive // work right here. if let Some((stop1, stop2, route)) = map.should_use_transit(start_spot.sidewalk_pos, goal.sidewalk_pos) { scenario.people.push(PersonSpec { id, orig_id: None, trips: vec![IndividTrip { depart, trip: SpawnTrip::UsingTransit(start_spot, goal, route, stop1, stop2), }], }); return; } } scenario.people.push(PersonSpec { id, orig_id: None, trips: vec![IndividTrip { depart, trip: SpawnTrip::JustWalking(start_spot, goal), }], }); return; } timer.warn(format!("Couldn't fulfill {:?} at all", self)); } } impl BorderSpawnOverTime { fn spawn_peds( &self, rng: &mut XorShiftRng, scenario: &mut Scenario, map: &Map, timer: &mut Timer, ) { if self.num_peds == 0 { return; } let start = if let Some(s) = SidewalkSpot::start_at_border(self.start_from_border.src_i(map), None, map) { s } else { timer.warn(format!( "Can't start_at_border for {} without sidewalk", self.start_from_border )); return; }; for _ in 0..self.num_peds { let depart = rand_time(rng, self.start_time, self.stop_time); let id = PersonID(scenario.people.len()); if let Some(goal) = self.goal.pick_walking_goal(map, rng, timer) { if rng.gen_bool(self.percent_use_transit) { // TODO This throws away some work. It also sequentially does expensive // work right here. if let Some((stop1, stop2, route)) = map.should_use_transit(start.sidewalk_pos, goal.sidewalk_pos) { scenario.people.push(PersonSpec { id, orig_id: None, trips: vec![IndividTrip { depart, trip: SpawnTrip::UsingTransit( start.clone(), goal, route, stop1, stop2, ), }], }); continue; } } scenario.people.push(PersonSpec { id, orig_id: None, trips: vec![IndividTrip { depart, trip: SpawnTrip::JustWalking(start.clone(), goal), }], }); } } } fn spawn_vehicles( &self, num: usize, constraints: PathConstraints, rng: &mut XorShiftRng, scenario: &mut Scenario, map: &Map, timer: &mut Timer, ) { for _ in 0..num { let depart = rand_time(rng, self.start_time, self.stop_time); if let Some(goal) = self.goal.pick_driving_goal(constraints, map, rng, timer) { let id = PersonID(scenario.people.len()); scenario.people.push(PersonSpec { id, orig_id: None, trips: vec![IndividTrip { depart, trip: SpawnTrip::FromBorder { dr: self.start_from_border, goal, is_bike: constraints == PathConstraints::Bike, origin: None, }, }], }); } } } } #[derive(Clone, Serialize, Deserialize, Debug)] pub enum OriginDestination { Anywhere, EndOfRoad(DirectedRoadID), GotoBldg(BuildingID), } impl OriginDestination { fn pick_driving_goal( &self, constraints: PathConstraints, map: &Map, rng: &mut XorShiftRng, timer: &mut Timer, ) -> Option<DrivingGoal> { match self { OriginDestination::Anywhere => Some(DrivingGoal::ParkNear( map.all_buildings().choose(rng).unwrap().id, )), OriginDestination::GotoBldg(b) => Some(DrivingGoal::ParkNear(*b)), OriginDestination::EndOfRoad(dr) => { let goal = DrivingGoal::end_at_border(*dr, constraints, None, map); if goal.is_none() { timer.warn(format!( "Can't spawn a {:?} ending at border {}; no appropriate lanes there", constraints, dr )); } goal } } } fn pick_walking_goal( &self, map: &Map, rng: &mut XorShiftRng, timer: &mut Timer, ) -> Option<SidewalkSpot> { match self { OriginDestination::Anywhere => Some(SidewalkSpot::building( map.all_buildings().choose(rng).unwrap().id, map, )), OriginDestination::EndOfRoad(dr) => { let goal = SidewalkSpot::end_at_border(dr.dst_i(map), None, map); if goal.is_none() { timer.warn(format!("Can't end_at_border for {} without a sidewalk", dr)); } goal } OriginDestination::GotoBldg(b) => Some(SidewalkSpot::building(*b, map)), } } } fn rand_time(rng: &mut XorShiftRng, low: Time, high: Time) -> Time { assert!(high > low); Time::START_OF_DAY + Duration::seconds(rng.gen_range(low.inner_seconds(), high.inner_seconds())) }
34.911548
100
0.503413
de03283d0f16c3e2cccffb4f84ec2161ec0fcab6
205
use structopt::StructOpt; use bom; use bom::bom::options::Options; fn main() -> anyhow::Result<()> { let opt = Options::from_args(); let ec = bom::run_bom(opt)?; std::process::exit(ec); }
14.642857
35
0.604878
913de56f3b834a1ea94fe41dbd80c3616bb25969
5,009
//! Custom derives for working with the [`slog`] crate. //! //! # The `KV` Derive //! //! Say you've got a struct like this, //! //! ```rust //! # use std::path::PathBuf; //! pub struct Config { //! width: f64, //! height: f64, //! output_file: PathBuf, //! } //! ``` //! //! Sometimes you'll want to log the struct's contents in your application, for //! example when you've just started and want to record the configuration //! details for debugging purposes. Usually you'd need to do something like //! this: //! //! ```rust //! # #[macro_use] //! # extern crate slog; //! # use std::path::PathBuf; //! # fn main() { //! # let logger = slog::Logger::root(slog::Discard, o!()); //! # struct Config { width: f64, height: f64, output_file: PathBuf } //! # let cfg = Config { width: 1.0, height: 0.0, output_file: "Foo".into() }; //! debug!(logger, "Loaded Config"; //! "width" => cfg.width, //! "height" => cfg.height, //! "output-file" => cfg.output_file.display()); //! # } //! ``` //! //! This is where the [`KV`] trait comes in. Implementing it lets you translate //! the previous log statement into something like this: //! //! ```rust //! # #[macro_use] //! # extern crate slog; //! # fn main() { //! # let logger = slog::Logger::root(slog::Discard, o!()); //! # let cfg = o!(); //! debug!(logger, "Loaded Config"; cfg); //! # } //! ``` //! //! This crate provides a custom derive which will implement [`KV`] for you. //! It'll just iterate over each field in your `struct` and invoke //! [`Value::serialize()`] on each. //! //! ```rust //! # #[macro_use] //! # extern crate slog_derive; //! # extern crate slog; //! #[derive(KV)] //! pub struct Config { //! width: f64, //! height: f64, //! output_file: String, //! } //! # fn main() {} //! ``` //! //! You can also skip fields using the `#[skip]` attribute, this is useful when //! you don't want to log complex data structures or the particular field //! doesn't implement `Value`. //! //! ```rust //! # #[macro_use] //! # extern crate slog_derive; //! # extern crate slog; //! # use std::path::PathBuf; //! #[derive(KV)] //! pub struct Config { //! width: f64, //! height: f64, //! #[slog(skip)] //! output_file: PathBuf, //! } //! # fn main() {} //! ``` //! //! # The `SerdeValue` Derive //! //! Implementing the [`SerdeValue`] is usually trivial and tedious so it also //! has a custom derive. //! //! ```rust //! extern crate slog; //! #[macro_use] //! extern crate slog_derive; //! extern crate serde; //! extern crate erased_serde; //! //! use std::path::PathBuf; //! use serde::{Serialize, Deserialize}; //! //! #[derive(Clone, SerdeValue, Serialize, Deserialize)] //! pub struct Config { //! width: f64, //! height: f64, //! output_file: PathBuf, //! } //! # fn main() {} //! ``` //! //! This will require enabling `slog`'s `nested-values` feature flag, as well //! as implementing (or deriving) `serde::Serialize` for your type. You will //! also need to pull in the [`erased_serde`] crate because it's part of the //! `SerdeValue` signature. //! //! For convenience this will also generate a `Value` impl for your type (to //! implement `SerdeValue` you must also implement `Value`). This impl simply //! calls `Serializer::emit_serde()`, but if you want to write your own `Value` //! implementation you can add the `#[slog(no_value_impl)]` attribute. //! //! ```rust //! extern crate slog; //! #[macro_use] //! extern crate slog_derive; //! extern crate serde; //! extern crate erased_serde; //! //! use std::path::PathBuf; //! use slog::{Key, Record, Serializer, Value}; //! use serde::Serialize; //! //! #[derive(Clone, SerdeValue, Serialize)] //! #[slog(no_value_impl)] //! pub struct Config { //! width: f64, //! height: f64, //! output_file: PathBuf, //! } //! //! impl Value for Config { //! fn serialize(&self, _record: &Record, key: Key, ser: &mut Serializer) -> slog::Result { //! unimplemented!() //! } //! } //! # fn main() {} //! ``` //! //! [`slog`]: https://crates.io/crates/slog //! [`KV`]: https://docs.rs/slog/2.1.1/slog/trait.KV.html //! [`Value::serialize()`]: https://docs.rs/slog/2.1.1/slog/trait.Value.html#tymethod.serialize //! [`SerdeValue`]: https://docs.rs/slog/2.1.1/slog/trait.SerdeValue.html //! [`erased_serde`]: https://docs.rs/erased_serde extern crate proc_macro; extern crate proc_macro2; #[macro_use] extern crate quote; extern crate syn; mod derive_kv; mod derive_serde_value; mod utils; use proc_macro::TokenStream; use syn::DeriveInput; #[proc_macro_derive(KV, attributes(slog))] pub fn derive_kv(input: TokenStream) -> TokenStream { let ast: DeriveInput = syn::parse(input).unwrap(); let gen = derive_kv::impl_kv(&ast); gen.to_string().parse().unwrap() } #[proc_macro_derive(SerdeValue, attributes(slog))] pub fn derive_serde_value(input: TokenStream) -> TokenStream { let ast: DeriveInput = syn::parse(input).unwrap(); let gen = derive_serde_value::impl_serde_value(ast); gen.to_string().parse().unwrap() }
27.827778
95
0.62228
e22bc80d1108319b79b96c41b86817b1d6cef71e
1,697
// https://leetcode-cn.com/problems/smallest-string-starting-from-leaf/ // Runtime: 0 ms // Memory Usage: 2.7 MB use std::{cell::RefCell, rc::Rc}; pub fn smallest_from_leaf(root: Option<Rc<RefCell<TreeNode>>>) -> String { let mut cur = Vec::new(); let mut res = "".to_string(); preorder(root.as_deref(), &mut cur, &mut res); res } fn preorder(root: Option<&RefCell<TreeNode>>, cur: &mut Vec<char>, min: &mut String) { if let Some(node) = root { let node = node.borrow(); let val = (node.val as u8 + b'a') as char; cur.push(val); if node.left.is_none() && node.right.is_none() { let s = cur.iter().rev().copied().collect::<String>(); if min.is_empty() || s < *min { *min = s; } } preorder(node.left.as_deref(), cur, min); preorder(node.right.as_deref(), cur, min); cur.pop(); } } // Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<Self>>>, pub right: Option<Rc<RefCell<Self>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { Self { val, left: None, right: None, } } } // tree depth_first_search #[test] fn test1_988() { use leetcode_prelude::btree; assert_eq!( smallest_from_leaf(btree![0, 1, 2, 3, 4, 3, 4]), "dba".to_string() ); assert_eq!( smallest_from_leaf(btree![25, 1, 3, 1, 3, 0, 2]), "adz".to_string() ); assert_eq!( smallest_from_leaf(btree![2, 2, 1, null, 1, 0, null, 0]), "abc".to_string() ); }
26.107692
86
0.542133
09197bbd085cf41140d1501f42d66b0e749cdf8d
11,379
//! The default matrix data storage allocator. //! //! This will use stack-allocated buffers for matrices with dimensions known at compile-time, and //! heap-allocated buffers for matrices with at least one dimension unknown at compile-time. use std::cmp; use std::ptr; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::vec::Vec; use super::Const; use crate::base::allocator::{Allocator, Reallocator}; use crate::base::array_storage::ArrayStorage; #[cfg(any(feature = "alloc", feature = "std"))] use crate::base::dimension::Dynamic; use crate::base::dimension::{Dim, DimName}; use crate::base::storage::{RawStorage, RawStorageMut}; #[cfg(any(feature = "std", feature = "alloc"))] use crate::base::vec_storage::VecStorage; use crate::base::Scalar; use std::mem::{ManuallyDrop, MaybeUninit}; /* * * Allocator. * */ /// An allocator based on `GenericArray` and `VecStorage` for statically-sized and dynamically-sized /// matrices respectively. #[derive(Copy, Clone, Debug)] pub struct DefaultAllocator; // Static - Static impl<T: Scalar, const R: usize, const C: usize> Allocator<T, Const<R>, Const<C>> for DefaultAllocator { type Buffer = ArrayStorage<T, R, C>; type BufferUninit = ArrayStorage<MaybeUninit<T>, R, C>; #[inline(always)] fn allocate_uninit(_: Const<R>, _: Const<C>) -> ArrayStorage<MaybeUninit<T>, R, C> { // SAFETY: An uninitialized `[MaybeUninit<_>; _]` is valid. let array: [[MaybeUninit<T>; R]; C] = unsafe { MaybeUninit::uninit().assume_init() }; ArrayStorage(array) } #[inline(always)] unsafe fn assume_init(uninit: ArrayStorage<MaybeUninit<T>, R, C>) -> ArrayStorage<T, R, C> { // Safety: // * The caller guarantees that all elements of the array are initialized // * `MaybeUninit<T>` and T are guaranteed to have the same layout // * `MaybeUninit` does not drop, so there are no double-frees // And thus the conversion is safe ArrayStorage((&uninit as *const _ as *const [_; C]).read()) } #[inline] fn allocate_from_iterator<I: IntoIterator<Item = T>>( nrows: Const<R>, ncols: Const<C>, iter: I, ) -> Self::Buffer { let mut res = Self::allocate_uninit(nrows, ncols); let mut count = 0; // Safety: conversion to a slice is OK because the Buffer is known to be contiguous. let res_slice = unsafe { res.as_mut_slice_unchecked() }; for (res, e) in res_slice.iter_mut().zip(iter.into_iter()) { *res = MaybeUninit::new(e); count += 1; } assert!( count == nrows.value() * ncols.value(), "Matrix init. from iterator: iterator not long enough." ); // Safety: the assertion above made sure that the iterator // yielded enough elements to initialize our matrix. unsafe { <Self as Allocator<T, Const<R>, Const<C>>>::assume_init(res) } } } // Dynamic - Static // Dynamic - Dynamic #[cfg(any(feature = "std", feature = "alloc"))] impl<T: Scalar, C: Dim> Allocator<T, Dynamic, C> for DefaultAllocator { type Buffer = VecStorage<T, Dynamic, C>; type BufferUninit = VecStorage<MaybeUninit<T>, Dynamic, C>; #[inline] fn allocate_uninit(nrows: Dynamic, ncols: C) -> VecStorage<MaybeUninit<T>, Dynamic, C> { let mut data = Vec::new(); let length = nrows.value() * ncols.value(); data.reserve_exact(length); data.resize_with(length, MaybeUninit::uninit); VecStorage::new(nrows, ncols, data) } #[inline] unsafe fn assume_init( uninit: VecStorage<MaybeUninit<T>, Dynamic, C>, ) -> VecStorage<T, Dynamic, C> { // Avoids a double-drop. let (nrows, ncols) = uninit.shape(); let vec: Vec<_> = uninit.into(); let mut md = ManuallyDrop::new(vec); // Safety: // - MaybeUninit<T> has the same alignment and layout as T. // - The length and capacity come from a valid vector. let new_data = Vec::from_raw_parts(md.as_mut_ptr() as *mut _, md.len(), md.capacity()); VecStorage::new(nrows, ncols, new_data) } #[inline] fn allocate_from_iterator<I: IntoIterator<Item = T>>( nrows: Dynamic, ncols: C, iter: I, ) -> Self::Buffer { let it = iter.into_iter(); let res: Vec<T> = it.collect(); assert!(res.len() == nrows.value() * ncols.value(), "Allocation from iterator error: the iterator did not yield the correct number of elements."); VecStorage::new(nrows, ncols, res) } } // Static - Dynamic #[cfg(any(feature = "std", feature = "alloc"))] impl<T: Scalar, R: DimName> Allocator<T, R, Dynamic> for DefaultAllocator { type Buffer = VecStorage<T, R, Dynamic>; type BufferUninit = VecStorage<MaybeUninit<T>, R, Dynamic>; #[inline] fn allocate_uninit(nrows: R, ncols: Dynamic) -> VecStorage<MaybeUninit<T>, R, Dynamic> { let mut data = Vec::new(); let length = nrows.value() * ncols.value(); data.reserve_exact(length); data.resize_with(length, MaybeUninit::uninit); VecStorage::new(nrows, ncols, data) } #[inline] unsafe fn assume_init( uninit: VecStorage<MaybeUninit<T>, R, Dynamic>, ) -> VecStorage<T, R, Dynamic> { // Avoids a double-drop. let (nrows, ncols) = uninit.shape(); let vec: Vec<_> = uninit.into(); let mut md = ManuallyDrop::new(vec); // Safety: // - MaybeUninit<T> has the same alignment and layout as T. // - The length and capacity come from a valid vector. let new_data = Vec::from_raw_parts(md.as_mut_ptr() as *mut _, md.len(), md.capacity()); VecStorage::new(nrows, ncols, new_data) } #[inline] fn allocate_from_iterator<I: IntoIterator<Item = T>>( nrows: R, ncols: Dynamic, iter: I, ) -> Self::Buffer { let it = iter.into_iter(); let res: Vec<T> = it.collect(); assert!(res.len() == nrows.value() * ncols.value(), "Allocation from iterator error: the iterator did not yield the correct number of elements."); VecStorage::new(nrows, ncols, res) } } /* * * Reallocator. * */ // Anything -> Static × Static impl<T: Scalar, RFrom, CFrom, const RTO: usize, const CTO: usize> Reallocator<T, RFrom, CFrom, Const<RTO>, Const<CTO>> for DefaultAllocator where RFrom: Dim, CFrom: Dim, Self: Allocator<T, RFrom, CFrom>, { #[inline] unsafe fn reallocate_copy( rto: Const<RTO>, cto: Const<CTO>, buf: <Self as Allocator<T, RFrom, CFrom>>::Buffer, ) -> ArrayStorage<MaybeUninit<T>, RTO, CTO> { let mut res = <Self as Allocator<T, Const<RTO>, Const<CTO>>>::allocate_uninit(rto, cto); let (rfrom, cfrom) = buf.shape(); let len_from = rfrom.value() * cfrom.value(); let len_to = rto.value() * cto.value(); let len_copied = cmp::min(len_from, len_to); ptr::copy_nonoverlapping(buf.ptr(), res.ptr_mut() as *mut T, len_copied); // Safety: // - We don’t care about dropping elements because the caller is responsible for dropping things. // - We forget `buf` so that we don’t drop the other elements. std::mem::forget(buf); res } } // Static × Static -> Dynamic × Any #[cfg(any(feature = "std", feature = "alloc"))] impl<T: Scalar, CTo, const RFROM: usize, const CFROM: usize> Reallocator<T, Const<RFROM>, Const<CFROM>, Dynamic, CTo> for DefaultAllocator where CTo: Dim, { #[inline] unsafe fn reallocate_copy( rto: Dynamic, cto: CTo, buf: ArrayStorage<T, RFROM, CFROM>, ) -> VecStorage<MaybeUninit<T>, Dynamic, CTo> { let mut res = <Self as Allocator<T, Dynamic, CTo>>::allocate_uninit(rto, cto); let (rfrom, cfrom) = buf.shape(); let len_from = rfrom.value() * cfrom.value(); let len_to = rto.value() * cto.value(); let len_copied = cmp::min(len_from, len_to); ptr::copy_nonoverlapping(buf.ptr(), res.ptr_mut() as *mut T, len_copied); // Safety: // - We don’t care about dropping elements because the caller is responsible for dropping things. // - We forget `buf` so that we don’t drop the other elements. std::mem::forget(buf); res } } // Static × Static -> Static × Dynamic #[cfg(any(feature = "std", feature = "alloc"))] impl<T: Scalar, RTo, const RFROM: usize, const CFROM: usize> Reallocator<T, Const<RFROM>, Const<CFROM>, RTo, Dynamic> for DefaultAllocator where RTo: DimName, { #[inline] unsafe fn reallocate_copy( rto: RTo, cto: Dynamic, buf: ArrayStorage<T, RFROM, CFROM>, ) -> VecStorage<MaybeUninit<T>, RTo, Dynamic> { let mut res = <Self as Allocator<T, RTo, Dynamic>>::allocate_uninit(rto, cto); let (rfrom, cfrom) = buf.shape(); let len_from = rfrom.value() * cfrom.value(); let len_to = rto.value() * cto.value(); let len_copied = cmp::min(len_from, len_to); ptr::copy_nonoverlapping(buf.ptr(), res.ptr_mut() as *mut T, len_copied); // Safety: // - We don’t care about dropping elements because the caller is responsible for dropping things. // - We forget `buf` so that we don’t drop the other elements. std::mem::forget(buf); res } } // All conversion from a dynamic buffer to a dynamic buffer. #[cfg(any(feature = "std", feature = "alloc"))] impl<T: Scalar, CFrom: Dim, CTo: Dim> Reallocator<T, Dynamic, CFrom, Dynamic, CTo> for DefaultAllocator { #[inline] unsafe fn reallocate_copy( rto: Dynamic, cto: CTo, buf: VecStorage<T, Dynamic, CFrom>, ) -> VecStorage<MaybeUninit<T>, Dynamic, CTo> { let new_buf = buf.resize(rto.value() * cto.value()); VecStorage::new(rto, cto, new_buf) } } #[cfg(any(feature = "std", feature = "alloc"))] impl<T: Scalar, CFrom: Dim, RTo: DimName> Reallocator<T, Dynamic, CFrom, RTo, Dynamic> for DefaultAllocator { #[inline] unsafe fn reallocate_copy( rto: RTo, cto: Dynamic, buf: VecStorage<T, Dynamic, CFrom>, ) -> VecStorage<MaybeUninit<T>, RTo, Dynamic> { let new_buf = buf.resize(rto.value() * cto.value()); VecStorage::new(rto, cto, new_buf) } } #[cfg(any(feature = "std", feature = "alloc"))] impl<T: Scalar, RFrom: DimName, CTo: Dim> Reallocator<T, RFrom, Dynamic, Dynamic, CTo> for DefaultAllocator { #[inline] unsafe fn reallocate_copy( rto: Dynamic, cto: CTo, buf: VecStorage<T, RFrom, Dynamic>, ) -> VecStorage<MaybeUninit<T>, Dynamic, CTo> { let new_buf = buf.resize(rto.value() * cto.value()); VecStorage::new(rto, cto, new_buf) } } #[cfg(any(feature = "std", feature = "alloc"))] impl<T: Scalar, RFrom: DimName, RTo: DimName> Reallocator<T, RFrom, Dynamic, RTo, Dynamic> for DefaultAllocator { #[inline] unsafe fn reallocate_copy( rto: RTo, cto: Dynamic, buf: VecStorage<T, RFrom, Dynamic>, ) -> VecStorage<MaybeUninit<T>, RTo, Dynamic> { let new_buf = buf.resize(rto.value() * cto.value()); VecStorage::new(rto, cto, new_buf) } }
33.467647
110
0.60928
b9ba116a149788c17300a1b7796f26201b247294
448
#![feature(io)] extern crate hyper; use std::old_io::net::ip::Ipv4Addr; use hyper::server::{Request, Response}; static PHRASE: &'static [u8] = b"Hello World!"; fn hello(_: Request, res: Response) { let mut res = res.start().unwrap(); res.write_all(PHRASE).unwrap(); res.end().unwrap(); } fn main() { hyper::Server::http(Ipv4Addr(127, 0, 0, 1), 3000).listen(hello).unwrap(); println!("Listening on http://127.0.0.1:3000"); }
23.578947
77
0.631696
297881546cdf17f49b42a856f73a19cadaba3670
246
use gsvk::prelude::command::*; use gsvk::prelude::pipeline::*; use gsvk::prelude::descriptor::*; pub struct PipelineResource { pub pipeline: GsPipeline<Graphics>, pub viewport: CmdViewportInfo, pub descriptor_set: DescriptorSet, }
20.5
39
0.719512
d5e2d5a9a32bd2fbbd464d1388bed6de105fc8f2
5,779
use std::fmt; #[derive(Clone, Debug)] pub struct DataPoint { pub name: &'static str, pub timestamp: u64, pub fields: Vec<(&'static str, String)>, } impl DataPoint { pub fn new(name: &'static str) -> Self { DataPoint { name, timestamp: solana_sdk::timing::timestamp(), fields: vec![], } } pub fn add_field_str(&mut self, name: &'static str, value: &str) -> &mut Self { self.fields .push((name, format!("\"{}\"", value.replace("\"", "\\\"")))); self } pub fn add_field_bool(&mut self, name: &'static str, value: bool) -> &mut Self { self.fields.push((name, value.to_string())); self } pub fn add_field_i64(&mut self, name: &'static str, value: i64) -> &mut Self { self.fields.push((name, value.to_string() + "i")); self } pub fn add_field_f64(&mut self, name: &'static str, value: f64) -> &mut Self { self.fields.push((name, value.to_string())); self } } impl fmt::Display for DataPoint { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "datapoint: {}", self.name)?; for field in &self.fields { write!(f, " {}={}", field.0, field.1)?; } Ok(()) } } #[macro_export] macro_rules! create_datapoint { (@field $point:ident $name:expr, $string:expr, String) => { $point.add_field_str($name, &$string); }; (@field $point:ident $name:expr, $value:expr, i64) => { $point.add_field_i64($name, $value as i64); }; (@field $point:ident $name:expr, $value:expr, f64) => { $point.add_field_f64($name, $value as f64); }; (@field $point:ident $name:expr, $value:expr, bool) => { $point.add_field_bool($name, $value as bool); }; (@fields $point:ident) => {}; (@fields $point:ident ($name:expr, $value:expr, $type:ident) , $($rest:tt)*) => { $crate::create_datapoint!(@field $point $name, $value, $type); $crate::create_datapoint!(@fields $point $($rest)*); }; (@fields $point:ident ($name:expr, $value:expr, $type:ident)) => { $crate::create_datapoint!(@field $point $name, $value, $type); }; (@point $name:expr, $($fields:tt)+) => { { let mut point = $crate::datapoint::DataPoint::new(&$name); $crate::create_datapoint!(@fields point $($fields)+); point } }; (@point $name:expr) => { $crate::datapoint::DataPoint::new(&$name) }; } #[macro_export] macro_rules! datapoint { ($level:expr, $name:expr) => { if log::log_enabled!($level) { $crate::submit($crate::create_datapoint!(@point $name), $level); } }; ($level:expr, $name:expr, $($fields:tt)+) => { if log::log_enabled!($level) { $crate::submit($crate::create_datapoint!(@point $name, $($fields)+), $level); } }; } #[macro_export] macro_rules! datapoint_error { ($name:expr) => { $crate::datapoint!(log::Level::Error, $name); }; ($name:expr, $($fields:tt)+) => { $crate::datapoint!(log::Level::Error, $name, $($fields)+); }; } #[macro_export] macro_rules! datapoint_warn { ($name:expr) => { $crate::datapoint!(log::Level::Warn, $name); }; ($name:expr, $($fields:tt)+) => { $crate::datapoint!(log::Level::Warn, $name, $($fields)+); }; } #[macro_export] macro_rules! datapoint_info { ($name:expr) => { $crate::datapoint!(log::Level::Info, $name); }; ($name:expr, $($fields:tt)+) => { $crate::datapoint!(log::Level::Info, $name, $($fields)+); }; } #[macro_export] macro_rules! datapoint_debug { ($name:expr) => { $crate::datapoint!(log::Level::Debug, $name); }; ($name:expr, $($fields:tt)+) => { $crate::datapoint!(log::Level::Debug, $name, $($fields)+); }; } #[macro_export] macro_rules! datapoint_trace { ($name:expr) => { $crate::datapoint!(log::Level::Trace, $name); }; ($name:expr, $($fields:tt)+) => { $crate::datapoint!(log::Level::Trace, $name, $($fields)+); }; } #[cfg(test)] mod test { #[test] fn test_datapoint() { datapoint_debug!("name", ("field name", "test".to_string(), String)); datapoint_info!("name", ("field name", 12.34_f64, f64)); datapoint_trace!("name", ("field name", true, bool)); datapoint_warn!("name", ("field name", 1, i64)); datapoint_error!("name", ("field name", 1, i64),); datapoint!( log::Level::Warn, "name", ("field1 name", 2, i64), ("field2 name", 2, i64) ); datapoint_info!("name", ("field1 name", 2, i64), ("field2 name", 2, i64),); datapoint_trace!( "name", ("field1 name", 2, i64), ("field2 name", 2, i64), ("field3 name", 3, i64) ); datapoint!( log::Level::Error, "name", ("field1 name", 2, i64), ("field2 name", 2, i64), ("field3 name", 3, i64), ); let point = create_datapoint!( @point "name", ("i64", 1, i64), ("String", "string space string".to_string(), String), ("f64", 12.34_f64, f64), ("bool", true, bool) ); assert_eq!(point.name, "name"); assert_eq!(point.fields[0], ("i64", "1i".to_string())); assert_eq!( point.fields[1], ("String", "\"string space string\"".to_string()) ); assert_eq!(point.fields[2], ("f64", "12.34".to_string())); assert_eq!(point.fields[3], ("bool", "true".to_string())); } }
29.335025
89
0.512718
1ca31a6066b852d5b1d6eb251140b28ef9c69532
3,021
use std::{io::Read, path::Path, sync::mpsc::Receiver, time::Duration}; use gwg::{ graphics::{Font, Rect}, Context, }; use serde::de::DeserializeOwned; use crate::{error::ZError, ZResult}; pub fn time_s(s: f32) -> Duration { let ms = s * 1000.0; Duration::from_millis(ms as u64) } /// Read a file to a string. pub fn read_file<P: AsRef<Path>>(context: &mut Context, path: P) -> ZResult<String> { let mut buf = String::new(); let mut file = gwg::filesystem::open(context, path)?; file.read_to_string(&mut buf)?; Ok(buf) } pub fn deserialize_from_file<P, D>(context: &mut Context, path: P) -> ZResult<D> where P: AsRef<Path>, D: DeserializeOwned, { let path = path.as_ref(); let s = read_file(context, path)?; ron::de::from_str(&s).map_err(|e| ZError::from_ron_de_error(e, path.into())) } pub fn default_font(context: &mut Context) -> Font { Font::new(context, "/OpenSans-Regular.ttf").expect("Can't load the default font") } // TODO: Move to some config (https://github.com/ozkriff/zemeroth/issues/424) pub const fn font_size() -> f32 { 128.0 } pub struct LineHeights { pub small: f32, pub normal: f32, pub big: f32, pub large: f32, } pub fn line_heights() -> LineHeights { LineHeights { small: 1.0 / 20.0, normal: 1.0 / 12.0, big: 1.0 / 9.0, large: 1.0 / 6.0, } } pub const OFFSET_SMALL: f32 = 0.02; pub const OFFSET_BIG: f32 = 0.04; pub fn add_bg(context: &mut Context, w: Box<dyn ui::Widget>) -> ZResult<ui::LayersLayout> { let bg = ui::ColoredRect::new(context, ui::SPRITE_COLOR_BG, w.rect())?.stretchable(true); let mut layers = ui::LayersLayout::new(); layers.add(Box::new(bg)); layers.add(w); Ok(layers) } pub fn add_offsets(w: Box<dyn ui::Widget>, offset: f32) -> Box<dyn ui::Widget> { let spacer = || { ui::Spacer::new(Rect { w: offset, h: offset, ..Default::default() }) }; let mut layout_h = ui::HLayout::new().stretchable(true); layout_h.add(Box::new(spacer())); layout_h.add(w); layout_h.add(Box::new(spacer())); let mut layout_v = ui::VLayout::new().stretchable(true); layout_v.add(Box::new(spacer())); layout_v.add(Box::new(layout_h)); layout_v.add(Box::new(spacer())); Box::new(layout_v) } pub fn add_offsets_and_bg( context: &mut Context, w: Box<dyn ui::Widget>, offset: f32, ) -> ZResult<ui::LayersLayout> { add_bg(context, add_offsets(w, offset)) } pub fn add_offsets_and_bg_big( context: &mut Context, w: Box<dyn ui::Widget>, ) -> ZResult<ui::LayersLayout> { add_offsets_and_bg(context, w, OFFSET_BIG) } pub fn remove_widget<M: Clone>(gui: &mut ui::Gui<M>, widget: &mut Option<ui::RcWidget>) -> ZResult { if let Some(w) = widget.take() { gui.remove(&w)?; } Ok(()) } pub fn try_receive<Message>(opt_rx: &Option<Receiver<Message>>) -> Option<Message> { opt_rx.as_ref().and_then(|rx| rx.try_recv().ok()) }
26.5
100
0.61569
0190e74df69533e0be712482fe9fe99a24c1d78e
6,585
// 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. use hir::def::Def; use hir::def_id::DefId; use hir::{self, PatKind}; use syntax::ast; use syntax::codemap::Spanned; use syntax_pos::Span; use std::iter::{Enumerate, ExactSizeIterator}; pub struct EnumerateAndAdjust<I> { enumerate: Enumerate<I>, gap_pos: usize, gap_len: usize, } impl<I> Iterator for EnumerateAndAdjust<I> where I: Iterator { type Item = (usize, <I as Iterator>::Item); fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> { self.enumerate.next().map(|(i, elem)| { (if i < self.gap_pos { i } else { i + self.gap_len }, elem) }) } } pub trait EnumerateAndAdjustIterator { fn enumerate_and_adjust(self, expected_len: usize, gap_pos: Option<usize>) -> EnumerateAndAdjust<Self> where Self: Sized; } impl<T: ExactSizeIterator> EnumerateAndAdjustIterator for T { fn enumerate_and_adjust(self, expected_len: usize, gap_pos: Option<usize>) -> EnumerateAndAdjust<Self> where Self: Sized { let actual_len = self.len(); EnumerateAndAdjust { enumerate: self.enumerate(), gap_pos: if let Some(gap_pos) = gap_pos { gap_pos } else { expected_len }, gap_len: expected_len - actual_len, } } } impl hir::Pat { pub fn is_refutable(&self) -> bool { match self.node { PatKind::Lit(_) | PatKind::Range(..) | PatKind::Path(hir::QPath::Resolved(Some(..), _)) | PatKind::Path(hir::QPath::TypeRelative(..)) => true, PatKind::Path(hir::QPath::Resolved(_, ref path)) | PatKind::TupleStruct(hir::QPath::Resolved(_, ref path), ..) | PatKind::Struct(hir::QPath::Resolved(_, ref path), ..) => { match path.def { Def::Variant(..) | Def::VariantCtor(..) => true, _ => false } } PatKind::Slice(..) => true, _ => false } } pub fn is_const(&self) -> bool { match self.node { PatKind::Path(hir::QPath::TypeRelative(..)) => true, PatKind::Path(hir::QPath::Resolved(_, ref path)) => { match path.def { Def::Const(..) | Def::AssociatedConst(..) => true, _ => false } } _ => false } } /// Call `f` on every "binding" in a pattern, e.g., on `a` in /// `match foo() { Some(a) => (), None => () }` pub fn each_binding<F>(&self, mut f: F) where F: FnMut(hir::BindingMode, ast::NodeId, Span, &Spanned<ast::Name>), { self.walk(|p| { if let PatKind::Binding(binding_mode, _, ref pth, _) = p.node { f(binding_mode, p.id, p.span, pth); } true }); } /// Checks if the pattern contains any patterns that bind something to /// an ident, e.g. `foo`, or `Foo(foo)` or `foo @ Bar(..)`. pub fn contains_bindings(&self) -> bool { let mut contains_bindings = false; self.walk(|p| { if let PatKind::Binding(..) = p.node { contains_bindings = true; false // there's at least one binding, can short circuit now. } else { true } }); contains_bindings } /// Checks if the pattern contains any patterns that bind something to /// an ident or wildcard, e.g. `foo`, or `Foo(_)`, `foo @ Bar(..)`, pub fn contains_bindings_or_wild(&self) -> bool { let mut contains_bindings = false; self.walk(|p| { match p.node { PatKind::Binding(..) | PatKind::Wild => { contains_bindings = true; false // there's at least one binding/wildcard, can short circuit now. } _ => true } }); contains_bindings } pub fn simple_name(&self) -> Option<ast::Name> { match self.node { PatKind::Binding(hir::BindByValue(..), _, ref path1, None) => { Some(path1.node) } _ => { None } } } /// Return variants that are necessary to exist for the pattern to match. pub fn necessary_variants(&self) -> Vec<DefId> { let mut variants = vec![]; self.walk(|p| { match p.node { PatKind::Path(hir::QPath::Resolved(_, ref path)) | PatKind::TupleStruct(hir::QPath::Resolved(_, ref path), ..) | PatKind::Struct(hir::QPath::Resolved(_, ref path), ..) => { match path.def { Def::Variant(id) | Def::VariantCtor(id, ..) => variants.push(id), _ => () } } _ => () } true }); variants.sort(); variants.dedup(); variants } /// Checks if the pattern contains any `ref` or `ref mut` bindings, /// and if yes whether its containing mutable ones or just immutables ones. pub fn contains_ref_binding(&self) -> Option<hir::Mutability> { let mut result = None; self.each_binding(|mode, _, _, _| { if let hir::BindingMode::BindByRef(m) = mode { // Pick Mutable as maximum match result { None | Some(hir::MutImmutable) => result = Some(m), _ => (), } } }); result } } impl hir::Arm { /// Checks if the patterns for this arm contain any `ref` or `ref mut` /// bindings, and if yes whether its containing mutable ones or just immutables ones. pub fn contains_ref_binding(&self) -> Option<hir::Mutability> { self.pats.iter() .filter_map(|pat| pat.contains_ref_binding()) .max_by_key(|m| match *m { hir::MutMutable => 1, hir::MutImmutable => 0, }) } }
33.943299
90
0.518603
23910af22786985fe73b8ae7b04831353a8fd9cb
18,319
#[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::PUPDR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct PUPD15R { bits: u8, } impl PUPD15R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD14R { bits: u8, } impl PUPD14R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD13R { bits: u8, } impl PUPD13R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD12R { bits: u8, } impl PUPD12R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD11R { bits: u8, } impl PUPD11R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD10R { bits: u8, } impl PUPD10R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD9R { bits: u8, } impl PUPD9R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD8R { bits: u8, } impl PUPD8R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD7R { bits: u8, } impl PUPD7R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD6R { bits: u8, } impl PUPD6R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD5R { bits: u8, } impl PUPD5R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD4R { bits: u8, } impl PUPD4R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD3R { bits: u8, } impl PUPD3R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD2R { bits: u8, } impl PUPD2R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD1R { bits: u8, } impl PUPD1R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct PUPD0R { bits: u8, } impl PUPD0R { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Proxy"] pub struct _PUPD15W<'a> { w: &'a mut W, } impl<'a> _PUPD15W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 30; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD14W<'a> { w: &'a mut W, } impl<'a> _PUPD14W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 28; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD13W<'a> { w: &'a mut W, } impl<'a> _PUPD13W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 26; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD12W<'a> { w: &'a mut W, } impl<'a> _PUPD12W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD11W<'a> { w: &'a mut W, } impl<'a> _PUPD11W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 22; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD10W<'a> { w: &'a mut W, } impl<'a> _PUPD10W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 20; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD9W<'a> { w: &'a mut W, } impl<'a> _PUPD9W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 18; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD8W<'a> { w: &'a mut W, } impl<'a> _PUPD8W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD7W<'a> { w: &'a mut W, } impl<'a> _PUPD7W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 14; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD6W<'a> { w: &'a mut W, } impl<'a> _PUPD6W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 12; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD5W<'a> { w: &'a mut W, } impl<'a> _PUPD5W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 10; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD4W<'a> { w: &'a mut W, } impl<'a> _PUPD4W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 8; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD3W<'a> { w: &'a mut W, } impl<'a> _PUPD3W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PUPD2W<'a> { w: &'a mut W, } impl<'a> _PUPD2W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; 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 _PUPD1W<'a> { w: &'a mut W, } impl<'a> _PUPD1W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; 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 _PUPD0W<'a> { w: &'a mut W, } impl<'a> _PUPD0W<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 30:31 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd15(&self) -> PUPD15R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 30; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD15R { bits } } #[doc = "Bits 28:29 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd14(&self) -> PUPD14R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD14R { bits } } #[doc = "Bits 26:27 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd13(&self) -> PUPD13R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 26; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD13R { bits } } #[doc = "Bits 24:25 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd12(&self) -> PUPD12R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD12R { bits } } #[doc = "Bits 22:23 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd11(&self) -> PUPD11R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 22; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD11R { bits } } #[doc = "Bits 20:21 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd10(&self) -> PUPD10R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD10R { bits } } #[doc = "Bits 18:19 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd9(&self) -> PUPD9R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD9R { bits } } #[doc = "Bits 16:17 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd8(&self) -> PUPD8R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD8R { bits } } #[doc = "Bits 14:15 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd7(&self) -> PUPD7R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD7R { bits } } #[doc = "Bits 12:13 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd6(&self) -> PUPD6R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD6R { bits } } #[doc = "Bits 10:11 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd5(&self) -> PUPD5R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD5R { bits } } #[doc = "Bits 8:9 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd4(&self) -> PUPD4R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD4R { bits } } #[doc = "Bits 6:7 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd3(&self) -> PUPD3R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD3R { bits } } #[doc = "Bits 4:5 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd2(&self) -> PUPD2R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD2R { bits } } #[doc = "Bits 2:3 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd1(&self) -> PUPD1R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD1R { bits } } #[doc = "Bits 0:1 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd0(&self) -> PUPD0R { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; PUPD0R { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 603979776 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 30:31 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd15(&mut self) -> _PUPD15W { _PUPD15W { w: self } } #[doc = "Bits 28:29 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd14(&mut self) -> _PUPD14W { _PUPD14W { w: self } } #[doc = "Bits 26:27 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd13(&mut self) -> _PUPD13W { _PUPD13W { w: self } } #[doc = "Bits 24:25 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd12(&mut self) -> _PUPD12W { _PUPD12W { w: self } } #[doc = "Bits 22:23 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd11(&mut self) -> _PUPD11W { _PUPD11W { w: self } } #[doc = "Bits 20:21 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd10(&mut self) -> _PUPD10W { _PUPD10W { w: self } } #[doc = "Bits 18:19 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd9(&mut self) -> _PUPD9W { _PUPD9W { w: self } } #[doc = "Bits 16:17 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd8(&mut self) -> _PUPD8W { _PUPD8W { w: self } } #[doc = "Bits 14:15 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd7(&mut self) -> _PUPD7W { _PUPD7W { w: self } } #[doc = "Bits 12:13 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd6(&mut self) -> _PUPD6W { _PUPD6W { w: self } } #[doc = "Bits 10:11 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd5(&mut self) -> _PUPD5W { _PUPD5W { w: self } } #[doc = "Bits 8:9 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd4(&mut self) -> _PUPD4W { _PUPD4W { w: self } } #[doc = "Bits 6:7 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd3(&mut self) -> _PUPD3W { _PUPD3W { w: self } } #[doc = "Bits 4:5 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd2(&mut self) -> _PUPD2W { _PUPD2W { w: self } } #[doc = "Bits 2:3 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd1(&mut self) -> _PUPD1W { _PUPD1W { w: self } } #[doc = "Bits 0:1 - Port x configuration bits (y = 0..15)"] #[inline] pub fn pupd0(&mut self) -> _PUPD0W { _PUPD0W { w: self } } }
25.407767
65
0.491075
e96139f9085885753cb1f43d9ce3a00d301b9366
2,091
#[doc = "Reader of register US_IMR_LON_SPI_MODE"] pub type R = crate::R<u32, super::US_IMR_LON_SPI_MODE>; #[doc = "Reader of field `RXRDY`"] pub type RXRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `TXRDY`"] pub type TXRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `OVRE`"] pub type OVRE_R = crate::R<bool, bool>; #[doc = "Reader of field `TXEMPTY`"] pub type TXEMPTY_R = crate::R<bool, bool>; #[doc = "Reader of field `RIIC`"] pub type RIIC_R = crate::R<bool, bool>; #[doc = "Reader of field `DSRIC`"] pub type DSRIC_R = crate::R<bool, bool>; #[doc = "Reader of field `DCDIC`"] pub type DCDIC_R = crate::R<bool, bool>; #[doc = "Reader of field `UNRE`"] pub type UNRE_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - RXRDY Interrupt Mask"] #[inline(always)] pub fn rxrdy(&self) -> RXRDY_R { RXRDY_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - TXRDY Interrupt Mask"] #[inline(always)] pub fn txrdy(&self) -> TXRDY_R { TXRDY_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 5 - Overrun Error Interrupt Mask"] #[inline(always)] pub fn ovre(&self) -> OVRE_R { OVRE_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 9 - TXEMPTY Interrupt Mask"] #[inline(always)] pub fn txempty(&self) -> TXEMPTY_R { TXEMPTY_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 16 - Ring Indicator Input Change Mask"] #[inline(always)] pub fn riic(&self) -> RIIC_R { RIIC_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - Data Set Ready Input Change Mask"] #[inline(always)] pub fn dsric(&self) -> DSRIC_R { DSRIC_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - Data Carrier Detect Input Change Interrupt Mask"] #[inline(always)] pub fn dcdic(&self) -> DCDIC_R { DCDIC_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 10 - SPI Underrun Error Interrupt Mask"] #[inline(always)] pub fn unre(&self) -> UNRE_R { UNRE_R::new(((self.bits >> 10) & 0x01) != 0) } }
34.278689
71
0.571975
5bc7d00fbdc65fbdca7ca9362e92146be0f4f9af
572
/// Converts String types to boolean types /// /// # Examples /// /// ``` /// let x: bool = str_to_bool("Y".to_string()) /// ``` pub fn str_to_bool(x: String) -> bool { match x.as_ref() { "Y" => true, _ => false, } } #[cfg(test)] mod tests { use super::*; #[test] fn test_str_to_bool() { assert_eq!(true, str_to_bool("Y".to_string())); assert_eq!(false, str_to_bool("N".to_string())); assert_eq!(false, str_to_bool("".to_string())); assert_eq!(false, str_to_bool("Hello, world!".to_string())); } }
21.185185
68
0.545455
09d134c0d0c32c6eb61ee12731a905f392c52423
6,709
//! Connection pooling via r2d2. //! //! Note: This module requires enabling the `r2d2` feature extern crate r2d2; pub use self::r2d2::*; /// A re-export of [`r2d2::Error`], which is only used by methods on [`r2d2::Pool`]. /// /// [`r2d2::Error`]: ../../r2d2/struct.Error.html /// [`r2d2::Pool`]: ../../r2d2/struct.Pool.html pub type PoolError = self::r2d2::Error; use std::convert::Into; use std::fmt; use std::marker::PhantomData; use crate::backend::UsesAnsiSavepointSyntax; use crate::connection::{AnsiTransactionManager, SimpleConnection}; use crate::deserialize::{Queryable, QueryableByName}; use crate::prelude::*; use crate::query_builder::{AsQuery, QueryFragment, QueryId}; use crate::sql_types::HasSqlType; /// An r2d2 connection manager for use with Diesel. /// /// See the [r2d2 documentation] for usage examples. /// /// [r2d2 documentation]: ../../r2d2 #[derive(Debug, Clone)] pub struct ConnectionManager<T> { database_url: String, _marker: PhantomData<T>, } unsafe impl<T: Send + 'static> Sync for ConnectionManager<T> {} impl<T> ConnectionManager<T> { /// Returns a new connection manager, /// which establishes connections to the given database URL. pub fn new<S: Into<String>>(database_url: S) -> Self { ConnectionManager { database_url: database_url.into(), _marker: PhantomData, } } } /// The error used when managing connections with `r2d2`. #[derive(Debug)] pub enum Error { /// An error occurred establishing the connection ConnectionError(ConnectionError), /// An error occurred pinging the database QueryError(crate::result::Error), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::ConnectionError(ref e) => e.fmt(f), Error::QueryError(ref e) => e.fmt(f), } } } impl ::std::error::Error for Error {} /// A trait indicating a connection could be used inside a r2d2 pool pub trait R2D2Connection: Connection { /// Check if a connection is still valid fn ping(&self) -> QueryResult<()>; } #[cfg(feature = "postgres")] impl R2D2Connection for crate::pg::PgConnection { fn ping(&self) -> QueryResult<()> { self.execute("SELECT 1").map(|_| ()) } } #[cfg(feature = "mysql")] impl R2D2Connection for crate::mysql::MysqlConnection { fn ping(&self) -> QueryResult<()> { self.execute("SELECT 1").map(|_| ()) } } #[cfg(feature = "sqlite")] impl R2D2Connection for crate::sqlite::SqliteConnection { fn ping(&self) -> QueryResult<()> { self.execute("SELECT 1").map(|_| ()) } } impl<T> ManageConnection for ConnectionManager<T> where T: R2D2Connection + Send + 'static, { type Connection = T; type Error = Error; fn connect(&self) -> Result<T, Error> { T::establish(&self.database_url).map_err(Error::ConnectionError) } fn is_valid(&self, conn: &mut T) -> Result<(), Error> { conn.ping().map_err(Error::QueryError) } fn has_broken(&self, _conn: &mut T) -> bool { false } } impl<M> SimpleConnection for PooledConnection<M> where M: ManageConnection, M::Connection: R2D2Connection + Send + 'static, { fn batch_execute(&self, query: &str) -> QueryResult<()> { (&**self).batch_execute(query) } } impl<M> Connection for PooledConnection<M> where M: ManageConnection, M::Connection: Connection<TransactionManager = AnsiTransactionManager> + R2D2Connection + Send + 'static, <M::Connection as Connection>::Backend: UsesAnsiSavepointSyntax, { type Backend = <M::Connection as Connection>::Backend; type TransactionManager = <M::Connection as Connection>::TransactionManager; fn establish(_: &str) -> ConnectionResult<Self> { Err(ConnectionError::BadConnection(String::from( "Cannot directly establish a pooled connection", ))) } fn execute(&self, query: &str) -> QueryResult<usize> { (&**self).execute(query) } fn query_by_index<T, U>(&self, source: T) -> QueryResult<Vec<U>> where T: AsQuery, T::Query: QueryFragment<Self::Backend> + QueryId, Self::Backend: HasSqlType<T::SqlType>, U: Queryable<T::SqlType, Self::Backend>, { (&**self).query_by_index(source) } fn query_by_name<T, U>(&self, source: &T) -> QueryResult<Vec<U>> where T: QueryFragment<Self::Backend> + QueryId, U: QueryableByName<Self::Backend>, { (&**self).query_by_name(source) } fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize> where T: QueryFragment<Self::Backend> + QueryId, { (&**self).execute_returning_count(source) } fn transaction_manager(&self) -> &Self::TransactionManager { (&**self).transaction_manager() } } #[cfg(test)] mod tests { use std::sync::mpsc; use std::sync::Arc; use std::thread; use crate::r2d2::*; use crate::test_helpers::*; #[test] fn establish_basic_connection() { let manager = ConnectionManager::<TestConnection>::new(database_url()); let pool = Arc::new(Pool::builder().max_size(2).build(manager).unwrap()); let (s1, r1) = mpsc::channel(); let (s2, r2) = mpsc::channel(); let pool1 = Arc::clone(&pool); let t1 = thread::spawn(move || { let conn = pool1.get().unwrap(); s1.send(()).unwrap(); r2.recv().unwrap(); drop(conn); }); let pool2 = Arc::clone(&pool); let t2 = thread::spawn(move || { let conn = pool2.get().unwrap(); s2.send(()).unwrap(); r1.recv().unwrap(); drop(conn); }); t1.join().unwrap(); t2.join().unwrap(); pool.get().unwrap(); } #[test] fn is_valid() { let manager = ConnectionManager::<TestConnection>::new(database_url()); let pool = Pool::builder() .max_size(1) .test_on_check_out(true) .build(manager) .unwrap(); pool.get().unwrap(); } #[test] fn pooled_connection_impls_connection() { use crate::select; use crate::sql_types::Text; let manager = ConnectionManager::<TestConnection>::new(database_url()); let pool = Pool::builder() .max_size(1) .test_on_check_out(true) .build(manager) .unwrap(); let conn = pool.get().unwrap(); let query = select("foo".into_sql::<Text>()); assert_eq!("foo", query.get_result::<String>(&conn).unwrap()); } }
27.272358
98
0.602474
118b16e5913eca6ce65a522caf4f32f875977a2f
76,986
use crate::extra::rust_logo::build_logo_path; use crate::math::*; use crate::geometry_builder::*; use crate::path::builder::PathBuilder; use crate::path::{Path, PathSlice}; use crate::{FillVertex, FillOptions, FillRule, FillTessellator, TessellationError, VertexId}; use std::env; fn tessellate(path: PathSlice, fill_rule: FillRule, log: bool) -> Result<usize, TessellationError> { let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); { let options = FillOptions::tolerance(0.05) .with_fill_rule(fill_rule); use crate::path::iterator::*; let mut builder = Path::builder(); for e in path.iter().flattened(0.05) { builder.path_event(e); } let mut vertex_builder = simple_builder(&mut buffers); let mut tess = FillTessellator::new(); tess.set_logging(log); tess.tessellate(&builder.build(), &options, &mut vertex_builder)?; } return Ok(buffers.indices.len() / 3); } #[test] fn test_too_many_vertices() { /// This test checks that the tessellator returns the proper error when /// the geometry builder run out of vertex ids. struct Builder { max_vertices: u32, } impl GeometryBuilder for Builder { fn begin_geometry(&mut self) {} fn add_triangle(&mut self, _a: VertexId, _b: VertexId, _c: VertexId) {} fn end_geometry(&mut self) -> Count { Count { vertices: 0, indices: 0, } } fn abort_geometry(&mut self) {} } impl FillGeometryBuilder for Builder { fn add_fill_vertex( &mut self, _: FillVertex, ) -> Result<VertexId, GeometryBuilderError> { if self.max_vertices == 0 { return Err(GeometryBuilderError::TooManyVertices); } self.max_vertices -= 1; Ok(VertexId(self.max_vertices)) } } let mut path = Path::builder().with_svg(); build_logo_path(&mut path); let path = path.build(); let mut tess = FillTessellator::new(); let options = FillOptions::tolerance(0.05); assert_eq!( tess.tessellate(&path, &options, &mut Builder { max_vertices: 0 }), Err(TessellationError::TooManyVertices), ); assert_eq!( tess.tessellate(&path, &options, &mut Builder { max_vertices: 10 }), Err(TessellationError::TooManyVertices), ); assert_eq!( tess.tessellate(&path, &options, &mut Builder { max_vertices: 100 }), Err(TessellationError::TooManyVertices), ); } fn test_path(path: PathSlice) { test_path_internal(path, FillRule::EvenOdd, None); test_path_internal(path, FillRule::NonZero, None); } fn test_path_and_count_triangles(path: PathSlice, expected_triangle_count: usize) { test_path_internal(path, FillRule::EvenOdd, Some(expected_triangle_count)); test_path_internal(path, FillRule::NonZero, None); } fn test_path_internal(path: PathSlice, fill_rule: FillRule, expected_triangle_count: Option<usize>) { let add_logging = env::var("LYON_ENABLE_LOGGING").is_ok(); let find_test_case = env::var("LYON_REDUCED_TESTCASE").is_ok(); let res = if find_test_case { ::std::panic::catch_unwind(|| tessellate(path, fill_rule, false)) } else { Ok(tessellate(path, fill_rule, false)) }; if let Ok(Ok(num_triangles)) = res { if let Some(expected_triangles) = expected_triangle_count { if num_triangles != expected_triangles { tessellate(path, fill_rule, add_logging).unwrap(); panic!( "expected {} triangles, got {}", expected_triangles, num_triangles ); } } return; } if find_test_case { crate::extra::debugging::find_reduced_test_case(path, &|path: Path| { return tessellate(path.as_slice(), fill_rule, false).is_err(); }); } if add_logging { tessellate(path, fill_rule, true).unwrap(); } panic!("Test failed with fill rule {:?}.", fill_rule); } fn test_path_with_rotations(path: Path, step: f32, expected_triangle_count: Option<usize>) { use std::f32::consts::PI; let mut angle = Angle::radians(0.0); while angle.radians < PI * 2.0 { //println!("\n\n ==================== angle = {:?}", angle); let tranformed_path = path.clone().transformed(&Rotation::new(angle)); test_path_internal(tranformed_path.as_slice(), FillRule::EvenOdd, expected_triangle_count); test_path_internal(tranformed_path.as_slice(), FillRule::NonZero, None); angle.radians += step; } } #[test] fn test_simple_triangle() { let mut path = Path::builder(); path.begin(point(0.0, 0.0)); path.line_to(point(1.0, 1.0)); path.line_to(point(0.0, 1.0)); path.end(true); test_path_with_rotations(path.build(), 0.01, Some(1)); } #[test] fn test_simple_monotone() { let mut path = Path::builder(); path.begin(point(0.0, 0.0)); path.line_to(point(-1.0, 1.0)); path.line_to(point(-3.0, 2.0)); path.line_to(point(-1.0, 3.0)); path.line_to(point(-4.0, 5.0)); path.line_to(point(0.0, 6.0)); path.end(true); let path = path.build(); test_path_and_count_triangles(path.as_slice(), 4); } #[test] fn test_simple_split() { let mut path = Path::builder(); path.begin(point(0.0, 0.0)); path.line_to(point(2.0, 1.0)); path.line_to(point(2.0, 3.0)); path.line_to(point(1.0, 2.0)); path.line_to(point(0.0, 3.0)); path.end(true); test_path_with_rotations(path.build(), 0.001, Some(3)); } #[test] fn test_simple_merge_split() { let mut path = Path::builder(); path.begin(point(0.0, 0.0)); path.line_to(point(1.0, 1.0)); path.line_to(point(2.0, 0.0)); path.line_to(point(2.0, 3.0)); path.line_to(point(1.0, 2.0)); path.line_to(point(0.0, 3.0)); path.end(true); test_path_with_rotations(path.build(), 0.001, Some(4)); // "M 0 0 L 1 1 L 2 0 L 1 3 L 0 4 L 0 3 Z" } #[test] fn test_simple_aligned() { let mut path = Path::builder(); path.begin(point(0.0, 0.0)); path.line_to(point(1.0, 0.0)); path.line_to(point(2.0, 0.0)); path.line_to(point(2.0, 1.0)); path.line_to(point(2.0, 2.0)); path.line_to(point(1.0, 2.0)); path.line_to(point(0.0, 2.0)); path.line_to(point(0.0, 1.0)); path.end(true); test_path_with_rotations(path.build(), 0.001, Some(6)); } #[test] fn test_simple_1() { let mut path = Path::builder(); path.begin(point(0.0, 0.0)); path.line_to(point(1.0, 1.0)); path.line_to(point(2.0, 0.0)); path.line_to(point(1.0, 3.0)); path.line_to(point(0.5, 4.0)); path.line_to(point(0.0, 3.0)); path.end(true); test_path_with_rotations(path.build(), 0.001, Some(4)); // "M 0 0 L 1 1 L 2 0 L 1 3 L 0 4 L 0 3 Z" } #[test] fn test_simple_2() { let mut path = Path::builder(); path.begin(point(0.0, 0.0)); path.line_to(point(1.0, 0.0)); path.line_to(point(2.0, 0.0)); path.line_to(point(3.0, 0.0)); path.line_to(point(3.0, 1.0)); path.line_to(point(3.0, 2.0)); path.line_to(point(3.0, 3.0)); path.line_to(point(2.0, 3.0)); path.line_to(point(1.0, 3.0)); path.line_to(point(0.0, 3.0)); path.line_to(point(0.0, 2.0)); path.line_to(point(0.0, 1.0)); path.end(true); test_path_with_rotations(path.build(), 0.001, Some(10)); } #[test] fn test_hole_1() { let mut path = Path::builder(); path.begin(point(-11.0, 5.0)); path.line_to(point(0.0, -5.0)); path.line_to(point(10.0, 5.0)); path.end(true); path.begin(point(-5.0, 2.0)); path.line_to(point(0.0, -2.0)); path.line_to(point(4.0, 2.0)); path.end(true); test_path_with_rotations(path.build(), 0.001, Some(6)); } #[test] fn test_degenerate_same_position() { let mut path = Path::builder(); path.begin(point(0.0, 0.0)); path.line_to(point(0.0, 0.0)); path.line_to(point(0.0, 0.0)); path.line_to(point(0.0, 0.0)); path.line_to(point(0.0, 0.0)); path.line_to(point(0.0, 0.0)); path.end(true); test_path_with_rotations(path.build(), 0.001, None); } #[test] fn test_intersecting_bow_tie() { // Simple self-intersecting shape. // x x // |\/| // |/\| // x x let mut path = Path::builder(); path.begin(point(0.0, 0.0)); path.line_to(point(2.0, 2.0)); path.line_to(point(2.0, 0.0)); path.line_to(point(0.0, 2.0)); path.end(true); test_path(path.build().as_slice()); } #[test] fn test_auto_intersection_type1() { // o.___ // \ 'o // \ / // x <-- intersection! // / \ // o.___\ // 'o let mut path = Path::builder(); path.begin(point(0.0, 0.0)); path.line_to(point(2.0, 1.0)); path.line_to(point(0.0, 2.0)); path.line_to(point(2.0, 3.0)); path.end(true); let path = path.build(); test_path_and_count_triangles(path.as_slice(), 2); } #[test] fn test_auto_intersection_type2() { // o // |\ ,o // | \ / | // | x | <-- intersection! // | / \ | // o' \| // o let mut path = Path::builder(); path.begin(point(0.0, 0.0)); path.line_to(point(2.0, 3.0)); path.line_to(point(2.0, 1.0)); path.line_to(point(0.0, 2.0)); path.end(true); let path = path.build(); test_path_and_count_triangles(path.as_slice(), 2); } #[test] fn test_auto_intersection_multi() { // . // ___/_\___ // | / \ | // |/ \| // /| |\ // \| |/ // |\ /| // |_\___/_| // \ / // ' let mut path = Path::builder(); path.begin(point(20.0, 20.0)); path.line_to(point(60.0, 20.0)); path.line_to(point(60.0, 60.0)); path.line_to(point(20.0, 60.0)); path.end(true); path.begin(point(40.0, 10.0)); path.line_to(point(70.0, 40.0)); path.line_to(point(40.0, 70.0)); path.line_to(point(10.0, 40.0)); path.end(true); let path = path.build(); test_path_with_rotations(path, 0.011, Some(8)); } #[test] fn three_edges_below() { let mut builder = Path::builder(); // . // /| // / | // x | // /|\ | // / | \| // /__| . builder.begin(point(1.0, 0.0)); builder.line_to(point(0.0, 1.0)); builder.line_to(point(2.0, 2.0)); builder.end(true); builder.begin(point(1.0, 0.0)); builder.line_to(point(-1.0, 2.0)); builder.line_to(point(0.0, 1.0)); builder.line_to(point(0.0, 2.0)); builder.end(true); test_path(builder.build().as_slice()); } #[test] fn test_rust_logo_no_intersection() { let mut path = Path::builder().flattened(0.011).with_svg(); build_logo_path(&mut path); test_path_with_rotations(path.build(), 0.011, None); } #[test] fn test_rust_logo_with_intersection() { let mut path = Path::builder().flattened(0.011).with_svg(); build_logo_path(&mut path); path.move_to(point(10.0, 30.0)); path.line_to(point(130.0, 30.0)); path.line_to(point(130.0, 60.0)); path.line_to(point(10.0, 60.0)); path.close(); let path = path.build(); test_path_with_rotations(path, 0.011, None); } #[cfg(test)] fn scale_path(path: &mut Path, scale: f32) { *path = path.clone().transformed(&Scale::new(scale)) } #[test] fn test_rust_logo_scale_up() { // The goal of this test is to check how resistant the tessellator is against integer // overflows, and catch regressions. let mut builder = Path::builder().with_svg(); build_logo_path(&mut builder); let mut path = builder.build(); scale_path(&mut path, 260.0); test_path(path.as_slice()); } #[test] fn test_rust_logo_scale_down() { // The goal of this test is to check that the tessellator can handle very small geometry. let mut builder = Path::builder().flattened(0.011).with_svg(); build_logo_path(&mut builder); let mut path = builder.build(); scale_path(&mut path, 0.005); test_path(path.as_slice()); } #[test] fn test_rust_logo_scale_down2() { // Issues with very small paths. let mut builder = Path::builder().flattened(0.011).with_svg(); build_logo_path(&mut builder); let mut path = builder.build(); scale_path(&mut path, 0.0000001); test_path(path.as_slice()); } #[test] fn test_simple_double_merge() { // This test triggers the code path where a merge event is resolved during another // merge event. // / \ / // \ / .-x <-- merge vertex // x-' <-- current merge vertex let mut path = Path::builder(); path.begin(point(0.0, 2.0)); path.line_to(point(1.0, 3.0)); path.line_to(point(2.0, 0.0)); path.line_to(point(3.0, 2.0)); path.line_to(point(4.0, 1.0)); path.line_to(point(2.0, 6.0)); path.end(true); // "M 0 2 L 1 3 L 2 0 L 3 2 L 4 1 L 2 6 Z" } #[test] fn test_double_merge_with_intersection() { // This test triggers the code path where a merge event is resolved during another // merge event. // / \ / // \ / .-x <-- merge vertex // x-' <-- current merge vertex // // The test case generated from a reduced rotation of // test_rust_logo_with_intersection and has a self-intersection. let mut path = Path::builder(); path.begin(point(80.041534, 19.24472)); path.line_to(point(76.56131, 23.062233)); path.line_to(point(67.26949, 23.039438)); path.line_to(point(65.989944, 23.178522)); path.line_to(point(59.90927, 19.969215)); path.line_to(point(56.916714, 25.207449)); path.line_to(point(50.333813, 23.25274)); path.line_to(point(48.42367, 28.978098)); path.end(true); path.begin(point(130.32213, 28.568213)); path.line_to(point(130.65213, 58.5664)); path.line_to(point(10.659382, 59.88637)); path.end(true); test_path(path.build().as_slice()); // "M 80.041534 19.24472 L 76.56131 23.062233 L 67.26949 23.039438 L 65.989944 23.178522 L 59.90927 19.969215 L 56.916714 25.207449 L 50.333813 23.25274 L 48.42367 28.978098 M 130.32213, 28.568213 L 130.65213 58.5664 L 10.659382 59.88637 Z" } #[test] fn test_chained_merge_end() { // This test creates a succession of merge events that need to be resolved during // an end event. // |\/\ /\ /| <-- merge // \ \/ \ / / <-- merge // \ \/ / <-- merge // \ / // \ / // \ / // \ / // \/ < -- end let mut path = Path::builder(); path.begin(point(1.0, 0.0)); path.line_to(point(2.0, 1.0)); // <-- merge path.line_to(point(3.0, 0.0)); path.line_to(point(4.0, 2.0)); // <-- merge path.line_to(point(5.0, 0.0)); path.line_to(point(6.0, 3.0)); // <-- merge path.line_to(point(7.0, 0.0)); path.line_to(point(5.0, 8.0)); // <-- end path.end(true); test_path_and_count_triangles(path.build().as_slice(), 6); } #[test] fn test_chained_merge_left() { // This test creates a succession of merge events that need to be resolved during // a left event. // |\/\ /\ /| <-- merge // | \/ \ / | <-- merge // | \/ | <-- merge // | | // \ | <-- left // \ | let mut path = Path::builder(); path.begin(point(1.0, 0.0)); path.line_to(point(2.0, 1.0)); // <-- merge path.line_to(point(3.0, 0.0)); path.line_to(point(4.0, 2.0)); // <-- merge path.line_to(point(5.0, 0.0)); path.line_to(point(6.0, 3.0)); // <-- merge path.line_to(point(7.0, 0.0)); path.line_to(point(7.0, 5.0)); path.line_to(point(0.0, 4.0)); // <-- left path.end(true); test_path_and_count_triangles(path.build().as_slice(), 7); } #[test] fn test_chained_merge_merge() { // This test creates a succession of merge events that need to be resolved during // another merge event. // /\/\ /\ /| <-- merge // / \/ \ / | <-- merge // / \/ | <-- merge // |\/ | <-- merge (resolving) // |_________________| let mut path = Path::builder(); path.begin(point(1.0, 0.0)); path.line_to(point(2.0, 1.0)); // <-- merge path.line_to(point(3.0, 0.0)); path.line_to(point(4.0, 2.0)); // <-- merge path.line_to(point(5.0, 0.0)); path.line_to(point(6.0, 3.0)); // <-- merge path.line_to(point(7.0, 0.0)); path.line_to(point(7.0, 5.0)); path.line_to(point(-1.0, 5.0)); path.line_to(point(-1.0, 0.0)); path.line_to(point(0.0, 4.0)); // <-- merge (resolving) path.end(true); test_path_and_count_triangles(path.build().as_slice(), 9); } #[test] fn test_chained_merge_split() { // This test creates a succession of merge events that need to be resolved during // a split event. // |\/\ /\ /| <-- merge // | \/ \ / | <-- merge // | \/ | <-- merge // | | // | /\ | <-- split let mut path = Path::builder(); path.begin(point(1.0, 0.0)); path.line_to(point(2.0, 1.0)); // <-- merge path.line_to(point(3.0, 0.0)); path.line_to(point(4.0, 2.0)); // <-- merge path.line_to(point(5.0, 0.0)); path.line_to(point(6.0, 3.0)); // <-- merge path.line_to(point(7.0, 0.0)); path.line_to(point(7.0, 5.0)); path.line_to(point(4.0, 4.0)); // <-- split path.line_to(point(1.0, 5.0)); path.end(true); test_path_and_count_triangles(path.build().as_slice(), 8); // "M 1 0 L 2 1 L 3 0 L 4 2 L 5 0 L 6 3 L 7 0 L 7 5 L 4 4 L 1 5 Z" } // TODO: Check that chained merge events can't mess with the way we handle complex events. #[test] fn test_intersection_horizontal_precision() { // TODO make a cleaner test case exercising the same edge case. // This test has an almost horizontal segment e1 going from right to left intersected // by another segment e2. Since e1 is almost horizontal the intersection point ends up // with the same y coordinate and at the left of the current position when it is found. // The difficulty is that the intersection is therefore technically "above" the current // position, but we can't allow that because the ordering of the events is a strong // invariant of the algorithm. let mut builder = Path::builder(); builder.begin(point(-34.619564, 111.88655)); builder.line_to(point(-35.656174, 111.891)); builder.line_to(point(-39.304527, 121.766914)); builder.end(true); builder.begin(point(1.4426613, 133.40884)); builder.line_to(point(-27.714422, 140.47032)); builder.line_to(point(-55.960342, 23.841988)); builder.end(true); test_path(builder.build().as_slice()); } #[test] fn test_overlapping_with_intersection() { // There are two overlapping segments a-b and b-a intersecting a segment // c-d. // This test used to fail until overlapping edges got dealt with before // intersection detection. The issue was that the one of the overlapping // edges would intersect properly and the second would end up in the degenerate // case where it would pass though a pain between two segments without // registering as an intersection. // // a // / | \ // c--|--d // | // b let mut builder = Path::builder(); builder.begin(point(2.0, -1.0)); builder.line_to(point(2.0, -3.0)); builder.line_to(point(3.0, -2.0)); builder.line_to(point(1.0, -2.0)); builder.line_to(point(2.0, -3.0)); builder.end(true); test_path(builder.build().as_slice()); } #[test] fn test_split_with_intersections() { // This is a reduced test case that was showing a bug where duplicate intersections // were found during a split event, due to the sweep line beeing into a temporarily // inconsistent state when insert_edge was called. let mut builder = Path::builder(); builder.begin(point(-21.004179, -71.57515)); builder.line_to(point(-21.927473, -70.94977)); builder.line_to(point(-23.024633, -70.68942)); builder.end(true); builder.begin(point(16.036617, -27.254852)); builder.line_to(point(-62.83691, -117.69249)); builder.line_to(point(38.646027, -46.973236)); builder.end(true); let path = builder.build(); test_path(path.as_slice()); } #[test] fn test_colinear_1() { let mut builder = Path::builder(); builder.begin(point(20.0, 150.0)); builder.line_to(point(80.0, 150.0)); builder.end(true); let path = builder.build(); test_path_with_rotations(path, 0.01, None); } #[test] fn test_colinear_2() { let mut builder = Path::builder(); builder.begin(point(20.0, 150.0)); builder.line_to(point(80.0, 150.0)); builder.line_to(point(20.0, 150.0)); builder.end(true); let path = builder.build(); test_path_with_rotations(path, 0.01, None); } #[test] fn test_colinear_3() { let mut builder = Path::builder(); // The path goes through many points along a line. builder.begin(point(0.0, 1.0)); builder.line_to(point(0.0, 3.0)); builder.line_to(point(0.0, 5.0)); builder.line_to(point(0.0, 4.0)); builder.line_to(point(0.0, 2.0)); builder.end(true); let path = builder.build(); test_path(path.as_slice()); } #[test] fn test_colinear_4() { // The path goes back and forth along a line. let mut builder = Path::builder(); builder.begin(point(0.0, 2.0)); builder.line_to(point(0.0, 1.0)); builder.line_to(point(0.0, 3.0)); builder.line_to(point(0.0, 0.0)); builder.end(true); let path = builder.build(); test_path(path.as_slice()); } #[test] fn test_colinear_touching_squares() { // Two squares touching. // // x-----x-----x // | | | // | | | // x-----x-----x // let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(1.0, 0.0)); builder.line_to(point(1.0, 1.0)); builder.line_to(point(0.0, 1.0)); builder.end(true); builder.begin(point(1.0, 0.0)); builder.line_to(point(2.0, 0.0)); builder.line_to(point(2.0, 1.0)); builder.line_to(point(1.0, 1.0)); builder.end(true); let path = builder.build(); test_path(path.as_slice()); } #[test] fn angle_precision() { // This test case has some edges that are almost parallel and the // imprecision of the angle computation causes them to be in the // wrong order in the sweep line. let mut builder = Path::builder(); builder.begin(point(0.007982401, 0.0121872)); builder.line_to(point(0.008415101, 0.0116545)); builder.line_to(point(0.008623006, 0.011589845)); builder.line_to(point(0.008464893, 0.011639819)); builder.line_to(point(0.0122631, 0.0069716)); builder.end(true); test_path(builder.build().as_slice()); } #[test] fn n_segments_intersecting() { use std::f32::consts::PI; // This test creates a lot of segments that intersect at the same // position (center). Very good at finding precision issues. for i in 1..10 { let mut builder = Path::builder(); let center = point(-2.0, -5.0); let n = i * 4 - 1; let delta = PI / n as f32; let mut radius = 1000.0; builder.begin(center + vector(radius, 0.0)); builder.line_to(center - vector(-radius, 0.0)); for i in 0..n { let (s, c) = (i as f32 * delta).sin_cos(); builder.line_to(center + vector(c, s) * radius); builder.line_to(center - vector(c, s) * radius); radius = -radius; } builder.end(true); test_path_with_rotations(builder.build(), 0.03, None); } } #[test] fn back_along_previous_edge() { // This test has edges that come back along the previous edge. let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(1.0, 1.0)); builder.line_to(point(0.8, 0.8)); builder.line_to(point(1.5, 1.5)); builder.end(true); test_path(builder.build().as_slice()); } #[test] fn test_colinear_touching_squares2() { // Two squares touching. // // x-----x // | x-----x // | | | // x-----x | // x-----x // let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(10.0, 0.0)); builder.line_to(point(10.0, 10.0)); builder.line_to(point(0.0, 10.0)); builder.end(true); builder.begin(point(10.0, 1.0)); builder.line_to(point(20.0, 1.0)); builder.line_to(point(20.0, 11.0)); builder.line_to(point(10.0, 11.0)); builder.end(true); let path = builder.build(); test_path(path.as_slice()); } #[test] fn test_colinear_touching_squares3() { // Two squares touching. // // x-----x // x-----x | // | | | // | x-----x // x-----x // let mut builder = Path::builder(); builder.begin(point(0.0, 1.0)); builder.line_to(point(10.0, 1.0)); builder.line_to(point(10.0, 11.0)); builder.line_to(point(0.0, 11.0)); builder.end(true); builder.begin(point(10.0, 0.0)); builder.line_to(point(20.0, 0.0)); builder.line_to(point(20.0, 10.0)); builder.line_to(point(10.0, 10.0)); builder.end(true); let path = builder.build(); test_path(path.as_slice()); } #[test] fn test_unknown_issue_1() { // This test case used to fail but does not fail anymore, probably thanks to // the fixed-to-f32 workaround (cf.) test_fixed_to_f32_precision. // TODO: figure out what the issue was and what fixed it. let mut builder = Path::builder(); builder.begin(point(-3.3709216, 9.467676)); builder.line_to(point(-13.078612, 7.0675235)); builder.line_to(point(-10.67846, -2.6401677)); builder.end(true); builder.begin(point(-4.800305, 19.415382)); builder.line_to(point(-14.507996, 17.01523)); builder.line_to(point(-12.107843, 7.307539)); builder.end(true); test_path(builder.build().as_slice()); } #[test] fn test_colinear_touching_squares_rotated() { // Two squares touching. // // x-----x // x-----x | // | | | // | x-----x // x-----x // let mut builder = Path::builder(); builder.begin(point(0.0, 1.0)); builder.line_to(point(10.0, 1.0)); builder.line_to(point(10.0, 11.0)); builder.line_to(point(0.0, 11.0)); builder.end(true); builder.begin(point(10.0, 0.0)); builder.line_to(point(20.0, 0.0)); builder.line_to(point(20.0, 10.0)); builder.line_to(point(10.0, 10.0)); builder.end(true); let path = builder.build(); test_path_with_rotations(path, 0.01, None) } #[test] fn test_point_on_edge_right() { // a // /| // / x <--- point exactly on edge ab // / /|\ // x-' | \ // b--x // let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(0.0, 100.0)); builder.line_to(point(50.0, 100.0)); builder.line_to(point(0.0, 50.0)); builder.line_to(point(-50.0, 100.0)); builder.end(true); let path = builder.build(); test_path(path.as_slice()); } #[test] fn test_point_on_edge_left() { // a // |\ // x \ <--- point exactly on edge ab // /|\ \ // / | `-x // x--b // let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(0.0, 100.0)); builder.line_to(point(-50.0, 100.0)); builder.line_to(point(0.0, 50.0)); builder.line_to(point(50.0, 100.0)); builder.end(true); let path = builder.build(); test_path(path.as_slice()); } #[test] fn test_point_on_edge2() { // Point b (from edges a-b and b-c) is positioned exactly on // the edge d-e. // // d-----+ // | | // a--b--c | // | | | | // +-----+ | // | | // e-----+ let mut builder = Path::builder(); builder.begin(point(1.0, 1.0)); builder.line_to(point(2.0, 1.0)); builder.line_to(point(3.0, 1.0)); builder.line_to(point(3.0, 2.0)); builder.line_to(point(1.0, 2.0)); builder.end(true); builder.begin(point(2.0, 0.0)); builder.line_to(point(2.0, 3.0)); builder.line_to(point(4.0, 3.0)); builder.line_to(point(4.0, 0.0)); builder.end(true); test_path(builder.build().as_slice()); } #[test] fn test_coincident_simple_1() { // 0___5 // \ / // 1 x 4 // /_\ // 2 3 // A self-intersecting path with two points at the same position. let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(1.0, 1.0)); // <-- builder.line_to(point(0.0, 2.0)); builder.line_to(point(2.0, 2.0)); builder.line_to(point(1.0, 1.0)); // <-- builder.line_to(point(2.0, 0.0)); builder.end(true); let path = builder.build(); test_path(path.as_slice()); // "M 0 0 L 1 1 L 0 2 L 2 2 L 1 1 L 2 0 Z" } #[test] fn test_coincident_simple_2() { // A self-intersecting path with two points at the same position. let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(1.0, 1.0)); // <-- builder.line_to(point(2.0, 0.0)); builder.line_to(point(2.0, 2.0)); builder.line_to(point(1.0, 1.0)); // <-- builder.line_to(point(0.0, 2.0)); builder.end(true); let path = builder.build(); test_path(path.as_slice()); } #[test] fn test_coincident_simple_rotated() { // Same as test_coincident_simple with the usual rotations // applied. let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(1.0, 1.0)); // <-- builder.line_to(point(0.0, 2.0)); builder.line_to(point(2.0, 2.0)); builder.line_to(point(1.0, 1.0)); // <-- builder.line_to(point(2.0, 0.0)); builder.end(true); let path = builder.build(); test_path_with_rotations(path, 0.01, None); } #[test] fn test_identical_squares() { // Two identical sub paths. It is pretty much the worst type of input for // the tessellator as far as I know. let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(1.0, 0.0)); builder.line_to(point(1.0, 1.0)); builder.line_to(point(0.0, 1.0)); builder.end(true); builder.begin(point(0.0, 0.0)); builder.line_to(point(1.0, 0.0)); builder.line_to(point(1.0, 1.0)); builder.line_to(point(0.0, 1.0)); builder.end(true); let path = builder.build(); test_path(path.as_slice()); } #[test] fn test_close_at_first_position() { // This path closes at the first position which requires some special handling in the event // builder in order to properly add the last vertex events (since first == current, we can't // test against the angle of (current, first, second)). let mut builder = Path::builder(); builder.begin(point(107.400665, 91.79798)); builder.line_to(point(108.93136, 91.51076)); builder.line_to(point(107.84248, 91.79686)); builder.line_to(point(107.400665, 91.79798)); builder.end(true); test_path(builder.build().as_slice()); } #[test] fn test_fixed_to_f32_precision() { // This test appears to hit a precision issue in the conversion from fixed 16.16 // to f32, causing a point to appear slightly above another when it should not. let mut builder = Path::builder(); builder.begin(point(68.97998, 796.05)); builder.line_to(point(61.27998, 805.35)); builder.line_to(point(55.37999, 799.14996)); builder.line_to(point(68.98, 796.05)); builder.end(true); test_path(builder.build().as_slice()); } #[test] fn test_no_close() { let mut builder = Path::builder(); builder.begin(point(1.0, 1.0)); builder.line_to(point(5.0, 1.0)); builder.line_to(point(1.0, 5.0)); builder.end(false); test_path(builder.build().as_slice()); } #[test] fn test_empty_path() { test_path_and_count_triangles(Path::new().as_slice(), 0); } #[test] fn test_exp_no_intersection_01() { let mut builder = Path::builder(); builder.begin(point(80.041534, 19.24472)); builder.line_to(point(76.56131, 23.062233)); builder.line_to(point(67.26949, 23.039438)); builder.line_to(point(48.42367, 28.978098)); builder.end(true); test_path(builder.build().as_slice()); // SVG path syntax: // "M 80.041534 19.24472 L 76.56131 23.062233 L 67.26949 23.039438 L 48.42367 28.978098 Z" } #[test] fn test_intersecting_star_shape() { let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(100.0, 0.0)); builder.line_to(point(50.0, 50.0)); builder.end(true); builder.begin(point(0.0, 25.0)); builder.line_to(point(100.0, 25.0)); builder.line_to(point(50.0, -25.0)); builder.end(true); let path = builder.build(); test_path_with_rotations(path, 0.01, None); } #[test] fn issue_476_original() { let mut builder = Path::builder(); builder.begin(point(10720.101, 7120.1816)); builder.line_to(point(10720.099, 7120.1816)); builder.line_to(point(10720.1, 7120.182)); builder.line_to(point(10720.099, 7120.1836)); builder.line_to(point(10720.101, 7120.1846)); builder.line_to(point(10720.098, 7120.1855)); builder.line_to(point(10720.096, 7120.189)); builder.line_to(point(10720.096, 7120.1885)); builder.line_to(point(10720.094, 7120.188)); builder.line_to(point(10720.095, 7120.1885)); builder.line_to(point(10720.095, 7120.1885)); builder.line_to(point(10720.094, 7120.189)); builder.line_to(point(10720.095, 7120.1885)); builder.line_to(point(10720.091, 7120.1865)); builder.line_to(point(10720.096, 7120.1855)); builder.line_to(point(10720.097, 7120.1836)); builder.line_to(point(10720.098, 7120.1846)); builder.line_to(point(10720.099, 7120.1816)); builder.line_to(point(10720.098, 7120.1826)); builder.line_to(point(10720.097, 7120.181)); builder.line_to(point(10720.1, 7120.1807)); builder.end(true); test_path(builder.build().as_slice()); } #[test] fn issue_476_reduced() { let mut builder = Path::builder(); builder.begin(point(10720.101, 7120.1816)); builder.line_to(point(10720.099, 7120.1816)); builder.line_to(point(10720.096, 7120.1855)); builder.line_to(point(10720.098, 7120.1846)); builder.line_to(point(10720.099, 7120.1816)); builder.line_to(point(10720.098, 7120.1826)); builder.line_to(point(10720.097, 7120.181)); builder.end(true); test_path(builder.build().as_slice()); // SVG path syntax: // "M 10720.101 7120.1816 L 10720.099 7120.1816 L 10720.096 7120.1855 L 10720.098 7120.1846 L 10720.099 7120.1816 L 10720.098 7120.1826 L 10720.097 7120.181 Z" } #[test] fn issue_481_original() { let mut builder = Path::builder(); builder.begin(point(0.9177246, 0.22070313)); builder.line_to(point(0.9111328, 0.21826172)); builder.line_to(point(0.91625977, 0.22265625)); builder.line_to(point(0.9111328, 0.22753906)); builder.line_to(point(0.9309082, 0.2397461)); builder.line_to(point(0.92163086, 0.24121094)); builder.line_to(point(0.91796875, 0.23486328)); builder.line_to(point(0.91845703, 0.23999023)); builder.line_to(point(0.90649414, 0.24633789)); builder.line_to(point(0.9038086, 0.23022461)); builder.line_to(point(0.89575195, 0.23779297)); builder.line_to(point(0.88671875, 0.23583984)); builder.line_to(point(0.88427734, 0.2277832)); builder.line_to(point(0.88671875, 0.22143555)); builder.line_to(point(0.8964844, 0.21972656)); builder.line_to(point(0.904541, 0.22460938)); builder.line_to(point(0.9111328, 0.21459961)); builder.line_to(point(0.907959, 0.24072266)); builder.line_to(point(0.9094238, 0.24169922)); builder.line_to(point(0.9104004, 0.24047852)); builder.line_to(point(0.9111328, 0.23950195)); builder.line_to(point(0.91674805, 0.24047852)); builder.line_to(point(0.91259766, 0.23803711)); builder.line_to(point(0.8864746, 0.22998047)); builder.line_to(point(0.88793945, 0.22998047)); builder.line_to(point(0.8874512, 0.22827148)); builder.line_to(point(0.8852539, 0.2265625)); builder.line_to(point(0.8864746, 0.22924805)); builder.line_to(point(0.8869629, 0.22607422)); builder.line_to(point(0.88793945, 0.22827148)); builder.line_to(point(0.8894043, 0.22729492)); builder.line_to(point(0.8869629, 0.22607422)); builder.line_to(point(0.8918457, 0.22680664)); builder.line_to(point(0.89453125, 0.2265625)); builder.line_to(point(0.89282227, 0.22558594)); builder.line_to(point(0.8911133, 0.2241211)); builder.line_to(point(0.8898926, 0.22436523)); builder.line_to(point(0.89038086, 0.22558594)); builder.line_to(point(0.9238281, 0.23022461)); builder.line_to(point(0.9213867, 0.23022461)); builder.line_to(point(0.91918945, 0.22729492)); builder.line_to(point(0.92211914, 0.22680664)); builder.end(true); test_path(builder.build().as_slice()); } #[test] fn issue_481_reduced() { let mut builder = Path::builder(); builder.begin(point(0.88427734, 0.2277832)); builder.line_to(point(0.88671875, 0.22143555)); builder.line_to(point(0.91259766, 0.23803711)); builder.line_to(point(0.8869629, 0.22607422)); builder.line_to(point(0.88793945, 0.22827148)); builder.line_to(point(0.8894043, 0.22729492)); builder.line_to(point(0.8869629, 0.22607422)); builder.line_to(point(0.89453125, 0.2265625)); builder.end(true); test_path(builder.build().as_slice()); // SVG path syntax: // "M 0.88427734 0.2277832 L 0.88671875 0.22143555 L 0.91259766 0.23803711 L 0.8869629 0.22607422 L 0.88793945 0.22827148 L 0.8894043 0.22729492 L 0.8869629 0.22607422 L 0.89453125 0.2265625 Z" } #[test] fn overlapping_horizontal() { let mut builder = Path::builder(); builder.begin(point(10.0, 0.0)); builder.line_to(point(0.0, 0.0)); builder.line_to(point(15.0, 0.0)); builder.line_to(point(10.0, 5.0)); builder.end(true); test_path(builder.build().as_slice()); // SVG path syntax: // "M 10 0 L 0 0 L 15 0 L 10 5 Z" } #[test] fn triangle() { let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(5.0, 1.0)); builder.line_to(point(3.0, 5.0)); builder.end(true); let path = builder.build(); let mut tess = FillTessellator::new(); tess.set_logging(true); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &path, &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); } #[test] fn new_tess_1() { let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(5.0, 0.0)); builder.line_to(point(5.0, 5.0)); builder.line_to(point(0.0, 5.0)); builder.end(true); builder.begin(point(1.0, 1.0)); builder.line_to(point(4.0, 1.0)); builder.line_to(point(4.0, 4.0)); builder.line_to(point(1.0, 4.0)); builder.end(true); let path = builder.build(); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &path, &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); } #[test] fn new_tess_2() { let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(5.0, -5.0)); builder.line_to(point(10.0, 0.0)); builder.line_to(point(9.0, 5.0)); builder.line_to(point(10.0, 10.0)); builder.line_to(point(5.0, 6.0)); builder.line_to(point(0.0, 10.0)); builder.line_to(point(1.0, 5.0)); builder.end(true); builder.begin(point(20.0, -1.0)); builder.line_to(point(25.0, 1.0)); builder.line_to(point(25.0, 9.0)); builder.end(true); let path = builder.build(); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &path, &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); } #[test] fn new_tess_merge() { let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); // start builder.line_to(point(5.0, 5.0)); // merge builder.line_to(point(5.0, 1.0)); // start builder.line_to(point(10.0, 6.0)); // merge builder.line_to(point(11.0, 2.0)); // start builder.line_to(point(11.0, 10.0)); // end builder.line_to(point(0.0, 9.0)); // left builder.end(true); let path = builder.build(); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &path, &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // "M 0 0 L 5 5 L 5 1 L 10 6 L 11 2 L 11 10 L 0 9 Z" } #[test] fn test_intersection_1() { let mut builder = Path::builder(); builder.begin(point(118.82771, 64.41283)); builder.line_to(point(23.451895, 50.336365)); builder.line_to(point(123.39044, 68.36287)); builder.end(true); builder.begin(point(80.39975, 58.73177)); builder.line_to(point(80.598236, 60.38033)); builder.line_to(point(63.05017, 63.488304)); builder.end(true); let path = builder.build(); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &path, &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 118.82771 64.41283 L 23.451895 50.336365 L 123.39044 68.36287 ZM 80.39975 58.73177 L 80.598236 60.38033 L 63.05017 63.488304 Z" } #[test] fn new_tess_points_too_close() { // The first and last point are almost equal but not quite. let mut builder = Path::builder(); builder.begin(point(52.90753, -72.15962)); builder.line_to(point(45.80301, -70.96051)); builder.line_to(point(50.91391, -83.96548)); builder.line_to(point(52.90654, -72.159454)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 52.90753 -72.15962 L 45.80301 -70.96051 L 50.91391 -83.96548 L 52.90654 -72.159454 Z" } #[test] fn new_tess_coincident_simple() { let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(0.0, 0.0)); builder.line_to(point(1.0, 0.0)); builder.line_to(point(1.0, 0.0)); builder.line_to(point(0.0, 1.0)); builder.line_to(point(0.0, 1.0)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); } #[test] fn new_tess_overlapping_1() { let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(2.0, 2.0)); builder.line_to(point(3.0, 1.0)); builder.line_to(point(0.0, 4.0)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); } #[test] fn reduced_test_case_01() { let mut builder = Path::builder(); builder.begin(point(0.73951757, 0.3810749)); builder.line_to(point(0.4420668, 0.05925262)); builder.line_to(point(0.54023945, 0.16737175)); builder.line_to(point(0.8839954, 0.39966547)); builder.line_to(point(0.77066493, 0.67880523)); builder.line_to(point(0.48341691, 0.09270251)); builder.line_to(point(0.053493023, 0.18919432)); builder.line_to(point(0.6088793, 0.57187665)); builder.line_to(point(0.2899257, 0.09821439)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 0.73951757 0.3810749 L 0.4420668 0.05925262 L 0.54023945 0.16737175 L 0.8839954 0.39966547 L 0.77066493 0.67880523 L 0.48341691 0.09270251 L 0.053493023 0.18919432 L 0.6088793 0.57187665 L 0.2899257 0.09821439 Z" } #[test] fn reduced_test_case_02() { let mut builder = Path::builder(); builder.begin(point(-849.0441, 524.5503)); builder.line_to(point(857.67084, -518.10205)); builder.line_to(point(900.9668, -439.50897)); builder.line_to(point(-892.3401, 445.9572)); builder.line_to(point(-478.20224, -872.66327)); builder.line_to(point(486.82892, 879.1116)); builder.line_to(point(406.3725, 918.8378)); builder.line_to(point(-397.74573, -912.3896)); builder.line_to(point(-314.0522, -944.7439)); builder.line_to(point(236.42209, 975.91394)); builder.line_to(point(-227.79541, -969.4657)); builder.line_to(point(-139.66971, -986.356)); builder.line_to(point(148.29639, 992.80426)); builder.line_to(point(-50.38492, -995.2788)); builder.line_to(point(39.340546, -996.16223)); builder.line_to(point(-30.713806, 1002.6105)); builder.line_to(point(-120.157104, 995.44745)); builder.line_to(point(128.78381, -988.9992)); builder.line_to(point(217.22491, -973.84735)); builder.line_to(point(-208.5982, 980.2956)); builder.line_to(point(303.95184, -950.8286)); builder.line_to(point(388.26636, -920.12854)); builder.line_to(point(-379.63965, 926.5768)); builder.line_to(point(-460.8624, 888.4425)); builder.line_to(point(469.48914, -881.99426)); builder.line_to(point(546.96686, -836.73254)); builder.line_to(point(-538.3402, 843.1808)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M -849.0441 524.5503 L 857.67084 -518.10205 L 900.9668 -439.50897 L -892.3401 445.9572 L -478.20224 -872.66327 L 486.82892 879.1116 L 406.3725 918.8378 L -397.74573 -912.3896 L -314.0522 -944.7439 L 236.42209 975.91394 L -227.79541 -969.4657 L -139.66971 -986.356 L 148.29639 992.80426 L -50.38492 -995.2788 L 39.340546 -996.16223 L -30.713806 1002.6105 L -120.157104 995.44745 L 128.78381 -988.9992 L 217.22491 -973.84735 L -208.5982 980.2956 L 303.95184 -950.8286 L 388.26636 -920.12854 L -379.63965 926.5768 L -460.8624 888.4425 L 469.48914 -881.99426 L 546.96686 -836.73254 L -538.3402 843.1808 Z" } #[test] fn reduced_test_case_03() { let mut builder = Path::builder(); builder.begin(point(997.2859, 38.078064)); builder.line_to(point(-1000.8505, -48.24139)); builder.line_to(point(-980.1207, -212.09396)); builder.line_to(point(976.556, 201.93065)); builder.line_to(point(929.13965, 360.13647)); builder.line_to(point(-932.70435, -370.29977)); builder.line_to(point(-859.89484, -518.5434)); builder.line_to(point(856.33014, 508.38007)); builder.line_to(point(760.1136, 642.6178)); builder.line_to(point(-763.6783, -652.7811)); builder.line_to(point(-646.6792, -769.3514)); builder.line_to(point(643.1145, 759.188)); builder.line_to(point(508.52423, 854.91095)); builder.line_to(point(-512.0889, -865.0742)); builder.line_to(point(-363.57895, -937.33875)); builder.line_to(point(360.01428, 927.1754)); builder.line_to(point(201.63538, 974.01044)); builder.line_to(point(-205.20004, -984.1737)); builder.line_to(point(-41.272438, -1004.30164)); builder.line_to(point(37.707764, 994.1383)); builder.line_to(point(-127.297035, 987.01013)); builder.line_to(point(123.73236, -997.1734)); builder.line_to(point(285.31345, -962.9835)); builder.line_to(point(-288.8781, 952.82025)); builder.line_to(point(-442.62796, 892.5013)); builder.line_to(point(439.0633, -902.6646)); builder.line_to(point(580.7881, -817.8619)); builder.line_to(point(-584.3528, 807.6986)); builder.line_to(point(-710.18646, 700.7254)); builder.line_to(point(706.62177, -710.8888)); builder.line_to(point(813.13196, -584.6631)); builder.line_to(point(-816.69666, 574.49976)); builder.line_to(point(-900.9784, 432.46442)); builder.line_to(point(897.4137, -442.62775)); builder.line_to(point(957.1676, -288.65726)); builder.line_to(point(-960.7323, 278.49396)); builder.line_to(point(-994.3284, 116.7885)); builder.line_to(point(990.76373, -126.95181)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 997.2859 38.078064 L -1000.8505 -48.24139 L -980.1207 -212.09396 L 976.556 201.93065 L 929.13965 360.13647 L -932.70435 -370.29977 L -859.89484 -518.5434 L 856.33014 508.38007 L 760.1136 642.6178 L -763.6783 -652.7811 L -646.6792 -769.3514 L 643.1145 759.188 L 508.52423 854.91095 L -512.0889 -865.0742 L -363.57895 -937.33875 L 360.01428 927.1754 L 201.63538 974.01044 L -205.20004 -984.1737 L -41.272438 -1004.30164 L 37.707764 994.1383 L -127.297035 987.01013 L 123.73236 -997.1734 L 285.31345 -962.9835 L -288.8781 952.82025 L -442.62796 892.5013 L 439.0633 -902.6646 L 580.7881 -817.8619 L -584.3528 807.6986 L -710.18646 700.7254 L 706.62177 -710.8888 L 813.13196 -584.6631 L -816.69666 574.49976 L -900.9784 432.46442 L 897.4137 -442.62775 L 957.1676 -288.65726 L -960.7323 278.49396 L -994.3284 116.7885 L 990.76373 -126.95181 Z" } #[test] fn reduced_test_case_04() { let mut builder = Path::builder(); builder.begin(point(540.7645, 838.81036)); builder.line_to(point(-534.48315, -847.5593)); builder.line_to(point(-347.42682, -940.912)); builder.line_to(point(151.33032, 984.5845)); builder.line_to(point(-145.04895, -993.33344)); builder.line_to(point(63.80545, -1002.5327)); builder.line_to(point(-57.52408, 993.78375)); builder.line_to(point(-263.7273, 959.35864)); builder.line_to(point(270.00864, -968.1076)); builder.line_to(point(464.54828, -891.56274)); builder.line_to(point(-458.26697, 882.81384)); builder.line_to(point(-632.64087, 767.49457)); builder.line_to(point(638.9222, -776.2435)); builder.line_to(point(785.5095, -627.18994)); builder.line_to(point(-779.22815, 618.4409)); builder.line_to(point(-891.62213, 442.1673)); builder.line_to(point(897.9035, -450.91632)); builder.line_to(point(971.192, -255.12662)); builder.line_to(point(-964.9106, 246.37766)); builder.line_to(point(-927.4177, -370.5181)); builder.line_to(point(933.6991, 361.7691)); builder.line_to(point(837.23865, 547.24194)); builder.line_to(point(-830.9573, -555.9909)); builder.line_to(point(-698.0427, -717.3555)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 540.7645 838.81036 L -534.48315 -847.5593 L -347.42682 -940.912 L 151.33032 984.5845 L -145.04895 -993.33344 L 63.80545 -1002.5327 L -57.52408 993.78375 L -263.7273 959.35864 L 270.00864 -968.1076 L 464.54828 -891.56274 L -458.26697 882.81384 L -632.64087 767.49457 L 638.9222 -776.2435 L 785.5095 -627.18994 L -779.22815 618.4409 L -891.62213 442.1673 L 897.9035 -450.91632 L 971.192 -255.12662 L -964.9106 246.37766 L -927.4177 -370.5181 L 933.6991 361.7691 L 837.23865 547.24194 L -830.9573 -555.9909 L -698.0427 -717.3555 Z" } #[test] fn reduced_test_case_05() { let mut builder = Path::builder(); builder.begin(point(540.7645, 838.81036)); builder.line_to(point(-534.48315, -847.5593)); builder.line_to(point(-347.42682, -940.912)); builder.line_to(point(353.70816, 932.163)); builder.line_to(point(151.33032, 984.5845)); builder.line_to(point(-145.04895, -993.33344)); builder.line_to(point(63.80545, -1002.5327)); builder.line_to(point(-263.7273, 959.35864)); builder.line_to(point(270.00864, -968.1076)); builder.line_to(point(464.54828, -891.56274)); builder.line_to(point(-458.26697, 882.81384)); builder.line_to(point(-632.64087, 767.49457)); builder.line_to(point(638.9222, -776.2435)); builder.line_to(point(785.5095, -627.18994)); builder.line_to(point(-779.22815, 618.4409)); builder.line_to(point(-891.62213, 442.1673)); builder.line_to(point(897.9035, -450.91632)); builder.line_to(point(971.192, -255.12662)); builder.line_to(point(-964.9106, 246.37766)); builder.line_to(point(-995.89075, 39.628937)); builder.line_to(point(1002.1721, -48.3779)); builder.line_to(point(989.48975, 160.29398)); builder.line_to(point(-983.2084, -169.04297)); builder.line_to(point(-927.4177, -370.5181)); builder.line_to(point(933.6991, 361.7691)); builder.line_to(point(837.23865, 547.24194)); builder.line_to(point(-830.9573, -555.9909)); builder.line_to(point(-698.0427, -717.3555)); builder.line_to(point(704.3241, 708.6065)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 540.7645 838.81036 L -534.48315 -847.5593 L -347.42682 -940.912 L 353.70816 932.163 L 151.33032 984.5845 L -145.04895 -993.33344 L 63.80545 -1002.5327 L -263.7273 959.35864 L 270.00864 -968.1076 L 464.54828 -891.56274 L -458.26697 882.81384 L -632.64087 767.49457 L 638.9222 -776.2435 L 785.5095 -627.18994 L -779.22815 618.4409 L -891.62213 442.1673 L 897.9035 -450.91632 L 971.192 -255.12662 L -964.9106 246.37766 L -995.89075 39.628937 L 1002.1721 -48.3779 L 989.48975 160.29398 L -983.2084 -169.04297 L -927.4177 -370.5181 L 933.6991 361.7691 L 837.23865 547.24194 L -830.9573 -555.9909 L -698.0427 -717.3555 L 704.3241 708.6065 Z" } #[test] fn reduced_test_case_06() { let mut builder = Path::builder(); builder.begin(point(831.9957, 561.9206)); builder.line_to(point(-829.447, -551.4562)); builder.line_to(point(-505.64172, -856.7632)); builder.line_to(point(508.19046, 867.2276)); builder.line_to(point(83.98413, 1001.80585)); builder.line_to(point(-81.435394, -991.34143)); builder.line_to(point(359.1525, -928.5361)); builder.line_to(point(-356.60376, 939.0005)); builder.line_to(point(-726.3096, 691.25085)); builder.line_to(point(728.8583, -680.78644)); builder.line_to(point(-951.90845, 307.6267)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 831.9957 561.9206 L -829.447 -551.4562 L -505.64172 -856.7632 L 508.19046 867.2276 L 83.98413 1001.80585 L -81.435394 -991.34143 L 359.1525 -928.5361 L -356.60376 939.0005 L -726.3096 691.25085 L 728.8583 -680.78644 L -951.90845 307.6267 Z" } #[test] fn reduced_test_case_07() { let mut builder = Path::builder(); builder.begin(point(960.5097, -271.01678)); builder.line_to(point(-967.03217, 262.446)); builder.line_to(point(-987.3192, -182.13324)); builder.line_to(point(980.7969, 173.56247)); builder.line_to(point(806.1792, 582.91675)); builder.line_to(point(-812.7016, -591.48755)); builder.line_to(point(-477.76422, -884.53925)); builder.line_to(point(471.24182, 875.9685)); builder.line_to(point(42.32347, 994.6751)); builder.line_to(point(-48.845886, -1003.2459)); builder.line_to(point(389.10114, -924.0962)); builder.line_to(point(-395.62357, 915.5254)); builder.line_to(point(-755.85846, 654.19574)); builder.line_to(point(749.3361, -662.7665)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 960.5097 -271.01678 L -967.03217 262.446 L -987.3192 -182.13324 L 980.7969 173.56247 L 806.1792 582.91675 L -812.7016 -591.48755 L -477.76422 -884.53925 L 471.24182 875.9685 L 42.32347 994.6751 L -48.845886 -1003.2459 L 389.10114 -924.0962 L -395.62357 915.5254 L -755.85846 654.19574 L 749.3361 -662.7665 Z" } #[test] fn reduced_test_case_08() { let mut builder = Path::builder(); builder.begin(point(-85.92998, 24.945076)); builder.line_to(point(-79.567345, 28.325748)); builder.line_to(point(-91.54697, 35.518726)); builder.line_to(point(-85.92909, 24.945545)); builder.end(true); builder.begin(point(-57.761955, 34.452206)); builder.line_to(point(-113.631676, 63.3717)); builder.line_to(point(-113.67784, 63.347214)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M -85.92998 24.945076 L -79.567345 28.325748 L -91.54697 35.518726 L -85.92909 24.945545 ZM -57.761955 34.452206 L -113.631676 63.3717 L -113.67784 63.347214 Z" } #[test] fn reduced_test_case_09() { let mut builder = Path::builder(); builder.begin(point(659.9835, 415.86328)); builder.line_to(point(70.36328, 204.36978)); builder.line_to(point(74.12529, 89.01107)); builder.end(true); builder.begin(point(840.2258, 295.46188)); builder.line_to(point(259.41193, 272.18054)); builder.line_to(point(728.914, 281.41678)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 659.9835 415.86328 L 70.36328 204.36978 L 74.12529 89.01107 ZM 840.2258 295.46188 L 259.41193 272.18054 L 728.914 281.41678 Z" } #[test] fn reduced_test_case_10() { let mut builder = Path::builder(); builder.begin(point(993.5114, -94.67855)); builder.line_to(point(-938.76056, -355.94995)); builder.line_to(point(933.8779, 346.34995)); builder.line_to(point(-693.6775, -727.42883)); builder.line_to(point(-311.68665, -955.7822)); builder.line_to(point(306.80408, 946.1823)); builder.line_to(point(-136.43655, 986.182)); builder.line_to(point(131.55396, -995.782)); builder.line_to(point(548.25525, -839.50555)); builder.line_to(point(-553.13776, 829.9056)); builder.line_to(point(-860.76697, 508.30533)); builder.line_to(point(855.88434, -517.90533)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 993.5114 -94.67855 L -938.76056 -355.94995 L 933.8779 346.34995 L -693.6775 -727.42883 L -311.68665 -955.7822 L 306.80408 946.1823 L -136.43655 986.182 L 131.55396 -995.782 L 548.25525 -839.50555 L -553.13776 829.9056 L -860.76697 508.30533 L 855.88434 -517.90533 Z" } #[test] fn reduced_test_case_11() { let mut builder = Path::builder(); builder.begin(point(10.0095005, 0.89995164)); builder.line_to(point(10.109498, 10.899451)); builder.line_to(point(0.10999817, 10.99945)); builder.end(true); builder.begin(point(19.999, -0.19999667)); builder.line_to(point(20.098999, 9.799503)); builder.line_to(point(10.099499, 9.899502)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 10.0095005 0.89995164 L 10.109498 10.899451 L 0.10999817 10.99945 ZM 19.999 -0.19999667 L 20.098999 9.799503 L 10.099499 9.899502 Z" } #[test] fn reduced_test_case_12() { let mut builder = Path::builder(); builder.begin(point(5.5114865, -8.40378)); builder.line_to(point(14.377752, -3.7789207)); builder.line_to(point(9.7528925, 5.0873456)); builder.end(true); builder.begin(point(4.62486, -8.866266)); builder.line_to(point(18.115986, -13.107673)); builder.line_to(point(13.491126, -4.2414064)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 5.5114865 -8.40378 L 14.377752 -3.7789207 L 9.7528925 5.0873456 ZM 4.62486 -8.866266 L 18.115986 -13.107673 L 13.491126 -4.2414064 Z" } #[test] fn reduced_test_case_13() { let mut builder = Path::builder(); builder.begin(point(-989.1437, 132.75488)); builder.line_to(point(994.39124, -123.3494)); builder.line_to(point(518.279, 861.4989)); builder.line_to(point(-513.03143, -852.09344)); builder.line_to(point(-364.97452, -925.282)); builder.line_to(point(370.2221, 934.68744)); builder.line_to(point(-206.8905, -973.10284)); builder.line_to(point(-43.09149, -994.2518)); builder.line_to(point(48.33908, 1003.6572)); builder.line_to(point(-116.706924, 997.5573)); builder.line_to(point(121.95452, -988.15186)); builder.line_to(point(283.74548, -954.96936)); builder.line_to(point(-278.49792, 964.3749)); builder.line_to(point(-432.6207, 905.0151)); builder.line_to(point(437.86832, -895.6096)); builder.line_to(point(959.78815, -284.84253)); builder.line_to(point(-954.5406, 294.24802)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M -989.1437 132.75488 L 994.39124 -123.3494 L 518.279 861.4989 L -513.03143 -852.09344 L -364.97452 -925.282 L 370.2221 934.68744 L -206.8905 -973.10284 L -43.09149 -994.2518 L 48.33908 1003.6572 L -116.706924 997.5573 L 121.95452 -988.15186 L 283.74548 -954.96936 L -278.49792 964.3749 L -432.6207 905.0151 L 437.86832 -895.6096 L 959.78815 -284.84253 L -954.5406 294.24802 Z" } #[test] fn reduced_test_case_14() { let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.line_to(point(10.0, 20.0)); builder.line_to(point(10.0, 10.0)); builder.line_to(point(40.0, 25.0)); builder.line_to(point(50.0, 0.0)); builder.line_to(point(50.0, 60.0)); builder.line_to(point(40.0, 30.0)); builder.line_to(point(40.0, 60.0)); builder.line_to(point(30.0, 60.0)); builder.line_to(point(40.0, 30.0)); builder.line_to(point(20.0, 60.0)); builder.line_to(point(0.0, 60.0)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); // SVG path syntax: // "M 0 0 L 100 200 100 100 400 250 500 0 500 600 400 300 400 600 300 600 400 300 200 600 100 600 400 300 0 600 Z" } #[test] fn issue_500() { let mut builder = Path::builder(); builder.begin(point(6.05, 11.65)); builder.line_to(point(5.6, 11.65)); builder.line_to(point(4.7, 12.25)); builder.line_to(point(5.15, 12.55)); builder.line_to(point(5.6, 11.65)); builder.line_to(point(5.6, 12.7)); builder.line_to(point(6.05, 11.65)); builder.line_to(point(8.3, 7.6)); builder.line_to(point(7.7, 7.6)); builder.line_to(point(8.0, 7.75)); builder.line_to(point(9.8, 7.15)); builder.line_to(point(9.8, 13.15)); builder.line_to(point(1.25, 13.15)); builder.line_to(point(1.25, 7.15)); builder.line_to(point(1.25, 7.15)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); } #[test] fn issue_518_1() { let mut builder = Path::builder(); builder.begin(point(-76.95, -461.8)); builder.quadratic_bezier_to(point(-75.95, -462.6), point(-74.65, -462.8)); builder.line_to(point(-79.1, -456.4)); builder.line_to(point(-83.4, -464.75)); builder.line_to(point(-80.75, -464.75)); builder.line_to(point(-79.05, -458.1)); builder.quadratic_bezier_to(point(-78.65, -460.2), point(-77.35, -461.45)); builder.line_to(point(-77.1, -461.65)); builder.line_to(point(-76.95, -461.8)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); } #[test] fn issue_518_2() { let mut builder = Path::builder(); builder.begin(point(-69.1, -465.5)); builder.line_to(point(-69.1, -461.65)); builder.quadratic_bezier_to(point(-70.95, -462.8), point(-72.95, -462.9)); builder.quadratic_bezier_to(point(-75.65, -463.1), point(-77.35, -461.45)); builder.quadratic_bezier_to(point(-78.65, -460.2), point(-79.05, -458.1)); builder.line_to(point(-80.55, -465.5)); builder.line_to(point(-69.1, -465.5)); builder.end(true); let mut tess = FillTessellator::new(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut simple_builder(&mut buffers), ) .unwrap(); } #[test] fn very_large_path() { /// Try tessellating a path with a large number of endpoints. const N: usize = 1_000_000; let mut d: f32 = 0.0; let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); for _ in 0..(N / 2) { builder.line_to(point(d.cos(), d)); d += 0.1; } for _ in 0..(N / 2) { builder.line_to(point(d.cos() + 30.0, d)); d -= 0.1; } builder.end(true); let mut tess = FillTessellator::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut NoOutput::new(), ) .unwrap(); } #[test] fn issue_529() { let mut builder = Path::builder(); builder.begin(point(203.01, 174.67)); builder.line_to(point(203.04, 174.72)); builder.line_to(point(203.0, 174.68)); builder.end(true); builder.begin(point(203.0, 174.66)); builder.line_to(point(203.01, 174.68)); builder.line_to(point(202.99, 174.68)); builder.end(true); let mut tess = FillTessellator::new(); tess.tessellate( &builder.build(), &FillOptions::default(), &mut NoOutput::new(), ) .unwrap(); // SVG path syntax: // "M 203.01 174.67 L 203.04 174.72 L 203 174.68 ZM 203 174.66 L 203.01 174.68 L 202.99 174.68 Z" } #[test] fn issue_562_1() { let mut builder = Path::builder(); builder.begin(point(757.26587, 494.72363)); builder.line_to(point(833.3479, 885.81494)); builder.line_to(point(342.08817, 855.6907)); builder.close(); builder.begin(point(580.21893, 759.2482)); builder.line_to(point(545.2758, 920.6801)); builder.line_to(point(739.3726, 23.550331)); builder.close(); test_path(builder.build().as_slice()); // SVG path syntax: // "M 757.26587 494.72363 L 833.3479 885.81494 L 342.08817 855.6907 ZM 580.21893 759.2482 L 545.2758 920.6801 L 739.3726 23.550331 Z" } #[test] fn issue_562_2() { let mut builder = Path::builder(); builder.begin(point(3071.0, 737.0)); builder.line_to(point(3071.0, 738.0)); builder.line_to(point(3071.0, 738.0)); builder.close(); builder.begin(point(3071.0, 3071.0)); builder.line_to(point(3071.0, 703.0)); builder.line_to(point(3071.0, 703.0)); builder.close(); test_path(builder.build().as_slice()); // SVG path syntax: // "M 3071 737 L 3071 738 L 3071 738 ZM 3071 3071 L 3071 703 L 3071 703 Z" } #[test] fn issue_562_3() { let mut builder = Path::builder(); builder.begin(point(4224.0, -128.0)); builder.line_to(point(3903.0, 3615.0)); builder.line_to(point(3903.0, 3590.0)); builder.line_to(point(3893.0, 3583.0)); builder.close(); builder.begin(point(3898.0, 3898.0)); builder.line_to(point(3898.0, 3585.0)); builder.line_to(point(3897.0, 3585.0)); builder.close(); builder.begin(point(3899.0, 3899.0)); builder.line_to(point(3899.0, 1252.0)); builder.line_to(point(3899.0, 1252.0)); builder.close(); builder.begin(point(3897.0, 3897.0)); builder.line_to(point(3897.0, 3536.0)); builder.line_to(point(3897.0, 3536.0)); builder.close(); test_path(builder.build().as_slice()); // SVG path syntax: // "M 4224 -128 L 3903 3615 L 3903 3590 L 3893 3583 ZM 3898 3898 L 3898 3585 L 3897 3585 ZM 3899 3899 L 3899 1252 L 3899 1252 ZM 3897 3897 L 3897 3536 L 3897 3536 Z" } #[test] fn issue_562_4() { let mut builder = Path::builder(); builder.begin(point(160.39546, 11.226683)); builder.line_to(point(160.36594, 11.247373)); builder.line_to(point(160.32234, 11.28461)); builder.line_to(point(160.36172, 11.299779)); builder.line_to(point(160.39265, 11.361827)); builder.close(); builder.begin(point(160.36313, 160.36313)); builder.line_to(point(160.36313, 11.14253)); builder.line_to(point(160.36313, 11.14253)); builder.close(); test_path(builder.build().as_slice()); // SVG path syntax: // "M 160.39546 11.226683 L 160.36594 11.247373 L 160.32234 11.28461 L 160.36172 11.299779 L 160.39265 11.361827 ZM 160.36313 160.36313 L 160.36313 11.14253 L 160.36313 11.14253 Z" } #[test] fn issue_562_5() { let mut builder = Path::builder(); builder.begin(point(0.88427734, 0.2277832)); builder.line_to(point(0.88671875, 0.22143555)); builder.line_to(point(0.91259766, 0.23803711)); builder.line_to(point(0.8869629, 0.22607422)); builder.line_to(point(0.88793945, 0.22827148)); builder.line_to(point(0.8869629, 0.22607422)); builder.line_to(point(0.89453125, 0.2265625)); builder.close(); test_path(builder.build().as_slice()); // SVG path syntax: // "M 0.88427734 0.2277832 L 0.88671875 0.22143555 L 0.91259766 0.23803711 L 0.8869629 0.22607422 L 0.88793945 0.22827148 L 0.8869629 0.22607422 L 0.89453125 0.2265625 Z" } #[test] fn issue_562_6() { let mut builder = Path::builder(); builder.begin(point(-499.51904, 864.00793)); builder.line_to(point(510.1705, -862.41235)); builder.line_to(point(1005.31006, 6.4012146)); builder.line_to(point(-994.65857, -4.8055725)); builder.line_to(point(-489.81372, -868.01575)); builder.line_to(point(500.4652, 869.6113)); builder.close(); test_path(builder.build().as_slice()); // SVG path syntax: // "M -499.51904 864.00793 L 510.1705 -862.41235 L 1005.31006 6.4012146 L -994.65857 -4.8055725 L -489.81372 -868.01575 L 500.4652 869.6113 Z" } #[test] fn issue_562_7() { let mut builder = Path::builder(); builder.begin(point(-880.59766, -480.86603)); builder.line_to(point(878.77014, 470.2519)); builder.line_to(point(709.1563, 698.824)); builder.line_to(point(-710.9838, -709.4381)); builder.line_to(point(-483.84427, -880.9657)); builder.line_to(point(482.01672, 870.35156)); builder.line_to(point(215.75311, 970.9385)); builder.line_to(point(-217.58063, -981.5527)); builder.line_to(point(66.236084, -1003.05)); builder.line_to(point(-68.063614, 992.4358)); builder.line_to(point(-346.44025, 933.1019)); builder.line_to(point(344.61273, -943.71606)); builder.line_to(point(594.9969, -808.35785)); builder.line_to(point(-596.8244, 797.7438)); builder.line_to(point(934.5602, -358.7028)); builder.line_to(point(-936.3877, 348.08868)); builder.line_to(point(-998.05756, 70.22009)); builder.line_to(point(996.23004, -80.83423)); builder.close(); test_path(builder.build().as_slice()); // SVG path syntax: // "M -880.59766 -480.86603 L 878.77014 470.2519 L 709.1563 698.824 L -710.9838 -709.4381 L -483.84427 -880.9657 L 482.01672 870.35156 L 215.75311 970.9385 L -217.58063 -981.5527 L 66.236084 -1003.05 L -68.063614 992.4358 L -346.44025 933.1019 L 344.61273 -943.71606 L 594.9969 -808.35785 L -596.8244 797.7438 L 934.5602 -358.7028 L -936.3877 348.08868 L -998.05756 70.22009 L 996.23004 -80.83423 Z" } #[test] fn issue_562_8() { let mut builder = Path::builder(); builder.begin(point(997.84753, -18.145767)); builder.line_to(point(-1001.9789, 8.1993265)); builder.line_to(point(690.0551, 716.8084)); builder.line_to(point(-694.1865, -726.7548)); builder.line_to(point(-589.4575, -814.2759)); builder.line_to(point(585.3262, 804.3294)); builder.line_to(point(469.6551, 876.7747)); builder.line_to(point(-473.78647, -886.7211)); builder.line_to(point(-349.32822, -942.74115)); builder.line_to(point(345.1968, 932.7947)); builder.line_to(point(-218.4011, -981.2923)); builder.line_to(point(-83.44396, -1001.6565)); builder.line_to(point(-57.160374, 993.50793)); builder.line_to(point(53.02899, -1003.4543)); builder.line_to(point(188.47563, -986.65234)); builder.line_to(point(-192.60701, 976.7059)); builder.line_to(point(-324.50436, 941.61707)); builder.line_to(point(320.37296, -951.56354)); builder.line_to(point(446.26376, -898.84155)); builder.line_to(point(-450.39514, 888.89514)); builder.line_to(point(-567.9344, 819.52203)); builder.line_to(point(563.80304, -829.4685)); builder.line_to(point(670.8013, -744.73676)); builder.line_to(point(-769.3966, 636.2781)); builder.line_to(point(909.81805, -415.4218)); builder.close(); test_path(builder.build().as_slice()); // SVG path syntax: // "M 997.84753 -18.145767 L -1001.9789 8.1993265 L 690.0551 716.8084 L -694.1865 -726.7548 L -589.4575 -814.2759 L 585.3262 804.3294 L 469.6551 876.7747 L -473.78647 -886.7211 L -349.32822 -942.74115 L 345.1968 932.7947 L -218.4011 -981.2923 L -83.44396 -1001.6565 L -57.160374 993.50793 L 53.02899 -1003.4543 L 188.47563 -986.65234 L -192.60701 976.7059 L -324.50436 941.61707 L 320.37296 -951.56354 L 446.26376 -898.84155 L -450.39514 888.89514 L -567.9344 819.52203 L 563.80304 -829.4685 L 670.8013 -744.73676 L -769.3966 636.2781 L 909.81805 -415.4218 Z" } #[test] fn low_tolerance_01() { let mut builder = Path::builder(); builder.begin(point(0.0, 0.0)); builder.cubic_bezier_to(point(100.0, 0.0), point(100.0, 100.0), point(100.0, 200.0)); builder.end(true); let path = builder.build(); let mut buffers: VertexBuffers<Point, u16> = VertexBuffers::new(); let mut tess = FillTessellator::new(); tess.tessellate( &path, &FillOptions::tolerance(0.00001), &mut simple_builder(&mut buffers), ).unwrap(); }
31.984213
847
0.627828
21743d7d0a19dfce248d33b50d7603cd919b7c9e
550
use structopt::StructOpt; use failure::ResultExt; use exitfailure::ExitFailure; #[derive(StructOpt)] struct Cli { pattern: String, #[structopt(parse(from_os_str))] path: std::path::PathBuf, } fn main() -> Result<(), ExitFailure> { let args = Cli::from_args(); let content = std::fs::read_to_string(&args.path) .with_context(|_| format!("could not read file `{:?}`", &args.path))?; for line in content.lines() { if line.contains(&args.pattern) { println!("{}", line); } } Ok(()) }
23.913043
78
0.592727
ebcd59835d98f07d65335e546663b38775f33809
359
mod util; #[actix_rt::test] async fn health_check_works() { let test_app = util::spawn_app().await; let client = awc::Client::default(); let response = client .get(&format!("{}/health_check", test_app.address)) .send() .await .expect("Failed to execute request"); assert!(response.status().is_success()); }
21.117647
59
0.607242
7224e5345e0d4733f7c50821ba2d5a8cedb437a6
6,628
use near_sdk::json_types::{U128, U64, Base64VecU8}; use near_sdk::serde_json::json; use near_sdk::{Balance, serde_json}; use near_sdk_sim::transaction::ExecutionStatus; use near_sdk_sim::{init_simulator, to_yocto, UserAccount, DEFAULT_GAS, STORAGE_AMOUNT, runtime::init_runtime}; use manager::{CronManager, Task, TaskStatus}; use near_sdk_sim::types::AccountId; use std::error::Error; use std::rc::Rc; use std::cell::RefCell; use near_sdk_sim::runtime::RuntimeStandalone; // Load in contract bytes at runtime near_sdk_sim::lazy_static_include::lazy_static_include_bytes! { CRON_MANAGER_WASM_BYTES => "../res/manager.wasm", COUNTER_WASM_BYTES => "../res/rust_counter_tutorial.wasm", } const MANAGER_ID: &str = "manager.sim"; const COUNTER_ID: &str = "counter.sim"; const TASK_BASE64: &str = "chUCZxP6uO5xZIjwI9XagXVUCV7nmE09HVRUap8qauo="; type TaskBase64Hash = String; fn helper_create_task(cron: &UserAccount, counter: &UserAccount) -> TaskBase64Hash { let execution_result = counter.call( cron.account_id(), "create_task", &json!({ "contract_id": COUNTER_ID, "function_id": "increment".to_string(), "cadence": "0 30 9,12,15 1,15 May-Aug Mon,Wed,Fri 2018/2".to_string(), "recurring": true, "deposit": 0, "gas": 3000000000000u64, }).to_string().into_bytes(), DEFAULT_GAS, 6_000_000_000_000u128, // deposit ); execution_result.assert_success(); let hash: Base64VecU8 = execution_result.unwrap_json(); serde_json::to_string(&hash).unwrap() } fn helper_next_epoch(runtime: &mut RuntimeStandalone) { let epoch_height = runtime.current_block().epoch_height; while epoch_height == runtime.current_block().epoch_height { runtime.produce_block().unwrap(); } } #[test] fn simulate_task_creation() { let (root, cron) = sim_helper_init(); let counter = sim_helper_init_counter(&root); helper_create_task(&cron, &counter); } #[test] fn simulate_next_epoch() { // TODO: fill this test out, this is just the basics of moving blocks forward. let (mut runtime, signer, root_account_id) = init_runtime(None); let root_account = UserAccount::new(&Rc::new(RefCell::new(runtime)), root_account_id, signer); let mut root_runtime = root_account.borrow_runtime_mut(); let block_production_result = root_runtime.produce_blocks(7); assert!(block_production_result.is_ok(), "Couldn't produce blocks"); println!("aloha current block height {}, epoch height {}", root_runtime.current_block().block_height, root_runtime.current_block().epoch_height); } #[test] fn simulate_basic_task_checks() { let (root, cron) = sim_helper_init(); let counter = sim_helper_init_counter(&root); helper_create_task(&cron, &counter); // Nonexistent task fails. let mut task_view_result = root .view( cron.account_id(), "get_task", &json!({ "task_hash": "doesnotexist" }).to_string().into_bytes(), ); assert!(task_view_result.is_err(), "Expected nonexistent task to throw error."); let error = task_view_result.unwrap_err(); let error_message = error.to_string(); assert!(error_message.contains("No task found by hash")); // Get has from task just added. task_view_result = root .view( cron.account_id(), "get_task", &json!({ "task_hash": TASK_BASE64 }).to_string().into_bytes(), ); assert!(task_view_result.is_ok(), "Expected to find hash of task just added."); let returned_task: Task = task_view_result.unwrap_json(); let expected_task = Task { owner_id: COUNTER_ID.to_string(), contract_id: COUNTER_ID.to_string(), function_id: "increment".to_string(), cadence: "0 30 9,12,15 1,15 May-Aug Mon,Wed,Fri 2018/2".to_string(), recurring: true, status: TaskStatus::Ready, total_deposit: 6000000000000, deposit: 0, gas: 3000000000000, arguments: vec![] }; assert_eq!(expected_task, returned_task, "Task returned was not expected."); // Attempt to remove task with non-owner account. let mut removal_result = root.call( cron.account_id(), "remove_task", &json!({ "task_hash": TASK_BASE64 }).to_string().into_bytes(), DEFAULT_GAS, 0, // deposit ); let status = removal_result.status(); if let ExecutionStatus::Failure(err) = status { // At this time, this is the way to check for error messages. assert!(err.to_string().contains("Only owner can remove their task.")); } else { panic!("Non-owner account should not succeed in removing task."); } counter.call( cron.account_id(), "remove_task", &json!({ "task_hash": TASK_BASE64 }).to_string().into_bytes(), DEFAULT_GAS, 0, // deposit ).assert_success(); // Get has from task just added. task_view_result = root .view( cron.account_id(), "get_task", &json!({ "task_hash": TASK_BASE64 }).to_string().into_bytes(), ); assert!(task_view_result.is_err(), "Expected error when trying to retrieve removed task."); } /// Basic initialization returning the "root account" for the simulator /// and the NFT account with the contract deployed and initialized. fn sim_helper_init() -> (UserAccount, UserAccount) { let mut root_account = init_simulator(None); root_account = root_account.create_user("sim".to_string(), to_yocto("1000000")); // Deploy cron manager and call "new" method let cron = root_account.deploy(&CRON_MANAGER_WASM_BYTES, MANAGER_ID.into(), STORAGE_AMOUNT); cron.call( cron.account_id(), "new", &[], DEFAULT_GAS, 0, // attached deposit ) .assert_success(); (root_account, cron) } fn sim_helper_create_agent_user(root_account: &UserAccount) -> (UserAccount, UserAccount) { let hundred_near = to_yocto("100"); let agent = root_account.create_user("agent.sim".to_string(), hundred_near); let user = root_account.create_user("user.sim".to_string(), hundred_near); (agent, user) } fn sim_helper_init_counter(root_account: &UserAccount) -> UserAccount { // Deploy counter and call "new" method let counter = root_account.deploy(&COUNTER_WASM_BYTES, COUNTER_ID.into(), STORAGE_AMOUNT); counter }
35.068783
149
0.650272
3a5f71372729e2dd2fdeae95d4593e1b91fadfea
568
//! # 全局属性 //! - `#![no_std]` //! 禁用标准库 #![no_std] //! //! - `#![no_main]` //! 不使用 `main` 函数等全部 Rust-level 入口点来作为程序入口 #![no_main] //! # 一些 unstable 的功能需要在 crate 层级声明后才可以使用 //! - `#![feature(llvm_asm)]` //! 内嵌汇编 #![feature(llvm_asm)] #[macro_use] extern crate redos; /// Rust 的入口函数 /// /// 在 `_start` 为我们进行了一系列准备之后,这是第一个被调用的 Rust 函数 #[no_mangle] pub extern "C" fn rust_main() -> ! { println!("Hello test_ebreak!"); // 初始化各种模块 redos::interrupt::init(); unsafe { llvm_asm!("ebreak"::::"volatile"); }; panic!("end of rust_main") }
18.322581
46
0.572183
fbe3eaf3483ec9cad6f2984569ee184ab482f335
1,000
use crate::constants; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use sqlx::FromRow; #[derive(Serialize, Deserialize, FromRow, Clone, Debug)] pub struct User { pub id: i64, pub email: String, pub username: String, pub password: String, pub timestamp: DateTime<Utc>, } #[derive(Serialize, Deserialize, FromRow, Clone, Debug)] pub struct Register { pub email: String, pub username: String, pub password: String, } #[derive(Serialize, Deserialize, FromRow, Clone, Debug)] pub struct UserPassword { pub username: String, pub password: String, } pub fn verify(user: Register) -> bool { if user.username.len() > 32 || user.username.len() < 3 || !&constants::USERNAME_REGEX.is_match(&user.username) { return false; } if !&constants::EMAIL_REGEX.is_match(&user.email) { return false; } if !&constants::PASSWORD_REGEX.is_match(&user.password) { return false; } true }
21.73913
63
0.646
f8128f9d508e3e3e3e3ae0b7d2afe5459ec28d8b
768
use super::trans::TranslationError; use std::{error::Error, fmt::Debug}; #[derive(Debug, Clone)] pub enum ExecutorError { Translation(TranslationError), Clipboard(String), Notifier(String), } impl std::error::Error for ExecutorError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } } impl std::fmt::Display for ExecutorError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "{}", match self { ExecutorError::Translation(err) => err.to_owned().to_string(), ExecutorError::Clipboard(err) => err.to_string(), ExecutorError::Notifier(err) => err.to_string(), } ) } }
25.6
78
0.559896
de2843ab6e66c816e6fc154cd4c3beb77486d79b
14,843
//! Implementation of AES with 128 bit key. use super::super::sbox::Sbox; use super::{Cipher, CipherStructure}; use super::PropertyType; /***************************************************************** AES ******************************************************************/ /// A structure representing the AES cipher. #[derive(Clone)] pub struct Aes { size: usize, key_size: usize, sbox: Sbox, isbox: Sbox, shift_rows_table: [usize; 16], ishift_rows_table: [usize; 16], } impl Aes { /// Create a new instance of the cipher. pub fn new() -> Aes { let table = vec![ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16, ]; let itable = vec![ 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D, ]; let shift_rows_table = [0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3]; let ishift_rows_table = [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11]; Aes { size: 128, key_size: 128, sbox: Sbox::new(8, 8, table), isbox: Sbox::new(8, 8, itable), shift_rows_table, ishift_rows_table, } } } /// Performs multiplication by two in the AES field fn aes_times2(x: u128) -> u128 { ((x << 1) & 0xff) ^ (((x >> 7) & 0x1) * 0x1b) } impl Cipher for Aes { fn structure(&self) -> CipherStructure { CipherStructure::Spn } fn size(&self) -> usize { self.size } fn key_size(&self) -> usize { self.key_size } fn num_sboxes(&self) -> usize { self.size / self.sbox.size_in() } fn sbox(&self, _i: usize) -> &Sbox { &self.sbox } fn sbox_pos_in(&self, i: usize) -> usize { i * self.sbox(i).size_in() } fn sbox_pos_out(&self, i: usize) -> usize { i * self.sbox(i).size_out() } fn linear_layer(&self, input: u128) -> u128 { let mut x = 0; // Apply ShiftRows for i in 0..16 { x ^= ((input >> (i * 8)) & 0xff) << (self.shift_rows_table[i] * 8); } // Apply MixColumns let mut y = 0; for i in 0..4 { let t = ((x >> (32 * i)) & 0xff) ^ ((x >> (8 + 32 * i)) & 0xff) ^ ((x >> (16 + 32 * i)) & 0xff) ^ ((x >> (24 + 32 * i)) & 0xff); let u = (x >> (32 * i)) & 0xff; y ^= (((x >> (32 * i)) & 0xff) ^ aes_times2(((x >> (32 * i)) & 0xff) ^ ((x >> (8 + 32 * i)) & 0xff)) ^ t) << (32 * i); y ^= (((x >> (8 + 32 * i)) & 0xff) ^ aes_times2(((x >> (8 + 32 * i)) & 0xff) ^ ((x >> (16 + 32 * i)) & 0xff)) ^ t) << (8 + 32 * i); y ^= (((x >> (16 + 32 * i)) & 0xff) ^ aes_times2(((x >> (16 + 32 * i)) & 0xff) ^ ((x >> (24 + 32 * i)) & 0xff)) ^ t) << (16 + 32 * i); y ^= (((x >> (24 + 32 * i)) & 0xff) ^ aes_times2(((x >> (24 + 32 * i)) & 0xff) ^ u) ^ t) << (24 + 32 * i); } y } fn linear_layer_inv(&self, input: u128) -> u128 { // Apply MixColumnsInv let x = input; let mut y = 0; for i in 0..4 { let u = aes_times2(aes_times2( ((x >> (32 * i)) & 0xff) ^ ((x >> (16 + 32 * i)) & 0xff), )); y ^= (((x >> (32 * i)) & 0xff) ^ u) << (32 * i); y ^= (((x >> (16 + 32 * i)) & 0xff) ^ u) << (16 + 32 * i); let u = aes_times2(aes_times2( ((x >> (8 + 32 * i)) & 0xff) ^ ((x >> (24 + 32 * i)) & 0xff), )); y ^= (((x >> (8 + 32 * i)) & 0xff) ^ u) << (8 + 32 * i); y ^= (((x >> (24 + 32 * i)) & 0xff) ^ u) << (24 + 32 * i); } let x = y; let mut y = 0; for i in 0..4 { let t = ((x >> (32 * i)) & 0xff) ^ ((x >> (8 + 32 * i)) & 0xff) ^ ((x >> (16 + 32 * i)) & 0xff) ^ ((x >> (24 + 32 * i)) & 0xff); let u = (x >> (32 * i)) & 0xff; y ^= (((x >> (32 * i)) & 0xff) ^ aes_times2(((x >> (32 * i)) & 0xff) ^ ((x >> (8 + 32 * i)) & 0xff)) ^ t) << (32 * i); y ^= (((x >> (8 + 32 * i)) & 0xff) ^ aes_times2(((x >> (8 + 32 * i)) & 0xff) ^ ((x >> (16 + 32 * i)) & 0xff)) ^ t) << (8 + 32 * i); y ^= (((x >> (16 + 32 * i)) & 0xff) ^ aes_times2(((x >> (16 + 32 * i)) & 0xff) ^ ((x >> (24 + 32 * i)) & 0xff)) ^ t) << (16 + 32 * i); y ^= (((x >> (24 + 32 * i)) & 0xff) ^ aes_times2(((x >> (24 + 32 * i)) & 0xff) ^ u) ^ t) << (24 + 32 * i); } // Apply ShiftRowsInv let mut x = 0; for i in 0..16 { x ^= ((y >> (i * 8)) & 0xff) << (self.ishift_rows_table[i] * 8); } x } fn reflection_layer(&self, _input: u128) -> u128 { panic!("Not implemented for this type of cipher") } fn key_schedule(&self, rounds: usize, key: &[u8]) -> Vec<u128> { if key.len() * 8 != self.key_size { panic!("invalid key-length"); } let mut keys = Vec::new(); let mut k = 0; for &x in key.iter().take(16) { k <<= 8; k |= u128::from(x); } keys.push(k); let mut r_const = 0x01; for _ in 0..rounds { let mut tmp = k >> 96; tmp = ((tmp >> 8) ^ (tmp << 24)) & 0xffffffff; for j in 0..4 { k ^= u128::from(self.sbox.apply((tmp >> (8 * j)) & 0xff)) << (8 * j); } k ^= r_const; for j in 1..4 { k ^= (k & (0xffffffff << (32 * (j - 1)))) << 32; } keys.push(k); r_const = aes_times2(r_const); } keys } fn encrypt(&self, input: u128, round_keys: &[u128]) -> u128 { let mut output = input; // AddRoundKey output ^= round_keys[0]; for i in 0..9 { // SubBytes let mut tmp = 0; for j in 0..16 { tmp ^= u128::from(self.sbox.apply((output >> (j * 8)) & 0xff)) << (j * 8); } // ShiftRows + MixColumns output = self.linear_layer(tmp); // AddRoundKey output ^= round_keys[i + 1] } // SubBytes let mut tmp = 0; for j in 0..16 { tmp ^= u128::from(self.sbox.apply((output >> (j * 8)) & 0xff)) << (j * 8); } // ShiftRows output = 0; for i in 0..16 { output ^= ((tmp >> (i * 8)) & 0xff) << (self.shift_rows_table[i] * 8); } // AddRoundKey output ^= round_keys[10]; output } fn decrypt(&self, input: u128, round_keys: &[u128]) -> u128 { let mut output = input; // AddRoundKey output ^= round_keys[10]; // InvShiftRows let mut tmp = 0; for i in 0..16 { tmp ^= ((output >> (i * 8)) & 0xff) << (self.ishift_rows_table[i] * 8); } // InvSubBytes output = 0; for j in 0..16 { output ^= u128::from(self.isbox.apply((tmp >> (j * 8)) & 0xff)) << (j * 8); } for i in 0..9 { // AddRoundKey output ^= round_keys[9 - i]; // InvShiftRows + InvMixColumns let tmp = self.linear_layer_inv(output); // InvSubBytes output = 0; for j in 0..16 { output ^= u128::from(self.isbox.apply((tmp >> (j * 8)) & 0xff)) << (j * 8); } } output ^= round_keys[0]; output } fn name(&self) -> String { String::from("AES") } fn sbox_mask_transform( &self, input: u128, output: u128, _property_type: PropertyType, ) -> (u128, u128) { (input, self.linear_layer(output)) } #[inline(always)] fn whitening(&self) -> bool { true } } impl Default for Aes { fn default() -> Self { Aes::new() } } #[cfg(test)] mod tests { use super::super::super::cipher; #[test] fn linear() { let cipher = cipher::name_to_cipher("aes").unwrap(); let x = 0x00112233445566778899aabbccddeeff; assert_eq!(x, cipher.linear_layer_inv(cipher.linear_layer(x))); } #[test] fn encryption_test() { let cipher = cipher::name_to_cipher("aes").unwrap(); let key = [ 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, ]; let round_keys = cipher.key_schedule(10, &key); let plaintext = 0xffeeddccbbaa99887766554433221100; let ciphertext = 0x5ac5b47080b7cdd830047b6ad8e0c469; assert_eq!(ciphertext, cipher.encrypt(plaintext, &round_keys)); let key = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let round_keys = cipher.key_schedule(10, &key); let plaintext = 0x00000000000000f8ffffffffffffffff; let ciphertext = 0x11b57e6e49d55493602bb7d633404066; assert_eq!(ciphertext, cipher.encrypt(plaintext, &round_keys)); } #[test] fn decryption_test() { let cipher = cipher::name_to_cipher("aes").unwrap(); let key = [ 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, ]; let round_keys = cipher.key_schedule(10, &key); let plaintext = 0xffeeddccbbaa99887766554433221100; let ciphertext = 0x5ac5b47080b7cdd830047b6ad8e0c469; assert_eq!(plaintext, cipher.decrypt(ciphertext, &round_keys)); let key = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let round_keys = cipher.key_schedule(10, &key); let plaintext = 0x00000000000000f8ffffffffffffffff; let ciphertext = 0x11b57e6e49d55493602bb7d633404066; assert_eq!(plaintext, cipher.decrypt(ciphertext, &round_keys)); } #[test] fn encryption_decryption_test() { let cipher = cipher::name_to_cipher("aes").unwrap(); let key = [ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, ]; let round_keys = cipher.key_schedule(10, &key); let plaintext = 0x00112233445566778899aabbccddeeff; let ciphertext = cipher.encrypt(plaintext, &round_keys); assert_eq!(plaintext, cipher.decrypt(ciphertext, &round_keys)); let key = [ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, ]; let round_keys = cipher.key_schedule(10, &key); let plaintext = 0xffffffffffffffffffffffffffffffff; let ciphertext = cipher.encrypt(plaintext, &round_keys); assert_eq!(plaintext, cipher.decrypt(ciphertext, &round_keys)); } }
33.734091
99
0.474635
713140e598853c9090cc3506236a0d09d9240d32
8,865
extern crate image; use image::{DynamicImage, GenericImageView, Rgba, RgbaImage, imageops}; use imageproc::geometric_transformations::{Projection, Interpolation, warp_into}; use crate::RenderOptions; use crate::skin::Layer::Bottom; use crate::skin::BodyPart::{ArmLeft, LegLeft, Body, Head}; use crate::utils::{apply_minecraft_transparency, fast_overlay}; pub(crate) struct MinecraftSkin(DynamicImage); #[derive(Copy, Clone, PartialEq)] pub(crate) enum MinecraftSkinVersion { Classic, // 64x32 Modern, // 64x64 Invalid } #[derive(Clone, Copy, PartialEq)] pub(crate) enum SkinModel { Slim, Regular, } #[derive(Copy, Clone, PartialEq)] pub(crate) enum Layer { Bottom, Top, Both, } #[derive(Copy, Clone, PartialEq)] pub(crate) enum BodyPart { Head, Body, ArmLeft, ArmRight, LegLeft, LegRight, } const skew_a: f32 = 26.0 / 45.0; // 0.57777777 const skew_b: f32 = skew_a * 2.0; // 1.15555555 impl MinecraftSkin { pub fn new(skin: DynamicImage) -> MinecraftSkin { MinecraftSkin(skin) } fn version(&self) -> MinecraftSkinVersion { match self.0.dimensions() { (64, 32) => MinecraftSkinVersion::Classic, (64, 64) => MinecraftSkinVersion::Modern, _ => MinecraftSkinVersion::Invalid } } pub(crate) fn get_part(&self, layer: Layer, part: BodyPart, model: SkinModel) -> DynamicImage { let arm_width = match model { SkinModel::Slim => 3, SkinModel::Regular => 4 }; match layer { Layer::Both => { if self.version() != MinecraftSkinVersion::Modern && part != Head { return self.get_part(Layer::Bottom, part, model); } let mut bottom = self.get_part(Layer::Bottom, part, model); let mut top = self.get_part(Layer::Top, part, model); apply_minecraft_transparency(&mut top); fast_overlay(&mut bottom, &top, 0, 0); bottom }, Layer::Bottom => { match part { BodyPart::Head => self.0.crop_imm(8, 8, 8, 8), BodyPart::Body => self.0.crop_imm(20, 20, 8, 12), BodyPart::ArmRight => { match self.version() { MinecraftSkinVersion::Modern => self.0.crop_imm(36, 52, arm_width, 12), _ => self.get_part(Bottom, ArmLeft, model).fliph() } }, BodyPart::ArmLeft => self.0.crop_imm(44, 20, arm_width, 12), BodyPart::LegRight => { match self.version() { MinecraftSkinVersion::Modern => self.0.crop_imm(20, 52, 4, 12), _ => self.get_part(Bottom, LegLeft, model).fliph() } }, BodyPart::LegLeft => self.0.crop_imm(4, 20, 4, 12), } }, Layer::Top => { match part { BodyPart::Head => self.0.crop_imm(40, 8, 8, 8), BodyPart::Body => { match self.version() { MinecraftSkinVersion::Modern => self.0.crop_imm(20, 36, 8, 12), _ => self.get_part(Bottom, Body, model) } }, BodyPart::ArmLeft => { match self.version() { MinecraftSkinVersion::Modern => self.0.crop_imm(52, 52, arm_width, 12), _ => self.get_part(Bottom, ArmLeft, model) } }, BodyPart::ArmRight => { match self.version() { MinecraftSkinVersion::Modern => self.0.crop_imm(44, 36, arm_width, 12), _ => self.get_part(Bottom, ArmLeft, model).fliph(), } }, BodyPart::LegLeft => { match self.version() { MinecraftSkinVersion::Modern => self.0.crop_imm(4, 52, 4, 12), _ => self.get_part(Bottom, LegLeft, model), } }, BodyPart::LegRight => { match self.version() { MinecraftSkinVersion::Modern => self.0.crop_imm(4, 36, 4, 12), _ => self.get_part(Bottom, LegLeft, model).fliph(), } }, } }, } } pub(crate) fn get_cape(&self) -> DynamicImage { self.0.crop_imm(1, 1, 10, 16) } pub(crate) fn render_body(&self, options: RenderOptions) -> DynamicImage { let layer_type = match options.armored { true => Layer::Both, false => Layer::Bottom }; let img_width = match options.model { SkinModel::Slim => 14, SkinModel::Regular => 16 }; let arm_width = match options.model { SkinModel::Slim => 3, SkinModel::Regular => 4 }; let mut image = RgbaImage::new(img_width, 32); imageops::overlay(&mut image, &self.get_part(layer_type, BodyPart::Head, options.model), arm_width, 0); imageops::overlay(&mut image, &self.get_part(layer_type, BodyPart::Body, options.model), arm_width, 8); imageops::overlay(&mut image, &self.get_part(layer_type, BodyPart::ArmLeft, options.model), 0, 8); imageops::overlay(&mut image, &self.get_part(layer_type, BodyPart::ArmRight, options.model), arm_width + 8, 8); imageops::overlay(&mut image, &self.get_part(layer_type, BodyPart::LegLeft, options.model), arm_width, 20); imageops::overlay(&mut image, &self.get_part(layer_type, BodyPart::LegRight, options.model), arm_width + 4, 20); DynamicImage::ImageRgba8(image) } pub(crate) fn render_cube(&self, overlay: bool, width: u32) -> DynamicImage { let scale = (width as f32) / 20.0 as f32; let height = (18.5 * scale).ceil() as u32; let layer_type = match overlay { true => Layer::Both, false => Layer::Bottom }; let mut render = RgbaImage::new(width, height); let z_offset = scale * 3.0; let x_offset = scale * 2.0; let head_orig_top = self.0.crop_imm(8, 0, 8, 8); let head_orig_right = self.0.crop_imm(0, 8, 8, 8); let head_orig_front = self.0.crop_imm(8, 8, 8, 8); // The warp_into function clears every part of the output image that is not part of the pre-image. // As a workaround, we ask warp_into to draw into a scratch image, overlay the final image with the // scratch image, and let the scratch be overwritten. let mut scratch = RgbaImage::new(width, height); // head top let head_top_skew = Projection::from_matrix([ 1.0, 1.0, 0.0, -skew_a, skew_a, 0.0, 0.0, 0.0, 1.0, ]).unwrap() * Projection::translate(-0.5 - z_offset, x_offset + z_offset - 0.5) * Projection::scale(scale, scale + (1.0 / 8.0)); warp_into(&head_orig_top.into_rgba8(), &head_top_skew, Interpolation::Nearest, Rgba([0, 0, 0, 0]), &mut scratch); imageops::overlay(&mut render, &scratch, 0, 0); // head front let head_front_skew = Projection::from_matrix([ 1.0, 0.0, 0.0, -skew_a, skew_b, skew_a, 0.0, 0.0, 1.0, ]).unwrap() * Projection::translate(x_offset + 7.5 * scale - 0.5, (x_offset + 8.0 * scale) + z_offset - 0.5) * Projection::scale(scale, scale); warp_into(&head_orig_front.into_rgba8(), &head_front_skew, Interpolation::Nearest, Rgba([0, 0, 0, 0]), &mut scratch); imageops::overlay(&mut render, &scratch, 0, 0); // head right let head_right_skew = Projection::from_matrix([ 1.0, 0.0, 0.0, skew_a, skew_b, 0.0, 0.0, 0.0, 1.0, ]).unwrap() * Projection::translate(x_offset - (scale / 2.0), z_offset + scale) * Projection::scale(scale + (0.5 / 8.0), scale + (1.0 / 8.0)); warp_into(&head_orig_right.into_rgba8(), &head_right_skew, Interpolation::Nearest, Rgba([0, 0, 0, 0]), &mut scratch); imageops::overlay(&mut render, &scratch, 0, 0); DynamicImage::ImageRgba8(render) } }
40.852535
151
0.509645
f5a87bc158d89ddee818b99ecb37b52a701af244
875,302
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn parse_http_generic_error( response: &http::Response<bytes::Bytes>, ) -> Result<smithy_types::Error, smithy_json::deserialize::Error> { crate::json_errors::parse_generic_error(response.body(), response.headers()) } pub fn deser_structure_crate_error_bad_request_exceptionjson_err( input: &[u8], mut builder: crate::error::bad_request_exception::Builder, ) -> Result<crate::error::bad_request_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_crate_error_conflict_exceptionjson_err( input: &[u8], mut builder: crate::error::conflict_exception::Builder, ) -> Result<crate::error::conflict_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_crate_error_forbidden_exceptionjson_err( input: &[u8], mut builder: crate::error::forbidden_exception::Builder, ) -> Result<crate::error::forbidden_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_crate_error_internal_server_error_exceptionjson_err( input: &[u8], mut builder: crate::error::internal_server_error_exception::Builder, ) -> Result<crate::error::internal_server_error_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_crate_error_not_found_exceptionjson_err( input: &[u8], mut builder: crate::error::not_found_exception::Builder, ) -> Result<crate::error::not_found_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_crate_error_too_many_requests_exceptionjson_err( input: &[u8], mut builder: crate::error::too_many_requests_exception::Builder, ) -> Result<crate::error::too_many_requests_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_create_job( input: &[u8], mut builder: crate::output::create_job_output::Builder, ) -> Result<crate::output::create_job_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "job" => { builder = builder .set_job(crate::json_deser::deser_structure_crate_model_job(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_create_job_template( input: &[u8], mut builder: crate::output::create_job_template_output::Builder, ) -> Result<crate::output::create_job_template_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "jobTemplate" => { builder = builder.set_job_template( crate::json_deser::deser_structure_crate_model_job_template(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_create_preset( input: &[u8], mut builder: crate::output::create_preset_output::Builder, ) -> Result<crate::output::create_preset_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "preset" => { builder = builder.set_preset( crate::json_deser::deser_structure_crate_model_preset(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_create_queue( input: &[u8], mut builder: crate::output::create_queue_output::Builder, ) -> Result<crate::output::create_queue_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "queue" => { builder = builder.set_queue( crate::json_deser::deser_structure_crate_model_queue(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_describe_endpoints( input: &[u8], mut builder: crate::output::describe_endpoints_output::Builder, ) -> Result<crate::output::describe_endpoints_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "endpoints" => { builder = builder.set_endpoints( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_endpoint(tokens)? ); } "nextToken" => { builder = builder.set_next_token( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_get_job( input: &[u8], mut builder: crate::output::get_job_output::Builder, ) -> Result<crate::output::get_job_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "job" => { builder = builder .set_job(crate::json_deser::deser_structure_crate_model_job(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_get_job_template( input: &[u8], mut builder: crate::output::get_job_template_output::Builder, ) -> Result<crate::output::get_job_template_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "jobTemplate" => { builder = builder.set_job_template( crate::json_deser::deser_structure_crate_model_job_template(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_get_preset( input: &[u8], mut builder: crate::output::get_preset_output::Builder, ) -> Result<crate::output::get_preset_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "preset" => { builder = builder.set_preset( crate::json_deser::deser_structure_crate_model_preset(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_get_queue( input: &[u8], mut builder: crate::output::get_queue_output::Builder, ) -> Result<crate::output::get_queue_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "queue" => { builder = builder.set_queue( crate::json_deser::deser_structure_crate_model_queue(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_list_jobs( input: &[u8], mut builder: crate::output::list_jobs_output::Builder, ) -> Result<crate::output::list_jobs_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "jobs" => { builder = builder.set_jobs( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_job( tokens, )?, ); } "nextToken" => { builder = builder.set_next_token( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_list_job_templates( input: &[u8], mut builder: crate::output::list_job_templates_output::Builder, ) -> Result<crate::output::list_job_templates_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "jobTemplates" => { builder = builder.set_job_templates( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_job_template(tokens)? ); } "nextToken" => { builder = builder.set_next_token( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_list_presets( input: &[u8], mut builder: crate::output::list_presets_output::Builder, ) -> Result<crate::output::list_presets_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "nextToken" => { builder = builder.set_next_token( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "presets" => { builder = builder.set_presets( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_preset(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_list_queues( input: &[u8], mut builder: crate::output::list_queues_output::Builder, ) -> Result<crate::output::list_queues_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "nextToken" => { builder = builder.set_next_token( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "queues" => { builder = builder.set_queues( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_queue(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_list_tags_for_resource( input: &[u8], mut builder: crate::output::list_tags_for_resource_output::Builder, ) -> Result<crate::output::list_tags_for_resource_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "resourceTags" => { builder = builder.set_resource_tags( crate::json_deser::deser_structure_crate_model_resource_tags(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_update_job_template( input: &[u8], mut builder: crate::output::update_job_template_output::Builder, ) -> Result<crate::output::update_job_template_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "jobTemplate" => { builder = builder.set_job_template( crate::json_deser::deser_structure_crate_model_job_template(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_update_preset( input: &[u8], mut builder: crate::output::update_preset_output::Builder, ) -> Result<crate::output::update_preset_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "preset" => { builder = builder.set_preset( crate::json_deser::deser_structure_crate_model_preset(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_crate_operation_update_queue( input: &[u8], mut builder: crate::output::update_queue_output::Builder, ) -> Result<crate::output::update_queue_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "queue" => { builder = builder.set_queue( crate::json_deser::deser_structure_crate_model_queue(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn or_empty_doc(data: &[u8]) -> &[u8] { if data.is_empty() { b"{}" } else { data } } pub fn deser_structure_crate_model_job<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Job>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Job::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "accelerationSettings" => { builder = builder.set_acceleration_settings( crate::json_deser::deser_structure_crate_model_acceleration_settings(tokens)? ); } "accelerationStatus" => { builder = builder.set_acceleration_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AccelerationStatus::from(u.as_ref()) }) }) .transpose()?, ); } "arn" => { builder = builder.set_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "billingTagsSource" => { builder = builder.set_billing_tags_source( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::BillingTagsSource::from(u.as_ref()) }) }) .transpose()?, ); } "createdAt" => { builder = builder.set_created_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "currentPhase" => { builder = builder.set_current_phase( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::JobPhase::from(u.as_ref())) }) .transpose()?, ); } "errorCode" => { builder = builder.set_error_code( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "errorMessage" => { builder = builder.set_error_message( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "hopDestinations" => { builder = builder.set_hop_destinations( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_hop_destination(tokens)? ); } "id" => { builder = builder.set_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "jobPercentComplete" => { builder = builder.set_job_percent_complete( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "jobTemplate" => { builder = builder.set_job_template( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "messages" => { builder = builder.set_messages( crate::json_deser::deser_structure_crate_model_job_messages( tokens, )?, ); } "outputGroupDetails" => { builder = builder.set_output_group_details( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_output_group_detail(tokens)? ); } "priority" => { builder = builder.set_priority( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "queue" => { builder = builder.set_queue( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "queueTransitions" => { builder = builder.set_queue_transitions( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_queue_transition(tokens)? ); } "retryCount" => { builder = builder.set_retry_count( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "role" => { builder = builder.set_role( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "settings" => { builder = builder.set_settings( crate::json_deser::deser_structure_crate_model_job_settings( tokens, )?, ); } "simulateReservedQueue" => { builder = builder.set_simulate_reserved_queue( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::SimulateReservedQueue::from(u.as_ref()) }) }) .transpose()?, ); } "status" => { builder = builder.set_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::JobStatus::from(u.as_ref())) }) .transpose()?, ); } "statusUpdateInterval" => { builder = builder.set_status_update_interval( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::StatusUpdateInterval::from(u.as_ref()) }) }) .transpose()?, ); } "timing" => { builder = builder.set_timing( crate::json_deser::deser_structure_crate_model_timing(tokens)?, ); } "userMetadata" => { builder = builder.set_user_metadata( crate::json_deser::deser_map_com_amazonaws_mediaconvert___map_of__string(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_job_template<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::JobTemplate>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::JobTemplate::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "accelerationSettings" => { builder = builder.set_acceleration_settings( crate::json_deser::deser_structure_crate_model_acceleration_settings(tokens)? ); } "arn" => { builder = builder.set_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "category" => { builder = builder.set_category( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "createdAt" => { builder = builder.set_created_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "description" => { builder = builder.set_description( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "hopDestinations" => { builder = builder.set_hop_destinations( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_hop_destination(tokens)? ); } "lastUpdated" => { builder = builder.set_last_updated( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "priority" => { builder = builder.set_priority( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "queue" => { builder = builder.set_queue( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "settings" => { builder = builder.set_settings( crate::json_deser::deser_structure_crate_model_job_template_settings(tokens)? ); } "statusUpdateInterval" => { builder = builder.set_status_update_interval( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::StatusUpdateInterval::from(u.as_ref()) }) }) .transpose()?, ); } "type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Type::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_preset<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Preset>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Preset::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "arn" => { builder = builder.set_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "category" => { builder = builder.set_category( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "createdAt" => { builder = builder.set_created_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "description" => { builder = builder.set_description( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "lastUpdated" => { builder = builder.set_last_updated( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "settings" => { builder = builder.set_settings( crate::json_deser::deser_structure_crate_model_preset_settings( tokens, )?, ); } "type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Type::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_queue<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Queue>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Queue::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "arn" => { builder = builder.set_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "createdAt" => { builder = builder.set_created_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "description" => { builder = builder.set_description( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "lastUpdated" => { builder = builder.set_last_updated( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "pricingPlan" => { builder = builder.set_pricing_plan( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::PricingPlan::from(u.as_ref())) }) .transpose()?, ); } "progressingJobsCount" => { builder = builder.set_progressing_jobs_count( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "reservationPlan" => { builder = builder.set_reservation_plan( crate::json_deser::deser_structure_crate_model_reservation_plan(tokens)? ); } "status" => { builder = builder.set_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::QueueStatus::from(u.as_ref())) }) .transpose()?, ); } "submittedJobsCount" => { builder = builder.set_submitted_jobs_count( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Type::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_endpoint<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Endpoint>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_endpoint(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_job<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Job>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_job(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_job_template<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::JobTemplate>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_job_template(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_preset<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Preset>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_preset(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_queue<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Queue>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_queue(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_resource_tags<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ResourceTags>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ResourceTags::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "arn" => { builder = builder.set_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "tags" => { builder = builder.set_tags( crate::json_deser::deser_map_com_amazonaws_mediaconvert___map_of__string(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_acceleration_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AccelerationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AccelerationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "mode" => { builder = builder.set_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AccelerationMode::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_hop_destination<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::HopDestination>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_hop_destination(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_job_messages<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::JobMessages>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::JobMessages::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "info" => { builder = builder.set_info( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__string(tokens)? ); } "warning" => { builder = builder.set_warning( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__string(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_output_group_detail<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::OutputGroupDetail>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_output_group_detail( tokens, )?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_queue_transition<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::QueueTransition>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_queue_transition( tokens, )?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_job_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::JobSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::JobSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "adAvailOffset" => { builder = builder.set_ad_avail_offset( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "availBlanking" => { builder = builder.set_avail_blanking( crate::json_deser::deser_structure_crate_model_avail_blanking( tokens, )?, ); } "esam" => { builder = builder.set_esam( crate::json_deser::deser_structure_crate_model_esam_settings( tokens, )?, ); } "extendedDataServices" => { builder = builder.set_extended_data_services( crate::json_deser::deser_structure_crate_model_extended_data_services(tokens)? ); } "inputs" => { builder = builder.set_inputs( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_input(tokens)? ); } "kantarWatermark" => { builder = builder.set_kantar_watermark( crate::json_deser::deser_structure_crate_model_kantar_watermark_settings(tokens)? ); } "motionImageInserter" => { builder = builder.set_motion_image_inserter( crate::json_deser::deser_structure_crate_model_motion_image_inserter(tokens)? ); } "nielsenConfiguration" => { builder = builder.set_nielsen_configuration( crate::json_deser::deser_structure_crate_model_nielsen_configuration(tokens)? ); } "nielsenNonLinearWatermark" => { builder = builder.set_nielsen_non_linear_watermark( crate::json_deser::deser_structure_crate_model_nielsen_non_linear_watermark_settings(tokens)? ); } "outputGroups" => { builder = builder.set_output_groups( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_output_group(tokens)? ); } "timecodeConfig" => { builder = builder.set_timecode_config( crate::json_deser::deser_structure_crate_model_timecode_config( tokens, )?, ); } "timedMetadataInsertion" => { builder = builder.set_timed_metadata_insertion( crate::json_deser::deser_structure_crate_model_timed_metadata_insertion(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_timing<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Timing>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Timing::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "finishTime" => { builder = builder.set_finish_time( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "startTime" => { builder = builder.set_start_time( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "submitTime" => { builder = builder.set_submit_time( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_com_amazonaws_mediaconvert___map_of__string<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::collections::HashMap<std::string::String, std::string::String>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key.to_unescaped().map(|u| u.into_owned())?; let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_job_template_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::JobTemplateSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::JobTemplateSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "adAvailOffset" => { builder = builder.set_ad_avail_offset( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "availBlanking" => { builder = builder.set_avail_blanking( crate::json_deser::deser_structure_crate_model_avail_blanking( tokens, )?, ); } "esam" => { builder = builder.set_esam( crate::json_deser::deser_structure_crate_model_esam_settings( tokens, )?, ); } "extendedDataServices" => { builder = builder.set_extended_data_services( crate::json_deser::deser_structure_crate_model_extended_data_services(tokens)? ); } "inputs" => { builder = builder.set_inputs( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_input_template(tokens)? ); } "kantarWatermark" => { builder = builder.set_kantar_watermark( crate::json_deser::deser_structure_crate_model_kantar_watermark_settings(tokens)? ); } "motionImageInserter" => { builder = builder.set_motion_image_inserter( crate::json_deser::deser_structure_crate_model_motion_image_inserter(tokens)? ); } "nielsenConfiguration" => { builder = builder.set_nielsen_configuration( crate::json_deser::deser_structure_crate_model_nielsen_configuration(tokens)? ); } "nielsenNonLinearWatermark" => { builder = builder.set_nielsen_non_linear_watermark( crate::json_deser::deser_structure_crate_model_nielsen_non_linear_watermark_settings(tokens)? ); } "outputGroups" => { builder = builder.set_output_groups( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_output_group(tokens)? ); } "timecodeConfig" => { builder = builder.set_timecode_config( crate::json_deser::deser_structure_crate_model_timecode_config( tokens, )?, ); } "timedMetadataInsertion" => { builder = builder.set_timed_metadata_insertion( crate::json_deser::deser_structure_crate_model_timed_metadata_insertion(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_preset_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::PresetSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::PresetSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioDescriptions" => { builder = builder.set_audio_descriptions( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_audio_description(tokens)? ); } "captionDescriptions" => { builder = builder.set_caption_descriptions( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_caption_description_preset(tokens)? ); } "containerSettings" => { builder = builder.set_container_settings( crate::json_deser::deser_structure_crate_model_container_settings(tokens)? ); } "videoDescription" => { builder = builder.set_video_description( crate::json_deser::deser_structure_crate_model_video_description(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_reservation_plan<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ReservationPlan>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ReservationPlan::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "commitment" => { builder = builder.set_commitment( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Commitment::from(u.as_ref())) }) .transpose()?, ); } "expiresAt" => { builder = builder.set_expires_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "purchasedAt" => { builder = builder.set_purchased_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "renewalType" => { builder = builder.set_renewal_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::RenewalType::from(u.as_ref())) }) .transpose()?, ); } "reservedSlots" => { builder = builder.set_reserved_slots( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "status" => { builder = builder.set_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ReservationPlanStatus::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_endpoint<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Endpoint>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Endpoint::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "url" => { builder = builder.set_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_hop_destination<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::HopDestination>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::HopDestination::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "priority" => { builder = builder.set_priority( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "queue" => { builder = builder.set_queue( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "waitMinutes" => { builder = builder.set_wait_minutes( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of__string<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_output_group_detail<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::OutputGroupDetail>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::OutputGroupDetail::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "outputDetails" => { builder = builder.set_output_details( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_output_detail(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_queue_transition<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::QueueTransition>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::QueueTransition::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "destinationQueue" => { builder = builder.set_destination_queue( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "sourceQueue" => { builder = builder.set_source_queue( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "timestamp" => { builder = builder.set_timestamp( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_avail_blanking<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AvailBlanking>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AvailBlanking::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "availBlankingImage" => { builder = builder.set_avail_blanking_image( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_esam_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::EsamSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::EsamSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "manifestConfirmConditionNotification" => { builder = builder.set_manifest_confirm_condition_notification( crate::json_deser::deser_structure_crate_model_esam_manifest_confirm_condition_notification(tokens)? ); } "responseSignalPreroll" => { builder = builder.set_response_signal_preroll( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "signalProcessingNotification" => { builder = builder.set_signal_processing_notification( crate::json_deser::deser_structure_crate_model_esam_signal_processing_notification(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_extended_data_services<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ExtendedDataServices>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ExtendedDataServices::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "copyProtectionAction" => { builder = builder.set_copy_protection_action( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CopyProtectionAction::from(u.as_ref()) }) }) .transpose()?, ); } "vchipAction" => { builder = builder.set_vchip_action( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::VchipAction::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_input<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Input>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_input(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_kantar_watermark_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::KantarWatermarkSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::KantarWatermarkSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "channelName" => { builder = builder.set_channel_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "contentReference" => { builder = builder.set_content_reference( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "credentialsSecretName" => { builder = builder.set_credentials_secret_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "fileOffset" => { builder = builder.set_file_offset( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "kantarLicenseId" => { builder = builder.set_kantar_license_id( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "kantarServerUrl" => { builder = builder.set_kantar_server_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "logDestination" => { builder = builder.set_log_destination( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "metadata3" => { builder = builder.set_metadata3( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "metadata4" => { builder = builder.set_metadata4( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "metadata5" => { builder = builder.set_metadata5( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "metadata6" => { builder = builder.set_metadata6( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "metadata7" => { builder = builder.set_metadata7( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "metadata8" => { builder = builder.set_metadata8( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_motion_image_inserter<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MotionImageInserter>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MotionImageInserter::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "framerate" => { builder = builder.set_framerate( crate::json_deser::deser_structure_crate_model_motion_image_insertion_framerate(tokens)? ); } "input" => { builder = builder.set_input( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "insertionMode" => { builder = builder.set_insertion_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MotionImageInsertionMode::from(u.as_ref()) }) }) .transpose()?, ); } "offset" => { builder = builder.set_offset( crate::json_deser::deser_structure_crate_model_motion_image_insertion_offset(tokens)? ); } "playback" => { builder = builder.set_playback( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MotionImagePlayback::from(u.as_ref()) }) }) .transpose()?, ); } "startTime" => { builder = builder.set_start_time( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_nielsen_configuration<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::NielsenConfiguration>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::NielsenConfiguration::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "breakoutCode" => { builder = builder.set_breakout_code( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "distributorId" => { builder = builder.set_distributor_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_nielsen_non_linear_watermark_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::NielsenNonLinearWatermarkSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::NielsenNonLinearWatermarkSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "activeWatermarkProcess" => { builder = builder.set_active_watermark_process( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::NielsenActiveWatermarkProcessType::from( u.as_ref(), ) }) }) .transpose()?, ); } "adiFilename" => { builder = builder.set_adi_filename( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "assetId" => { builder = builder.set_asset_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "assetName" => { builder = builder.set_asset_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "cbetSourceId" => { builder = builder.set_cbet_source_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "episodeId" => { builder = builder.set_episode_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "metadataDestination" => { builder = builder.set_metadata_destination( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "sourceId" => { builder = builder.set_source_id( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "sourceWatermarkStatus" => { builder = builder.set_source_watermark_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::NielsenSourceWatermarkStatusType::from( u.as_ref(), ) }) }) .transpose()?, ); } "ticServerUrl" => { builder = builder.set_tic_server_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "uniqueTicPerAudioTrack" => { builder = builder.set_unique_tic_per_audio_track( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::NielsenUniqueTicPerAudioTrackType::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_output_group<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::OutputGroup>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_output_group(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_timecode_config<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::TimecodeConfig>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TimecodeConfig::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "anchor" => { builder = builder.set_anchor( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "source" => { builder = builder.set_source( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::TimecodeSource::from(u.as_ref())) }) .transpose()?, ); } "start" => { builder = builder.set_start( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "timestampOffset" => { builder = builder.set_timestamp_offset( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_timed_metadata_insertion<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::TimedMetadataInsertion>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TimedMetadataInsertion::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "id3Insertions" => { builder = builder.set_id3_insertions( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_id3_insertion(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_input_template<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::InputTemplate>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_input_template(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_audio_description<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::AudioDescription>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_audio_description( tokens, )?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_caption_description_preset<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::CaptionDescriptionPreset>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_caption_description_preset(tokens)? ; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_container_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ContainerSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ContainerSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "cmfcSettings" => { builder = builder.set_cmfc_settings( crate::json_deser::deser_structure_crate_model_cmfc_settings( tokens, )?, ); } "container" => { builder = builder.set_container( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ContainerType::from(u.as_ref())) }) .transpose()?, ); } "f4vSettings" => { builder = builder.set_f4v_settings( crate::json_deser::deser_structure_crate_model_f4v_settings( tokens, )?, ); } "m2tsSettings" => { builder = builder.set_m2ts_settings( crate::json_deser::deser_structure_crate_model_m2ts_settings( tokens, )?, ); } "m3u8Settings" => { builder = builder.set_m3u8_settings( crate::json_deser::deser_structure_crate_model_m3u8_settings( tokens, )?, ); } "movSettings" => { builder = builder.set_mov_settings( crate::json_deser::deser_structure_crate_model_mov_settings( tokens, )?, ); } "mp4Settings" => { builder = builder.set_mp4_settings( crate::json_deser::deser_structure_crate_model_mp4_settings( tokens, )?, ); } "mpdSettings" => { builder = builder.set_mpd_settings( crate::json_deser::deser_structure_crate_model_mpd_settings( tokens, )?, ); } "mxfSettings" => { builder = builder.set_mxf_settings( crate::json_deser::deser_structure_crate_model_mxf_settings( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_video_description<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::VideoDescription>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::VideoDescription::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "afdSignaling" => { builder = builder.set_afd_signaling( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::AfdSignaling::from(u.as_ref())) }) .transpose()?, ); } "antiAlias" => { builder = builder.set_anti_alias( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::AntiAlias::from(u.as_ref())) }) .transpose()?, ); } "codecSettings" => { builder = builder.set_codec_settings( crate::json_deser::deser_structure_crate_model_video_codec_settings(tokens)? ); } "colorMetadata" => { builder = builder.set_color_metadata( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ColorMetadata::from(u.as_ref())) }) .transpose()?, ); } "crop" => { builder = builder.set_crop( crate::json_deser::deser_structure_crate_model_rectangle( tokens, )?, ); } "dropFrameTimecode" => { builder = builder.set_drop_frame_timecode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DropFrameTimecode::from(u.as_ref()) }) }) .transpose()?, ); } "fixedAfd" => { builder = builder.set_fixed_afd( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "height" => { builder = builder.set_height( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "position" => { builder = builder.set_position( crate::json_deser::deser_structure_crate_model_rectangle( tokens, )?, ); } "respondToAfd" => { builder = builder.set_respond_to_afd( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::RespondToAfd::from(u.as_ref())) }) .transpose()?, ); } "scalingBehavior" => { builder = builder.set_scaling_behavior( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ScalingBehavior::from(u.as_ref()) }) }) .transpose()?, ); } "sharpness" => { builder = builder.set_sharpness( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "timecodeInsertion" => { builder = builder.set_timecode_insertion( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::VideoTimecodeInsertion::from(u.as_ref()) }) }) .transpose()?, ); } "videoPreprocessors" => { builder = builder.set_video_preprocessors( crate::json_deser::deser_structure_crate_model_video_preprocessor(tokens)? ); } "width" => { builder = builder.set_width( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_output_detail<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::OutputDetail>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_output_detail(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_esam_manifest_confirm_condition_notification<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::EsamManifestConfirmConditionNotification>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::EsamManifestConfirmConditionNotification::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "mccXml" => { builder = builder.set_mcc_xml( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_esam_signal_processing_notification<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::EsamSignalProcessingNotification>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::EsamSignalProcessingNotification::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "sccXml" => { builder = builder.set_scc_xml( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_input<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Input>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Input::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioSelectorGroups" => { builder = builder.set_audio_selector_groups( crate::json_deser::deser_map_com_amazonaws_mediaconvert___map_of_audio_selector_group(tokens)? ); } "audioSelectors" => { builder = builder.set_audio_selectors( crate::json_deser::deser_map_com_amazonaws_mediaconvert___map_of_audio_selector(tokens)? ); } "captionSelectors" => { builder = builder.set_caption_selectors( crate::json_deser::deser_map_com_amazonaws_mediaconvert___map_of_caption_selector(tokens)? ); } "crop" => { builder = builder.set_crop( crate::json_deser::deser_structure_crate_model_rectangle( tokens, )?, ); } "deblockFilter" => { builder = builder.set_deblock_filter( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InputDeblockFilter::from(u.as_ref()) }) }) .transpose()?, ); } "decryptionSettings" => { builder = builder.set_decryption_settings( crate::json_deser::deser_structure_crate_model_input_decryption_settings(tokens)? ); } "denoiseFilter" => { builder = builder.set_denoise_filter( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InputDenoiseFilter::from(u.as_ref()) }) }) .transpose()?, ); } "fileInput" => { builder = builder.set_file_input( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "filterEnable" => { builder = builder.set_filter_enable( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InputFilterEnable::from(u.as_ref()) }) }) .transpose()?, ); } "filterStrength" => { builder = builder.set_filter_strength( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "imageInserter" => { builder = builder.set_image_inserter( crate::json_deser::deser_structure_crate_model_image_inserter( tokens, )?, ); } "inputClippings" => { builder = builder.set_input_clippings( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_input_clipping(tokens)? ); } "inputScanType" => { builder = builder.set_input_scan_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::InputScanType::from(u.as_ref())) }) .transpose()?, ); } "position" => { builder = builder.set_position( crate::json_deser::deser_structure_crate_model_rectangle( tokens, )?, ); } "programNumber" => { builder = builder.set_program_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "psiControl" => { builder = builder.set_psi_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InputPsiControl::from(u.as_ref()) }) }) .transpose()?, ); } "supplementalImps" => { builder = builder.set_supplemental_imps( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__string_pattern_s3_assetmap_xml(tokens)? ); } "timecodeSource" => { builder = builder.set_timecode_source( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InputTimecodeSource::from(u.as_ref()) }) }) .transpose()?, ); } "timecodeStart" => { builder = builder.set_timecode_start( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "videoSelector" => { builder = builder.set_video_selector( crate::json_deser::deser_structure_crate_model_video_selector( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_motion_image_insertion_framerate<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MotionImageInsertionFramerate>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MotionImageInsertionFramerate::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_motion_image_insertion_offset<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MotionImageInsertionOffset>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MotionImageInsertionOffset::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "imageX" => { builder = builder.set_image_x( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "imageY" => { builder = builder.set_image_y( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_output_group<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::OutputGroup>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::OutputGroup::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "automatedEncodingSettings" => { builder = builder.set_automated_encoding_settings( crate::json_deser::deser_structure_crate_model_automated_encoding_settings(tokens)? ); } "customName" => { builder = builder.set_custom_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "outputGroupSettings" => { builder = builder.set_output_group_settings( crate::json_deser::deser_structure_crate_model_output_group_settings(tokens)? ); } "outputs" => { builder = builder.set_outputs( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_output(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_id3_insertion<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Id3Insertion>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_id3_insertion(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_input_template<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::InputTemplate>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::InputTemplate::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioSelectorGroups" => { builder = builder.set_audio_selector_groups( crate::json_deser::deser_map_com_amazonaws_mediaconvert___map_of_audio_selector_group(tokens)? ); } "audioSelectors" => { builder = builder.set_audio_selectors( crate::json_deser::deser_map_com_amazonaws_mediaconvert___map_of_audio_selector(tokens)? ); } "captionSelectors" => { builder = builder.set_caption_selectors( crate::json_deser::deser_map_com_amazonaws_mediaconvert___map_of_caption_selector(tokens)? ); } "crop" => { builder = builder.set_crop( crate::json_deser::deser_structure_crate_model_rectangle( tokens, )?, ); } "deblockFilter" => { builder = builder.set_deblock_filter( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InputDeblockFilter::from(u.as_ref()) }) }) .transpose()?, ); } "denoiseFilter" => { builder = builder.set_denoise_filter( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InputDenoiseFilter::from(u.as_ref()) }) }) .transpose()?, ); } "filterEnable" => { builder = builder.set_filter_enable( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InputFilterEnable::from(u.as_ref()) }) }) .transpose()?, ); } "filterStrength" => { builder = builder.set_filter_strength( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "imageInserter" => { builder = builder.set_image_inserter( crate::json_deser::deser_structure_crate_model_image_inserter( tokens, )?, ); } "inputClippings" => { builder = builder.set_input_clippings( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_input_clipping(tokens)? ); } "inputScanType" => { builder = builder.set_input_scan_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::InputScanType::from(u.as_ref())) }) .transpose()?, ); } "position" => { builder = builder.set_position( crate::json_deser::deser_structure_crate_model_rectangle( tokens, )?, ); } "programNumber" => { builder = builder.set_program_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "psiControl" => { builder = builder.set_psi_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InputPsiControl::from(u.as_ref()) }) }) .transpose()?, ); } "timecodeSource" => { builder = builder.set_timecode_source( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InputTimecodeSource::from(u.as_ref()) }) }) .transpose()?, ); } "timecodeStart" => { builder = builder.set_timecode_start( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "videoSelector" => { builder = builder.set_video_selector( crate::json_deser::deser_structure_crate_model_video_selector( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_audio_description<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AudioDescription>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AudioDescription::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioChannelTaggingSettings" => { builder = builder.set_audio_channel_tagging_settings( crate::json_deser::deser_structure_crate_model_audio_channel_tagging_settings(tokens)? ); } "audioNormalizationSettings" => { builder = builder.set_audio_normalization_settings( crate::json_deser::deser_structure_crate_model_audio_normalization_settings(tokens)? ); } "audioSourceName" => { builder = builder.set_audio_source_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "audioType" => { builder = builder.set_audio_type( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "audioTypeControl" => { builder = builder.set_audio_type_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AudioTypeControl::from(u.as_ref()) }) }) .transpose()?, ); } "codecSettings" => { builder = builder.set_codec_settings( crate::json_deser::deser_structure_crate_model_audio_codec_settings(tokens)? ); } "customLanguageCode" => { builder = builder.set_custom_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "languageCode" => { builder = builder.set_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::LanguageCode::from(u.as_ref())) }) .transpose()?, ); } "languageCodeControl" => { builder = builder.set_language_code_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AudioLanguageCodeControl::from(u.as_ref()) }) }) .transpose()?, ); } "remixSettings" => { builder = builder.set_remix_settings( crate::json_deser::deser_structure_crate_model_remix_settings( tokens, )?, ); } "streamName" => { builder = builder.set_stream_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_caption_description_preset<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CaptionDescriptionPreset>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CaptionDescriptionPreset::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "customLanguageCode" => { builder = builder.set_custom_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "destinationSettings" => { builder = builder.set_destination_settings( crate::json_deser::deser_structure_crate_model_caption_destination_settings(tokens)? ); } "languageCode" => { builder = builder.set_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::LanguageCode::from(u.as_ref())) }) .transpose()?, ); } "languageDescription" => { builder = builder.set_language_description( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_cmfc_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CmfcSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CmfcSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioDuration" => { builder = builder.set_audio_duration( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmfcAudioDuration::from(u.as_ref()) }) }) .transpose()?, ); } "audioGroupId" => { builder = builder.set_audio_group_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "audioRenditionSets" => { builder = builder.set_audio_rendition_sets( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "audioTrackType" => { builder = builder.set_audio_track_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmfcAudioTrackType::from(u.as_ref()) }) }) .transpose()?, ); } "descriptiveVideoServiceFlag" => { builder = builder.set_descriptive_video_service_flag( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmfcDescriptiveVideoServiceFlag::from( u.as_ref(), ) }) }) .transpose()?, ); } "iFrameOnlyManifest" => { builder = builder.set_i_frame_only_manifest( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmfcIFrameOnlyManifest::from(u.as_ref()) }) }) .transpose()?, ); } "scte35Esam" => { builder = builder.set_scte35_esam( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::CmfcScte35Esam::from(u.as_ref())) }) .transpose()?, ); } "scte35Source" => { builder = builder.set_scte35_source( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmfcScte35Source::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_f4v_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::F4vSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::F4vSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "moovPlacement" => { builder = builder.set_moov_placement( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::F4vMoovPlacement::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_m2ts_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::M2tsSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::M2tsSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioBufferModel" => { builder = builder.set_audio_buffer_model( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M2tsAudioBufferModel::from(u.as_ref()) }) }) .transpose()?, ); } "audioDuration" => { builder = builder.set_audio_duration( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M2tsAudioDuration::from(u.as_ref()) }) }) .transpose()?, ); } "audioFramesPerPes" => { builder = builder.set_audio_frames_per_pes( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "audioPids" => { builder = builder.set_audio_pids( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__integer_min32_max8182(tokens)? ); } "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "bufferModel" => { builder = builder.set_buffer_model( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M2tsBufferModel::from(u.as_ref()) }) }) .transpose()?, ); } "dataPTSControl" => { builder = builder.set_data_pts_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M2tsDataPtsControl::from(u.as_ref()) }) }) .transpose()?, ); } "dvbNitSettings" => { builder = builder.set_dvb_nit_settings( crate::json_deser::deser_structure_crate_model_dvb_nit_settings(tokens)? ); } "dvbSdtSettings" => { builder = builder.set_dvb_sdt_settings( crate::json_deser::deser_structure_crate_model_dvb_sdt_settings(tokens)? ); } "dvbSubPids" => { builder = builder.set_dvb_sub_pids( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__integer_min32_max8182(tokens)? ); } "dvbTdtSettings" => { builder = builder.set_dvb_tdt_settings( crate::json_deser::deser_structure_crate_model_dvb_tdt_settings(tokens)? ); } "dvbTeletextPid" => { builder = builder.set_dvb_teletext_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "ebpAudioInterval" => { builder = builder.set_ebp_audio_interval( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M2tsEbpAudioInterval::from(u.as_ref()) }) }) .transpose()?, ); } "ebpPlacement" => { builder = builder.set_ebp_placement( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M2tsEbpPlacement::from(u.as_ref()) }) }) .transpose()?, ); } "esRateInPes" => { builder = builder.set_es_rate_in_pes( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M2tsEsRateInPes::from(u.as_ref()) }) }) .transpose()?, ); } "forceTsVideoEbpOrder" => { builder = builder.set_force_ts_video_ebp_order( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M2tsForceTsVideoEbpOrder::from(u.as_ref()) }) }) .transpose()?, ); } "fragmentTime" => { builder = builder.set_fragment_time( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "maxPcrInterval" => { builder = builder.set_max_pcr_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "minEbpInterval" => { builder = builder.set_min_ebp_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "nielsenId3" => { builder = builder.set_nielsen_id3( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::M2tsNielsenId3::from(u.as_ref())) }) .transpose()?, ); } "nullPacketBitrate" => { builder = builder.set_null_packet_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "patInterval" => { builder = builder.set_pat_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "pcrControl" => { builder = builder.set_pcr_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::M2tsPcrControl::from(u.as_ref())) }) .transpose()?, ); } "pcrPid" => { builder = builder.set_pcr_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "pmtInterval" => { builder = builder.set_pmt_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "pmtPid" => { builder = builder.set_pmt_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "privateMetadataPid" => { builder = builder.set_private_metadata_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "programNumber" => { builder = builder.set_program_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "rateMode" => { builder = builder.set_rate_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::M2tsRateMode::from(u.as_ref())) }) .transpose()?, ); } "scte35Esam" => { builder = builder.set_scte35_esam( crate::json_deser::deser_structure_crate_model_m2ts_scte35_esam(tokens)? ); } "scte35Pid" => { builder = builder.set_scte35_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "scte35Source" => { builder = builder.set_scte35_source( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M2tsScte35Source::from(u.as_ref()) }) }) .transpose()?, ); } "segmentationMarkers" => { builder = builder.set_segmentation_markers( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M2tsSegmentationMarkers::from(u.as_ref()) }) }) .transpose()?, ); } "segmentationStyle" => { builder = builder.set_segmentation_style( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M2tsSegmentationStyle::from(u.as_ref()) }) }) .transpose()?, ); } "segmentationTime" => { builder = builder.set_segmentation_time( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "timedMetadataPid" => { builder = builder.set_timed_metadata_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "transportStreamId" => { builder = builder.set_transport_stream_id( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "videoPid" => { builder = builder.set_video_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_m3u8_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::M3u8Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::M3u8Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioDuration" => { builder = builder.set_audio_duration( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M3u8AudioDuration::from(u.as_ref()) }) }) .transpose()?, ); } "audioFramesPerPes" => { builder = builder.set_audio_frames_per_pes( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "audioPids" => { builder = builder.set_audio_pids( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__integer_min32_max8182(tokens)? ); } "dataPTSControl" => { builder = builder.set_data_pts_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M3u8DataPtsControl::from(u.as_ref()) }) }) .transpose()?, ); } "maxPcrInterval" => { builder = builder.set_max_pcr_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "nielsenId3" => { builder = builder.set_nielsen_id3( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::M3u8NielsenId3::from(u.as_ref())) }) .transpose()?, ); } "patInterval" => { builder = builder.set_pat_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "pcrControl" => { builder = builder.set_pcr_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::M3u8PcrControl::from(u.as_ref())) }) .transpose()?, ); } "pcrPid" => { builder = builder.set_pcr_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "pmtInterval" => { builder = builder.set_pmt_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "pmtPid" => { builder = builder.set_pmt_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "privateMetadataPid" => { builder = builder.set_private_metadata_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "programNumber" => { builder = builder.set_program_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "scte35Pid" => { builder = builder.set_scte35_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "scte35Source" => { builder = builder.set_scte35_source( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::M3u8Scte35Source::from(u.as_ref()) }) }) .transpose()?, ); } "timedMetadata" => { builder = builder.set_timed_metadata( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::TimedMetadata::from(u.as_ref())) }) .transpose()?, ); } "timedMetadataPid" => { builder = builder.set_timed_metadata_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "transportStreamId" => { builder = builder.set_transport_stream_id( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "videoPid" => { builder = builder.set_video_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_mov_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MovSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MovSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "clapAtom" => { builder = builder.set_clap_atom( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::MovClapAtom::from(u.as_ref())) }) .transpose()?, ); } "cslgAtom" => { builder = builder.set_cslg_atom( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::MovCslgAtom::from(u.as_ref())) }) .transpose()?, ); } "mpeg2FourCCControl" => { builder = builder.set_mpeg2_four_cc_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MovMpeg2FourCcControl::from(u.as_ref()) }) }) .transpose()?, ); } "paddingControl" => { builder = builder.set_padding_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MovPaddingControl::from(u.as_ref()) }) }) .transpose()?, ); } "reference" => { builder = builder.set_reference( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::MovReference::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_mp4_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Mp4Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Mp4Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioDuration" => { builder = builder.set_audio_duration( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmfcAudioDuration::from(u.as_ref()) }) }) .transpose()?, ); } "cslgAtom" => { builder = builder.set_cslg_atom( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Mp4CslgAtom::from(u.as_ref())) }) .transpose()?, ); } "cttsVersion" => { builder = builder.set_ctts_version( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "freeSpaceBox" => { builder = builder.set_free_space_box( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mp4FreeSpaceBox::from(u.as_ref()) }) }) .transpose()?, ); } "moovPlacement" => { builder = builder.set_moov_placement( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mp4MoovPlacement::from(u.as_ref()) }) }) .transpose()?, ); } "mp4MajorBrand" => { builder = builder.set_mp4_major_brand( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_mpd_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MpdSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MpdSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "accessibilityCaptionHints" => { builder = builder.set_accessibility_caption_hints( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MpdAccessibilityCaptionHints::from( u.as_ref(), ) }) }) .transpose()?, ); } "audioDuration" => { builder = builder.set_audio_duration( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MpdAudioDuration::from(u.as_ref()) }) }) .transpose()?, ); } "captionContainerType" => { builder = builder.set_caption_container_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MpdCaptionContainerType::from(u.as_ref()) }) }) .transpose()?, ); } "scte35Esam" => { builder = builder.set_scte35_esam( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::MpdScte35Esam::from(u.as_ref())) }) .transpose()?, ); } "scte35Source" => { builder = builder.set_scte35_source( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MpdScte35Source::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_mxf_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MxfSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MxfSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "afdSignaling" => { builder = builder.set_afd_signaling( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MxfAfdSignaling::from(u.as_ref()) }) }) .transpose()?, ); } "profile" => { builder = builder.set_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::MxfProfile::from(u.as_ref())) }) .transpose()?, ); } "xavcProfileSettings" => { builder = builder.set_xavc_profile_settings( crate::json_deser::deser_structure_crate_model_mxf_xavc_profile_settings(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_video_codec_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::VideoCodecSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::VideoCodecSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "av1Settings" => { builder = builder.set_av1_settings( crate::json_deser::deser_structure_crate_model_av1_settings( tokens, )?, ); } "avcIntraSettings" => { builder = builder.set_avc_intra_settings( crate::json_deser::deser_structure_crate_model_avc_intra_settings(tokens)? ); } "codec" => { builder = builder.set_codec( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::VideoCodec::from(u.as_ref())) }) .transpose()?, ); } "frameCaptureSettings" => { builder = builder.set_frame_capture_settings( crate::json_deser::deser_structure_crate_model_frame_capture_settings(tokens)? ); } "h264Settings" => { builder = builder.set_h264_settings( crate::json_deser::deser_structure_crate_model_h264_settings( tokens, )?, ); } "h265Settings" => { builder = builder.set_h265_settings( crate::json_deser::deser_structure_crate_model_h265_settings( tokens, )?, ); } "mpeg2Settings" => { builder = builder.set_mpeg2_settings( crate::json_deser::deser_structure_crate_model_mpeg2_settings( tokens, )?, ); } "proresSettings" => { builder = builder.set_prores_settings( crate::json_deser::deser_structure_crate_model_prores_settings( tokens, )?, ); } "vc3Settings" => { builder = builder.set_vc3_settings( crate::json_deser::deser_structure_crate_model_vc3_settings( tokens, )?, ); } "vp8Settings" => { builder = builder.set_vp8_settings( crate::json_deser::deser_structure_crate_model_vp8_settings( tokens, )?, ); } "vp9Settings" => { builder = builder.set_vp9_settings( crate::json_deser::deser_structure_crate_model_vp9_settings( tokens, )?, ); } "xavcSettings" => { builder = builder.set_xavc_settings( crate::json_deser::deser_structure_crate_model_xavc_settings( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_rectangle<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Rectangle>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Rectangle::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "height" => { builder = builder.set_height( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "width" => { builder = builder.set_width( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "x" => { builder = builder.set_x( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "y" => { builder = builder.set_y( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_video_preprocessor<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::VideoPreprocessor>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::VideoPreprocessor::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "colorCorrector" => { builder = builder.set_color_corrector( crate::json_deser::deser_structure_crate_model_color_corrector( tokens, )?, ); } "deinterlacer" => { builder = builder.set_deinterlacer( crate::json_deser::deser_structure_crate_model_deinterlacer( tokens, )?, ); } "dolbyVision" => { builder = builder.set_dolby_vision( crate::json_deser::deser_structure_crate_model_dolby_vision( tokens, )?, ); } "hdr10Plus" => { builder = builder.set_hdr10_plus( crate::json_deser::deser_structure_crate_model_hdr10_plus( tokens, )?, ); } "imageInserter" => { builder = builder.set_image_inserter( crate::json_deser::deser_structure_crate_model_image_inserter( tokens, )?, ); } "noiseReducer" => { builder = builder.set_noise_reducer( crate::json_deser::deser_structure_crate_model_noise_reducer( tokens, )?, ); } "partnerWatermarking" => { builder = builder.set_partner_watermarking( crate::json_deser::deser_structure_crate_model_partner_watermarking(tokens)? ); } "timecodeBurnin" => { builder = builder.set_timecode_burnin( crate::json_deser::deser_structure_crate_model_timecode_burnin( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_output_detail<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::OutputDetail>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::OutputDetail::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "durationInMs" => { builder = builder.set_duration_in_ms( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "videoDetails" => { builder = builder.set_video_details( crate::json_deser::deser_structure_crate_model_video_detail( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_com_amazonaws_mediaconvert___map_of_audio_selector_group<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::collections::HashMap<std::string::String, crate::model::AudioSelectorGroup>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key.to_unescaped().map(|u| u.into_owned())?; let value = crate::json_deser::deser_structure_crate_model_audio_selector_group( tokens, )?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_com_amazonaws_mediaconvert___map_of_audio_selector<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::collections::HashMap<std::string::String, crate::model::AudioSelector>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key.to_unescaped().map(|u| u.into_owned())?; let value = crate::json_deser::deser_structure_crate_model_audio_selector(tokens)?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_com_amazonaws_mediaconvert___map_of_caption_selector<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::collections::HashMap<std::string::String, crate::model::CaptionSelector>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key.to_unescaped().map(|u| u.into_owned())?; let value = crate::json_deser::deser_structure_crate_model_caption_selector( tokens, )?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_input_decryption_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::InputDecryptionSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::InputDecryptionSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "decryptionMode" => { builder = builder.set_decryption_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::DecryptionMode::from(u.as_ref())) }) .transpose()?, ); } "encryptedDecryptionKey" => { builder = builder.set_encrypted_decryption_key( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "initializationVector" => { builder = builder.set_initialization_vector( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "kmsKeyRegion" => { builder = builder.set_kms_key_region( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_image_inserter<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ImageInserter>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ImageInserter::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "insertableImages" => { builder = builder.set_insertable_images( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_insertable_image(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_input_clipping<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::InputClipping>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_input_clipping(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of__string_pattern_s3_assetmap_xml<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_video_selector<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::VideoSelector>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::VideoSelector::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "alphaBehavior" => { builder = builder.set_alpha_behavior( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::AlphaBehavior::from(u.as_ref())) }) .transpose()?, ); } "colorSpace" => { builder = builder.set_color_space( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ColorSpace::from(u.as_ref())) }) .transpose()?, ); } "colorSpaceUsage" => { builder = builder.set_color_space_usage( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ColorSpaceUsage::from(u.as_ref()) }) }) .transpose()?, ); } "hdr10Metadata" => { builder = builder.set_hdr10_metadata( crate::json_deser::deser_structure_crate_model_hdr10_metadata( tokens, )?, ); } "pid" => { builder = builder.set_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "programNumber" => { builder = builder.set_program_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "rotate" => { builder = builder.set_rotate( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::InputRotate::from(u.as_ref())) }) .transpose()?, ); } "sampleRange" => { builder = builder.set_sample_range( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InputSampleRange::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_automated_encoding_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AutomatedEncodingSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AutomatedEncodingSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "abrSettings" => { builder = builder.set_abr_settings( crate::json_deser::deser_structure_crate_model_automated_abr_settings(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_output_group_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::OutputGroupSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::OutputGroupSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "cmafGroupSettings" => { builder = builder.set_cmaf_group_settings( crate::json_deser::deser_structure_crate_model_cmaf_group_settings(tokens)? ); } "dashIsoGroupSettings" => { builder = builder.set_dash_iso_group_settings( crate::json_deser::deser_structure_crate_model_dash_iso_group_settings(tokens)? ); } "fileGroupSettings" => { builder = builder.set_file_group_settings( crate::json_deser::deser_structure_crate_model_file_group_settings(tokens)? ); } "hlsGroupSettings" => { builder = builder.set_hls_group_settings( crate::json_deser::deser_structure_crate_model_hls_group_settings(tokens)? ); } "msSmoothGroupSettings" => { builder = builder.set_ms_smooth_group_settings( crate::json_deser::deser_structure_crate_model_ms_smooth_group_settings(tokens)? ); } "type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::OutputGroupType::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_output<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Output>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_output(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_id3_insertion<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Id3Insertion>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Id3Insertion::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "id3" => { builder = builder.set_id3( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "timecode" => { builder = builder.set_timecode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_audio_channel_tagging_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AudioChannelTaggingSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AudioChannelTaggingSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "channelTag" => { builder = builder.set_channel_tag( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AudioChannelTag::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_audio_normalization_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AudioNormalizationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AudioNormalizationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "algorithm" => { builder = builder.set_algorithm( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AudioNormalizationAlgorithm::from( u.as_ref(), ) }) }) .transpose()?, ); } "algorithmControl" => { builder = builder.set_algorithm_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AudioNormalizationAlgorithmControl::from( u.as_ref(), ) }) }) .transpose()?, ); } "correctionGateLevel" => { builder = builder.set_correction_gate_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "loudnessLogging" => { builder = builder.set_loudness_logging( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AudioNormalizationLoudnessLogging::from( u.as_ref(), ) }) }) .transpose()?, ); } "peakCalculation" => { builder = builder.set_peak_calculation( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AudioNormalizationPeakCalculation::from( u.as_ref(), ) }) }) .transpose()?, ); } "targetLkfs" => { builder = builder.set_target_lkfs( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_audio_codec_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AudioCodecSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AudioCodecSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "aacSettings" => { builder = builder.set_aac_settings( crate::json_deser::deser_structure_crate_model_aac_settings( tokens, )?, ); } "ac3Settings" => { builder = builder.set_ac3_settings( crate::json_deser::deser_structure_crate_model_ac3_settings( tokens, )?, ); } "aiffSettings" => { builder = builder.set_aiff_settings( crate::json_deser::deser_structure_crate_model_aiff_settings( tokens, )?, ); } "codec" => { builder = builder.set_codec( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::AudioCodec::from(u.as_ref())) }) .transpose()?, ); } "eac3AtmosSettings" => { builder = builder.set_eac3_atmos_settings( crate::json_deser::deser_structure_crate_model_eac3_atmos_settings(tokens)? ); } "eac3Settings" => { builder = builder.set_eac3_settings( crate::json_deser::deser_structure_crate_model_eac3_settings( tokens, )?, ); } "mp2Settings" => { builder = builder.set_mp2_settings( crate::json_deser::deser_structure_crate_model_mp2_settings( tokens, )?, ); } "mp3Settings" => { builder = builder.set_mp3_settings( crate::json_deser::deser_structure_crate_model_mp3_settings( tokens, )?, ); } "opusSettings" => { builder = builder.set_opus_settings( crate::json_deser::deser_structure_crate_model_opus_settings( tokens, )?, ); } "vorbisSettings" => { builder = builder.set_vorbis_settings( crate::json_deser::deser_structure_crate_model_vorbis_settings( tokens, )?, ); } "wavSettings" => { builder = builder.set_wav_settings( crate::json_deser::deser_structure_crate_model_wav_settings( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_remix_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::RemixSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::RemixSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "channelMapping" => { builder = builder.set_channel_mapping( crate::json_deser::deser_structure_crate_model_channel_mapping( tokens, )?, ); } "channelsIn" => { builder = builder.set_channels_in( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "channelsOut" => { builder = builder.set_channels_out( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_caption_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CaptionDestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CaptionDestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "burninDestinationSettings" => { builder = builder.set_burnin_destination_settings( crate::json_deser::deser_structure_crate_model_burnin_destination_settings(tokens)? ); } "destinationType" => { builder = builder.set_destination_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CaptionDestinationType::from(u.as_ref()) }) }) .transpose()?, ); } "dvbSubDestinationSettings" => { builder = builder.set_dvb_sub_destination_settings( crate::json_deser::deser_structure_crate_model_dvb_sub_destination_settings(tokens)? ); } "embeddedDestinationSettings" => { builder = builder.set_embedded_destination_settings( crate::json_deser::deser_structure_crate_model_embedded_destination_settings(tokens)? ); } "imscDestinationSettings" => { builder = builder.set_imsc_destination_settings( crate::json_deser::deser_structure_crate_model_imsc_destination_settings(tokens)? ); } "sccDestinationSettings" => { builder = builder.set_scc_destination_settings( crate::json_deser::deser_structure_crate_model_scc_destination_settings(tokens)? ); } "srtDestinationSettings" => { builder = builder.set_srt_destination_settings( crate::json_deser::deser_structure_crate_model_srt_destination_settings(tokens)? ); } "teletextDestinationSettings" => { builder = builder.set_teletext_destination_settings( crate::json_deser::deser_structure_crate_model_teletext_destination_settings(tokens)? ); } "ttmlDestinationSettings" => { builder = builder.set_ttml_destination_settings( crate::json_deser::deser_structure_crate_model_ttml_destination_settings(tokens)? ); } "webvttDestinationSettings" => { builder = builder.set_webvtt_destination_settings( crate::json_deser::deser_structure_crate_model_webvtt_destination_settings(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of__integer_min32_max8182<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<i32>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_number_or_null(tokens.next())? .map(|v| v.to_i32()); if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_dvb_nit_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DvbNitSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DvbNitSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "networkId" => { builder = builder.set_network_id( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "networkName" => { builder = builder.set_network_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "nitInterval" => { builder = builder.set_nit_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_dvb_sdt_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DvbSdtSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DvbSdtSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "outputSdt" => { builder = builder.set_output_sdt( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::OutputSdt::from(u.as_ref())) }) .transpose()?, ); } "sdtInterval" => { builder = builder.set_sdt_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "serviceName" => { builder = builder.set_service_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "serviceProviderName" => { builder = builder.set_service_provider_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_dvb_tdt_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DvbTdtSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DvbTdtSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "tdtInterval" => { builder = builder.set_tdt_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_m2ts_scte35_esam<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::M2tsScte35Esam>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::M2tsScte35Esam::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "scte35EsamPid" => { builder = builder.set_scte35_esam_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_mxf_xavc_profile_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MxfXavcProfileSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MxfXavcProfileSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "durationMode" => { builder = builder.set_duration_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MxfXavcDurationMode::from(u.as_ref()) }) }) .transpose()?, ); } "maxAncDataSize" => { builder = builder.set_max_anc_data_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_av1_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Av1Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Av1Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "adaptiveQuantization" => { builder = builder.set_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Av1AdaptiveQuantization::from(u.as_ref()) }) }) .transpose()?, ); } "framerateControl" => { builder = builder.set_framerate_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Av1FramerateControl::from(u.as_ref()) }) }) .transpose()?, ); } "framerateConversionAlgorithm" => { builder = builder.set_framerate_conversion_algorithm( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Av1FramerateConversionAlgorithm::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "gopSize" => { builder = builder.set_gop_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "maxBitrate" => { builder = builder.set_max_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "numberBFramesBetweenReferenceFrames" => { builder = builder.set_number_b_frames_between_reference_frames( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qvbrSettings" => { builder = builder.set_qvbr_settings( crate::json_deser::deser_structure_crate_model_av1_qvbr_settings(tokens)? ); } "rateControlMode" => { builder = builder.set_rate_control_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Av1RateControlMode::from(u.as_ref()) }) }) .transpose()?, ); } "slices" => { builder = builder.set_slices( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "spatialAdaptiveQuantization" => { builder = builder.set_spatial_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Av1SpatialAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_avc_intra_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AvcIntraSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AvcIntraSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "avcIntraClass" => { builder = builder.set_avc_intra_class( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::AvcIntraClass::from(u.as_ref())) }) .transpose()?, ); } "avcIntraUhdSettings" => { builder = builder.set_avc_intra_uhd_settings( crate::json_deser::deser_structure_crate_model_avc_intra_uhd_settings(tokens)? ); } "framerateControl" => { builder = builder.set_framerate_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AvcIntraFramerateControl::from(u.as_ref()) }) }) .transpose()?, ); } "framerateConversionAlgorithm" => { builder = builder.set_framerate_conversion_algorithm( smithy_json::deserialize::token::expect_string_or_null(tokens.next())?.map(|s| s.to_unescaped().map(|u| crate::model::AvcIntraFramerateConversionAlgorithm::from(u.as_ref()) ) ).transpose()? ); } "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "interlaceMode" => { builder = builder.set_interlace_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AvcIntraInterlaceMode::from(u.as_ref()) }) }) .transpose()?, ); } "scanTypeConversionMode" => { builder = builder.set_scan_type_conversion_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AvcIntraScanTypeConversionMode::from( u.as_ref(), ) }) }) .transpose()?, ); } "slowPal" => { builder = builder.set_slow_pal( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AvcIntraSlowPal::from(u.as_ref()) }) }) .transpose()?, ); } "telecine" => { builder = builder.set_telecine( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AvcIntraTelecine::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_frame_capture_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::FrameCaptureSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::FrameCaptureSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "maxCaptures" => { builder = builder.set_max_captures( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "quality" => { builder = builder.set_quality( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_h264_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::H264Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::H264Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "adaptiveQuantization" => { builder = builder.set_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264AdaptiveQuantization::from(u.as_ref()) }) }) .transpose()?, ); } "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "codecLevel" => { builder = builder.set_codec_level( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::H264CodecLevel::from(u.as_ref())) }) .transpose()?, ); } "codecProfile" => { builder = builder.set_codec_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264CodecProfile::from(u.as_ref()) }) }) .transpose()?, ); } "dynamicSubGop" => { builder = builder.set_dynamic_sub_gop( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264DynamicSubGop::from(u.as_ref()) }) }) .transpose()?, ); } "entropyEncoding" => { builder = builder.set_entropy_encoding( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264EntropyEncoding::from(u.as_ref()) }) }) .transpose()?, ); } "fieldEncoding" => { builder = builder.set_field_encoding( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264FieldEncoding::from(u.as_ref()) }) }) .transpose()?, ); } "flickerAdaptiveQuantization" => { builder = builder.set_flicker_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264FlickerAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerateControl" => { builder = builder.set_framerate_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264FramerateControl::from(u.as_ref()) }) }) .transpose()?, ); } "framerateConversionAlgorithm" => { builder = builder.set_framerate_conversion_algorithm( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264FramerateConversionAlgorithm::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "gopBReference" => { builder = builder.set_gop_b_reference( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264GopBReference::from(u.as_ref()) }) }) .transpose()?, ); } "gopClosedCadence" => { builder = builder.set_gop_closed_cadence( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "gopSize" => { builder = builder.set_gop_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "gopSizeUnits" => { builder = builder.set_gop_size_units( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264GopSizeUnits::from(u.as_ref()) }) }) .transpose()?, ); } "hrdBufferInitialFillPercentage" => { builder = builder.set_hrd_buffer_initial_fill_percentage( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "hrdBufferSize" => { builder = builder.set_hrd_buffer_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "interlaceMode" => { builder = builder.set_interlace_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264InterlaceMode::from(u.as_ref()) }) }) .transpose()?, ); } "maxBitrate" => { builder = builder.set_max_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "minIInterval" => { builder = builder.set_min_i_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "numberBFramesBetweenReferenceFrames" => { builder = builder.set_number_b_frames_between_reference_frames( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "numberReferenceFrames" => { builder = builder.set_number_reference_frames( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "parControl" => { builder = builder.set_par_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::H264ParControl::from(u.as_ref())) }) .transpose()?, ); } "parDenominator" => { builder = builder.set_par_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "parNumerator" => { builder = builder.set_par_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qualityTuningLevel" => { builder = builder.set_quality_tuning_level( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264QualityTuningLevel::from(u.as_ref()) }) }) .transpose()?, ); } "qvbrSettings" => { builder = builder.set_qvbr_settings( crate::json_deser::deser_structure_crate_model_h264_qvbr_settings(tokens)? ); } "rateControlMode" => { builder = builder.set_rate_control_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264RateControlMode::from(u.as_ref()) }) }) .transpose()?, ); } "repeatPps" => { builder = builder.set_repeat_pps( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::H264RepeatPps::from(u.as_ref())) }) .transpose()?, ); } "scanTypeConversionMode" => { builder = builder.set_scan_type_conversion_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264ScanTypeConversionMode::from( u.as_ref(), ) }) }) .transpose()?, ); } "sceneChangeDetect" => { builder = builder.set_scene_change_detect( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264SceneChangeDetect::from(u.as_ref()) }) }) .transpose()?, ); } "slices" => { builder = builder.set_slices( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "slowPal" => { builder = builder.set_slow_pal( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::H264SlowPal::from(u.as_ref())) }) .transpose()?, ); } "softness" => { builder = builder.set_softness( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "spatialAdaptiveQuantization" => { builder = builder.set_spatial_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264SpatialAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "syntax" => { builder = builder.set_syntax( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::H264Syntax::from(u.as_ref())) }) .transpose()?, ); } "telecine" => { builder = builder.set_telecine( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::H264Telecine::from(u.as_ref())) }) .transpose()?, ); } "temporalAdaptiveQuantization" => { builder = builder.set_temporal_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264TemporalAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "unregisteredSeiTimecode" => { builder = builder.set_unregistered_sei_timecode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H264UnregisteredSeiTimecode::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_h265_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::H265Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::H265Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "adaptiveQuantization" => { builder = builder.set_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265AdaptiveQuantization::from(u.as_ref()) }) }) .transpose()?, ); } "alternateTransferFunctionSei" => { builder = builder.set_alternate_transfer_function_sei( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265AlternateTransferFunctionSei::from( u.as_ref(), ) }) }) .transpose()?, ); } "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "codecLevel" => { builder = builder.set_codec_level( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::H265CodecLevel::from(u.as_ref())) }) .transpose()?, ); } "codecProfile" => { builder = builder.set_codec_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265CodecProfile::from(u.as_ref()) }) }) .transpose()?, ); } "dynamicSubGop" => { builder = builder.set_dynamic_sub_gop( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265DynamicSubGop::from(u.as_ref()) }) }) .transpose()?, ); } "flickerAdaptiveQuantization" => { builder = builder.set_flicker_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265FlickerAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerateControl" => { builder = builder.set_framerate_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265FramerateControl::from(u.as_ref()) }) }) .transpose()?, ); } "framerateConversionAlgorithm" => { builder = builder.set_framerate_conversion_algorithm( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265FramerateConversionAlgorithm::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "gopBReference" => { builder = builder.set_gop_b_reference( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265GopBReference::from(u.as_ref()) }) }) .transpose()?, ); } "gopClosedCadence" => { builder = builder.set_gop_closed_cadence( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "gopSize" => { builder = builder.set_gop_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "gopSizeUnits" => { builder = builder.set_gop_size_units( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265GopSizeUnits::from(u.as_ref()) }) }) .transpose()?, ); } "hrdBufferInitialFillPercentage" => { builder = builder.set_hrd_buffer_initial_fill_percentage( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "hrdBufferSize" => { builder = builder.set_hrd_buffer_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "interlaceMode" => { builder = builder.set_interlace_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265InterlaceMode::from(u.as_ref()) }) }) .transpose()?, ); } "maxBitrate" => { builder = builder.set_max_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "minIInterval" => { builder = builder.set_min_i_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "numberBFramesBetweenReferenceFrames" => { builder = builder.set_number_b_frames_between_reference_frames( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "numberReferenceFrames" => { builder = builder.set_number_reference_frames( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "parControl" => { builder = builder.set_par_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::H265ParControl::from(u.as_ref())) }) .transpose()?, ); } "parDenominator" => { builder = builder.set_par_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "parNumerator" => { builder = builder.set_par_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qualityTuningLevel" => { builder = builder.set_quality_tuning_level( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265QualityTuningLevel::from(u.as_ref()) }) }) .transpose()?, ); } "qvbrSettings" => { builder = builder.set_qvbr_settings( crate::json_deser::deser_structure_crate_model_h265_qvbr_settings(tokens)? ); } "rateControlMode" => { builder = builder.set_rate_control_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265RateControlMode::from(u.as_ref()) }) }) .transpose()?, ); } "sampleAdaptiveOffsetFilterMode" => { builder = builder.set_sample_adaptive_offset_filter_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265SampleAdaptiveOffsetFilterMode::from( u.as_ref(), ) }) }) .transpose()?, ); } "scanTypeConversionMode" => { builder = builder.set_scan_type_conversion_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265ScanTypeConversionMode::from( u.as_ref(), ) }) }) .transpose()?, ); } "sceneChangeDetect" => { builder = builder.set_scene_change_detect( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265SceneChangeDetect::from(u.as_ref()) }) }) .transpose()?, ); } "slices" => { builder = builder.set_slices( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "slowPal" => { builder = builder.set_slow_pal( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::H265SlowPal::from(u.as_ref())) }) .transpose()?, ); } "spatialAdaptiveQuantization" => { builder = builder.set_spatial_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265SpatialAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "telecine" => { builder = builder.set_telecine( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::H265Telecine::from(u.as_ref())) }) .transpose()?, ); } "temporalAdaptiveQuantization" => { builder = builder.set_temporal_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265TemporalAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "temporalIds" => { builder = builder.set_temporal_ids( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265TemporalIds::from(u.as_ref()) }) }) .transpose()?, ); } "tiles" => { builder = builder.set_tiles( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::H265Tiles::from(u.as_ref())) }) .transpose()?, ); } "unregisteredSeiTimecode" => { builder = builder.set_unregistered_sei_timecode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265UnregisteredSeiTimecode::from( u.as_ref(), ) }) }) .transpose()?, ); } "writeMp4PackagingType" => { builder = builder.set_write_mp4_packaging_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::H265WriteMp4PackagingType::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_mpeg2_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Mpeg2Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Mpeg2Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "adaptiveQuantization" => { builder = builder.set_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2AdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "codecLevel" => { builder = builder.set_codec_level( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2CodecLevel::from(u.as_ref()) }) }) .transpose()?, ); } "codecProfile" => { builder = builder.set_codec_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2CodecProfile::from(u.as_ref()) }) }) .transpose()?, ); } "dynamicSubGop" => { builder = builder.set_dynamic_sub_gop( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2DynamicSubGop::from(u.as_ref()) }) }) .transpose()?, ); } "framerateControl" => { builder = builder.set_framerate_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2FramerateControl::from(u.as_ref()) }) }) .transpose()?, ); } "framerateConversionAlgorithm" => { builder = builder.set_framerate_conversion_algorithm( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2FramerateConversionAlgorithm::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "gopClosedCadence" => { builder = builder.set_gop_closed_cadence( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "gopSize" => { builder = builder.set_gop_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "gopSizeUnits" => { builder = builder.set_gop_size_units( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2GopSizeUnits::from(u.as_ref()) }) }) .transpose()?, ); } "hrdBufferInitialFillPercentage" => { builder = builder.set_hrd_buffer_initial_fill_percentage( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "hrdBufferSize" => { builder = builder.set_hrd_buffer_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "interlaceMode" => { builder = builder.set_interlace_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2InterlaceMode::from(u.as_ref()) }) }) .transpose()?, ); } "intraDcPrecision" => { builder = builder.set_intra_dc_precision( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2IntraDcPrecision::from(u.as_ref()) }) }) .transpose()?, ); } "maxBitrate" => { builder = builder.set_max_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "minIInterval" => { builder = builder.set_min_i_interval( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "numberBFramesBetweenReferenceFrames" => { builder = builder.set_number_b_frames_between_reference_frames( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "parControl" => { builder = builder.set_par_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2ParControl::from(u.as_ref()) }) }) .transpose()?, ); } "parDenominator" => { builder = builder.set_par_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "parNumerator" => { builder = builder.set_par_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qualityTuningLevel" => { builder = builder.set_quality_tuning_level( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2QualityTuningLevel::from(u.as_ref()) }) }) .transpose()?, ); } "rateControlMode" => { builder = builder.set_rate_control_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2RateControlMode::from(u.as_ref()) }) }) .transpose()?, ); } "scanTypeConversionMode" => { builder = builder.set_scan_type_conversion_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2ScanTypeConversionMode::from( u.as_ref(), ) }) }) .transpose()?, ); } "sceneChangeDetect" => { builder = builder.set_scene_change_detect( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2SceneChangeDetect::from(u.as_ref()) }) }) .transpose()?, ); } "slowPal" => { builder = builder.set_slow_pal( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Mpeg2SlowPal::from(u.as_ref())) }) .transpose()?, ); } "softness" => { builder = builder.set_softness( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "spatialAdaptiveQuantization" => { builder = builder.set_spatial_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2SpatialAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "syntax" => { builder = builder.set_syntax( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Mpeg2Syntax::from(u.as_ref())) }) .transpose()?, ); } "telecine" => { builder = builder.set_telecine( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Mpeg2Telecine::from(u.as_ref())) }) .transpose()?, ); } "temporalAdaptiveQuantization" => { builder = builder.set_temporal_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mpeg2TemporalAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_prores_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ProresSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ProresSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "chromaSampling" => { builder = builder.set_chroma_sampling( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ProresChromaSampling::from(u.as_ref()) }) }) .transpose()?, ); } "codecProfile" => { builder = builder.set_codec_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ProresCodecProfile::from(u.as_ref()) }) }) .transpose()?, ); } "framerateControl" => { builder = builder.set_framerate_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ProresFramerateControl::from(u.as_ref()) }) }) .transpose()?, ); } "framerateConversionAlgorithm" => { builder = builder.set_framerate_conversion_algorithm( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ProresFramerateConversionAlgorithm::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "interlaceMode" => { builder = builder.set_interlace_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ProresInterlaceMode::from(u.as_ref()) }) }) .transpose()?, ); } "parControl" => { builder = builder.set_par_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ProresParControl::from(u.as_ref()) }) }) .transpose()?, ); } "parDenominator" => { builder = builder.set_par_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "parNumerator" => { builder = builder.set_par_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "scanTypeConversionMode" => { builder = builder.set_scan_type_conversion_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ProresScanTypeConversionMode::from( u.as_ref(), ) }) }) .transpose()?, ); } "slowPal" => { builder = builder.set_slow_pal( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ProresSlowPal::from(u.as_ref())) }) .transpose()?, ); } "telecine" => { builder = builder.set_telecine( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ProresTelecine::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_vc3_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Vc3Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Vc3Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "framerateControl" => { builder = builder.set_framerate_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vc3FramerateControl::from(u.as_ref()) }) }) .transpose()?, ); } "framerateConversionAlgorithm" => { builder = builder.set_framerate_conversion_algorithm( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vc3FramerateConversionAlgorithm::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "interlaceMode" => { builder = builder.set_interlace_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vc3InterlaceMode::from(u.as_ref()) }) }) .transpose()?, ); } "scanTypeConversionMode" => { builder = builder.set_scan_type_conversion_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vc3ScanTypeConversionMode::from( u.as_ref(), ) }) }) .transpose()?, ); } "slowPal" => { builder = builder.set_slow_pal( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Vc3SlowPal::from(u.as_ref())) }) .transpose()?, ); } "telecine" => { builder = builder.set_telecine( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Vc3Telecine::from(u.as_ref())) }) .transpose()?, ); } "vc3Class" => { builder = builder.set_vc3_class( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Vc3Class::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_vp8_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Vp8Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Vp8Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateControl" => { builder = builder.set_framerate_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vp8FramerateControl::from(u.as_ref()) }) }) .transpose()?, ); } "framerateConversionAlgorithm" => { builder = builder.set_framerate_conversion_algorithm( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vp8FramerateConversionAlgorithm::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "gopSize" => { builder = builder.set_gop_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "hrdBufferSize" => { builder = builder.set_hrd_buffer_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "maxBitrate" => { builder = builder.set_max_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "parControl" => { builder = builder.set_par_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Vp8ParControl::from(u.as_ref())) }) .transpose()?, ); } "parDenominator" => { builder = builder.set_par_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "parNumerator" => { builder = builder.set_par_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qualityTuningLevel" => { builder = builder.set_quality_tuning_level( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vp8QualityTuningLevel::from(u.as_ref()) }) }) .transpose()?, ); } "rateControlMode" => { builder = builder.set_rate_control_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vp8RateControlMode::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_vp9_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Vp9Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Vp9Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateControl" => { builder = builder.set_framerate_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vp9FramerateControl::from(u.as_ref()) }) }) .transpose()?, ); } "framerateConversionAlgorithm" => { builder = builder.set_framerate_conversion_algorithm( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vp9FramerateConversionAlgorithm::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "gopSize" => { builder = builder.set_gop_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "hrdBufferSize" => { builder = builder.set_hrd_buffer_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "maxBitrate" => { builder = builder.set_max_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "parControl" => { builder = builder.set_par_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Vp9ParControl::from(u.as_ref())) }) .transpose()?, ); } "parDenominator" => { builder = builder.set_par_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "parNumerator" => { builder = builder.set_par_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qualityTuningLevel" => { builder = builder.set_quality_tuning_level( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vp9QualityTuningLevel::from(u.as_ref()) }) }) .transpose()?, ); } "rateControlMode" => { builder = builder.set_rate_control_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Vp9RateControlMode::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_xavc_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::XavcSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::XavcSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "adaptiveQuantization" => { builder = builder.set_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcAdaptiveQuantization::from(u.as_ref()) }) }) .transpose()?, ); } "entropyEncoding" => { builder = builder.set_entropy_encoding( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcEntropyEncoding::from(u.as_ref()) }) }) .transpose()?, ); } "framerateControl" => { builder = builder.set_framerate_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcFramerateControl::from(u.as_ref()) }) }) .transpose()?, ); } "framerateConversionAlgorithm" => { builder = builder.set_framerate_conversion_algorithm( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcFramerateConversionAlgorithm::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "profile" => { builder = builder.set_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::XavcProfile::from(u.as_ref())) }) .transpose()?, ); } "slowPal" => { builder = builder.set_slow_pal( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::XavcSlowPal::from(u.as_ref())) }) .transpose()?, ); } "softness" => { builder = builder.set_softness( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "spatialAdaptiveQuantization" => { builder = builder.set_spatial_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcSpatialAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "temporalAdaptiveQuantization" => { builder = builder.set_temporal_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcTemporalAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "xavc4kIntraCbgProfileSettings" => { builder = builder.set_xavc4k_intra_cbg_profile_settings( crate::json_deser::deser_structure_crate_model_xavc4k_intra_cbg_profile_settings(tokens)? ); } "xavc4kIntraVbrProfileSettings" => { builder = builder.set_xavc4k_intra_vbr_profile_settings( crate::json_deser::deser_structure_crate_model_xavc4k_intra_vbr_profile_settings(tokens)? ); } "xavc4kProfileSettings" => { builder = builder.set_xavc4k_profile_settings( crate::json_deser::deser_structure_crate_model_xavc4k_profile_settings(tokens)? ); } "xavcHdIntraCbgProfileSettings" => { builder = builder.set_xavc_hd_intra_cbg_profile_settings( crate::json_deser::deser_structure_crate_model_xavc_hd_intra_cbg_profile_settings(tokens)? ); } "xavcHdProfileSettings" => { builder = builder.set_xavc_hd_profile_settings( crate::json_deser::deser_structure_crate_model_xavc_hd_profile_settings(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_color_corrector<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ColorCorrector>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ColorCorrector::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "brightness" => { builder = builder.set_brightness( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "colorSpaceConversion" => { builder = builder.set_color_space_conversion( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ColorSpaceConversion::from(u.as_ref()) }) }) .transpose()?, ); } "contrast" => { builder = builder.set_contrast( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "hdr10Metadata" => { builder = builder.set_hdr10_metadata( crate::json_deser::deser_structure_crate_model_hdr10_metadata( tokens, )?, ); } "hue" => { builder = builder.set_hue( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "sampleRangeConversion" => { builder = builder.set_sample_range_conversion( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::SampleRangeConversion::from(u.as_ref()) }) }) .transpose()?, ); } "saturation" => { builder = builder.set_saturation( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_deinterlacer<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Deinterlacer>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Deinterlacer::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "algorithm" => { builder = builder.set_algorithm( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DeinterlaceAlgorithm::from(u.as_ref()) }) }) .transpose()?, ); } "control" => { builder = builder.set_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DeinterlacerControl::from(u.as_ref()) }) }) .transpose()?, ); } "mode" => { builder = builder.set_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DeinterlacerMode::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_dolby_vision<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DolbyVision>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DolbyVision::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "l6Metadata" => { builder = builder.set_l6_metadata( crate::json_deser::deser_structure_crate_model_dolby_vision_level6_metadata(tokens)? ); } "l6Mode" => { builder = builder.set_l6_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DolbyVisionLevel6Mode::from(u.as_ref()) }) }) .transpose()?, ); } "profile" => { builder = builder.set_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DolbyVisionProfile::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_hdr10_plus<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Hdr10Plus>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Hdr10Plus::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "masteringMonitorNits" => { builder = builder.set_mastering_monitor_nits( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "targetMonitorNits" => { builder = builder.set_target_monitor_nits( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_noise_reducer<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::NoiseReducer>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::NoiseReducer::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "filter" => { builder = builder.set_filter( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::NoiseReducerFilter::from(u.as_ref()) }) }) .transpose()?, ); } "filterSettings" => { builder = builder.set_filter_settings( crate::json_deser::deser_structure_crate_model_noise_reducer_filter_settings(tokens)? ); } "spatialFilterSettings" => { builder = builder.set_spatial_filter_settings( crate::json_deser::deser_structure_crate_model_noise_reducer_spatial_filter_settings(tokens)? ); } "temporalFilterSettings" => { builder = builder.set_temporal_filter_settings( crate::json_deser::deser_structure_crate_model_noise_reducer_temporal_filter_settings(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_partner_watermarking<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::PartnerWatermarking>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::PartnerWatermarking::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "nexguardFileMarkerSettings" => { builder = builder.set_nexguard_file_marker_settings( crate::json_deser::deser_structure_crate_model_nex_guard_file_marker_settings(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_timecode_burnin<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::TimecodeBurnin>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TimecodeBurnin::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "fontSize" => { builder = builder.set_font_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "position" => { builder = builder.set_position( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::TimecodeBurninPosition::from(u.as_ref()) }) }) .transpose()?, ); } "prefix" => { builder = builder.set_prefix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_video_detail<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::VideoDetail>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::VideoDetail::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "heightInPx" => { builder = builder.set_height_in_px( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "widthInPx" => { builder = builder.set_width_in_px( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_audio_selector_group<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AudioSelectorGroup>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AudioSelectorGroup::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioSelectorNames" => { builder = builder.set_audio_selector_names( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__string_min1(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_audio_selector<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AudioSelector>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AudioSelector::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "customLanguageCode" => { builder = builder.set_custom_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "defaultSelection" => { builder = builder.set_default_selection( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AudioDefaultSelection::from(u.as_ref()) }) }) .transpose()?, ); } "externalAudioFileInput" => { builder = builder.set_external_audio_file_input( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "hlsRenditionGroupSettings" => { builder = builder.set_hls_rendition_group_settings( crate::json_deser::deser_structure_crate_model_hls_rendition_group_settings(tokens)? ); } "languageCode" => { builder = builder.set_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::LanguageCode::from(u.as_ref())) }) .transpose()?, ); } "offset" => { builder = builder.set_offset( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "pids" => { builder = builder.set_pids( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__integer_min1_max2147483647(tokens)? ); } "programSelection" => { builder = builder.set_program_selection( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "remixSettings" => { builder = builder.set_remix_settings( crate::json_deser::deser_structure_crate_model_remix_settings( tokens, )?, ); } "selectorType" => { builder = builder.set_selector_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AudioSelectorType::from(u.as_ref()) }) }) .transpose()?, ); } "tracks" => { builder = builder.set_tracks( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__integer_min1_max2147483647(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_caption_selector<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CaptionSelector>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CaptionSelector::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "customLanguageCode" => { builder = builder.set_custom_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "languageCode" => { builder = builder.set_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::LanguageCode::from(u.as_ref())) }) .transpose()?, ); } "sourceSettings" => { builder = builder.set_source_settings( crate::json_deser::deser_structure_crate_model_caption_source_settings(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_insertable_image<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::InsertableImage>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_insertable_image( tokens, )?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_input_clipping<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::InputClipping>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::InputClipping::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "endTimecode" => { builder = builder.set_end_timecode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "startTimecode" => { builder = builder.set_start_timecode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_hdr10_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Hdr10Metadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Hdr10Metadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bluePrimaryX" => { builder = builder.set_blue_primary_x( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "bluePrimaryY" => { builder = builder.set_blue_primary_y( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "greenPrimaryX" => { builder = builder.set_green_primary_x( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "greenPrimaryY" => { builder = builder.set_green_primary_y( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "maxContentLightLevel" => { builder = builder.set_max_content_light_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "maxFrameAverageLightLevel" => { builder = builder.set_max_frame_average_light_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "maxLuminance" => { builder = builder.set_max_luminance( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "minLuminance" => { builder = builder.set_min_luminance( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "redPrimaryX" => { builder = builder.set_red_primary_x( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "redPrimaryY" => { builder = builder.set_red_primary_y( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "whitePointX" => { builder = builder.set_white_point_x( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "whitePointY" => { builder = builder.set_white_point_y( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_automated_abr_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AutomatedAbrSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AutomatedAbrSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "maxAbrBitrate" => { builder = builder.set_max_abr_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "maxRenditions" => { builder = builder.set_max_renditions( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "minAbrBitrate" => { builder = builder.set_min_abr_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_cmaf_group_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CmafGroupSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CmafGroupSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "additionalManifests" => { builder = builder.set_additional_manifests( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_cmaf_additional_manifest(tokens)? ); } "baseUrl" => { builder = builder.set_base_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "clientCache" => { builder = builder.set_client_cache( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafClientCache::from(u.as_ref()) }) }) .transpose()?, ); } "codecSpecification" => { builder = builder.set_codec_specification( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafCodecSpecification::from(u.as_ref()) }) }) .transpose()?, ); } "destination" => { builder = builder.set_destination( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "destinationSettings" => { builder = builder.set_destination_settings( crate::json_deser::deser_structure_crate_model_destination_settings(tokens)? ); } "encryption" => { builder = builder.set_encryption( crate::json_deser::deser_structure_crate_model_cmaf_encryption_settings(tokens)? ); } "fragmentLength" => { builder = builder.set_fragment_length( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "imageBasedTrickPlay" => { builder = builder.set_image_based_trick_play( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafImageBasedTrickPlay::from(u.as_ref()) }) }) .transpose()?, ); } "manifestCompression" => { builder = builder.set_manifest_compression( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafManifestCompression::from(u.as_ref()) }) }) .transpose()?, ); } "manifestDurationFormat" => { builder = builder.set_manifest_duration_format( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafManifestDurationFormat::from( u.as_ref(), ) }) }) .transpose()?, ); } "minBufferTime" => { builder = builder.set_min_buffer_time( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "minFinalSegmentLength" => { builder = builder.set_min_final_segment_length( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "mpdProfile" => { builder = builder.set_mpd_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::CmafMpdProfile::from(u.as_ref())) }) .transpose()?, ); } "ptsOffsetHandlingForBFrames" => { builder = builder.set_pts_offset_handling_for_b_frames( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafPtsOffsetHandlingForBFrames::from( u.as_ref(), ) }) }) .transpose()?, ); } "segmentControl" => { builder = builder.set_segment_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafSegmentControl::from(u.as_ref()) }) }) .transpose()?, ); } "segmentLength" => { builder = builder.set_segment_length( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "segmentLengthControl" => { builder = builder.set_segment_length_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafSegmentLengthControl::from(u.as_ref()) }) }) .transpose()?, ); } "streamInfResolution" => { builder = builder.set_stream_inf_resolution( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafStreamInfResolution::from(u.as_ref()) }) }) .transpose()?, ); } "targetDurationCompatibilityMode" => { builder = builder.set_target_duration_compatibility_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafTargetDurationCompatibilityMode::from( u.as_ref(), ) }) }) .transpose()?, ); } "writeDashManifest" => { builder = builder.set_write_dash_manifest( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafWriteDashManifest::from(u.as_ref()) }) }) .transpose()?, ); } "writeHlsManifest" => { builder = builder.set_write_hls_manifest( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafWriteHlsManifest::from(u.as_ref()) }) }) .transpose()?, ); } "writeSegmentTimelineInRepresentation" => { builder = builder.set_write_segment_timeline_in_representation( smithy_json::deserialize::token::expect_string_or_null(tokens.next())?.map(|s| s.to_unescaped().map(|u| crate::model::CmafWriteSegmentTimelineInRepresentation::from(u.as_ref()) ) ).transpose()? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_dash_iso_group_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DashIsoGroupSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DashIsoGroupSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "additionalManifests" => { builder = builder.set_additional_manifests( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_dash_additional_manifest(tokens)? ); } "audioChannelConfigSchemeIdUri" => { builder = builder.set_audio_channel_config_scheme_id_uri( smithy_json::deserialize::token::expect_string_or_null(tokens.next())?.map(|s| s.to_unescaped().map(|u| crate::model::DashIsoGroupAudioChannelConfigSchemeIdUri::from(u.as_ref()) ) ).transpose()? ); } "baseUrl" => { builder = builder.set_base_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "destination" => { builder = builder.set_destination( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "destinationSettings" => { builder = builder.set_destination_settings( crate::json_deser::deser_structure_crate_model_destination_settings(tokens)? ); } "encryption" => { builder = builder.set_encryption( crate::json_deser::deser_structure_crate_model_dash_iso_encryption_settings(tokens)? ); } "fragmentLength" => { builder = builder.set_fragment_length( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "hbbtvCompliance" => { builder = builder.set_hbbtv_compliance( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DashIsoHbbtvCompliance::from(u.as_ref()) }) }) .transpose()?, ); } "imageBasedTrickPlay" => { builder = builder.set_image_based_trick_play( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DashIsoImageBasedTrickPlay::from( u.as_ref(), ) }) }) .transpose()?, ); } "minBufferTime" => { builder = builder.set_min_buffer_time( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "minFinalSegmentLength" => { builder = builder.set_min_final_segment_length( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "mpdProfile" => { builder = builder.set_mpd_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DashIsoMpdProfile::from(u.as_ref()) }) }) .transpose()?, ); } "ptsOffsetHandlingForBFrames" => { builder = builder.set_pts_offset_handling_for_b_frames( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DashIsoPtsOffsetHandlingForBFrames::from( u.as_ref(), ) }) }) .transpose()?, ); } "segmentControl" => { builder = builder.set_segment_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DashIsoSegmentControl::from(u.as_ref()) }) }) .transpose()?, ); } "segmentLength" => { builder = builder.set_segment_length( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "segmentLengthControl" => { builder = builder.set_segment_length_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DashIsoSegmentLengthControl::from( u.as_ref(), ) }) }) .transpose()?, ); } "writeSegmentTimelineInRepresentation" => { builder = builder.set_write_segment_timeline_in_representation( smithy_json::deserialize::token::expect_string_or_null(tokens.next())?.map(|s| s.to_unescaped().map(|u| crate::model::DashIsoWriteSegmentTimelineInRepresentation::from(u.as_ref()) ) ).transpose()? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_file_group_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::FileGroupSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::FileGroupSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "destination" => { builder = builder.set_destination( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "destinationSettings" => { builder = builder.set_destination_settings( crate::json_deser::deser_structure_crate_model_destination_settings(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_hls_group_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::HlsGroupSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::HlsGroupSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "adMarkers" => { builder = builder.set_ad_markers( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_hls_ad_markers(tokens)? ); } "additionalManifests" => { builder = builder.set_additional_manifests( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_hls_additional_manifest(tokens)? ); } "audioOnlyHeader" => { builder = builder.set_audio_only_header( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsAudioOnlyHeader::from(u.as_ref()) }) }) .transpose()?, ); } "baseUrl" => { builder = builder.set_base_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "captionLanguageMappings" => { builder = builder.set_caption_language_mappings( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_hls_caption_language_mapping(tokens)? ); } "captionLanguageSetting" => { builder = builder.set_caption_language_setting( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsCaptionLanguageSetting::from( u.as_ref(), ) }) }) .transpose()?, ); } "clientCache" => { builder = builder.set_client_cache( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::HlsClientCache::from(u.as_ref())) }) .transpose()?, ); } "codecSpecification" => { builder = builder.set_codec_specification( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsCodecSpecification::from(u.as_ref()) }) }) .transpose()?, ); } "destination" => { builder = builder.set_destination( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "destinationSettings" => { builder = builder.set_destination_settings( crate::json_deser::deser_structure_crate_model_destination_settings(tokens)? ); } "directoryStructure" => { builder = builder.set_directory_structure( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsDirectoryStructure::from(u.as_ref()) }) }) .transpose()?, ); } "encryption" => { builder = builder.set_encryption( crate::json_deser::deser_structure_crate_model_hls_encryption_settings(tokens)? ); } "imageBasedTrickPlay" => { builder = builder.set_image_based_trick_play( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsImageBasedTrickPlay::from(u.as_ref()) }) }) .transpose()?, ); } "manifestCompression" => { builder = builder.set_manifest_compression( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsManifestCompression::from(u.as_ref()) }) }) .transpose()?, ); } "manifestDurationFormat" => { builder = builder.set_manifest_duration_format( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsManifestDurationFormat::from( u.as_ref(), ) }) }) .transpose()?, ); } "minFinalSegmentLength" => { builder = builder.set_min_final_segment_length( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "minSegmentLength" => { builder = builder.set_min_segment_length( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "outputSelection" => { builder = builder.set_output_selection( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsOutputSelection::from(u.as_ref()) }) }) .transpose()?, ); } "programDateTime" => { builder = builder.set_program_date_time( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsProgramDateTime::from(u.as_ref()) }) }) .transpose()?, ); } "programDateTimePeriod" => { builder = builder.set_program_date_time_period( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "segmentControl" => { builder = builder.set_segment_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsSegmentControl::from(u.as_ref()) }) }) .transpose()?, ); } "segmentLength" => { builder = builder.set_segment_length( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "segmentLengthControl" => { builder = builder.set_segment_length_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsSegmentLengthControl::from(u.as_ref()) }) }) .transpose()?, ); } "segmentsPerSubdirectory" => { builder = builder.set_segments_per_subdirectory( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "streamInfResolution" => { builder = builder.set_stream_inf_resolution( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsStreamInfResolution::from(u.as_ref()) }) }) .transpose()?, ); } "targetDurationCompatibilityMode" => { builder = builder.set_target_duration_compatibility_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsTargetDurationCompatibilityMode::from( u.as_ref(), ) }) }) .transpose()?, ); } "timedMetadataId3Frame" => { builder = builder.set_timed_metadata_id3_frame( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsTimedMetadataId3Frame::from(u.as_ref()) }) }) .transpose()?, ); } "timedMetadataId3Period" => { builder = builder.set_timed_metadata_id3_period( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "timestampDeltaMilliseconds" => { builder = builder.set_timestamp_delta_milliseconds( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_ms_smooth_group_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MsSmoothGroupSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MsSmoothGroupSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "additionalManifests" => { builder = builder.set_additional_manifests( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_ms_smooth_additional_manifest(tokens)? ); } "audioDeduplication" => { builder = builder.set_audio_deduplication( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MsSmoothAudioDeduplication::from( u.as_ref(), ) }) }) .transpose()?, ); } "destination" => { builder = builder.set_destination( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "destinationSettings" => { builder = builder.set_destination_settings( crate::json_deser::deser_structure_crate_model_destination_settings(tokens)? ); } "encryption" => { builder = builder.set_encryption( crate::json_deser::deser_structure_crate_model_ms_smooth_encryption_settings(tokens)? ); } "fragmentLength" => { builder = builder.set_fragment_length( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "fragmentLengthControl" => { builder = builder.set_fragment_length_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MsSmoothFragmentLengthControl::from( u.as_ref(), ) }) }) .transpose()?, ); } "manifestEncoding" => { builder = builder.set_manifest_encoding( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MsSmoothManifestEncoding::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_output<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Output>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Output::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioDescriptions" => { builder = builder.set_audio_descriptions( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_audio_description(tokens)? ); } "captionDescriptions" => { builder = builder.set_caption_descriptions( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_caption_description(tokens)? ); } "containerSettings" => { builder = builder.set_container_settings( crate::json_deser::deser_structure_crate_model_container_settings(tokens)? ); } "extension" => { builder = builder.set_extension( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "nameModifier" => { builder = builder.set_name_modifier( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "outputSettings" => { builder = builder.set_output_settings( crate::json_deser::deser_structure_crate_model_output_settings( tokens, )?, ); } "preset" => { builder = builder.set_preset( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "videoDescription" => { builder = builder.set_video_description( crate::json_deser::deser_structure_crate_model_video_description(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_aac_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AacSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AacSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioDescriptionBroadcasterMix" => { builder = builder.set_audio_description_broadcaster_mix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AacAudioDescriptionBroadcasterMix::from( u.as_ref(), ) }) }) .transpose()?, ); } "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "codecProfile" => { builder = builder.set_codec_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AacCodecProfile::from(u.as_ref()) }) }) .transpose()?, ); } "codingMode" => { builder = builder.set_coding_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::AacCodingMode::from(u.as_ref())) }) .transpose()?, ); } "rateControlMode" => { builder = builder.set_rate_control_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AacRateControlMode::from(u.as_ref()) }) }) .transpose()?, ); } "rawFormat" => { builder = builder.set_raw_format( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::AacRawFormat::from(u.as_ref())) }) .transpose()?, ); } "sampleRate" => { builder = builder.set_sample_rate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "specification" => { builder = builder.set_specification( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AacSpecification::from(u.as_ref()) }) }) .transpose()?, ); } "vbrQuality" => { builder = builder.set_vbr_quality( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::AacVbrQuality::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_ac3_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Ac3Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Ac3Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "bitstreamMode" => { builder = builder.set_bitstream_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Ac3BitstreamMode::from(u.as_ref()) }) }) .transpose()?, ); } "codingMode" => { builder = builder.set_coding_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Ac3CodingMode::from(u.as_ref())) }) .transpose()?, ); } "dialnorm" => { builder = builder.set_dialnorm( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "dynamicRangeCompressionLine" => { builder = builder.set_dynamic_range_compression_line( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Ac3DynamicRangeCompressionLine::from( u.as_ref(), ) }) }) .transpose()?, ); } "dynamicRangeCompressionProfile" => { builder = builder.set_dynamic_range_compression_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Ac3DynamicRangeCompressionProfile::from( u.as_ref(), ) }) }) .transpose()?, ); } "dynamicRangeCompressionRf" => { builder = builder.set_dynamic_range_compression_rf( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Ac3DynamicRangeCompressionRf::from( u.as_ref(), ) }) }) .transpose()?, ); } "lfeFilter" => { builder = builder.set_lfe_filter( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Ac3LfeFilter::from(u.as_ref())) }) .transpose()?, ); } "metadataControl" => { builder = builder.set_metadata_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Ac3MetadataControl::from(u.as_ref()) }) }) .transpose()?, ); } "sampleRate" => { builder = builder.set_sample_rate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_aiff_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AiffSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AiffSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bitDepth" => { builder = builder.set_bit_depth( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "channels" => { builder = builder.set_channels( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "sampleRate" => { builder = builder.set_sample_rate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_eac3_atmos_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Eac3AtmosSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Eac3AtmosSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "bitstreamMode" => { builder = builder.set_bitstream_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3AtmosBitstreamMode::from(u.as_ref()) }) }) .transpose()?, ); } "codingMode" => { builder = builder.set_coding_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3AtmosCodingMode::from(u.as_ref()) }) }) .transpose()?, ); } "dialogueIntelligence" => { builder = builder.set_dialogue_intelligence( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3AtmosDialogueIntelligence::from( u.as_ref(), ) }) }) .transpose()?, ); } "downmixControl" => { builder = builder.set_downmix_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3AtmosDownmixControl::from(u.as_ref()) }) }) .transpose()?, ); } "dynamicRangeCompressionLine" => { builder = builder.set_dynamic_range_compression_line( smithy_json::deserialize::token::expect_string_or_null(tokens.next())?.map(|s| s.to_unescaped().map(|u| crate::model::Eac3AtmosDynamicRangeCompressionLine::from(u.as_ref()) ) ).transpose()? ); } "dynamicRangeCompressionRf" => { builder = builder.set_dynamic_range_compression_rf( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3AtmosDynamicRangeCompressionRf::from( u.as_ref(), ) }) }) .transpose()?, ); } "dynamicRangeControl" => { builder = builder.set_dynamic_range_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3AtmosDynamicRangeControl::from( u.as_ref(), ) }) }) .transpose()?, ); } "loRoCenterMixLevel" => { builder = builder.set_lo_ro_center_mix_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "loRoSurroundMixLevel" => { builder = builder.set_lo_ro_surround_mix_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "ltRtCenterMixLevel" => { builder = builder.set_lt_rt_center_mix_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "ltRtSurroundMixLevel" => { builder = builder.set_lt_rt_surround_mix_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "meteringMode" => { builder = builder.set_metering_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3AtmosMeteringMode::from(u.as_ref()) }) }) .transpose()?, ); } "sampleRate" => { builder = builder.set_sample_rate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "speechThreshold" => { builder = builder.set_speech_threshold( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "stereoDownmix" => { builder = builder.set_stereo_downmix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3AtmosStereoDownmix::from(u.as_ref()) }) }) .transpose()?, ); } "surroundExMode" => { builder = builder.set_surround_ex_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3AtmosSurroundExMode::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_eac3_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Eac3Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Eac3Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "attenuationControl" => { builder = builder.set_attenuation_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3AttenuationControl::from(u.as_ref()) }) }) .transpose()?, ); } "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "bitstreamMode" => { builder = builder.set_bitstream_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3BitstreamMode::from(u.as_ref()) }) }) .transpose()?, ); } "codingMode" => { builder = builder.set_coding_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Eac3CodingMode::from(u.as_ref())) }) .transpose()?, ); } "dcFilter" => { builder = builder.set_dc_filter( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Eac3DcFilter::from(u.as_ref())) }) .transpose()?, ); } "dialnorm" => { builder = builder.set_dialnorm( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "dynamicRangeCompressionLine" => { builder = builder.set_dynamic_range_compression_line( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3DynamicRangeCompressionLine::from( u.as_ref(), ) }) }) .transpose()?, ); } "dynamicRangeCompressionRf" => { builder = builder.set_dynamic_range_compression_rf( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3DynamicRangeCompressionRf::from( u.as_ref(), ) }) }) .transpose()?, ); } "lfeControl" => { builder = builder.set_lfe_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Eac3LfeControl::from(u.as_ref())) }) .transpose()?, ); } "lfeFilter" => { builder = builder.set_lfe_filter( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::Eac3LfeFilter::from(u.as_ref())) }) .transpose()?, ); } "loRoCenterMixLevel" => { builder = builder.set_lo_ro_center_mix_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "loRoSurroundMixLevel" => { builder = builder.set_lo_ro_surround_mix_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "ltRtCenterMixLevel" => { builder = builder.set_lt_rt_center_mix_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "ltRtSurroundMixLevel" => { builder = builder.set_lt_rt_surround_mix_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } "metadataControl" => { builder = builder.set_metadata_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3MetadataControl::from(u.as_ref()) }) }) .transpose()?, ); } "passthroughControl" => { builder = builder.set_passthrough_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3PassthroughControl::from(u.as_ref()) }) }) .transpose()?, ); } "phaseControl" => { builder = builder.set_phase_control( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3PhaseControl::from(u.as_ref()) }) }) .transpose()?, ); } "sampleRate" => { builder = builder.set_sample_rate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "stereoDownmix" => { builder = builder.set_stereo_downmix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3StereoDownmix::from(u.as_ref()) }) }) .transpose()?, ); } "surroundExMode" => { builder = builder.set_surround_ex_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3SurroundExMode::from(u.as_ref()) }) }) .transpose()?, ); } "surroundMode" => { builder = builder.set_surround_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Eac3SurroundMode::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_mp2_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Mp2Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Mp2Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "channels" => { builder = builder.set_channels( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "sampleRate" => { builder = builder.set_sample_rate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_mp3_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Mp3Settings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Mp3Settings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "channels" => { builder = builder.set_channels( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "rateControlMode" => { builder = builder.set_rate_control_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Mp3RateControlMode::from(u.as_ref()) }) }) .transpose()?, ); } "sampleRate" => { builder = builder.set_sample_rate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "vbrQuality" => { builder = builder.set_vbr_quality( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_opus_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::OpusSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::OpusSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bitrate" => { builder = builder.set_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "channels" => { builder = builder.set_channels( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "sampleRate" => { builder = builder.set_sample_rate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_vorbis_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::VorbisSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::VorbisSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "channels" => { builder = builder.set_channels( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "sampleRate" => { builder = builder.set_sample_rate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "vbrQuality" => { builder = builder.set_vbr_quality( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_wav_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::WavSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::WavSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bitDepth" => { builder = builder.set_bit_depth( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "channels" => { builder = builder.set_channels( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "format" => { builder = builder.set_format( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::WavFormat::from(u.as_ref())) }) .transpose()?, ); } "sampleRate" => { builder = builder.set_sample_rate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_channel_mapping<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ChannelMapping>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ChannelMapping::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "outputChannels" => { builder = builder.set_output_channels( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_output_channel_mapping(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_burnin_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::BurninDestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::BurninDestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "alignment" => { builder = builder.set_alignment( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::BurninSubtitleAlignment::from(u.as_ref()) }) }) .transpose()?, ); } "backgroundColor" => { builder = builder.set_background_color( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::BurninSubtitleBackgroundColor::from( u.as_ref(), ) }) }) .transpose()?, ); } "backgroundOpacity" => { builder = builder.set_background_opacity( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "fontColor" => { builder = builder.set_font_color( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::BurninSubtitleFontColor::from(u.as_ref()) }) }) .transpose()?, ); } "fontOpacity" => { builder = builder.set_font_opacity( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "fontResolution" => { builder = builder.set_font_resolution( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "fontScript" => { builder = builder.set_font_script( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::FontScript::from(u.as_ref())) }) .transpose()?, ); } "fontSize" => { builder = builder.set_font_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "outlineColor" => { builder = builder.set_outline_color( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::BurninSubtitleOutlineColor::from( u.as_ref(), ) }) }) .transpose()?, ); } "outlineSize" => { builder = builder.set_outline_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "shadowColor" => { builder = builder.set_shadow_color( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::BurninSubtitleShadowColor::from( u.as_ref(), ) }) }) .transpose()?, ); } "shadowOpacity" => { builder = builder.set_shadow_opacity( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "shadowXOffset" => { builder = builder.set_shadow_x_offset( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "shadowYOffset" => { builder = builder.set_shadow_y_offset( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "teletextSpacing" => { builder = builder.set_teletext_spacing( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::BurninSubtitleTeletextSpacing::from( u.as_ref(), ) }) }) .transpose()?, ); } "xPosition" => { builder = builder.set_x_position( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "yPosition" => { builder = builder.set_y_position( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_dvb_sub_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DvbSubDestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DvbSubDestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "alignment" => { builder = builder.set_alignment( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DvbSubtitleAlignment::from(u.as_ref()) }) }) .transpose()?, ); } "backgroundColor" => { builder = builder.set_background_color( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DvbSubtitleBackgroundColor::from( u.as_ref(), ) }) }) .transpose()?, ); } "backgroundOpacity" => { builder = builder.set_background_opacity( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "ddsHandling" => { builder = builder.set_dds_handling( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::DvbddsHandling::from(u.as_ref())) }) .transpose()?, ); } "ddsXCoordinate" => { builder = builder.set_dds_x_coordinate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "ddsYCoordinate" => { builder = builder.set_dds_y_coordinate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "fontColor" => { builder = builder.set_font_color( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DvbSubtitleFontColor::from(u.as_ref()) }) }) .transpose()?, ); } "fontOpacity" => { builder = builder.set_font_opacity( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "fontResolution" => { builder = builder.set_font_resolution( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "fontScript" => { builder = builder.set_font_script( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::FontScript::from(u.as_ref())) }) .transpose()?, ); } "fontSize" => { builder = builder.set_font_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "height" => { builder = builder.set_height( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "outlineColor" => { builder = builder.set_outline_color( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DvbSubtitleOutlineColor::from(u.as_ref()) }) }) .transpose()?, ); } "outlineSize" => { builder = builder.set_outline_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "shadowColor" => { builder = builder.set_shadow_color( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DvbSubtitleShadowColor::from(u.as_ref()) }) }) .transpose()?, ); } "shadowOpacity" => { builder = builder.set_shadow_opacity( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "shadowXOffset" => { builder = builder.set_shadow_x_offset( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "shadowYOffset" => { builder = builder.set_shadow_y_offset( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "subtitlingType" => { builder = builder.set_subtitling_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DvbSubtitlingType::from(u.as_ref()) }) }) .transpose()?, ); } "teletextSpacing" => { builder = builder.set_teletext_spacing( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DvbSubtitleTeletextSpacing::from( u.as_ref(), ) }) }) .transpose()?, ); } "width" => { builder = builder.set_width( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "xPosition" => { builder = builder.set_x_position( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "yPosition" => { builder = builder.set_y_position( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_embedded_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::EmbeddedDestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::EmbeddedDestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "destination608ChannelNumber" => { builder = builder.set_destination608_channel_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "destination708ServiceNumber" => { builder = builder.set_destination708_service_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_imsc_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ImscDestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ImscDestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "stylePassthrough" => { builder = builder.set_style_passthrough( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ImscStylePassthrough::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_scc_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SccDestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SccDestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "framerate" => { builder = builder.set_framerate( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::SccDestinationFramerate::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_srt_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SrtDestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SrtDestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "stylePassthrough" => { builder = builder.set_style_passthrough( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::SrtStylePassthrough::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_teletext_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::TeletextDestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TeletextDestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "pageNumber" => { builder = builder.set_page_number( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "pageTypes" => { builder = builder.set_page_types( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of_teletext_page_type(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_ttml_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::TtmlDestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TtmlDestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "stylePassthrough" => { builder = builder.set_style_passthrough( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::TtmlStylePassthrough::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_webvtt_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::WebvttDestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::WebvttDestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "stylePassthrough" => { builder = builder.set_style_passthrough( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::WebvttStylePassthrough::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_av1_qvbr_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Av1QvbrSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Av1QvbrSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "qvbrQualityLevel" => { builder = builder.set_qvbr_quality_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qvbrQualityLevelFineTune" => { builder = builder.set_qvbr_quality_level_fine_tune( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_avc_intra_uhd_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AvcIntraUhdSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AvcIntraUhdSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "qualityTuningLevel" => { builder = builder.set_quality_tuning_level( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AvcIntraUhdQualityTuningLevel::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_h264_qvbr_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::H264QvbrSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::H264QvbrSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "maxAverageBitrate" => { builder = builder.set_max_average_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qvbrQualityLevel" => { builder = builder.set_qvbr_quality_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qvbrQualityLevelFineTune" => { builder = builder.set_qvbr_quality_level_fine_tune( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_h265_qvbr_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::H265QvbrSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::H265QvbrSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "maxAverageBitrate" => { builder = builder.set_max_average_bitrate( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qvbrQualityLevel" => { builder = builder.set_qvbr_quality_level( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qvbrQualityLevelFineTune" => { builder = builder.set_qvbr_quality_level_fine_tune( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_f64()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_xavc4k_intra_cbg_profile_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Xavc4kIntraCbgProfileSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Xavc4kIntraCbgProfileSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "xavcClass" => { builder = builder.set_xavc_class( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Xavc4kIntraCbgProfileClass::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_xavc4k_intra_vbr_profile_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Xavc4kIntraVbrProfileSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Xavc4kIntraVbrProfileSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "xavcClass" => { builder = builder.set_xavc_class( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Xavc4kIntraVbrProfileClass::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_xavc4k_profile_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Xavc4kProfileSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Xavc4kProfileSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bitrateClass" => { builder = builder.set_bitrate_class( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Xavc4kProfileBitrateClass::from( u.as_ref(), ) }) }) .transpose()?, ); } "codecProfile" => { builder = builder.set_codec_profile( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Xavc4kProfileCodecProfile::from( u.as_ref(), ) }) }) .transpose()?, ); } "flickerAdaptiveQuantization" => { builder = builder.set_flicker_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcFlickerAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "gopBReference" => { builder = builder.set_gop_b_reference( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcGopBReference::from(u.as_ref()) }) }) .transpose()?, ); } "gopClosedCadence" => { builder = builder.set_gop_closed_cadence( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "hrdBufferSize" => { builder = builder.set_hrd_buffer_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "qualityTuningLevel" => { builder = builder.set_quality_tuning_level( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::Xavc4kProfileQualityTuningLevel::from( u.as_ref(), ) }) }) .transpose()?, ); } "slices" => { builder = builder.set_slices( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_xavc_hd_intra_cbg_profile_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::XavcHdIntraCbgProfileSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::XavcHdIntraCbgProfileSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "xavcClass" => { builder = builder.set_xavc_class( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcHdIntraCbgProfileClass::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_xavc_hd_profile_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::XavcHdProfileSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::XavcHdProfileSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bitrateClass" => { builder = builder.set_bitrate_class( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcHdProfileBitrateClass::from( u.as_ref(), ) }) }) .transpose()?, ); } "flickerAdaptiveQuantization" => { builder = builder.set_flicker_adaptive_quantization( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcFlickerAdaptiveQuantization::from( u.as_ref(), ) }) }) .transpose()?, ); } "gopBReference" => { builder = builder.set_gop_b_reference( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcGopBReference::from(u.as_ref()) }) }) .transpose()?, ); } "gopClosedCadence" => { builder = builder.set_gop_closed_cadence( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "hrdBufferSize" => { builder = builder.set_hrd_buffer_size( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "interlaceMode" => { builder = builder.set_interlace_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcInterlaceMode::from(u.as_ref()) }) }) .transpose()?, ); } "qualityTuningLevel" => { builder = builder.set_quality_tuning_level( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcHdProfileQualityTuningLevel::from( u.as_ref(), ) }) }) .transpose()?, ); } "slices" => { builder = builder.set_slices( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "telecine" => { builder = builder.set_telecine( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::XavcHdProfileTelecine::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_dolby_vision_level6_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DolbyVisionLevel6Metadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DolbyVisionLevel6Metadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "maxCll" => { builder = builder.set_max_cll( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "maxFall" => { builder = builder.set_max_fall( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_noise_reducer_filter_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::NoiseReducerFilterSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::NoiseReducerFilterSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "strength" => { builder = builder.set_strength( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_noise_reducer_spatial_filter_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::NoiseReducerSpatialFilterSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::NoiseReducerSpatialFilterSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "postFilterSharpenStrength" => { builder = builder.set_post_filter_sharpen_strength( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "speed" => { builder = builder.set_speed( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "strength" => { builder = builder.set_strength( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_noise_reducer_temporal_filter_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::NoiseReducerTemporalFilterSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::NoiseReducerTemporalFilterSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "aggressiveMode" => { builder = builder.set_aggressive_mode( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "postTemporalSharpening" => { builder = builder.set_post_temporal_sharpening( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::NoiseFilterPostTemporalSharpening::from( u.as_ref(), ) }) }) .transpose()?, ); } "speed" => { builder = builder.set_speed( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "strength" => { builder = builder.set_strength( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_nex_guard_file_marker_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::NexGuardFileMarkerSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::NexGuardFileMarkerSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "license" => { builder = builder.set_license( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "payload" => { builder = builder.set_payload( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "preset" => { builder = builder.set_preset( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "strength" => { builder = builder.set_strength( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::WatermarkingStrength::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of__string_min1<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_hls_rendition_group_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::HlsRenditionGroupSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::HlsRenditionGroupSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "renditionGroupId" => { builder = builder.set_rendition_group_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "renditionLanguageCode" => { builder = builder.set_rendition_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::LanguageCode::from(u.as_ref())) }) .transpose()?, ); } "renditionName" => { builder = builder.set_rendition_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of__integer_min1_max2147483647<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<i32>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_number_or_null(tokens.next())? .map(|v| v.to_i32()); if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_caption_source_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CaptionSourceSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CaptionSourceSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "ancillarySourceSettings" => { builder = builder.set_ancillary_source_settings( crate::json_deser::deser_structure_crate_model_ancillary_source_settings(tokens)? ); } "dvbSubSourceSettings" => { builder = builder.set_dvb_sub_source_settings( crate::json_deser::deser_structure_crate_model_dvb_sub_source_settings(tokens)? ); } "embeddedSourceSettings" => { builder = builder.set_embedded_source_settings( crate::json_deser::deser_structure_crate_model_embedded_source_settings(tokens)? ); } "fileSourceSettings" => { builder = builder.set_file_source_settings( crate::json_deser::deser_structure_crate_model_file_source_settings(tokens)? ); } "sourceType" => { builder = builder.set_source_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CaptionSourceType::from(u.as_ref()) }) }) .transpose()?, ); } "teletextSourceSettings" => { builder = builder.set_teletext_source_settings( crate::json_deser::deser_structure_crate_model_teletext_source_settings(tokens)? ); } "trackSourceSettings" => { builder = builder.set_track_source_settings( crate::json_deser::deser_structure_crate_model_track_source_settings(tokens)? ); } "webvttHlsSourceSettings" => { builder = builder.set_webvtt_hls_source_settings( crate::json_deser::deser_structure_crate_model_webvtt_hls_source_settings(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_insertable_image<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::InsertableImage>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::InsertableImage::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "duration" => { builder = builder.set_duration( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "fadeIn" => { builder = builder.set_fade_in( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "fadeOut" => { builder = builder.set_fade_out( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "height" => { builder = builder.set_height( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "imageInserterInput" => { builder = builder.set_image_inserter_input( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "imageX" => { builder = builder.set_image_x( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "imageY" => { builder = builder.set_image_y( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "layer" => { builder = builder.set_layer( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "opacity" => { builder = builder.set_opacity( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "startTime" => { builder = builder.set_start_time( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "width" => { builder = builder.set_width( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_cmaf_additional_manifest<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::CmafAdditionalManifest>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_cmaf_additional_manifest(tokens)? ; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "s3Settings" => { builder = builder.set_s3_settings( crate::json_deser::deser_structure_crate_model_s3_destination_settings(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_cmaf_encryption_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CmafEncryptionSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CmafEncryptionSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "constantInitializationVector" => { builder = builder.set_constant_initialization_vector( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "encryptionMethod" => { builder = builder.set_encryption_method( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafEncryptionType::from(u.as_ref()) }) }) .transpose()?, ); } "initializationVectorInManifest" => { builder = builder.set_initialization_vector_in_manifest( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafInitializationVectorInManifest::from( u.as_ref(), ) }) }) .transpose()?, ); } "spekeKeyProvider" => { builder = builder.set_speke_key_provider( crate::json_deser::deser_structure_crate_model_speke_key_provider_cmaf(tokens)? ); } "staticKeyProvider" => { builder = builder.set_static_key_provider( crate::json_deser::deser_structure_crate_model_static_key_provider(tokens)? ); } "type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::CmafKeyProviderType::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_dash_additional_manifest<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::DashAdditionalManifest>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_dash_additional_manifest(tokens)? ; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_dash_iso_encryption_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DashIsoEncryptionSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DashIsoEncryptionSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "playbackDeviceCompatibility" => { builder = builder.set_playback_device_compatibility( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DashIsoPlaybackDeviceCompatibility::from( u.as_ref(), ) }) }) .transpose()?, ); } "spekeKeyProvider" => { builder = builder.set_speke_key_provider( crate::json_deser::deser_structure_crate_model_speke_key_provider(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_hls_ad_markers<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::HlsAdMarkers>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::HlsAdMarkers::from(u.as_ref())) }) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_hls_additional_manifest<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::HlsAdditionalManifest>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_hls_additional_manifest( tokens, )?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_hls_caption_language_mapping<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::HlsCaptionLanguageMapping>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_hls_caption_language_mapping(tokens)? ; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_hls_encryption_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::HlsEncryptionSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::HlsEncryptionSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "constantInitializationVector" => { builder = builder.set_constant_initialization_vector( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "encryptionMethod" => { builder = builder.set_encryption_method( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsEncryptionType::from(u.as_ref()) }) }) .transpose()?, ); } "initializationVectorInManifest" => { builder = builder.set_initialization_vector_in_manifest( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsInitializationVectorInManifest::from( u.as_ref(), ) }) }) .transpose()?, ); } "offlineEncrypted" => { builder = builder.set_offline_encrypted( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsOfflineEncrypted::from(u.as_ref()) }) }) .transpose()?, ); } "spekeKeyProvider" => { builder = builder.set_speke_key_provider( crate::json_deser::deser_structure_crate_model_speke_key_provider(tokens)? ); } "staticKeyProvider" => { builder = builder.set_static_key_provider( crate::json_deser::deser_structure_crate_model_static_key_provider(tokens)? ); } "type" => { builder = builder.set_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsKeyProviderType::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_ms_smooth_additional_manifest<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::MsSmoothAdditionalManifest>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_ms_smooth_additional_manifest(tokens)? ; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_ms_smooth_encryption_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MsSmoothEncryptionSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MsSmoothEncryptionSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "spekeKeyProvider" => { builder = builder.set_speke_key_provider( crate::json_deser::deser_structure_crate_model_speke_key_provider(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_caption_description<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::CaptionDescription>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_caption_description( tokens, )?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_output_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::OutputSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::OutputSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "hlsSettings" => { builder = builder.set_hls_settings( crate::json_deser::deser_structure_crate_model_hls_settings( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_output_channel_mapping<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::OutputChannelMapping>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_crate_model_output_channel_mapping( tokens, )?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of_teletext_page_type<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::TeletextPageType>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::TeletextPageType::from(u.as_ref())) }) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_crate_model_ancillary_source_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AncillarySourceSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AncillarySourceSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "convert608To708" => { builder = builder.set_convert608_to708( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AncillaryConvert608To708::from(u.as_ref()) }) }) .transpose()?, ); } "sourceAncillaryChannelNumber" => { builder = builder.set_source_ancillary_channel_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "terminateCaptions" => { builder = builder.set_terminate_captions( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AncillaryTerminateCaptions::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_dvb_sub_source_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DvbSubSourceSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DvbSubSourceSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "pid" => { builder = builder.set_pid( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_embedded_source_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::EmbeddedSourceSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::EmbeddedSourceSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "convert608To708" => { builder = builder.set_convert608_to708( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::EmbeddedConvert608To708::from(u.as_ref()) }) }) .transpose()?, ); } "source608ChannelNumber" => { builder = builder.set_source608_channel_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "source608TrackNumber" => { builder = builder.set_source608_track_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "terminateCaptions" => { builder = builder.set_terminate_captions( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::EmbeddedTerminateCaptions::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_file_source_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::FileSourceSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::FileSourceSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "convert608To708" => { builder = builder.set_convert608_to708( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::FileSourceConvert608To708::from( u.as_ref(), ) }) }) .transpose()?, ); } "framerate" => { builder = builder.set_framerate( crate::json_deser::deser_structure_crate_model_caption_source_framerate(tokens)? ); } "sourceFile" => { builder = builder.set_source_file( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "timeDelta" => { builder = builder.set_time_delta( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_teletext_source_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::TeletextSourceSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TeletextSourceSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "pageNumber" => { builder = builder.set_page_number( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_track_source_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::TrackSourceSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TrackSourceSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "trackNumber" => { builder = builder.set_track_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_webvtt_hls_source_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::WebvttHlsSourceSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::WebvttHlsSourceSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "renditionGroupId" => { builder = builder.set_rendition_group_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "renditionLanguageCode" => { builder = builder.set_rendition_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::LanguageCode::from(u.as_ref())) }) .transpose()?, ); } "renditionName" => { builder = builder.set_rendition_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_cmaf_additional_manifest<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CmafAdditionalManifest>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CmafAdditionalManifest::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "manifestNameModifier" => { builder = builder.set_manifest_name_modifier( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "selectedOutputs" => { builder = builder.set_selected_outputs( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__string_min1(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_s3_destination_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::S3DestinationSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::S3DestinationSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "accessControl" => { builder = builder.set_access_control( crate::json_deser::deser_structure_crate_model_s3_destination_access_control(tokens)? ); } "encryption" => { builder = builder.set_encryption( crate::json_deser::deser_structure_crate_model_s3_encryption_settings(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_speke_key_provider_cmaf<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SpekeKeyProviderCmaf>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SpekeKeyProviderCmaf::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "certificateArn" => { builder = builder.set_certificate_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "dashSignaledSystemIds" => { builder = builder.set_dash_signaled_system_ids( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__string_min36_max36_pattern09a_faf809a_faf409a_faf409a_faf409a_faf12(tokens)? ); } "hlsSignaledSystemIds" => { builder = builder.set_hls_signaled_system_ids( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__string_min36_max36_pattern09a_faf809a_faf409a_faf409a_faf409a_faf12(tokens)? ); } "resourceId" => { builder = builder.set_resource_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "url" => { builder = builder.set_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_static_key_provider<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::StaticKeyProvider>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::StaticKeyProvider::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "keyFormat" => { builder = builder.set_key_format( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "keyFormatVersions" => { builder = builder.set_key_format_versions( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "staticKeyValue" => { builder = builder.set_static_key_value( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "url" => { builder = builder.set_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_dash_additional_manifest<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DashAdditionalManifest>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DashAdditionalManifest::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "manifestNameModifier" => { builder = builder.set_manifest_name_modifier( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "selectedOutputs" => { builder = builder.set_selected_outputs( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__string_min1(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_speke_key_provider<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SpekeKeyProvider>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SpekeKeyProvider::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "certificateArn" => { builder = builder.set_certificate_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "resourceId" => { builder = builder.set_resource_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "systemIds" => { builder = builder.set_system_ids( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__string_pattern09a_faf809a_faf409a_faf409a_faf409a_faf12(tokens)? ); } "url" => { builder = builder.set_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_hls_additional_manifest<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::HlsAdditionalManifest>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::HlsAdditionalManifest::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "manifestNameModifier" => { builder = builder.set_manifest_name_modifier( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "selectedOutputs" => { builder = builder.set_selected_outputs( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__string_min1(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_hls_caption_language_mapping<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::HlsCaptionLanguageMapping>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::HlsCaptionLanguageMapping::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "captionChannel" => { builder = builder.set_caption_channel( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "customLanguageCode" => { builder = builder.set_custom_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "languageCode" => { builder = builder.set_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::LanguageCode::from(u.as_ref())) }) .transpose()?, ); } "languageDescription" => { builder = builder.set_language_description( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_ms_smooth_additional_manifest<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MsSmoothAdditionalManifest>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MsSmoothAdditionalManifest::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "manifestNameModifier" => { builder = builder.set_manifest_name_modifier( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "selectedOutputs" => { builder = builder.set_selected_outputs( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__string_min1(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_caption_description<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CaptionDescription>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CaptionDescription::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "captionSelectorName" => { builder = builder.set_caption_selector_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "customLanguageCode" => { builder = builder.set_custom_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "destinationSettings" => { builder = builder.set_destination_settings( crate::json_deser::deser_structure_crate_model_caption_destination_settings(tokens)? ); } "languageCode" => { builder = builder.set_language_code( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::LanguageCode::from(u.as_ref())) }) .transpose()?, ); } "languageDescription" => { builder = builder.set_language_description( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_hls_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::HlsSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::HlsSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "audioGroupId" => { builder = builder.set_audio_group_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "audioOnlyContainer" => { builder = builder.set_audio_only_container( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsAudioOnlyContainer::from(u.as_ref()) }) }) .transpose()?, ); } "audioRenditionSets" => { builder = builder.set_audio_rendition_sets( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "audioTrackType" => { builder = builder.set_audio_track_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsAudioTrackType::from(u.as_ref()) }) }) .transpose()?, ); } "descriptiveVideoServiceFlag" => { builder = builder.set_descriptive_video_service_flag( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsDescriptiveVideoServiceFlag::from( u.as_ref(), ) }) }) .transpose()?, ); } "iFrameOnlyManifest" => { builder = builder.set_i_frame_only_manifest( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::HlsIFrameOnlyManifest::from(u.as_ref()) }) }) .transpose()?, ); } "segmentModifier" => { builder = builder.set_segment_modifier( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_output_channel_mapping<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::OutputChannelMapping>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::OutputChannelMapping::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "inputChannels" => { builder = builder.set_input_channels( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__integer_min_negative60_max6(tokens)? ); } "inputChannelsFineTune" => { builder = builder.set_input_channels_fine_tune( crate::json_deser::deser_list_com_amazonaws_mediaconvert___list_of__double_min_negative60_max6(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_caption_source_framerate<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CaptionSourceFramerate>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CaptionSourceFramerate::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "framerateDenominator" => { builder = builder.set_framerate_denominator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "framerateNumerator" => { builder = builder.set_framerate_numerator( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_s3_destination_access_control<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::S3DestinationAccessControl>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::S3DestinationAccessControl::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "cannedAcl" => { builder = builder.set_canned_acl( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::S3ObjectCannedAcl::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_crate_model_s3_encryption_settings<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::S3EncryptionSettings>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::S3EncryptionSettings::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "encryptionType" => { builder = builder.set_encryption_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::S3ServerSideEncryptionType::from( u.as_ref(), ) }) }) .transpose()?, ); } "kmsEncryptionContext" => { builder = builder.set_kms_encryption_context( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "kmsKeyArn" => { builder = builder.set_kms_key_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of__string_min36_max36_pattern09a_faf809a_faf409a_faf409a_faf409a_faf12< 'a, I, >( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of__string_pattern09a_faf809a_faf409a_faf409a_faf409a_faf12< 'a, I, >( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of__integer_min_negative60_max6<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<i32>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_number_or_null(tokens.next())? .map(|v| v.to_i32()); if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_com_amazonaws_mediaconvert___list_of__double_min_negative60_max6<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<f64>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_number_or_null(tokens.next())? .map(|v| v.to_f64()); if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } }
48.528137
180
0.358769
f948fa5ce76984f90246f8a91ad6464c262ca40e
135,776
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::cell::{Cell, RefCell}; use std::rc::Rc; use bumpalo::{ collections::{String, Vec}, Bump, }; use hh_autoimport_rust as hh_autoimport; use naming_special_names_rust as naming_special_names; use arena_collections::{AssocListMut, MultiSetMut}; use flatten_smart_constructors::{FlattenOp, FlattenSmartConstructors}; use oxidized_by_ref::{ aast, aast_defs, ast_defs::{Bop, ClassKind, ConstraintKind, FunKind, Id, ShapeFieldName, Uop, Variance}, decl_defs::MethodReactivity, errors::Errors, file_info::Mode, i_set::ISet, nast, pos::Pos, relative_path::RelativePath, shallow_decl_defs::{self, ShallowClassConst, ShallowMethod, ShallowProp, ShallowTypeconst}, shape_map::ShapeField, typing_defs, typing_defs::{ EnumType, FunArity, FunElt, FunParam, FunParams, FunType, ParamMode, ParamMutability, PossiblyEnforcedTy, Reactivity, ShapeFieldType, ShapeKind, Tparam, Ty, Ty_, TypeconstAbstractKind, TypedefType, }, typing_defs_flags::{FunParamFlags, FunTypeFlags}, typing_reason::Reason, }; use parser_core_types::{ indexed_source_text::IndexedSourceText, lexable_token::LexableToken, lexable_trivia::LexablePositionedTrivia, positioned_token::PositionedToken, source_text::SourceText, syntax_kind::SyntaxKind, token_kind::TokenKind, trivia_kind::TriviaKind, }; mod direct_decl_smart_constructors_generated; pub use direct_decl_smart_constructors_generated::DirectDeclSmartConstructors; type SSet<'a> = arena_collections::SortedSet<'a, &'a str>; /// If the given option is `None`, return `Node::Ignored`. Otherwise, unwrap it. macro_rules! unwrap_or_return { ($expr:expr) => { match $expr { None => return Node::Ignored, Some(node) => node, } }; ($expr:expr,) => { unwrap_or_return!($expr) }; } impl<'a> DirectDeclSmartConstructors<'a> { pub fn new(src: &SourceText<'a>, arena: &'a Bump) -> Self { Self { state: State::new(IndexedSourceText::new(src.clone()), arena), } } #[inline(always)] pub fn alloc<T>(&self, val: T) -> &'a T { self.state.arena.alloc(val) } pub fn get_name(&self, namespace: &'a str, name: Node<'a>) -> Option<Id<'a>> { fn qualified_name_from_parts<'a>( this: &DirectDeclSmartConstructors<'a>, namespace: &'a str, parts: &'a [Node<'a>], pos: &'a Pos<'a>, ) -> Option<Id<'a>> { let mut qualified_name = String::with_capacity_in(namespace.len() + parts.len() * 10, this.state.arena); match parts.first() { Some(Node::Backslash(_)) => (), // Already fully-qualified _ => qualified_name.push_str(namespace), } for part in parts { match part { Node::Name(&(name, _pos)) => qualified_name.push_str(&name), Node::Backslash(_) => qualified_name.push('\\'), Node::ListItem(listitem) => { if let (Node::Name(&(name, _)), Node::Backslash(_)) = &**listitem { qualified_name.push_str(&name); qualified_name.push_str("\\"); } else { panic!("Expected a name or backslash, but got {:?}", listitem); } } n => { panic!("Expected a name, backslash, or list item, but got {:?}", n); } } } Some(Id(pos, qualified_name.into_bump_str())) } match name { Node::Name(&(name, pos)) => { // always a simple name let mut fully_qualified = String::with_capacity_in(namespace.len() + name.len(), self.state.arena); fully_qualified.push_str(namespace); fully_qualified.push_str(name); Some(Id(pos, fully_qualified.into_bump_str())) } Node::XhpName(&(name, pos)) => { // xhp names are always unqualified Some(Id(pos, name)) } Node::QualifiedName(&(parts, pos)) => { qualified_name_from_parts(self, namespace, parts, pos) } Node::Construct(pos) => Some(Id(pos, naming_special_names::members::__CONSTRUCT)), _ => None, } } fn map_to_slice<T>( &self, node: Node<'a>, mut f: impl FnMut(Node<'a>) -> Option<T>, ) -> Option<&'a [T]> { let mut result = Vec::with_capacity_in(node.len(), self.state.arena); for node in node.iter() { result.push(f(*node)?) } Some(result.into_bump_slice()) } fn filter_map_to_slice<T>( &self, node: Node<'a>, mut f: impl FnMut(Node<'a>) -> Option<T>, ) -> Option<&'a [T]> { let mut result = Vec::with_capacity_in(node.len(), self.state.arena); for node in node.iter() { if let Some(mapped) = f(*node) { result.push(mapped) } } Some(result.into_bump_slice()) } fn slice_from_iter<T>(&self, iter: impl Iterator<Item = T>) -> &'a [T] { let mut result = match iter.size_hint().1 { Some(upper_bound) => Vec::with_capacity_in(upper_bound, self.state.arena), None => Vec::new_in(self.state.arena), }; for item in iter { result.push(item); } result.into_bump_slice() } fn maybe_slice_from_iter<T>(&self, iter: impl Iterator<Item = Option<T>>) -> Option<&'a [T]> { let mut result = match iter.size_hint().1 { Some(upper_bound) => Vec::with_capacity_in(upper_bound, self.state.arena), None => Vec::new_in(self.state.arena), }; for item in iter { result.push(item?); } Some(result.into_bump_slice()) } } #[derive(Clone, Debug)] pub struct InProgressDecls<'a> { pub classes: AssocListMut<'a, &'a str, shallow_decl_defs::ShallowClass<'a>>, pub funs: AssocListMut<'a, &'a str, typing_defs::FunElt<'a>>, pub typedefs: AssocListMut<'a, &'a str, typing_defs::TypedefType<'a>>, pub consts: AssocListMut<'a, &'a str, typing_defs::Ty<'a>>, } pub fn empty_decls<'a>(arena: &'a Bump) -> InProgressDecls<'a> { InProgressDecls { classes: AssocListMut::new_in(arena), funs: AssocListMut::new_in(arena), typedefs: AssocListMut::new_in(arena), consts: AssocListMut::new_in(arena), } } fn prefix_slash<'a>(arena: &'a Bump, name: &str) -> &'a str { let mut s = String::with_capacity_in(1 + name.len(), arena); s.push('\\'); s.push_str(name); s.into_bump_str() } fn concat<'a>(arena: &'a Bump, str1: &str, str2: &str) -> &'a str { let mut result = String::with_capacity_in(str1.len() + str2.len(), arena); result.push_str(str1); result.push_str(str2); result.into_bump_str() } fn strip_dollar_prefix<'a>(name: &'a str) -> &'a str { name.trim_start_matches("$") } const TANY_: Ty_<'_> = Ty_::Tany(oxidized_by_ref::tany_sentinel::TanySentinel); const TANY: Ty<'_> = Ty(Reason::none(), &TANY_); fn tany() -> Ty<'static> { TANY } fn tarraykey<'a>(arena: &'a Bump) -> Ty<'a> { Ty( Reason::none(), arena.alloc(Ty_::Tprim(arena.alloc(aast::Tprim::Tarraykey))), ) } #[derive(Debug)] struct Modifiers { is_static: bool, visibility: aast::Visibility, is_abstract: bool, is_final: bool, } fn read_member_modifiers<'a: 'b, 'b>(modifiers: impl Iterator<Item = &'b Node<'a>>) -> Modifiers { let mut ret = Modifiers { is_static: false, visibility: aast::Visibility::Public, is_abstract: false, is_final: false, }; for modifier in modifiers { if let Some(vis) = modifier.as_visibility() { ret.visibility = vis; } match modifier { Node::Token(TokenKind::Static) => ret.is_static = true, Node::Token(TokenKind::Abstract) => ret.is_abstract = true, Node::Token(TokenKind::Final) => ret.is_final = true, _ => (), } } ret } #[derive(Clone, Debug)] struct NamespaceInfo<'a> { name: &'a str, imports: AssocListMut<'a, &'a str, &'a str>, } #[derive(Clone, Debug)] struct NamespaceBuilder<'a> { arena: &'a Bump, stack: Vec<'a, NamespaceInfo<'a>>, } impl<'a> NamespaceBuilder<'a> { fn new_in(arena: &'a Bump) -> Self { NamespaceBuilder { arena, stack: bumpalo::vec![in arena; NamespaceInfo { name: "\\", imports: AssocListMut::new_in(arena), }], } } fn push_namespace(&mut self, name: Option<&str>) { let current = self.current_namespace(); if let Some(name) = name { let mut fully_qualified = String::with_capacity_in(current.len() + name.len() + 1, self.arena); fully_qualified.push_str(current); fully_qualified.push_str(name); fully_qualified.push('\\'); self.stack.push(NamespaceInfo { name: fully_qualified.into_bump_str(), imports: AssocListMut::new_in(self.arena), }); } else { self.stack.push(NamespaceInfo { name: current, imports: AssocListMut::new_in(self.arena), }); } } fn pop_namespace(&mut self) { // We'll never push a namespace for a declaration of items in the global // namespace (e.g., `namespace { ... }`), so only pop if we are in some // namespace other than the global one. if self.stack.len() > 1 { self.stack.pop().unwrap(); } } fn current_namespace(&self) -> &'a str { self.stack.last().map(|ni| ni.name).unwrap_or("\\") } fn add_import(&mut self, name: &'a str, aliased_name: Option<&'a str>) { let imports = &mut self .stack .last_mut() .expect("Attempted to get the current import map, but namespace stack was empty") .imports; let aliased_name = aliased_name.unwrap_or_else(|| { name.rsplit_terminator('\\') .nth(0) .expect("Expected at least one entry in import name") }); let name = if name.starts_with('\\') { name } else { prefix_slash(self.arena, name) }; imports.insert(aliased_name, name); } fn rename_import(&self, name: &'a str) -> &'a str { if name.starts_with('\\') { return name; } for ni in self.stack.iter().rev() { if let Some(name) = ni.imports.get(name) { return name; } } if let Some(renamed) = hh_autoimport::TYPES_MAP.get(name) { return prefix_slash(self.arena, renamed); } for ns in hh_autoimport::NAMESPACES { if name.starts_with(ns) { let ns_trimmed = &name[ns.len()..]; if ns_trimmed.starts_with('\\') { return concat(self.arena, "\\HH\\", name); } } } name } } #[derive(Clone, Debug)] enum ClassishNameBuilder<'a> { /// We are not in a classish declaration. NotInClassish, /// We saw a classish keyword token followed by a Name, so we make it /// available as the name of the containing class declaration. InClassish(&'a (&'a str, &'a Pos<'a>, TokenKind)), } impl<'a> ClassishNameBuilder<'a> { fn new() -> Self { ClassishNameBuilder::NotInClassish } fn lexed_name_after_classish_keyword( &mut self, arena: &'a Bump, name: &str, pos: &'a Pos<'a>, token_kind: TokenKind, ) { use ClassishNameBuilder::*; match self { NotInClassish => { let mut class_name = String::with_capacity_in(1 + name.len(), arena); class_name.push('\\'); class_name.push_str(name); *self = InClassish(arena.alloc((class_name.into_bump_str(), pos, token_kind))) } InClassish(_) => (), } } fn parsed_classish_declaration(&mut self) { *self = ClassishNameBuilder::NotInClassish; } fn get_current_classish_name(&self) -> Option<(&'a str, &'a Pos<'a>)> { use ClassishNameBuilder::*; match self { NotInClassish => None, InClassish((name, pos, _)) => Some((name, pos)), } } fn in_interface(&self) -> bool { use ClassishNameBuilder::*; match self { InClassish((_, _, TokenKind::Interface)) => true, InClassish((_, _, _)) | NotInClassish => false, } } } #[derive(Clone, Debug)] enum FileModeBuilder { // We haven't seen any tokens yet. None, // We've seen <? and we're waiting for the next token, which has the trivia // with the mode. Pending, // We either saw a <?, then `hh`, then a mode, or we didn't see that // sequence and we're defaulting to Mstrict. Set(Mode), } #[derive(Clone, Debug)] pub struct State<'a> { pub source_text: IndexedSourceText<'a>, pub arena: &'a bumpalo::Bump, pub decls: Rc<InProgressDecls<'a>>, filename: &'a RelativePath<'a>, namespace_builder: Rc<NamespaceBuilder<'a>>, classish_name_builder: ClassishNameBuilder<'a>, type_parameters: Rc<Vec<'a, SSet<'a>>>, // We don't need to wrap this in a Cow because it's very small. file_mode_builder: FileModeBuilder, previous_token_kind: TokenKind, } impl<'a> State<'a> { pub fn new(source_text: IndexedSourceText<'a>, arena: &'a Bump) -> State<'a> { let path = source_text.source_text().file_path(); let prefix = path.prefix(); let path = String::from_str_in(path.path_str(), arena).into_bump_str(); let filename = RelativePath::make(prefix, path); State { source_text, arena, filename: arena.alloc(filename), decls: Rc::new(empty_decls(arena)), namespace_builder: Rc::new(NamespaceBuilder::new_in(arena)), classish_name_builder: ClassishNameBuilder::new(), type_parameters: Rc::new(Vec::new_in(arena)), file_mode_builder: FileModeBuilder::None, // EndOfFile is used here as a None value (signifying "beginning of // file") to save space. There is no legitimate circumstance where // we would parse a token and the previous token kind would be // EndOfFile. previous_token_kind: TokenKind::EndOfFile, } } } #[derive(Clone, Debug)] pub struct FunParamDecl<'a> { attributes: Node<'a>, visibility: Node<'a>, kind: ParamMode, hint: Node<'a>, id: Id<'a>, variadic: bool, initializer: Node<'a>, } #[derive(Clone, Debug)] pub struct FunctionHeader<'a> { name: Node<'a>, modifiers: Node<'a>, type_params: Node<'a>, param_list: Node<'a>, ret_hint: Node<'a>, } #[derive(Clone, Debug)] pub struct RequireClause<'a> { require_type: Node<'a>, name: Node<'a>, } #[derive(Clone, Debug)] pub struct TypeParameterDecl<'a> { name: Node<'a>, reified: aast::ReifyKind, variance: Variance, constraints: &'a [(ConstraintKind, Node<'a>)], } #[derive(Clone, Debug)] pub struct ClosureTypeHint<'a> { args: Node<'a>, ret_hint: Node<'a>, } #[derive(Clone, Debug)] pub struct NamespaceUseClause<'a> { id: Id<'a>, as_: Option<&'a str>, } #[derive(Clone, Debug)] pub struct ConstructorNode<'a> { method: &'a ShallowMethod<'a>, properties: &'a [ShallowProp<'a>], } #[derive(Clone, Debug)] pub struct MethodNode<'a> { method: &'a ShallowMethod<'a>, is_static: bool, } #[derive(Clone, Debug)] pub struct PropertyNode<'a> { decls: &'a [ShallowProp<'a>], is_static: bool, } #[derive(Clone, Debug)] pub struct ShapeFieldNode<'a> { name: &'a ShapeField<'a>, type_: &'a ShapeFieldType<'a>, } #[derive(Copy, Clone, Debug)] pub enum Node<'a> { Ignored, List(&'a &'a [Node<'a>]), BracketedList(&'a (&'a Pos<'a>, &'a [Node<'a>], &'a Pos<'a>)), Name(&'a (&'a str, &'a Pos<'a>)), XhpName(&'a (&'a str, &'a Pos<'a>)), QualifiedName(&'a (&'a [Node<'a>], &'a Pos<'a>)), Array(&'a Pos<'a>), Darray(&'a Pos<'a>), Varray(&'a Pos<'a>), StringLiteral(&'a (&'a str, &'a Pos<'a>)), // For shape keys and const expressions. IntLiteral(&'a (&'a str, &'a Pos<'a>)), // For const expressions. FloatingLiteral(&'a (&'a str, &'a Pos<'a>)), // For const expressions. BooleanLiteral(&'a (&'a str, &'a Pos<'a>)), // For const expressions. Null(&'a Pos<'a>), // For const expressions. Ty(&'a Ty<'a>), TypeconstAccess(&'a (Cell<&'a Pos<'a>>, Ty<'a>, RefCell<Vec<'a, Id<'a>>>)), Backslash(&'a Pos<'a>), // This needs a pos since it shows up in names. ListItem(&'a (Node<'a>, Node<'a>)), Const(&'a ShallowClassConst<'a>), FunParam(&'a FunParamDecl<'a>), Attribute(&'a nast::UserAttribute<'a>), FunctionHeader(&'a FunctionHeader<'a>), Constructor(&'a ConstructorNode<'a>), Method(&'a MethodNode<'a>), Property(&'a PropertyNode<'a>), TraitUse(&'a Node<'a>), TypeConstant(&'a ShallowTypeconst<'a>), RequireClause(&'a RequireClause<'a>), ClassishBody(&'a &'a [Node<'a>]), TypeParameter(&'a TypeParameterDecl<'a>), TypeConstraint(&'a (ConstraintKind, Node<'a>)), ShapeFieldSpecifier(&'a ShapeFieldNode<'a>), NamespaceUseClause(&'a NamespaceUseClause<'a>), Expr(&'a nast::Expr<'a>), Operator(&'a (&'a Pos<'a>, TokenKind)), Construct(&'a Pos<'a>), This(&'a Pos<'a>), // This needs a pos since it shows up in Taccess. TypeParameters(&'a &'a [Tparam<'a>]), // For cases where the position of a node is included in some outer // position, but we do not need to track any further information about that // node (for instance, the parentheses surrounding a tuple type). Pos(&'a Pos<'a>), // Simple keywords and tokens. Token(TokenKind), // For nodes which are not useful to the direct decl smart constructors, but // which the parser needs to distinguish in some circumstances. An adapter // called WithKind exists to track this information, but in the direct decl // parser, we want to avoid the extra 8 bytes of overhead on each node. IgnoredSyntaxKind(SyntaxKind), } impl<'a> smart_constructors::NodeType for Node<'a> { type R = Node<'a>; fn extract(self) -> Self::R { self } fn is_abstract(&self) -> bool { matches!(self, Node::Token(TokenKind::Abstract)) } fn is_name(&self) -> bool { matches!(self, Node::Name(..)) } fn is_qualified_name(&self) -> bool { matches!(self, Node::QualifiedName(..)) } fn is_prefix_unary_expression(&self) -> bool { matches!(self, Node::Expr(aast::Expr(_, aast::Expr_::Unop(..)))) } fn is_scope_resolution_expression(&self) -> bool { matches!(self, Node::Expr(aast::Expr(_, aast::Expr_::ClassConst(..)))) } fn is_missing(&self) -> bool { matches!(self, Node::IgnoredSyntaxKind(SyntaxKind::Missing)) } fn is_variable_expression(&self) -> bool { matches!( self, Node::IgnoredSyntaxKind(SyntaxKind::VariableExpression) ) } fn is_subscript_expression(&self) -> bool { matches!( self, Node::IgnoredSyntaxKind(SyntaxKind::SubscriptExpression) ) } fn is_member_selection_expression(&self) -> bool { matches!( self, Node::IgnoredSyntaxKind(SyntaxKind::MemberSelectionExpression) ) } fn is_object_creation_expression(&self) -> bool { matches!( self, Node::IgnoredSyntaxKind(SyntaxKind::ObjectCreationExpression) ) } fn is_safe_member_selection_expression(&self) -> bool { matches!( self, Node::IgnoredSyntaxKind(SyntaxKind::SafeMemberSelectionExpression) ) } fn is_function_call_expression(&self) -> bool { matches!( self, Node::IgnoredSyntaxKind(SyntaxKind::FunctionCallExpression) ) } fn is_list_expression(&self) -> bool { matches!(self, Node::IgnoredSyntaxKind(SyntaxKind::ListExpression)) } } impl<'a> Node<'a> { pub fn get_pos(self, arena: &'a Bump) -> Option<&'a Pos<'a>> { match self { Node::Name(&(_, pos)) => Some(pos), Node::Ty(ty) => Some(ty.get_pos().unwrap_or(Pos::none())), Node::TypeconstAccess((pos, _, _)) => Some(pos.get()), Node::XhpName(&(_, pos)) => Some(pos), Node::QualifiedName(&(_, pos)) => Some(pos), Node::Pos(pos) | Node::Backslash(pos) | Node::Construct(pos) | Node::This(pos) | Node::Array(pos) | Node::Darray(pos) | Node::Varray(pos) | Node::IntLiteral(&(_, pos)) | Node::FloatingLiteral(&(_, pos)) | Node::Null(pos) | Node::StringLiteral(&(_, pos)) | Node::BooleanLiteral(&(_, pos)) | Node::Operator(&(pos, _)) => Some(pos), Node::ListItem(items) => { let fst = &items.0; let snd = &items.1; match (fst.get_pos(arena), snd.get_pos(arena)) { (Some(fst_pos), Some(snd_pos)) => Pos::merge(arena, fst_pos, snd_pos).ok(), (Some(pos), None) => Some(pos), (None, Some(pos)) => Some(pos), (None, None) => None, } } Node::List(items) => self.pos_from_slice(&items, arena), Node::BracketedList(&(first_pos, inner_list, second_pos)) => Pos::merge( arena, first_pos, Pos::merge( arena, self.pos_from_slice(&inner_list, arena).unwrap(), second_pos, ) .ok()?, ) .ok(), Node::Expr(&aast::Expr(pos, _)) => Some(pos), _ => None, } } fn pos_from_slice(&self, nodes: &'a [Node<'a>], arena: &'a Bump) -> Option<&'a Pos<'a>> { nodes .iter() .fold(None, |acc, elem| match (acc, elem.get_pos(arena)) { (Some(acc_pos), Some(elem_pos)) => Pos::merge(arena, acc_pos, elem_pos).ok(), (None, Some(elem_pos)) => Some(elem_pos), (acc, None) => acc, }) } fn as_slice(self, b: &'a Bump) -> &'a [Self] { match self { Node::List(items) => items, Node::BracketedList(innards) => { let (_, items, _) = *innards; items } n if n.is_ignored() => &[], n => bumpalo::vec![in b; n].into_bump_slice(), } } fn iter<'b>(&'b self) -> NodeIterHelper<'a, 'b> where 'a: 'b, { match self { &Node::List(&items) | Node::BracketedList(&(_, items, _)) => { NodeIterHelper::Vec(items.iter()) } n if n.is_ignored() => NodeIterHelper::Empty, n => NodeIterHelper::Single(n), } } // The number of elements which would be yielded by `self.iter()`. // Must return the upper bound returned by NodeIterHelper::size_hint. fn len(&self) -> usize { match self { &Node::List(&items) | Node::BracketedList(&(_, items, _)) => items.len(), n if n.is_ignored() => 0, _ => 1, } } fn as_visibility(&self) -> Option<aast::Visibility> { match self { Node::Token(TokenKind::Private) => Some(aast::Visibility::Private), Node::Token(TokenKind::Protected) => Some(aast::Visibility::Protected), Node::Token(TokenKind::Public) => Some(aast::Visibility::Public), _ => None, } } fn as_attributes(self, arena: &'a Bump) -> Option<Attributes<'a>> { let mut attributes = Attributes { reactivity: Reactivity::Nonreactive, param_mutability: None, deprecated: None, reifiable: None, returns_mutable: false, late_init: false, const_: false, lsb: false, memoizelsb: false, override_: false, at_most_rx_as_func: false, enforceable: None, returns_void_to_rx: false, }; let mut reactivity_condition_type = None; for attribute in self.iter() { match attribute { // If we see the attribute `__OnlyRxIfImpl(Foo::class)`, set // `reactivity_condition_type` to `Foo`. Node::Attribute(nast::UserAttribute { name: Id(_, "__OnlyRxIfImpl"), params: [aast::Expr( pos, aast::Expr_::ClassConst(( aast::ClassId(_, aast::ClassId_::CI(class_name)), (_, "class"), )), )], }) => { reactivity_condition_type = Some(Ty( arena.alloc(Reason::hint(*pos)), arena.alloc(Ty_::Tapply(arena.alloc((*class_name, &[][..])))), )); } _ => (), } } for attribute in self.iter() { if let Node::Attribute(attribute) = attribute { match attribute.name.1.as_ref() { // NB: It is an error to specify more than one of __Rx, // __RxShallow, and __RxLocal, so to avoid cloning the // condition type, we use Option::take here. "__Rx" => { attributes.reactivity = Reactivity::Reactive(reactivity_condition_type.take()) } "__RxShallow" => { attributes.reactivity = Reactivity::Shallow(reactivity_condition_type.take()) } "__RxLocal" => { attributes.reactivity = Reactivity::Local(reactivity_condition_type.take()) } "__Mutable" => { attributes.param_mutability = Some(ParamMutability::ParamBorrowedMutable) } "__MaybeMutable" => { attributes.param_mutability = Some(ParamMutability::ParamMaybeMutable) } "__OwnedMutable" => { attributes.param_mutability = Some(ParamMutability::ParamOwnedMutable) } "__MutableReturn" => attributes.returns_mutable = true, "__ReturnsVoidToRx" => attributes.returns_void_to_rx = true, "__Deprecated" => { fn fold_string_concat<'a>(expr: &nast::Expr<'a>, acc: &mut String<'a>) { match expr { &aast::Expr(_, aast::Expr_::String(val)) => acc.push_str(val), &aast::Expr(_, aast::Expr_::Binop(&(Bop::Dot, e1, e2))) => { fold_string_concat(&e1, acc); fold_string_concat(&e2, acc); } _ => (), } } attributes.deprecated = attribute.params.first().and_then(|expr| match expr { &aast::Expr(_, aast::Expr_::String(val)) => Some(val), &aast::Expr(_, aast::Expr_::Binop(_)) => { let mut acc = String::new_in(arena); fold_string_concat(expr, &mut acc); Some(acc.into_bump_str()) } _ => None, }) } "__Reifiable" => attributes.reifiable = Some(attribute.name.0), "__LateInit" => { attributes.late_init = true; } "__Const" => { attributes.const_ = true; } "__LSB" => { attributes.lsb = true; } "__MemoizeLSB" => { attributes.memoizelsb = true; } "__Override" => { attributes.override_ = true; } "__AtMostRxAsFunc" => { attributes.at_most_rx_as_func = true; } "__Enforceable" => { attributes.enforceable = Some(attribute.name.0); } _ => (), } } else { panic!("Expected an attribute, but was {:?}", self); } } Some(attributes) } fn is_ignored(&self) -> bool { matches!(self, Node::Ignored | Node::IgnoredSyntaxKind(..)) } fn is_present(&self) -> bool { !self.is_ignored() } } struct Attributes<'a> { reactivity: Reactivity<'a>, param_mutability: Option<ParamMutability>, deprecated: Option<&'a str>, reifiable: Option<&'a Pos<'a>>, returns_mutable: bool, late_init: bool, const_: bool, lsb: bool, memoizelsb: bool, override_: bool, at_most_rx_as_func: bool, enforceable: Option<&'a Pos<'a>>, returns_void_to_rx: bool, } impl<'a> DirectDeclSmartConstructors<'a> { fn set_mode(&mut self, token: &PositionedToken) { for trivia in &token.trailing { if trivia.kind == TriviaKind::SingleLineComment { if let Ok(text) = std::str::from_utf8(trivia.text_raw(self.state.source_text.source_text())) { match text.trim_start_matches('/').trim() { "decl" => self.state.file_mode_builder = FileModeBuilder::Set(Mode::Mdecl), "partial" => { self.state.file_mode_builder = FileModeBuilder::Set(Mode::Mpartial) } "strict" => { self.state.file_mode_builder = FileModeBuilder::Set(Mode::Mstrict) } _ => self.state.file_mode_builder = FileModeBuilder::Set(Mode::Mstrict), } } } } } #[inline(always)] fn concat(&self, str1: &str, str2: &str) -> &'a str { concat(self.state.arena, str1, str2) } fn token_bytes(&self, token: &PositionedToken) -> &'a [u8] { self.state.source_text.source_text().sub( token.leading_start_offset().unwrap_or(0) + token.leading_width(), token.width(), ) } // Check that the slice is valid UTF-8. If it is, return a &str referencing // the same data. Otherwise, copy the slice into our arena using // String::from_utf8_lossy_in, and return a reference to the arena str. fn str_from_utf8(&self, slice: &'a [u8]) -> &'a str { if let Ok(s) = std::str::from_utf8(slice) { s } else { String::from_utf8_lossy_in(slice, self.state.arena).into_bump_str() } } fn node_to_expr(&self, node: Node<'a>) -> Option<nast::Expr<'a>> { let expr_ = match node { Node::Expr(&expr) => return Some(expr), Node::IntLiteral(&(s, _)) => aast::Expr_::Int(s), Node::FloatingLiteral(&(s, _)) => aast::Expr_::Float(s), Node::StringLiteral(&(s, _)) => aast::Expr_::String(s), Node::BooleanLiteral((s, _)) => { if s.eq_ignore_ascii_case("true") { aast::Expr_::True } else { aast::Expr_::False } } Node::Null(_) => aast::Expr_::Null, Node::Name(..) | Node::QualifiedName(..) => aast::Expr_::Id( self.alloc(self.get_name(self.state.namespace_builder.current_namespace(), node)?), ), _ => return None, }; let pos = node.get_pos(self.state.arena)?; Some(aast::Expr(pos, expr_)) } fn node_to_ty(&self, node: Node<'a>) -> Option<Ty<'a>> { match node { Node::Ty(&ty) => Some(ty), Node::TypeconstAccess((pos, ty, names)) => { let pos = pos.get(); let names = self.slice_from_iter(names.borrow().iter().copied()); Some(Ty( self.alloc(Reason::hint(pos)), self.alloc(Ty_::Taccess( self.alloc(typing_defs::TaccessType(*ty, names)), )), )) } Node::Array(pos) => Some(Ty( self.alloc(Reason::hint(pos)), self.alloc(Ty_::Tarray(self.alloc((None, None)))), )), Node::Varray(pos) => Some(Ty( self.alloc(Reason::hint(pos)), self.alloc(Ty_::Tvarray(tany())), )), Node::Darray(pos) => Some(Ty( self.alloc(Reason::hint(pos)), self.alloc(Ty_::Tdarray(self.alloc((tany(), tany())))), )), Node::This(pos) => Some(Ty(self.alloc(Reason::hint(pos)), self.alloc(Ty_::Tthis))), Node::Expr(&expr) => { fn expr_to_ty<'a>(arena: &'a Bump, expr: nast::Expr<'a>) -> Option<Ty_<'a>> { use aast::Expr_::*; match expr.1 { Null => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tnull))), This => Some(Ty_::Tthis), True | False => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tbool))), Int(_) => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tint))), Float(_) => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tfloat))), String(_) => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tstring))), String2(_) => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tstring))), PrefixedString(_) => Some(Ty_::Tprim(arena.alloc(aast::Tprim::Tstring))), Unop(&(_op, expr)) => expr_to_ty(arena, expr), ParenthesizedExpr(&expr) => expr_to_ty(arena, expr), Any => Some(TANY_), Array(_) | ArrayGet(_) | As(_) | Assert(_) | Await(_) | Binop(_) | BracedExpr(_) | Call(_) | Callconv(_) | Cast(_) | ClassConst(_) | ClassGet(_) | Clone(_) | Collection(_) | Darray(_) | Dollardollar(_) | Efun(_) | Eif(_) | ExprList(_) | FunctionPointer(_) | FunId(_) | Id(_) | Import(_) | Is(_) | KeyValCollection(_) | Lfun(_) | List(_) | Lplaceholder(_) | Lvar(_) | MethodCaller(_) | MethodId(_) | New(_) | ObjGet(_) | Omitted | Pair(_) | Pipe(_) | PUAtom(_) | PUIdentifier(_) | Record(_) | Shape(_) | SmethodId(_) | Suspend(_) | ValCollection(_) | Varray(_) | Xml(_) | Yield(_) | YieldBreak | YieldFrom(_) => None, } } Some(Ty( self.alloc(Reason::witness(expr.0)), self.alloc(expr_to_ty(self.state.arena, expr)?), )) } Node::IntLiteral((_, pos)) => Some(Ty( self.alloc(Reason::witness(pos)), self.alloc(Ty_::Tprim(self.alloc(aast::Tprim::Tint))), )), Node::FloatingLiteral((_, pos)) => Some(Ty( self.alloc(Reason::witness(pos)), self.alloc(Ty_::Tprim(self.alloc(aast::Tprim::Tfloat))), )), Node::StringLiteral((_, pos)) => Some(Ty( self.alloc(Reason::witness(pos)), self.alloc(Ty_::Tprim(self.alloc(aast::Tprim::Tstring))), )), Node::BooleanLiteral((_, pos)) => Some(Ty( self.alloc(Reason::witness(pos)), self.alloc(Ty_::Tprim(self.alloc(aast::Tprim::Tbool))), )), Node::Null(pos) => Some(Ty( self.alloc(Reason::hint(pos)), self.alloc(Ty_::Tprim(self.alloc(aast::Tprim::Tnull))), )), node => { let Id(pos, name) = self.get_name("", node)?; let reason = self.alloc(Reason::hint(pos)); let ty_ = if self.is_type_param_in_scope(name) { Ty_::Tgeneric(name) } else { match name.as_ref() { "nothing" => Ty_::Tunion(&[]), "nonnull" => Ty_::Tnonnull, "dynamic" => Ty_::Tdynamic, "varray_or_darray" => { Ty_::TvarrayOrDarray(self.alloc((tarraykey(self.state.arena), tany()))) } _ => { let name = self.prefix_ns(self.state.namespace_builder.rename_import(name)); Ty_::Tapply(self.alloc((Id(pos, name), &[][..]))) } } }; Some(Ty(reason, self.alloc(ty_))) } } } fn pop_type_params(&mut self, node: Node<'a>) -> &'a [Tparam<'a>] { match node { Node::TypeParameters(tparams) => { Rc::make_mut(&mut self.state.type_parameters).pop().unwrap(); tparams } _ => &[], } } fn is_type_param_in_scope(&self, name: &str) -> bool { self.state .type_parameters .iter() .any(|tps| tps.contains(name)) } fn function_into_ty( &mut self, namespace: &'a str, attributes: Node<'a>, header: &'a FunctionHeader<'a>, body: Node, ) -> Option<(Id<'a>, Ty<'a>, &'a [ShallowProp<'a>])> { let id = self.get_name(namespace, header.name)?; let (params, properties, arity) = self.as_fun_params(header.param_list)?; let type_ = match header.name { Node::Construct(pos) => Ty( self.alloc(Reason::witness(pos)), self.alloc(Ty_::Tprim(self.alloc(aast::Tprim::Tvoid))), ), _ => self.node_to_ty(header.ret_hint).unwrap_or_else(|| { self.tany_with_pos(header.name.get_pos(self.state.arena).unwrap_or(Pos::none())) }), }; let (async_, is_coroutine) = header.modifiers.iter().fold( (false, false), |(async_, is_coroutine), node| match node { Node::Token(TokenKind::Async) => (true, is_coroutine), Node::Token(TokenKind::Coroutine) => (async_, true), _ => (async_, is_coroutine), }, ); let fun_kind = if is_coroutine { FunKind::FCoroutine } else { if body.iter().any(|node| match node { Node::Token(TokenKind::Yield) => true, _ => false, }) { if async_ { FunKind::FAsyncGenerator } else { FunKind::FGenerator } } else { if async_ { FunKind::FAsync } else { FunKind::FSync } } }; let attributes = attributes.as_attributes(self.state.arena)?; // TODO(hrust) Put this in a helper. Possibly do this for all flags. let mut flags = match fun_kind { FunKind::FSync => FunTypeFlags::empty(), FunKind::FAsync => FunTypeFlags::ASYNC, FunKind::FGenerator => FunTypeFlags::GENERATOR, FunKind::FAsyncGenerator => FunTypeFlags::ASYNC | FunTypeFlags::GENERATOR, FunKind::FCoroutine => FunTypeFlags::IS_COROUTINE, }; if attributes.returns_mutable { flags |= FunTypeFlags::RETURNS_MUTABLE; } if attributes.returns_void_to_rx { flags |= FunTypeFlags::RETURNS_VOID_TO_RX; } match attributes.param_mutability { Some(ParamMutability::ParamBorrowedMutable) => { flags |= FunTypeFlags::MUTABLE_FLAGS_BORROWED; } Some(ParamMutability::ParamOwnedMutable) => { flags |= FunTypeFlags::MUTABLE_FLAGS_OWNED; } Some(ParamMutability::ParamMaybeMutable) => { flags |= FunTypeFlags::MUTABLE_FLAGS_MAYBE; } None => (), }; // Pop the type params stack only after creating all inner types. let tparams = self.pop_type_params(header.type_params); let ft = self.alloc(FunType { arity, tparams, where_constraints: &[], params, ret: PossiblyEnforcedTy { enforced: false, type_, }, reactive: attributes.reactivity, flags, }); let ty = Ty(self.alloc(Reason::witness(id.0)), self.alloc(Ty_::Tfun(ft))); Some((id, ty, properties)) } fn prefix_ns(&self, name: &'a str) -> &'a str { if name.starts_with("\\") { name } else { let current = self.state.namespace_builder.current_namespace(); let mut fully_qualified = String::with_capacity_in(current.len() + name.len(), self.state.arena); fully_qualified.push_str(current); fully_qualified.push_str(&name); fully_qualified.into_bump_str() } } fn as_fun_params( &self, list: Node<'a>, ) -> Option<(FunParams<'a>, &'a [ShallowProp<'a>], FunArity<'a>)> { match list { Node::List(nodes) => { let mut params = Vec::with_capacity_in(nodes.len(), self.state.arena); let mut properties = Vec::new_in(self.state.arena); let mut arity = FunArity::Fstandard; for node in nodes.iter() { match node { Node::FunParam(&FunParamDecl { attributes, visibility, kind, hint, id, variadic, initializer, }) => { let attributes = attributes.as_attributes(self.state.arena)?; if let Some(visibility) = visibility.as_visibility() { let Id(pos, name) = id; let name = strip_dollar_prefix(name); properties.push(ShallowProp { const_: false, xhp_attr: None, lateinit: false, lsb: false, name: Id(pos, name), needs_init: true, type_: self.node_to_ty(hint), abstract_: false, visibility, fixme_codes: ISet::empty(), }); } let type_ = if hint.is_ignored() { tany() } else { self.node_to_ty(hint).map(|ty| match ty { Ty(r, &Ty_::Tfun(ref fun_type)) if attributes.at_most_rx_as_func => { let mut fun_type = (*fun_type).clone(); fun_type.reactive = Reactivity::RxVar(None); Ty(r, self.alloc(Ty_::Tfun(self.alloc(fun_type)))) } Ty(r, &Ty_::Toption(Ty(r1, &Ty_::Tfun(ref fun_type)))) if attributes.at_most_rx_as_func => { let mut fun_type = (*fun_type).clone(); fun_type.reactive = Reactivity::RxVar(None); Ty( r, self.alloc(Ty_::Toption(Ty( r1, self.alloc(Ty_::Tfun(self.alloc(fun_type))), ))), ) } ty => ty, })? }; let mut flags = match attributes.param_mutability { Some(ParamMutability::ParamBorrowedMutable) => { FunParamFlags::MUTABLE_FLAGS_BORROWED } Some(ParamMutability::ParamOwnedMutable) => { FunParamFlags::MUTABLE_FLAGS_OWNED } Some(ParamMutability::ParamMaybeMutable) => { FunParamFlags::MUTABLE_FLAGS_MAYBE } None => FunParamFlags::empty(), }; match kind { ParamMode::FPinout => { flags |= FunParamFlags::INOUT; } ParamMode::FPnormal => {} }; if initializer.is_present() { flags |= FunParamFlags::HAS_DEFAULT; } let param = self.alloc(FunParam { pos: id.0, name: Some(id.1), type_: PossiblyEnforcedTy { enforced: false, type_, }, flags, rx_annotation: None, }); arity = match arity { FunArity::Fstandard if initializer.is_ignored() && variadic => { FunArity::Fvariadic(param) } arity => { params.push(param); arity } }; } n => panic!("Expected a function parameter, but got {:?}", n), } } Some(( params.into_bump_slice(), properties.into_bump_slice(), arity, )) } n if n.is_ignored() => Some((&[], &[], FunArity::Fstandard)), n => panic!("Expected a list of function parameters, but got {:?}", n), } } fn make_shape_field_name(name: Node<'a>) -> Option<ShapeFieldName<'a>> { Some(match name { Node::StringLiteral(&(s, pos)) => ShapeFieldName::SFlitStr((pos, s)), // TODO: OCaml decl produces SFlitStr here instead of SFlitInt, so // we must also. Looks like int literal keys have become a parse // error--perhaps that's why. Node::IntLiteral(&(s, pos)) => ShapeFieldName::SFlitStr((pos, s)), Node::Expr(aast::Expr( _, aast::Expr_::ClassConst(&( aast::ClassId(_, aast::ClassId_::CI(class_name)), const_name, )), )) => ShapeFieldName::SFclassConst(class_name, const_name), Node::Expr(aast::Expr( _, aast::Expr_::ClassConst(&(aast::ClassId(pos, aast::ClassId_::CIself), const_name)), )) => ShapeFieldName::SFclassConst(Id(pos, "self"), const_name), _ => return None, }) } fn make_apply( &self, base_ty: Id<'a>, type_arguments: Node<'a>, pos_to_merge: Option<&'a Pos<'a>>, ) -> Node<'a> { let type_arguments = unwrap_or_return!(self .maybe_slice_from_iter(type_arguments.iter().map(|&node| self.node_to_ty(node)))); let ty_ = Ty_::Tapply(self.alloc((base_ty, type_arguments))); let pos = match pos_to_merge { Some(p) => unwrap_or_return!(Pos::merge(self.state.arena, base_ty.0, p).ok()), None => base_ty.0, }; self.hint_ty(pos, ty_) } fn hint_ty(&self, pos: &'a Pos<'a>, ty_: Ty_<'a>) -> Node<'a> { Node::Ty(self.alloc(Ty(self.alloc(Reason::hint(pos)), self.alloc(ty_)))) } fn prim_ty(&self, tprim: aast::Tprim<'a>, pos: &'a Pos<'a>) -> Node<'a> { self.hint_ty(pos, Ty_::Tprim(self.alloc(tprim))) } fn tany_with_pos(&self, pos: &'a Pos<'a>) -> Ty<'a> { Ty(self.alloc(Reason::witness(pos)), &TANY_) } fn source_text_at_pos(&self, pos: &'a Pos<'a>) -> &'a [u8] { let start = pos.start_cnum(); let end = pos.end_cnum(); self.state.source_text.source_text().sub(start, end - start) } // While we usually can tell whether to allocate a Tapply or Tgeneric based // on our type_parameters stack, *constraints* on type parameters may // reference type parameters which we have not parsed yet. When constructing // a type parameter list, we use this function to rewrite the type of each // constraint, considering the full list of type parameters to be in scope. fn convert_tapply_to_tgeneric(&self, ty: Ty<'a>) -> Ty<'a> { let ty_ = match *ty.1 { Ty_::Tapply(&(id, [])) => { // If the name contained a namespace delimiter in the original // source text, then it can't have referred to a type parameter // (since type parameters cannot be namespaced). match ty.0.pos() { Some(pos) => { if self.source_text_at_pos(pos).contains(&b'\\') { return ty; } } None => return ty, } // However, the direct decl parser will unconditionally prefix // the name with the current namespace (as it does for any // Tapply). We need to remove it. match id.1.rsplit('\\').next() { Some(name) if self.is_type_param_in_scope(name) => Ty_::Tgeneric(name), _ => return ty, } } Ty_::Tapply(&(id, targs)) => { let converted_targs = self.slice_from_iter( targs .iter() .map(|&targ| self.convert_tapply_to_tgeneric(targ)), ); Ty_::Tapply(self.alloc((id, converted_targs))) } Ty_::Tarray(&(tk, tv)) => Ty_::Tarray(self.alloc(( tk.map(|tk| self.convert_tapply_to_tgeneric(tk)), tv.map(|tv| self.convert_tapply_to_tgeneric(tv)), ))), Ty_::Tlike(ty) => Ty_::Tlike(self.convert_tapply_to_tgeneric(ty)), Ty_::TpuAccess(&(ty, id)) => { Ty_::TpuAccess(self.alloc((self.convert_tapply_to_tgeneric(ty), id))) } Ty_::Toption(ty) => Ty_::Toption(self.convert_tapply_to_tgeneric(ty)), Ty_::Tfun(fun_type) => { let convert_param = |param: &'a FunParam<'a>| { self.alloc(FunParam { type_: PossiblyEnforcedTy { enforced: param.type_.enforced, type_: self.convert_tapply_to_tgeneric(param.type_.type_), }, rx_annotation: param.rx_annotation.clone(), ..*param }) }; let arity = match fun_type.arity { FunArity::Fstandard => FunArity::Fstandard, FunArity::Fvariadic(param) => FunArity::Fvariadic(convert_param(param)), }; let params = self.slice_from_iter(fun_type.params.iter().cloned().map(convert_param)); let ret = PossiblyEnforcedTy { enforced: fun_type.ret.enforced, type_: self.convert_tapply_to_tgeneric(fun_type.ret.type_), }; Ty_::Tfun(self.alloc(FunType { arity, params, ret, reactive: fun_type.reactive.clone(), ..*fun_type })) } Ty_::Tshape(&(kind, fields)) => { let mut converted_fields = AssocListMut::with_capacity_in(fields.len(), self.state.arena); for (name, ty) in fields.iter() { converted_fields.insert( name.clone(), ShapeFieldType { optional: ty.optional, ty: self.convert_tapply_to_tgeneric(ty.ty), }, ); } Ty_::Tshape(self.alloc((kind, converted_fields.into()))) } Ty_::Tdarray(&(tk, tv)) => Ty_::Tdarray(self.alloc(( self.convert_tapply_to_tgeneric(tk), self.convert_tapply_to_tgeneric(tv), ))), Ty_::Tvarray(ty) => Ty_::Tvarray(self.convert_tapply_to_tgeneric(ty)), Ty_::TvarrayOrDarray(&(tk, tv)) => Ty_::TvarrayOrDarray(self.alloc(( self.convert_tapply_to_tgeneric(tk), self.convert_tapply_to_tgeneric(tv), ))), _ => return ty, }; Ty(ty.0, self.alloc(ty_)) } } enum NodeIterHelper<'a: 'b, 'b> { Empty, Single(&'b Node<'a>), Vec(std::slice::Iter<'b, Node<'a>>), } impl<'a, 'b> Iterator for NodeIterHelper<'a, 'b> { type Item = &'b Node<'a>; fn next(&mut self) -> Option<Self::Item> { match self { NodeIterHelper::Empty => None, NodeIterHelper::Single(node) => { let node = *node; *self = NodeIterHelper::Empty; Some(node) } NodeIterHelper::Vec(ref mut iter) => iter.next(), } } // Must return the upper bound returned by Node::len. fn size_hint(&self) -> (usize, Option<usize>) { match self { NodeIterHelper::Empty => (0, Some(0)), NodeIterHelper::Single(_) => (1, Some(1)), NodeIterHelper::Vec(iter) => iter.size_hint(), } } } impl<'a> FlattenOp for DirectDeclSmartConstructors<'a> { type S = Node<'a>; fn flatten(&self, lst: std::vec::Vec<Self::S>) -> Self::S { let size = lst .iter() .map(|s| match s { Node::List(children) => children.len(), x => { if Self::is_zero(x) { 0 } else { 1 } } }) .sum(); let mut r = Vec::with_capacity_in(size, self.state.arena); for s in lst.into_iter() { match s { Node::List(children) => r.extend(children.iter().cloned()), x => { if !Self::is_zero(&x) { r.push(x) } } } } match r.into_bump_slice() { [] => Node::Ignored, [node] => *node, slice => Node::List(self.alloc(slice)), } } fn zero() -> Self::S { Node::Ignored } fn is_zero(s: &Self::S) -> bool { match s { Node::Token(TokenKind::Yield) => false, Node::List(inner) => inner.iter().all(Self::is_zero), _ => true, } } } impl<'a> FlattenSmartConstructors<'a, State<'a>> for DirectDeclSmartConstructors<'a> { fn make_token(&mut self, token: Self::Token) -> Self::R { let token_text = |this: &Self| this.str_from_utf8(this.token_bytes(&token)); let token_pos = |this: &Self| { let start = this .state .source_text .offset_to_file_pos_triple(token.start_offset()); let end = this .state .source_text .offset_to_file_pos_triple(token.end_offset() + 1); Pos::from_lnum_bol_cnum(this.state.arena, this.state.filename, start, end) }; let kind = token.kind(); // We only want to check the mode if <? is the very first token we see. match (&self.state.file_mode_builder, &kind) { (FileModeBuilder::None, TokenKind::Markup) => (), (FileModeBuilder::None, TokenKind::LessThanQuestion) => { self.state.file_mode_builder = FileModeBuilder::Pending } (FileModeBuilder::Pending, TokenKind::Name) if token_text(self) == "hh" => { self.set_mode(&token); } (FileModeBuilder::None, _) | (FileModeBuilder::Pending, _) => { self.state.file_mode_builder = FileModeBuilder::Set(if self.state.filename.has_extension("hhi") { Mode::Mdecl } else { Mode::Mstrict }); } (_, _) => (), } let result = match kind { TokenKind::Name => { let name = token_text(self); let pos = token_pos(self); if self.state.previous_token_kind == TokenKind::Class || self.state.previous_token_kind == TokenKind::Trait || self.state.previous_token_kind == TokenKind::Interface { self.state .classish_name_builder .lexed_name_after_classish_keyword( self.state.arena, name, pos, self.state.previous_token_kind, ); } Node::Name(self.alloc((name, pos))) } TokenKind::Class => Node::Name(self.alloc((token_text(self), token_pos(self)))), // There are a few types whose string representations we have to // grab anyway, so just go ahead and treat them as generic names. TokenKind::Variable | TokenKind::Vec | TokenKind::Dict | TokenKind::Keyset | TokenKind::Tuple | TokenKind::Classname | TokenKind::SelfToken => Node::Name(self.alloc((token_text(self), token_pos(self)))), TokenKind::XHPClassName => { Node::XhpName(self.alloc((token_text(self), token_pos(self)))) } TokenKind::SingleQuotedStringLiteral => Node::StringLiteral(self.alloc(( unwrap_or_return!(escaper::unescape_single_in( self.str_from_utf8(escaper::unquote_slice(self.token_bytes(&token))), self.state.arena, ) .ok()), token_pos(self), ))), TokenKind::DoubleQuotedStringLiteral => Node::StringLiteral(self.alloc(( unwrap_or_return!(escaper::unescape_double_in( self.str_from_utf8(escaper::unquote_slice(self.token_bytes(&token))), self.state.arena, ) .ok()), token_pos(self), ))), TokenKind::HeredocStringLiteral => Node::StringLiteral(self.alloc(( unwrap_or_return!(escaper::unescape_heredoc_in( self.str_from_utf8(escaper::unquote_slice(self.token_bytes(&token))), self.state.arena, ) .ok()), token_pos(self), ))), TokenKind::NowdocStringLiteral => Node::StringLiteral(self.alloc(( unwrap_or_return!(escaper::unescape_nowdoc_in( self.str_from_utf8(escaper::unquote_slice(self.token_bytes(&token))), self.state.arena, ) .ok()), token_pos(self), ))), TokenKind::DecimalLiteral | TokenKind::OctalLiteral | TokenKind::HexadecimalLiteral | TokenKind::BinaryLiteral => { Node::IntLiteral(self.alloc((token_text(self), token_pos(self)))) } TokenKind::FloatingLiteral => { Node::FloatingLiteral(self.alloc((token_text(self), token_pos(self)))) } TokenKind::NullLiteral => Node::Null(token_pos(self)), TokenKind::BooleanLiteral => { Node::BooleanLiteral(self.alloc((token_text(self), token_pos(self)))) } TokenKind::String => self.prim_ty(aast::Tprim::Tstring, token_pos(self)), TokenKind::Int => self.prim_ty(aast::Tprim::Tint, token_pos(self)), TokenKind::Float => self.prim_ty(aast::Tprim::Tfloat, token_pos(self)), // "double" and "boolean" are parse errors--they should be written // "float" and "bool". The decl-parser treats the incorrect names as // type names rather than primitives. TokenKind::Double | TokenKind::Boolean => self.hint_ty( token_pos(self), Ty_::Tapply(self.alloc((Id(token_pos(self), token_text(self)), &[][..]))), ), TokenKind::Num => self.prim_ty(aast::Tprim::Tnum, token_pos(self)), TokenKind::Bool => self.prim_ty(aast::Tprim::Tbool, token_pos(self)), TokenKind::Mixed => Node::Ty(self.alloc(Ty( self.alloc(Reason::hint(token_pos(self))), self.alloc(Ty_::Tmixed), ))), TokenKind::Void => self.prim_ty(aast::Tprim::Tvoid, token_pos(self)), TokenKind::Arraykey => self.prim_ty(aast::Tprim::Tarraykey, token_pos(self)), TokenKind::Noreturn => self.prim_ty(aast::Tprim::Tnoreturn, token_pos(self)), TokenKind::Resource => self.prim_ty(aast::Tprim::Tresource, token_pos(self)), TokenKind::Array => Node::Array(token_pos(self)), TokenKind::Darray => Node::Darray(token_pos(self)), TokenKind::Varray => Node::Varray(token_pos(self)), TokenKind::Backslash => Node::Backslash(token_pos(self)), TokenKind::Construct => Node::Construct(token_pos(self)), TokenKind::LeftParen | TokenKind::RightParen | TokenKind::RightBracket | TokenKind::Shape | TokenKind::Question => Node::Pos(token_pos(self)), TokenKind::This => Node::This(token_pos(self)), TokenKind::Tilde | TokenKind::Exclamation | TokenKind::Plus | TokenKind::Minus | TokenKind::PlusPlus | TokenKind::MinusMinus | TokenKind::At | TokenKind::Star | TokenKind::Slash | TokenKind::EqualEqual | TokenKind::EqualEqualEqual | TokenKind::StarStar | TokenKind::AmpersandAmpersand | TokenKind::BarBar | TokenKind::LessThan | TokenKind::LessThanEqual | TokenKind::GreaterThan | TokenKind::GreaterThanEqual | TokenKind::Dot | TokenKind::Ampersand | TokenKind::Bar | TokenKind::LessThanLessThan | TokenKind::GreaterThanGreaterThan | TokenKind::Percent | TokenKind::QuestionQuestion | TokenKind::Equal => Node::Operator(self.alloc((token_pos(self), kind))), TokenKind::Abstract | TokenKind::As | TokenKind::Super | TokenKind::Async | TokenKind::Coroutine | TokenKind::DotDotDot | TokenKind::Extends | TokenKind::Final | TokenKind::Implements | TokenKind::Inout | TokenKind::Interface | TokenKind::Newtype | TokenKind::Type | TokenKind::XHP | TokenKind::Yield | TokenKind::Semicolon | TokenKind::Private | TokenKind::Protected | TokenKind::Public | TokenKind::Reify | TokenKind::Static | TokenKind::Trait => Node::Token(kind), _ => Node::Ignored, }; self.state.previous_token_kind = kind; result } fn make_missing(&mut self, _: usize) -> Self::R { Node::IgnoredSyntaxKind(SyntaxKind::Missing) } fn make_list(&mut self, items: std::vec::Vec<Self::R>, _: usize) -> Self::R { if items .iter() .any(|node| matches!(node, Node::Token(TokenKind::Yield))) { Node::Token(TokenKind::Yield) } else { let size = items.iter().filter(|node| node.is_present()).count(); let items_iter = items.into_iter(); let mut items = Vec::with_capacity_in(size, self.state.arena); for node in items_iter { if node.is_present() { items.push(node); } } let items = items.into_bump_slice(); if items.is_empty() { Node::Ignored } else { Node::List(self.alloc(items)) } } } fn make_qualified_name(&mut self, arg0: Self::R) -> Self::R { let pos = unwrap_or_return!(arg0.get_pos(self.state.arena)); match arg0 { Node::List(nodes) => Node::QualifiedName(self.alloc((nodes, pos))), node if node.is_ignored() => Node::Ignored, node => Node::QualifiedName(self.alloc(( bumpalo::vec![in self.state.arena; node].into_bump_slice(), pos, ))), } } fn make_simple_type_specifier(&mut self, arg0: Self::R) -> Self::R { // Return this explicitly because flatten filters out zero nodes, and // we treat most non-error nodes as zeroes. arg0 } fn make_literal_expression(&mut self, arg0: Self::R) -> Self::R { arg0 } fn make_simple_initializer(&mut self, equals: Self::R, expr: Self::R) -> Self::R { // If the expr is Ignored, bubble up the assignment operator so that we // can tell that *some* initializer was here. Useful for class // properties, where we need to enforce that properties without default // values are initialized in the constructor. if expr.is_ignored() { equals } else { expr } } fn make_array_intrinsic_expression( &mut self, array: Self::R, _arg1: Self::R, fields: Self::R, right_paren: Self::R, ) -> Self::R { let fields = unwrap_or_return!(self.map_to_slice(fields, |node| match node { Node::ListItem(&(key, value)) => { let key = self.node_to_expr(key)?; let value = self.node_to_expr(value)?; Some(aast::Afield::AFkvalue(key, value)) } node => Some(aast::Afield::AFvalue(self.node_to_expr(node)?)), })); Node::Expr(self.alloc(aast::Expr( unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(array.get_pos(self.state.arena)), unwrap_or_return!(right_paren.get_pos(self.state.arena)), ) .ok()), nast::Expr_::Array(fields), ))) } fn make_darray_intrinsic_expression( &mut self, darray: Self::R, _arg1: Self::R, _arg2: Self::R, fields: Self::R, right_bracket: Self::R, ) -> Self::R { let fields = unwrap_or_return!(self.map_to_slice(fields, |node| match node { Node::ListItem(&(key, value)) => { let key = self.node_to_expr(key)?; let value = self.node_to_expr(value)?; Some((key, value)) } n => panic!("Expected a ListItem but was {:?}", n), })); Node::Expr(self.alloc(aast::Expr( unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(darray.get_pos(self.state.arena)), unwrap_or_return!(right_bracket.get_pos(self.state.arena)), ) .ok()), nast::Expr_::Darray(self.alloc((None, fields))), ))) } fn make_dictionary_intrinsic_expression( &mut self, dict: Self::R, _arg1: Self::R, _arg2: Self::R, fields: Self::R, right_bracket: Self::R, ) -> Self::R { let fields = unwrap_or_return!(self.map_to_slice(fields, |node| match node { Node::ListItem(&(key, value)) => { let key = self.node_to_expr(key)?; let value = self.node_to_expr(value)?; Some(aast::Field(key, value)) } n => panic!("Expected a ListItem but was {:?}", n), })); Node::Expr(self.alloc(aast::Expr( unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(dict.get_pos(self.state.arena)), unwrap_or_return!(right_bracket.get_pos(self.state.arena)), ) .ok()), nast::Expr_::KeyValCollection(self.alloc((aast_defs::KvcKind::Dict, None, fields))), ))) } fn make_keyset_intrinsic_expression( &mut self, keyset: Self::R, _arg1: Self::R, _arg2: Self::R, fields: Self::R, right_bracket: Self::R, ) -> Self::R { let fields = unwrap_or_return!(self.map_to_slice(fields, |node| self.node_to_expr(node))); Node::Expr(self.alloc(aast::Expr( unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(keyset.get_pos(self.state.arena)), unwrap_or_return!(right_bracket.get_pos(self.state.arena)), ) .ok()), nast::Expr_::ValCollection(self.alloc((aast_defs::VcKind::Keyset, None, fields))), ))) } fn make_varray_intrinsic_expression( &mut self, varray: Self::R, _arg1: Self::R, _arg2: Self::R, fields: Self::R, right_bracket: Self::R, ) -> Self::R { let fields = unwrap_or_return!(self.map_to_slice(fields, |node| self.node_to_expr(node))); Node::Expr(self.alloc(aast::Expr( unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(varray.get_pos(self.state.arena)), unwrap_or_return!(right_bracket.get_pos(self.state.arena)), ) .ok()), nast::Expr_::Varray(self.alloc((None, fields))), ))) } fn make_vector_intrinsic_expression( &mut self, vec: Self::R, _arg1: Self::R, _arg2: Self::R, fields: Self::R, right_bracket: Self::R, ) -> Self::R { let fields = unwrap_or_return!(self.map_to_slice(fields, |node| self.node_to_expr(node))); Node::Expr(self.alloc(aast::Expr( unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(vec.get_pos(self.state.arena)), unwrap_or_return!(right_bracket.get_pos(self.state.arena)), ) .ok()), nast::Expr_::ValCollection(self.alloc((aast_defs::VcKind::Vec, None, fields))), ))) } fn make_element_initializer( &mut self, key: Self::R, _arg1: Self::R, value: Self::R, ) -> Self::R { Node::ListItem(self.alloc((key, value))) } fn make_prefix_unary_expression(&mut self, op: Self::R, value: Self::R) -> Self::R { let pos = unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(op.get_pos(self.state.arena)), unwrap_or_return!(value.get_pos(self.state.arena)) ) .ok()); let op = match &op { Node::Operator(&(_, op)) => match op { TokenKind::Tilde => Uop::Utild, TokenKind::Exclamation => Uop::Unot, TokenKind::Plus => Uop::Uplus, TokenKind::Minus => Uop::Uminus, TokenKind::PlusPlus => Uop::Uincr, TokenKind::MinusMinus => Uop::Udecr, TokenKind::At => Uop::Usilence, _ => return Node::Ignored, }, _ => return Node::Ignored, }; Node::Expr(self.alloc(aast::Expr( pos, aast::Expr_::Unop(self.alloc((op, unwrap_or_return!(self.node_to_expr(value))))), ))) } fn make_postfix_unary_expression(&mut self, value: Self::R, op: Self::R) -> Self::R { let pos = unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(value.get_pos(self.state.arena)), unwrap_or_return!(op.get_pos(self.state.arena)) ) .ok()); let op = match &op { Node::Operator(&(_, op)) => match op { TokenKind::PlusPlus => Uop::Upincr, TokenKind::MinusMinus => Uop::Updecr, _ => return Node::Ignored, }, _ => return Node::Ignored, }; Node::Expr(self.alloc(aast::Expr( pos, aast::Expr_::Unop(self.alloc((op, unwrap_or_return!(self.node_to_expr(value))))), ))) } fn make_binary_expression(&mut self, lhs: Self::R, op: Self::R, rhs: Self::R) -> Self::R { let pos = unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(lhs.get_pos(self.state.arena)), unwrap_or_return!(op.get_pos(self.state.arena)) ) .ok()), unwrap_or_return!(rhs.get_pos(self.state.arena)), ) .ok()); let op = match &op { Node::Operator(&(_, op)) => match op { TokenKind::Plus => Bop::Plus, TokenKind::Minus => Bop::Minus, TokenKind::Star => Bop::Star, TokenKind::Slash => Bop::Slash, TokenKind::EqualEqual => Bop::Eqeq, TokenKind::EqualEqualEqual => Bop::Eqeqeq, TokenKind::StarStar => Bop::Starstar, TokenKind::AmpersandAmpersand => Bop::Ampamp, TokenKind::BarBar => Bop::Barbar, TokenKind::LessThan => Bop::Lt, TokenKind::LessThanEqual => Bop::Lte, TokenKind::LessThanLessThan => Bop::Ltlt, TokenKind::GreaterThan => Bop::Gt, TokenKind::GreaterThanEqual => Bop::Gte, TokenKind::GreaterThanGreaterThan => Bop::Gtgt, TokenKind::Dot => Bop::Dot, TokenKind::Ampersand => Bop::Amp, TokenKind::Bar => Bop::Bar, TokenKind::Percent => Bop::Percent, TokenKind::QuestionQuestion => Bop::QuestionQuestion, _ => return Node::Ignored, }, _ => return Node::Ignored, }; Node::Expr(self.alloc(aast::Expr( pos, aast::Expr_::Binop(self.alloc(( op, unwrap_or_return!(self.node_to_expr(lhs)), unwrap_or_return!(self.node_to_expr(rhs)), ))), ))) } fn make_parenthesized_expression( &mut self, lparen: Self::R, expr: Self::R, rparen: Self::R, ) -> Self::R { let pos = unwrap_or_return!(lparen.get_pos(self.state.arena)); let pos = unwrap_or_return!(Pos::merge( self.state.arena, pos, unwrap_or_return!(rparen.get_pos(self.state.arena)) ) .ok()); Node::Expr(self.alloc(aast::Expr( pos, unwrap_or_return!(self.node_to_expr(expr)).1, ))) } fn make_list_item(&mut self, item: Self::R, sep: Self::R) -> Self::R { match (item.is_ignored(), sep.is_ignored()) { (true, true) => Node::Ignored, (false, true) => item, (true, false) => sep, (false, false) => Node::ListItem(self.alloc((item, sep))), } } fn make_type_arguments( &mut self, less_than: Self::R, arguments: Self::R, greater_than: Self::R, ) -> Self::R { Node::BracketedList(self.alloc(( unwrap_or_return!(less_than.get_pos(self.state.arena)), arguments.as_slice(self.state.arena), unwrap_or_return!(greater_than.get_pos(self.state.arena)), ))) } fn make_generic_type_specifier( &mut self, class_type: Self::R, type_arguments: Self::R, ) -> Self::R { let unqualified_id = unwrap_or_return!(self.get_name("", class_type)); if unqualified_id.1.trim_start_matches("\\") == "varray_or_darray" { let pos = unwrap_or_return!(Pos::merge( self.state.arena, unqualified_id.0, unwrap_or_return!(type_arguments.get_pos(self.state.arena)), ) .ok()); let type_arguments = type_arguments.as_slice(self.state.arena); let ty_ = match type_arguments { [tk, tv] => Ty_::TvarrayOrDarray(self.alloc(( self.node_to_ty(*tk).unwrap_or_else(|| tany()), self.node_to_ty(*tv).unwrap_or_else(|| tany()), ))), [tv] => Ty_::TvarrayOrDarray(self.alloc(( tarraykey(self.state.arena), self.node_to_ty(*tv).unwrap_or_else(|| tany()), ))), _ => TANY_, }; self.hint_ty(pos, ty_) } else { let Id(pos, class_type) = unwrap_or_return!(self.get_name("", class_type)); let class_type = self.state.namespace_builder.rename_import(class_type); let class_type = if class_type.starts_with("\\") { class_type } else { self.concat(self.state.namespace_builder.current_namespace(), class_type) }; self.make_apply( Id(pos, class_type), type_arguments, type_arguments.get_pos(self.state.arena), ) } } fn make_alias_declaration( &mut self, _attributes: Self::R, keyword: Self::R, name: Self::R, generic_params: Self::R, constraint: Self::R, _equal: Self::R, aliased_type: Self::R, _semicolon: Self::R, ) -> Self::R { if name.is_ignored() { return Node::Ignored; } let Id(pos, name) = unwrap_or_return!( self.get_name(self.state.namespace_builder.current_namespace(), name) ); let ty = unwrap_or_return!(self.node_to_ty(aliased_type)); let constraint = match constraint { Node::TypeConstraint(kind_and_hint) => { let (_kind, hint) = *kind_and_hint; Some(unwrap_or_return!(self.node_to_ty(hint))) } _ => None, }; // Pop the type params stack only after creating all inner types. let tparams = self.pop_type_params(generic_params); let typedef = TypedefType { pos, vis: match keyword { Node::Token(TokenKind::Type) => aast::TypedefVisibility::Transparent, Node::Token(TokenKind::Newtype) => aast::TypedefVisibility::Opaque, _ => aast::TypedefVisibility::Transparent, }, tparams, constraint, type_: ty, // NB: We have no intention of populating this // field. Any errors historically emitted during // shallow decl should be migrated to a NAST // check. decl_errors: Some(Errors::empty()), }; Rc::make_mut(&mut self.state.decls) .typedefs .insert(name, typedef); Node::Ignored } fn make_type_constraint(&mut self, kind: Self::R, value: Self::R) -> Self::R { let kind = match kind { Node::Token(TokenKind::As) => ConstraintKind::ConstraintAs, Node::Token(TokenKind::Super) => ConstraintKind::ConstraintSuper, n => panic!("Expected either As or Super, but was {:?}", n), }; Node::TypeConstraint(self.alloc((kind, value))) } fn make_type_parameter( &mut self, _arg0: Self::R, reify: Self::R, variance: Self::R, name: Self::R, constraints: Self::R, ) -> Self::R { let constraints = unwrap_or_return!(self.filter_map_to_slice(constraints, |node| match node { Node::TypeConstraint(&constraint) => Some(constraint), n if n.is_ignored() => None, n => panic!("Expected a type constraint, but was {:?}", n), })); Node::TypeParameter(self.alloc(TypeParameterDecl { name, variance: match variance { Node::Operator(&(_, TokenKind::Minus)) => Variance::Contravariant, Node::Operator(&(_, TokenKind::Plus)) => Variance::Covariant, _ => Variance::Invariant, }, reified: match reify { Node::Token(TokenKind::Reify) => aast::ReifyKind::Reified, _ => aast::ReifyKind::Erased, }, constraints, })) } fn make_type_parameters(&mut self, _lt: Self::R, tparams: Self::R, _gt: Self::R) -> Self::R { let size = tparams.len(); let mut tparams_with_name = Vec::with_capacity_in(size, self.state.arena); let mut tparam_names = MultiSetMut::with_capacity_in(size, self.state.arena); for node in tparams.iter() { match node { &Node::TypeParameter(decl) => { let name = unwrap_or_return!(self.get_name("", decl.name)); tparam_names.insert(name.1); tparams_with_name.push((decl, name)); } n => panic!("Expected a type parameter, but got {:?}", n), } } Rc::make_mut(&mut self.state.type_parameters).push(tparam_names.into()); let mut tparams = Vec::with_capacity_in(tparams_with_name.len(), self.state.arena); for (decl, name) in tparams_with_name.into_iter() { let &TypeParameterDecl { name: _, variance, reified, constraints, } = decl; let constraints = unwrap_or_return!(self.maybe_slice_from_iter( constraints.iter().map(|constraint| { let &(kind, ty) = constraint; let ty = self.node_to_ty(ty)?; let ty = self.convert_tapply_to_tgeneric(ty); Some((kind, ty)) }) )); tparams.push(Tparam { variance, name, constraints, reified, user_attributes: &[], }); } Node::TypeParameters(self.alloc(tparams.into_bump_slice())) } fn make_parameter_declaration( &mut self, attributes: Self::R, visibility: Self::R, inout: Self::R, hint: Self::R, name: Self::R, initializer: Self::R, ) -> Self::R { let (variadic, id) = match name { Node::ListItem(innards) => { let id = unwrap_or_return!(self.get_name("", innards.1)); match innards.0 { Node::Token(TokenKind::DotDotDot) => (true, id), _ => (false, id), } } name => (false, unwrap_or_return!(self.get_name("", name))), }; let kind = match inout { Node::Token(TokenKind::Inout) => ParamMode::FPinout, _ => ParamMode::FPnormal, }; Node::FunParam(self.alloc(FunParamDecl { attributes, visibility, kind, hint, id, variadic, initializer, })) } fn make_function_declaration( &mut self, attributes: Self::R, header: Self::R, body: Self::R, ) -> Self::R { let parsed_attributes = unwrap_or_return!(attributes.as_attributes(self.state.arena)); match header { Node::FunctionHeader(header) => { let (Id(pos, name), type_, _) = unwrap_or_return!(self.function_into_ty( self.state.namespace_builder.current_namespace(), attributes, header, body, )); let deprecated = parsed_attributes.deprecated.map(|msg| { let mut s = String::new_in(self.state.arena); s.push_str("The function "); s.push_str(name.trim_start_matches("\\")); s.push_str(" is deprecated: "); s.push_str(msg); s.into_bump_str() }); let fun_elt = FunElt { deprecated, type_, // NB: We have no intention of populating this field. // Any errors historically emitted during shallow decl // should be migrated to a NAST check. decl_errors: Some(Errors::empty()), pos, }; Rc::make_mut(&mut self.state.decls) .funs .insert(name, fun_elt); Node::Ignored } _ => Node::Ignored, } } fn make_function_declaration_header( &mut self, modifiers: Self::R, _keyword: Self::R, name: Self::R, type_params: Self::R, _left_parens: Self::R, param_list: Self::R, _right_parens: Self::R, _colon: Self::R, ret_hint: Self::R, _where: Self::R, ) -> Self::R { if name.is_ignored() { return Node::Ignored; } Node::FunctionHeader(self.alloc(FunctionHeader { name, modifiers, type_params, param_list, ret_hint, })) } fn make_yield_expression(&mut self, _arg0: Self::R, _arg1: Self::R) -> Self::R { Node::Token(TokenKind::Yield) } fn make_yield_from_expression( &mut self, _arg0: Self::R, _arg1: Self::R, _arg2: Self::R, ) -> Self::R { Node::Token(TokenKind::Yield) } fn make_const_declaration( &mut self, modifiers: Self::R, _arg1: Self::R, hint: Self::R, decls: Self::R, _arg4: Self::R, ) -> Self::R { // None of the Node::Ignoreds should happen in a well-formed file, but // they could happen in a malformed one. We also bubble up the const // declaration instead of inserting it immediately because consts can // appear in classes or directly in namespaces. match decls { Node::List([Node::List([name, initializer])]) => { let id = unwrap_or_return!(self.get_name( if self .state .classish_name_builder .get_current_classish_name() .is_some() { "" } else { self.state.namespace_builder.current_namespace() }, *name, )); let ty = self .node_to_ty(hint) .or_else(|| self.node_to_ty(*initializer)) .unwrap_or_else(|| tany()); let modifiers = read_member_modifiers(modifiers.iter()); if self .state .classish_name_builder .get_current_classish_name() .is_some() { Node::Const(self.alloc(shallow_decl_defs::ShallowClassConst { abstract_: modifiers.is_abstract, expr: match *initializer { Node::Expr(e) => Some(e.clone()), n if n.is_ignored() => None, n => self.node_to_expr(n), }, name: id, type_: ty, })) } else { Rc::make_mut(&mut self.state.decls).consts.insert(id.1, ty); Node::Ignored } } _ => Node::Ignored, } } fn make_constant_declarator(&mut self, name: Self::R, initializer: Self::R) -> Self::R { if name.is_ignored() { Node::Ignored } else { Node::List( self.alloc(bumpalo::vec![in self.state.arena; name, initializer].into_bump_slice()), ) } } fn make_namespace_declaration_header(&mut self, _keyword: Self::R, name: Self::R) -> Self::R { let name = self.get_name("", name).map(|Id(_, name)| name); Rc::make_mut(&mut self.state.namespace_builder).push_namespace(name); Node::Ignored } fn make_namespace_body(&mut self, _arg0: Self::R, body: Self::R, _arg2: Self::R) -> Self::R { let is_empty = matches!(body, Node::Token(TokenKind::Semicolon)); if !is_empty { Rc::make_mut(&mut self.state.namespace_builder).pop_namespace(); } Node::Ignored } fn make_namespace_use_declaration( &mut self, _arg0: Self::R, _arg1: Self::R, imports: Self::R, _arg3: Self::R, ) -> Self::R { for import in imports.iter() { if let Node::NamespaceUseClause(nuc) = import { Rc::make_mut(&mut self.state.namespace_builder).add_import(nuc.id.1, nuc.as_); } } Node::Ignored } fn make_namespace_group_use_declaration( &mut self, _arg0: Self::R, _arg1: Self::R, prefix: Self::R, _arg3: Self::R, imports: Self::R, _arg5: Self::R, _arg6: Self::R, ) -> Self::R { let Id(_, prefix) = unwrap_or_return!(self.get_name("", prefix)); for import in imports.iter() { if let Node::NamespaceUseClause(nuc) = import { let mut id = String::new_in(self.state.arena); id.push_str(prefix); id.push_str(nuc.id.1); Rc::make_mut(&mut self.state.namespace_builder) .add_import(id.into_bump_str(), nuc.as_); } } Node::Ignored } fn make_namespace_use_clause( &mut self, _arg0: Self::R, name: Self::R, as_: Self::R, aliased_name: Self::R, ) -> Self::R { let id = unwrap_or_return!(self.get_name("", name)); let as_ = if let Node::Token(TokenKind::As) = as_ { Some(unwrap_or_return!(self.get_name("", aliased_name)).1) } else { None }; Node::NamespaceUseClause(self.alloc(NamespaceUseClause { id, as_ })) } fn make_classish_declaration( &mut self, attributes: Self::R, modifiers: Self::R, xhp_keyword: Self::R, class_keyword: Self::R, name: Self::R, tparams: Self::R, _arg5: Self::R, extends: Self::R, _arg7: Self::R, implements: Self::R, _arg9: Self::R, body: Self::R, ) -> Self::R { let Id(pos, name) = unwrap_or_return!( self.get_name(self.state.namespace_builder.current_namespace(), name) ); let mut class_kind = match class_keyword { Node::Token(TokenKind::Interface) => ClassKind::Cinterface, Node::Token(TokenKind::Trait) => ClassKind::Ctrait, _ => ClassKind::Cnormal, }; let mut final_ = false; for modifier in modifiers.iter() { match modifier { Node::Token(TokenKind::Abstract) => class_kind = ClassKind::Cabstract, Node::Token(TokenKind::Final) => final_ = true, _ => (), } } let attributes = attributes; let body = match body { Node::ClassishBody(body) => body, body => panic!("Expected a classish body, but was {:?}", body), }; let mut uses_len = 0; let mut req_extends_len = 0; let mut req_implements_len = 0; let mut consts_len = 0; let mut typeconsts_len = 0; let mut props_len = 0; let mut sprops_len = 0; let mut static_methods_len = 0; let mut methods_len = 0; let mut user_attributes_len = 0; for attribute in attributes.iter() { match attribute { &Node::Attribute(..) => user_attributes_len += 1, _ => (), } } for element in body.iter().copied() { match element { Node::TraitUse(names) => uses_len += names.len(), Node::TypeConstant(..) => typeconsts_len += 1, Node::RequireClause(require) => match require.require_type { Node::Token(TokenKind::Extends) => req_extends_len += 1, Node::Token(TokenKind::Implements) => req_implements_len += 1, _ => {} }, Node::Const(..) => consts_len += 1, Node::Property(&PropertyNode { decls, is_static }) => { if is_static { sprops_len += decls.len() } else { props_len += decls.len() } } Node::Constructor(&ConstructorNode { properties, .. }) => { props_len += properties.len() } Node::Method(&MethodNode { is_static, .. }) => { if is_static { static_methods_len += 1 } else { methods_len += 1 } } _ => (), } } let mut constructor = None; let mut uses = Vec::with_capacity_in(uses_len, self.state.arena); let mut req_extends = Vec::with_capacity_in(req_extends_len, self.state.arena); let mut req_implements = Vec::with_capacity_in(req_implements_len, self.state.arena); let mut consts = Vec::with_capacity_in(consts_len, self.state.arena); let mut typeconsts = Vec::with_capacity_in(typeconsts_len, self.state.arena); let mut props = Vec::with_capacity_in(props_len, self.state.arena); let mut sprops = Vec::with_capacity_in(sprops_len, self.state.arena); let mut static_methods = Vec::with_capacity_in(static_methods_len, self.state.arena); let mut methods = Vec::with_capacity_in(methods_len, self.state.arena); let mut user_attributes = Vec::with_capacity_in(user_attributes_len, self.state.arena); for attribute in attributes.iter() { match attribute { &Node::Attribute(&attr) => user_attributes.push(attr), _ => (), } } // Match ordering of attributes produced by the OCaml decl parser (even // though it's the reverse of the syntactic ordering). user_attributes.reverse(); for element in body.iter().copied() { match element { Node::TraitUse(names) => { for name in names.iter() { uses.push(unwrap_or_return!(self.node_to_ty(*name))); } } Node::TypeConstant(constant) => typeconsts.push(constant.clone()), Node::RequireClause(require) => match require.require_type { Node::Token(TokenKind::Extends) => { req_extends.push(unwrap_or_return!(self.node_to_ty(require.name))) } Node::Token(TokenKind::Implements) => { req_implements.push(unwrap_or_return!(self.node_to_ty(require.name))) } _ => {} }, Node::Const(const_decl) => consts.push(const_decl.clone()), Node::Property(&PropertyNode { decls, is_static }) => { for property in decls { if is_static { sprops.push(property.clone()) } else { props.push(property.clone()) } } } Node::Constructor(&ConstructorNode { method, properties }) => { constructor = Some(method.clone()); for property in properties { props.push(property.clone()) } } Node::Method(&MethodNode { method, is_static }) => { if is_static { static_methods.push(method.clone()); } else { methods.push(method.clone()); } } _ => (), // It's not our job to report errors here. } } let uses = uses.into_bump_slice(); let req_extends = req_extends.into_bump_slice(); let req_implements = req_implements.into_bump_slice(); let consts = consts.into_bump_slice(); let typeconsts = typeconsts.into_bump_slice(); let props = props.into_bump_slice(); let sprops = sprops.into_bump_slice(); let static_methods = static_methods.into_bump_slice(); let methods = methods.into_bump_slice(); let user_attributes = user_attributes.into_bump_slice(); let extends = unwrap_or_return!(self.filter_map_to_slice(extends, |node| { self.node_to_ty(node) })); let implements = unwrap_or_return!( self.filter_map_to_slice(implements, |node| { self.node_to_ty(node) }) ); // Pop the type params stack only after creating all inner types. let tparams = self.pop_type_params(tparams); let cls: shallow_decl_defs::ShallowClass<'a> = shallow_decl_defs::ShallowClass { mode: match self.state.file_mode_builder { FileModeBuilder::None | FileModeBuilder::Pending => Mode::Mstrict, FileModeBuilder::Set(mode) => mode, }, final_, is_xhp: false, has_xhp_keyword: match xhp_keyword { Node::Token(TokenKind::XHP) => true, _ => false, }, kind: class_kind, name: Id(pos, name), tparams, where_constraints: &[], extends, uses, method_redeclarations: &[], xhp_attr_uses: &[], req_extends, req_implements, implements, consts, typeconsts, pu_enums: &[], props, sprops, constructor, static_methods, methods, user_attributes, enum_type: None, // NB: We have no intention of populating this field. Any errors // historically emitted during shallow decl should be migrated to a // NAST check. decl_errors: Errors::empty(), }; Rc::make_mut(&mut self.state.decls) .classes .insert(name, cls); self.state .classish_name_builder .parsed_classish_declaration(); Node::Ignored } fn make_property_declaration( &mut self, attrs: Self::R, modifiers: Self::R, hint: Self::R, declarators: Self::R, _arg4: Self::R, ) -> Self::R { let (attrs, modifiers, hint) = (attrs, modifiers, hint); let modifiers = read_member_modifiers(modifiers.iter()); let declarators = unwrap_or_return!(self.maybe_slice_from_iter(declarators.iter().map( |declarator| match declarator { Node::ListItem(&(name, initializer)) => { let attributes = attrs.as_attributes(self.state.arena)?; let Id(pos, name) = self.get_name("", name)?; let name = if modifiers.is_static { name } else { strip_dollar_prefix(name) }; let ty = self.node_to_ty(hint)?; Some(ShallowProp { const_: attributes.const_, xhp_attr: None, lateinit: attributes.late_init, lsb: attributes.lsb, name: Id(pos, name), needs_init: initializer.is_ignored(), type_: Some(ty), abstract_: modifiers.is_abstract, visibility: modifiers.visibility, fixme_codes: ISet::empty(), }) } n => panic!("Expected a ListItem, but was {:?}", n), } ))); Node::Property(self.alloc(PropertyNode { decls: declarators, is_static: modifiers.is_static, })) } fn make_property_declarator(&mut self, name: Self::R, initializer: Self::R) -> Self::R { Node::ListItem(self.alloc((name, initializer))) } fn make_methodish_declaration( &mut self, attributes: Self::R, header: Self::R, body: Self::R, closer: Self::R, ) -> Self::R { let header = match header { Node::FunctionHeader(header) => header, n => panic!("Expected a FunctionDecl header, but was {:?}", n), }; // If we don't have a body, use the closing token. A closing token of // '}' indicates a regular function, while a closing token of ';' // indicates an abstract function. let body = if body.is_ignored() { closer } else { body }; let modifiers = read_member_modifiers(header.modifiers.iter()); let is_constructor = match header.name { Node::Construct(_) => true, _ => false, }; let (id, ty, properties) = unwrap_or_return!(self.function_into_ty("", attributes, header, body)); let attributes = unwrap_or_return!(attributes.as_attributes(self.state.arena)); let deprecated = attributes.deprecated.map(|msg| { let mut s = String::new_in(self.state.arena); s.push_str("The method "); s.push_str(id.1); s.push_str(" is deprecated: "); s.push_str(msg); s.into_bump_str() }); fn get_condition_type_name<'a>(ty_opt: Option<Ty<'a>>) -> Option<&'a str> { ty_opt.and_then(|ty| { let Ty(_, ty_) = ty; match *ty_ { Ty_::Tapply(&(Id(_, class_name), _)) => Some(class_name), _ => None, } }) } let method = self.alloc(ShallowMethod { abstract_: self.state.classish_name_builder.in_interface() || modifiers.is_abstract, final_: modifiers.is_final, memoizelsb: attributes.memoizelsb, name: id, override_: attributes.override_, reactivity: match attributes.reactivity { Reactivity::Local(condition_type) => Some(MethodReactivity::MethodLocal( get_condition_type_name(condition_type), )), Reactivity::Shallow(condition_type) => Some(MethodReactivity::MethodShallow( get_condition_type_name(condition_type), )), Reactivity::Reactive(condition_type) => Some(MethodReactivity::MethodReactive( get_condition_type_name(condition_type), )), Reactivity::Nonreactive | Reactivity::MaybeReactive(_) | Reactivity::RxVar(_) | Reactivity::Pure(_) => None, }, dynamicallycallable: false, type_: ty, visibility: modifiers.visibility, fixme_codes: ISet::empty(), deprecated, }); if is_constructor { Node::Constructor(self.alloc(ConstructorNode { method, properties })) } else { Node::Method(self.alloc(MethodNode { method, is_static: modifiers.is_static, })) } } fn make_classish_body(&mut self, _arg0: Self::R, body: Self::R, _arg2: Self::R) -> Self::R { Node::ClassishBody(self.alloc(body.as_slice(self.state.arena))) } fn make_enum_declaration( &mut self, attributes: Self::R, _arg1: Self::R, name: Self::R, _arg3: Self::R, extends: Self::R, constraint: Self::R, _arg6: Self::R, cases: Self::R, _arg8: Self::R, ) -> Self::R { let id = unwrap_or_return!( self.get_name(self.state.namespace_builder.current_namespace(), name) ); let hint = unwrap_or_return!(self.node_to_ty(extends)); let extends = unwrap_or_return!(self.node_to_ty(self.make_apply( Id( unwrap_or_return!(name.get_pos(self.state.arena)), "\\HH\\BuiltinEnum" ), name, None, ))); let key = id.1; let consts = unwrap_or_return!(self.maybe_slice_from_iter(cases.iter().map( |node| match node { Node::ListItem(&(name, value)) => Some(shallow_decl_defs::ShallowClassConst { abstract_: false, expr: Some(self.node_to_expr(value)?), name: self.get_name("", name)?, type_: Ty( self.alloc(Reason::witness(value.get_pos(self.state.arena)?)), hint.1, ), }), n => panic!("Expected an enum case, got {:?}", n), } ))); let attributes = attributes; let mut user_attributes = Vec::with_capacity_in(attributes.len(), self.state.arena); for attribute in attributes.iter() { match attribute { &Node::Attribute(&attr) => user_attributes.push(attr), _ => (), } } // Match ordering of attributes produced by the OCaml decl parser (even // though it's the reverse of the syntactic ordering). user_attributes.reverse(); let user_attributes = user_attributes.into_bump_slice(); let constraint = match constraint { Node::TypeConstraint(&(_kind, ty)) => self.node_to_ty(ty), _ => None, }; let cls = shallow_decl_defs::ShallowClass { mode: match self.state.file_mode_builder { FileModeBuilder::None | FileModeBuilder::Pending => Mode::Mstrict, FileModeBuilder::Set(mode) => mode, }, final_: false, is_xhp: false, has_xhp_keyword: false, kind: ClassKind::Cenum, name: id, tparams: &[], where_constraints: &[], extends: bumpalo::vec![in self.state.arena; extends].into_bump_slice(), uses: &[], method_redeclarations: &[], xhp_attr_uses: &[], req_extends: &[], req_implements: &[], implements: &[], consts, typeconsts: &[], pu_enums: &[], props: &[], sprops: &[], constructor: None, static_methods: &[], methods: &[], user_attributes, enum_type: Some(EnumType { base: hint, constraint, }), // NB: We have no intention of populating this field. Any errors // historically emitted during shallow decl should be migrated to a // NAST check. decl_errors: Errors::empty(), }; Rc::make_mut(&mut self.state.decls).classes.insert(key, cls); Node::Ignored } fn make_enumerator( &mut self, name: Self::R, _arg1: Self::R, value: Self::R, _arg3: Self::R, ) -> Self::R { Node::ListItem(self.alloc((name, value))) } fn make_tuple_type_specifier( &mut self, left_paren: Self::R, tys: Self::R, right_paren: Self::R, ) -> Self::R { // We don't need to include the tys list in this position merging // because by definition it's already contained by the two brackets. let pos = unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(left_paren.get_pos(self.state.arena)), unwrap_or_return!(right_paren.get_pos(self.state.arena)), ) .ok()); let tys = unwrap_or_return!( self.maybe_slice_from_iter(tys.iter().map(|&node| self.node_to_ty(node))) ); self.hint_ty(pos, Ty_::Ttuple(tys)) } fn make_shape_type_specifier( &mut self, shape: Self::R, _arg1: Self::R, fields: Self::R, open: Self::R, rparen: Self::R, ) -> Self::R { let fields = fields; let fields_iter = fields.iter(); let mut fields = AssocListMut::new_in(self.state.arena); for node in fields_iter { match node { &Node::ShapeFieldSpecifier(&ShapeFieldNode { name, type_ }) => { fields.insert(name.clone(), type_.clone()) } n => panic!("Expected a shape field specifier, but was {:?}", n), } } let kind = match open { Node::Token(TokenKind::DotDotDot) => ShapeKind::OpenShape, _ => ShapeKind::ClosedShape, }; let pos = unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(shape.get_pos(self.state.arena)), unwrap_or_return!(rparen.get_pos(self.state.arena)), ) .ok()); self.hint_ty(pos, Ty_::Tshape(self.alloc((kind, fields.into())))) } fn make_shape_expression( &mut self, shape: Self::R, _left_paren: Self::R, fields: Self::R, right_paren: Self::R, ) -> Self::R { let fields = unwrap_or_return!( self.maybe_slice_from_iter(fields.iter().map(|node| match node { Node::ListItem(&(key, value)) => { let key = Self::make_shape_field_name(key)?; let value = self.node_to_expr(value)?; Some((key, value)) } n => panic!("Expected a ListItem but was {:?}", n), })) ); Node::Expr(self.alloc(aast::Expr( unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(shape.get_pos(self.state.arena)), unwrap_or_return!(right_paren.get_pos(self.state.arena)), ) .ok()), nast::Expr_::Shape(fields), ))) } fn make_tuple_expression( &mut self, tuple: Self::R, _left_paren: Self::R, fields: Self::R, right_paren: Self::R, ) -> Self::R { let fields = unwrap_or_return!( self.maybe_slice_from_iter(fields.iter().map(|&field| self.node_to_expr(field))) ); Node::Expr(self.alloc(aast::Expr( unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(tuple.get_pos(self.state.arena)), unwrap_or_return!(right_paren.get_pos(self.state.arena)), ) .ok()), nast::Expr_::List(fields), ))) } fn make_classname_type_specifier( &mut self, classname: Self::R, _lt: Self::R, targ: Self::R, _arg3: Self::R, gt: Self::R, ) -> Self::R { let id = unwrap_or_return!(self.get_name("", classname)); if gt.is_ignored() { self.prim_ty(aast::Tprim::Tstring, id.0) } else { self.make_apply( Id(id.0, self.state.namespace_builder.rename_import(id.1)), targ, Some(unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(classname.get_pos(self.state.arena)), unwrap_or_return!(gt.get_pos(self.state.arena)), ) .ok())), ) } } fn make_scope_resolution_expression( &mut self, class_name: Self::R, _arg1: Self::R, value: Self::R, ) -> Self::R { let pos = unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(class_name.get_pos(self.state.arena)), unwrap_or_return!(value.get_pos(self.state.arena)), ) .ok()); let Id(class_name_pos, class_name_str) = unwrap_or_return!( self.get_name(self.state.namespace_builder.current_namespace(), class_name) ); let class_id = aast::ClassId( class_name_pos, match class_name_str.to_ascii_lowercase().as_ref() { "\\self" => aast::ClassId_::CIself, _ => aast::ClassId_::CI(Id(class_name_pos, class_name_str)), }, ); let value_id = unwrap_or_return!(self.get_name("", value)); Node::Expr(self.alloc(aast::Expr( pos, nast::Expr_::ClassConst(self.alloc((class_id, (value_id.0, value_id.1)))), ))) } fn make_field_specifier( &mut self, question_token: Self::R, name: Self::R, _arg2: Self::R, type_: Self::R, ) -> Self::R { let optional = question_token.is_present(); let name = unwrap_or_return!(Self::make_shape_field_name(name)); Node::ShapeFieldSpecifier(self.alloc(ShapeFieldNode { name: self.alloc(ShapeField(name)), type_: self.alloc(ShapeFieldType { optional, ty: unwrap_or_return!(self.node_to_ty(type_)), }), })) } fn make_field_initializer(&mut self, key: Self::R, _arg1: Self::R, value: Self::R) -> Self::R { Node::ListItem(self.alloc((key, value))) } fn make_varray_type_specifier( &mut self, varray: Self::R, _less_than: Self::R, tparam: Self::R, _arg3: Self::R, greater_than: Self::R, ) -> Self::R { let pos = unwrap_or_return!(varray.get_pos(self.state.arena)); let pos = if let Some(gt_pos) = greater_than.get_pos(self.state.arena) { unwrap_or_return!(Pos::merge(self.state.arena, pos, gt_pos).ok()) } else { pos }; self.hint_ty( pos, Ty_::Tvarray(unwrap_or_return!(self.node_to_ty(tparam))), ) } fn make_vector_array_type_specifier( &mut self, array: Self::R, _less_than: Self::R, tparam: Self::R, greater_than: Self::R, ) -> Self::R { let pos = unwrap_or_return!(array.get_pos(self.state.arena)); let pos = if let Some(gt_pos) = greater_than.get_pos(self.state.arena) { unwrap_or_return!(Pos::merge(self.state.arena, pos, gt_pos).ok()) } else { pos }; let key_type = self.node_to_ty(tparam); self.hint_ty(pos, Ty_::Tarray(self.alloc((key_type, None)))) } fn make_darray_type_specifier( &mut self, darray: Self::R, _less_than: Self::R, key_type: Self::R, _comma: Self::R, value_type: Self::R, _arg5: Self::R, greater_than: Self::R, ) -> Self::R { let pos = unwrap_or_return!(darray.get_pos(self.state.arena)); let pos = if let Some(gt_pos) = greater_than.get_pos(self.state.arena) { unwrap_or_return!(Pos::merge(self.state.arena, pos, gt_pos).ok()) } else { pos }; let key_type = self.node_to_ty(key_type).unwrap_or(TANY); let value_type = self.node_to_ty(value_type).unwrap_or(TANY); self.hint_ty(pos, Ty_::Tdarray(self.alloc((key_type, value_type)))) } fn make_map_array_type_specifier( &mut self, array: Self::R, _less_than: Self::R, key_type: Self::R, _comma: Self::R, value_type: Self::R, greater_than: Self::R, ) -> Self::R { let pos = unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(array.get_pos(self.state.arena)), unwrap_or_return!(greater_than.get_pos(self.state.arena)), ) .ok()); let key_type = self.node_to_ty(key_type); let value_type = self.node_to_ty(value_type); self.hint_ty(pos, Ty_::Tarray(self.alloc((key_type, value_type)))) } fn make_old_attribute_specification( &mut self, ltlt: Self::R, attrs: Self::R, gtgt: Self::R, ) -> Self::R { match attrs { Node::List(nodes) => Node::BracketedList(self.alloc(( unwrap_or_return!(ltlt.get_pos(self.state.arena)), nodes, unwrap_or_return!(gtgt.get_pos(self.state.arena)), ))), node => panic!( "Expected List in old_attribute_specification, but got {:?}", node ), } } fn make_constructor_call( &mut self, name: Self::R, _arg1: Self::R, args: Self::R, _arg3: Self::R, ) -> Self::R { let unqualified_name = unwrap_or_return!(self.get_name("", name)); let name = if unqualified_name.1.starts_with("__") { unqualified_name } else { unwrap_or_return!(self.get_name(self.state.namespace_builder.current_namespace(), name)) }; Node::Attribute(self.alloc(nast::UserAttribute { name, params: unwrap_or_return!(self.map_to_slice(args, |node| self.node_to_expr(node))), })) } fn make_trait_use(&mut self, _arg0: Self::R, used: Self::R, _arg2: Self::R) -> Self::R { Node::TraitUse(self.alloc(used)) } fn make_require_clause( &mut self, _arg0: Self::R, require_type: Self::R, name: Self::R, _arg3: Self::R, ) -> Self::R { Node::RequireClause(self.alloc(RequireClause { require_type, name })) } fn make_nullable_type_specifier(&mut self, question_mark: Self::R, hint: Self::R) -> Self::R { let hint_pos = unwrap_or_return!(hint.get_pos(self.state.arena)); self.hint_ty( unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(question_mark.get_pos(self.state.arena)), hint_pos, ) .ok()), Ty_::Toption(unwrap_or_return!(self.node_to_ty(hint))), ) } fn make_like_type_specifier(&mut self, tilde: Self::R, type_: Self::R) -> Self::R { let pos = unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(tilde.get_pos(self.state.arena)), unwrap_or_return!(type_.get_pos(self.state.arena)), ) .ok()); self.hint_ty(pos, Ty_::Tlike(unwrap_or_return!(self.node_to_ty(type_)))) } fn make_closure_type_specifier( &mut self, left_paren: Self::R, _arg1: Self::R, _arg2: Self::R, _arg3: Self::R, args: Self::R, _arg5: Self::R, _arg6: Self::R, ret_hint: Self::R, right_paren: Self::R, ) -> Self::R { let params = unwrap_or_return!(self.maybe_slice_from_iter(args.iter().map(|&node| { Some(self.alloc(FunParam { pos: node.get_pos(self.state.arena)?, name: None, type_: PossiblyEnforcedTy { enforced: false, type_: self.node_to_ty(node)?, }, flags: FunParamFlags::empty(), rx_annotation: None, })) }))); let ret = unwrap_or_return!(self.node_to_ty(ret_hint)); let pos = unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(left_paren.get_pos(self.state.arena)), unwrap_or_return!(right_paren.get_pos(self.state.arena)), ) .ok()); self.hint_ty( pos, Ty_::Tfun(self.alloc(FunType { arity: FunArity::Fstandard, tparams: &[], where_constraints: &[], params, ret: PossiblyEnforcedTy { enforced: false, type_: ret, }, reactive: Reactivity::Nonreactive, flags: FunTypeFlags::empty(), })), ) } fn make_closure_parameter_type_specifier(&mut self, _arg0: Self::R, name: Self::R) -> Self::R { name } fn make_type_const_declaration( &mut self, attributes: Self::R, modifiers: Self::R, _arg2: Self::R, _arg3: Self::R, name: Self::R, _arg5: Self::R, constraint: Self::R, _arg7: Self::R, type_: Self::R, _semicolon: Self::R, ) -> Self::R { let attributes = unwrap_or_return!(attributes.as_attributes(self.state.arena)); let has_abstract_keyword = modifiers.iter().fold(false, |abstract_, node| match node { Node::Token(TokenKind::Abstract) => true, _ => abstract_, }); let constraint = match constraint { Node::TypeConstraint(innards) => self.node_to_ty(innards.1), _ => None, }; let type_ = self.node_to_ty(type_); let has_constraint = constraint.is_some(); let has_type = type_.is_some(); let (type_, abstract_) = match (has_abstract_keyword, has_constraint, has_type) { // Has no assigned type. Technically illegal, so if the constraint // is present, proceed as if the constraint was the assigned type. // const type TFoo; // const type TFoo as OtherType; (false, _, false) => (constraint, TypeconstAbstractKind::TCConcrete), // Has no constraint, but does have an assigned type. // const type TFoo = SomeType; (false, false, true) => (type_, TypeconstAbstractKind::TCConcrete), // Has both a constraint and an assigned type. // const type TFoo as OtherType = SomeType; (false, true, true) => (type_, TypeconstAbstractKind::TCPartiallyAbstract), // Has no default type. // abstract const type TFoo; // abstract const type TFoo as OtherType; (true, _, false) => (type_, TypeconstAbstractKind::TCAbstract(None)), // Has a default type. // abstract const Type TFoo = SomeType; // abstract const Type TFoo as OtherType = SomeType; (true, _, true) => (None, TypeconstAbstractKind::TCAbstract(type_)), }; let name = unwrap_or_return!(self.get_name("", name)); Node::TypeConstant(self.alloc(ShallowTypeconst { abstract_, constraint, name, type_, enforceable: match attributes.enforceable { Some(pos) => (pos, true), None => (Pos::none(), false), }, reifiable: attributes.reifiable, })) } fn make_decorated_expression(&mut self, decorator: Self::R, expr: Self::R) -> Self::R { Node::ListItem(self.alloc((decorator, expr))) } fn make_type_constant( &mut self, ty: Self::R, _coloncolon: Self::R, constant_name: Self::R, ) -> Self::R { let id = unwrap_or_return!(self.get_name("", constant_name)); let pos = unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(ty.get_pos(self.state.arena)), unwrap_or_return!(constant_name.get_pos(self.state.arena)), ) .ok()); match ty { Node::TypeconstAccess(innards) => { innards.0.set(pos); // Nested typeconst accesses have to be collapsed. innards.2.borrow_mut().push(id); Node::TypeconstAccess(innards) } ty => { let ty = match ty { Node::Name(("self", self_pos)) => { match self.state.classish_name_builder.get_current_classish_name() { Some((name, class_name_pos)) => { // In classes, we modify the position when // rewriting the `self` keyword to point to the // class name. In traits, we don't (because // traits are not types). We indicate that the // position shouldn't be rewritten with the none // Pos. let id_pos = if class_name_pos.is_none() { self_pos } else { class_name_pos }; let reason = self.alloc(Reason::hint(self_pos)); let ty_ = Ty_::Tapply(self.alloc((Id(id_pos, name), &[][..]))); Ty(reason, self.alloc(ty_)) } None => unwrap_or_return!(self.node_to_ty(ty.clone())), } } _ => unwrap_or_return!(self.node_to_ty(ty.clone())), }; Node::TypeconstAccess(self.alloc(( Cell::new(pos), ty, RefCell::new(bumpalo::vec![in self.state.arena; id]), ))) } } } fn make_soft_type_specifier(&mut self, at_token: Self::R, hint: Self::R) -> Self::R { let hint_pos = unwrap_or_return!(hint.get_pos(self.state.arena)); let hint = unwrap_or_return!(self.node_to_ty(hint)); // Use the type of the hint as-is (i.e., throw away the knowledge that // we had a soft type specifier here--the typechecker does not use it). // Replace its Reason with one including the position of the `@` token. self.hint_ty( unwrap_or_return!(Pos::merge( self.state.arena, unwrap_or_return!(at_token.get_pos(self.state.arena)), hint_pos, ) .ok()), *hint.1, ) } // A type specifier preceded by an attribute list. At the time of writing, // only the <<__Soft>> attribute is permitted here. fn make_attributized_specifier(&mut self, attributes: Self::R, hint: Self::R) -> Self::R { match attributes { Node::BracketedList(( ltlt_pos, [Node::Attribute(nast::UserAttribute { name: Id(_, "__Soft"), .. })], gtgt_pos, )) => { let attributes_pos = unwrap_or_return!(Pos::merge(self.state.arena, *ltlt_pos, *gtgt_pos).ok()); let hint_pos = unwrap_or_return!(hint.get_pos(self.state.arena)); // Use the type of the hint as-is (i.e., throw away the // knowledge that we had a soft type specifier here--the // typechecker does not use it). Replace its Reason with one // including the position of the attribute list. let hint = unwrap_or_return!(self.node_to_ty(hint)); self.hint_ty( unwrap_or_return!(Pos::merge(self.state.arena, attributes_pos, hint_pos).ok()), *hint.1, ) } _ => hint, } } fn make_vector_type_specifier( &mut self, vec: Self::R, _arg1: Self::R, hint: Self::R, _arg3: Self::R, greater_than: Self::R, ) -> Self::R { let id = unwrap_or_return!(self.get_name("", vec)); let id = Id(id.0, self.state.namespace_builder.rename_import(id.1)); self.make_apply(id, hint, greater_than.get_pos(self.state.arena)) } fn make_dictionary_type_specifier( &mut self, dict: Self::R, _arg1: Self::R, hint: Self::R, greater_than: Self::R, ) -> Self::R { let id = unwrap_or_return!(self.get_name("", dict)); let id = Id(id.0, self.state.namespace_builder.rename_import(id.1)); self.make_apply(id, hint, greater_than.get_pos(self.state.arena)) } fn make_keyset_type_specifier( &mut self, keyset: Self::R, _arg1: Self::R, hint: Self::R, _arg3: Self::R, greater_than: Self::R, ) -> Self::R { let id = unwrap_or_return!(self.get_name("", keyset)); let id = Id(id.0, self.state.namespace_builder.rename_import(id.1)); self.make_apply(id, hint, greater_than.get_pos(self.state.arena)) } fn make_variable_expression(&mut self, _arg0: Self::R) -> Self::R { Node::IgnoredSyntaxKind(SyntaxKind::VariableExpression) } fn make_subscript_expression( &mut self, _arg0: Self::R, _arg1: Self::R, _arg2: Self::R, _arg3: Self::R, ) -> Self::R { Node::IgnoredSyntaxKind(SyntaxKind::SubscriptExpression) } fn make_member_selection_expression( &mut self, _arg0: Self::R, _arg1: Self::R, _arg2: Self::R, ) -> Self::R { Node::IgnoredSyntaxKind(SyntaxKind::MemberSelectionExpression) } fn make_object_creation_expression(&mut self, _arg0: Self::R, _arg1: Self::R) -> Self::R { Node::IgnoredSyntaxKind(SyntaxKind::ObjectCreationExpression) } fn make_safe_member_selection_expression( &mut self, _arg0: Self::R, _arg1: Self::R, _arg2: Self::R, ) -> Self::R { Node::IgnoredSyntaxKind(SyntaxKind::SafeMemberSelectionExpression) } fn make_function_call_expression( &mut self, _arg0: Self::R, _arg1: Self::R, _arg2: Self::R, _arg3: Self::R, _arg4: Self::R, ) -> Self::R { Node::IgnoredSyntaxKind(SyntaxKind::FunctionCallExpression) } fn make_list_expression( &mut self, _arg0: Self::R, _arg1: Self::R, _arg2: Self::R, _arg3: Self::R, ) -> Self::R { Node::IgnoredSyntaxKind(SyntaxKind::ListExpression) } }
37.352407
100
0.499875
28dda5469b29efdbf671cd485d707fb0a26994b9
1,972
use rand::distributions::Alphanumeric; use rand::Rng; use std::collections::{BTreeMap, HashMap}; use std::time::{Instant}; fn main() { println!("=========== string keys of length 32 ============"); let mut hit_cnt: usize = 0; for n in vec![10, 100, 1000, 10_000, 100_000] { println!("-------------- container size: {}", n); let mut vector: Vec<String> = vec![]; let mut tree_map: BTreeMap<String, ()> = BTreeMap::new(); let mut hash_map: HashMap<String, ()> = HashMap::new(); generate_keys(&mut vector, n); let mut keys = vector.clone(); keys.sort(); for s in &vector { tree_map.insert(s.clone(), ()); hash_map.insert(s.clone(), ()); } { let start = Instant::now(); for s1 in &keys { if vector.iter().any(|s2| s1 == s2) { hit_cnt += 1; } } let duration = start.elapsed(); println!("Vector seek time elapsed: {:?}", duration / n as u32); } { let start = Instant::now(); for s1 in &keys { tree_map.get(s1); } let duration = start.elapsed(); println!("BTreeMap seek time elapsed: {:?}", duration / n as u32); } { let start = Instant::now(); for s1 in &keys { hash_map.get(s1); } let duration = start.elapsed(); println!("HashMap seek time elapsed: {:?}", duration / n as u32); } } println!("hit cnt: {}", hit_cnt); } fn generate_keys(vec: &mut Vec<String>, n: usize) { const KEY_LEN: usize = 32; for _ in 0 .. n { let s: String = rand::thread_rng() .sample_iter(&Alphanumeric) .take(KEY_LEN) .map(char::from) .collect(); //println!("{}", s); vec.push(s); } }
31.806452
78
0.463489
18357bac9e6f685bf7739ce91e4c223917ba1500
1,842
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Utility macros for implementing PartialEq on slice-like types #![doc(hidden)] #[macro_export] macro_rules! __impl_slice_eq1 { ($Lhs: ty, $Rhs: ty) => { #[stable(feature = "rust1", since = "1.0.0")] impl<'a, 'b, A, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> { #[inline] fn eq(&self, other: &$Rhs) -> bool { &self[..] == &other[..] } #[inline] fn ne(&self, other: &$Rhs) -> bool { &self[..] != &other[..] } } } } #[macro_export] macro_rules! __impl_slice_eq2 { ($Lhs: ty, $Rhs: ty) => { __impl_slice_eq2! { $Lhs, $Rhs, Sized } }; ($Lhs: ty, $Rhs: ty, $Bound: ident) => { #[stable(feature = "rust1", since = "1.0.0")] impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> { #[inline] fn eq(&self, other: &$Rhs) -> bool { &self[..] == &other[..] } #[inline] fn ne(&self, other: &$Rhs) -> bool { &self[..] != &other[..] } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, 'b, A: $Bound, B> PartialEq<$Lhs> for $Rhs where B: PartialEq<A> { #[inline] fn eq(&self, other: &$Lhs) -> bool { &self[..] == &other[..] } #[inline] fn ne(&self, other: &$Lhs) -> bool { &self[..] != &other[..] } } } }
36.117647
83
0.531488
ac0b9997cba0165c8505f069c7ff9e9b8045a5d7
5,361
#![cfg_attr(not(feature = "std"), no_std)] #[cfg(not(feature = "std"))] #[doc(hidden)] extern crate alloc; #[cfg(not(feature = "std"))] pub use alloc::*; #[cfg(not(feature = "std"))] pub use core::*; #[cfg(not(feature = "std"))] pub mod fmt { pub use alloc::fmt::*; pub use core::fmt::*; } #[cfg(not(feature = "std"))] pub mod borrow { pub use alloc::borrow::*; pub use core::borrow::*; } #[cfg(not(feature = "std"))] pub mod slice { pub use alloc::slice::*; pub use core::slice::*; } #[cfg(not(feature = "std"))] pub mod str { pub use alloc::str::*; pub use core::str::*; } #[cfg(not(feature = "std"))] pub mod io; #[cfg(not(feature = "std"))] pub mod error; #[cfg(feature = "std")] #[doc(hidden)] pub use std::*; mod rand_helper; pub use rand_helper::*; pub mod perf_trace; pub mod iterable; pub use num_traits::{One, Zero}; /// Returns the ceiling of the base-2 logarithm of `x`. /// /// ``` /// use ark_std::log2; /// /// assert_eq!(log2(16), 4); /// assert_eq!(log2(17), 5); /// assert_eq!(log2(1), 0); /// assert_eq!(log2(0), 0); /// assert_eq!(log2(usize::MAX), (core::mem::size_of::<usize>() * 8) as u32); /// assert_eq!(log2(1 << 15), 15); /// assert_eq!(log2(2usize.pow(18)), 18); /// ``` pub fn log2(x: usize) -> u32 { if x == 0 { 0 } else if x.is_power_of_two() { 1usize.leading_zeros() - x.leading_zeros() } else { 0usize.leading_zeros() - x.leading_zeros() } } /// Creates parallel iterator over refs if `parallel` feature is enabled. /// Additionally, if the object being iterated implements /// `IndexedParallelIterator`, then one can specify a minimum size for /// iteration. #[macro_export] macro_rules! cfg_iter { ($e: expr, $min_len: expr) => {{ #[cfg(feature = "parallel")] let result = $e.par_iter().with_min_len($min_len); #[cfg(not(feature = "parallel"))] let result = $e.iter(); result }}; ($e: expr) => {{ #[cfg(feature = "parallel")] let result = $e.par_iter(); #[cfg(not(feature = "parallel"))] let result = $e.iter(); result }}; } /// Creates parallel iterator over mut refs if `parallel` feature is enabled. /// Additionally, if the object being iterated implements /// `IndexedParallelIterator`, then one can specify a minimum size for /// iteration. #[macro_export] macro_rules! cfg_iter_mut { ($e: expr, $min_len: expr) => {{ #[cfg(feature = "parallel")] let result = $e.par_iter_mut().with_min_len($min_len); #[cfg(not(feature = "parallel"))] let result = $e.iter_mut(); result }}; ($e: expr) => {{ #[cfg(feature = "parallel")] let result = $e.par_iter_mut(); #[cfg(not(feature = "parallel"))] let result = $e.iter_mut(); result }}; } /// Creates parallel iterator if `parallel` feature is enabled. /// Additionally, if the object being iterated implements /// `IndexedParallelIterator`, then one can specify a minimum size for /// iteration. #[macro_export] macro_rules! cfg_into_iter { ($e: expr, $min_len: expr) => {{ #[cfg(feature = "parallel")] let result = $e.into_par_iter().with_min_len($min_len); #[cfg(not(feature = "parallel"))] let result = $e.into_iter(); result }}; ($e: expr) => {{ #[cfg(feature = "parallel")] let result = $e.into_par_iter(); #[cfg(not(feature = "parallel"))] let result = $e.into_iter(); result }}; } /// Returns an iterator over `chunk_size` elements of the slice at a /// time. #[macro_export] macro_rules! cfg_chunks { ($e: expr, $size: expr) => {{ #[cfg(feature = "parallel")] let result = $e.par_chunks($size); #[cfg(not(feature = "parallel"))] let result = $e.chunks($size); result }}; } /// Returns an iterator over `chunk_size` mutable elements of the slice at a /// time. #[macro_export] macro_rules! cfg_chunks_mut { ($e: expr, $size: expr) => {{ #[cfg(feature = "parallel")] let result = $e.par_chunks_mut($size); #[cfg(not(feature = "parallel"))] let result = $e.chunks_mut($size); result }}; } #[cfg(test)] mod test { use super::*; #[cfg(feature = "parallel")] use rayon::prelude::*; #[test] fn test_cfg_macros() { #[cfg(feature = "parallel")] println!("In parallel mode"); let mut thing = crate::vec![1, 2, 3, 4, 5u64]; println!("Iterating"); cfg_iter!(&thing).for_each(|i| println!("{:?}", i)); println!("Iterating Mut"); cfg_iter_mut!(&mut thing).for_each(|i| *i += 1); println!("Iterating By Value"); cfg_into_iter!(thing.clone()).for_each(|i| println!("{:?}", i)); println!("Chunks"); cfg_chunks!(&thing, 2).for_each(|chunk| println!("{:?}", chunk)); println!("Chunks Mut"); cfg_chunks_mut!(&mut thing, 2).for_each(|chunk| println!("{:?}", chunk)); println!("Iterating"); cfg_iter!(&thing, 3).for_each(|i| println!("{:?}", i)); println!("Iterating Mut"); cfg_iter_mut!(&mut thing, 3).for_each(|i| *i += 1); println!("Iterating By Value"); cfg_into_iter!(thing, 3).for_each(|i| println!("{:?}", i)); } }
24.591743
81
0.563887
897982af4bc85667ca1a6a3c8bc58cb08619e5bb
22,360
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! The definition of a TCP segment. use core::{convert::TryFrom as _, num::TryFromIntError, ops::Range}; use crate::transport::tcp::{ buffer::SendPayload, seqnum::{SeqNum, WindowSize}, Control, }; /// A TCP segment. #[derive(Debug, PartialEq, Eq)] #[cfg_attr(test, derive(Clone, Copy))] pub(super) struct Segment<P: Payload> { /// The sequence number of the segment. pub(super) seq: SeqNum, /// The acknowledge number of the segment. [`None`] if not present. pub(super) ack: Option<SeqNum>, /// The advertised window size. pub(super) wnd: WindowSize, /// The carried data and its control flag. pub(super) contents: Contents<P>, } /// The maximum length that the sequence number doesn't wrap around. pub(super) const MAX_PAYLOAD_AND_CONTROL_LEN: usize = 1 << 31; // The following `as` is sound because it is representable by `u32`. const MAX_PAYLOAD_AND_CONTROL_LEN_U32: u32 = MAX_PAYLOAD_AND_CONTROL_LEN as u32; /// The contents of a TCP segment that takes up some sequence number space. #[derive(Debug, PartialEq, Eq)] #[cfg_attr(test, derive(Clone, Copy))] pub(super) struct Contents<P: Payload> { /// The control flag of the segment. control: Option<Control>, /// The data carried by the segment; it is guaranteed that /// `data.len() + control_len <= MAX_PAYLOAD_AND_CONTROL_LEN`. data: P, } impl<P: Payload> Contents<P> { /// Returns the length of the segment in sequence number space. /// /// Per RFC 793 (https://tools.ietf.org/html/rfc793#page-25): /// SEG.LEN = the number of octets occupied by the data in the segment /// (counting SYN and FIN) pub(super) fn len(&self) -> u32 { let Self { data, control } = self; // The following unwrap and addition are fine because: // - `u32::from(has_control_len)` is 0 or 1. // - `self.data.len() <= 2^31`. let has_control_len = control.map(Control::has_sequence_no).unwrap_or(false); u32::try_from(data.len()).unwrap() + u32::from(has_control_len) } pub(super) fn control(&self) -> Option<Control> { self.control } pub(super) fn data(&self) -> &P { &self.data } } impl<P: Payload> Segment<P> { /// Creates a new segment with data. /// /// Returns the segment along with how many bytes were removed to make sure /// sequence numbers don't wrap around, i.e., `seq.before(seq + seg.len())`. pub(super) fn with_data( seq: SeqNum, ack: Option<SeqNum>, control: Option<Control>, wnd: WindowSize, data: P, ) -> (Self, usize) { let has_control_len = control.map(Control::has_sequence_no).unwrap_or(false); let discarded_len = data.len().saturating_sub(MAX_PAYLOAD_AND_CONTROL_LEN - usize::from(has_control_len)); let contents = if discarded_len > 0 { // If we have to truncate the segment, the FIN flag must be removed // because it is logically the last octet of the segment. let (control, control_len) = if control == Some(Control::FIN) { (None, 0) } else { (control, has_control_len.into()) }; // The following slice will not panic because `discarded_len > 0`, // thus `data.len() > MAX_PAYLOAD_AND_CONTROL_LEN - control_len`. Contents { control, data: data.slice(0..MAX_PAYLOAD_AND_CONTROL_LEN_U32 - control_len) } } else { Contents { control, data } }; (Segment { seq, ack, wnd, contents }, discarded_len) } } impl<P: Payload> Segment<P> { /// Returns the part of the incoming segment within the receive window. pub(super) fn overlap(self, rnxt: SeqNum, rwnd: WindowSize) -> Option<Segment<P>> { let Segment { seq, ack, wnd, contents } = self; let len = contents.len(); let Contents { control, data } = contents; // RFC 793 (https://tools.ietf.org/html/rfc793#page-69): // There are four cases for the acceptability test for an incoming // segment: // Segment Receive Test // Length Window // ------- ------- ------------------------------------------- // 0 0 SEG.SEQ = RCV.NXT // 0 >0 RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND // >0 0 not acceptable // >0 >0 RCV.NXT =< SEG.SEQ < RCV.NXT+RCV.WND // or RCV.NXT =< SEG.SEQ+SEG.LEN-1 < RCV.NXT+RCV.WND let overlap = match (len, rwnd) { (0, WindowSize::ZERO) => seq == rnxt, (0, rwnd) => !rnxt.after(seq) && seq.before(rnxt + rwnd), (_len, WindowSize::ZERO) => false, (len, rwnd) => { (!rnxt.after(seq) && seq.before(rnxt + rwnd)) // Note: here we use RCV.NXT <= SEG.SEQ+SEG.LEN instead of // the condition as quoted above because of the following // text immediately after the above table: // One could tailor actual segments to fit this assumption by // trimming off any portions that lie outside the window // (including SYN and FIN), and only processing further if // the segment then begins at RCV.NXT. // This is essential for TCP simultaneous open to work, // otherwise, the state machine would reject the SYN-ACK // sent by the peer. || (!(seq + len).before(rnxt) && !(seq + len).after(rnxt + rwnd)) } }; overlap.then(move || { // We deliberately don't define `PartialOrd` for `SeqNum`, so we use // `cmp` below to utilize `cmp::{max,min}_by`. let cmp = |lhs: &SeqNum, rhs: &SeqNum| (*lhs - *rhs).cmp(&0); let new_seq = core::cmp::max_by(seq, rnxt, cmp); let new_len = core::cmp::min_by(seq + len, rnxt + rwnd, cmp) - new_seq; // The following unwrap won't panic because: // 1. if `seq` is after `rnxt`, then `start` would be 0. // 2. the interesting case is when `rnxt` is after `seq`, in that // case, we have `rnxt - seq > 0`, thus `new_seq - seq > 0`. let start = u32::try_from(new_seq - seq).unwrap(); // The following unwrap won't panic because: // 1. The witness on `Segment` and `WindowSize` guarantees that // `len <= 2^31` and `rwnd <= 2^30-1` thus // `seq <= seq + len` and `rnxt <= rnxt + rwnd`. // 2. We are in the closure because `overlap` is true which means // `seq <= rnxt + rwnd` and `rnxt <= seq + len`. // With these two conditions combined, `new_len` can't be negative // so the unwrap can't panic. let new_len = u32::try_from(new_len).unwrap(); let (new_control, new_data) = { match control { Some(Control::SYN) => { if seq == new_seq { (Some(Control::SYN), data.slice(start..start + new_len - 1)) } else { (None, data.slice(start - 1..start + new_len - 1)) } } Some(Control::FIN) => { if seq + len == new_seq + new_len { (Some(Control::FIN), data.slice(start..start + new_len - 1)) } else { (None, data.slice(start..start + new_len)) } } Some(Control::RST) | None => (control, data.slice(start..start + new_len)), } }; Segment { seq: new_seq, ack, wnd, contents: Contents { control: new_control, data: new_data }, } }) } } impl Segment<()> { /// Creates a segment with no data. pub(super) fn new( seq: SeqNum, ack: Option<SeqNum>, control: Option<Control>, wnd: WindowSize, ) -> Self { // All of the checks on lengths are optimized out: // https://godbolt.org/z/KPd537G6Y let (seg, truncated) = Segment::with_data(seq, ack, control, wnd, ()); debug_assert_eq!(truncated, 0); seg } /// Creates an ACK segment. pub(super) fn ack(seq: SeqNum, ack: SeqNum, wnd: WindowSize) -> Self { Segment::new(seq, Some(ack), None, wnd) } /// Creates a SYN segment. pub(super) fn syn(seq: SeqNum, wnd: WindowSize) -> Self { Segment::new(seq, None, Some(Control::SYN), wnd) } /// Creates a SYN-ACK segment. pub(super) fn syn_ack(seq: SeqNum, ack: SeqNum, wnd: WindowSize) -> Self { Segment::new(seq, Some(ack), Some(Control::SYN), wnd) } /// Creates a RST segment. pub(super) fn rst(seq: SeqNum) -> Self { Segment::new(seq, None, Some(Control::RST), WindowSize::ZERO) } /// Creates a RST-ACK segment. pub(super) fn rst_ack(seq: SeqNum, ack: SeqNum) -> Self { Segment::new(seq, Some(ack), Some(Control::RST), WindowSize::ZERO) } /// Creates a FIN segment. pub(super) fn fin(seq: SeqNum, ack: SeqNum, wnd: WindowSize) -> Self { Segment::new(seq, Some(ack), Some(Control::FIN), wnd) } } /// A TCP payload that operates around `u32` instead of `usize`. pub trait Payload: Sized { /// Returns the length of the payload. fn len(&self) -> usize; /// Creates a slice of the payload, reducing it to only the bytes within /// `range`. /// /// # Panics /// /// Panics if the provided `range` is not within the bounds of this /// `Payload`, or if the range is nonsensical (the end precedes /// the start). fn slice(self, range: Range<u32>) -> Self; /// Copies part of the payload beginning at `offset` into `dst`. /// /// # Panics /// /// Panics if offset is too large or we couldn't fill the `dst` slice. fn partial_copy(&self, offset: usize, dst: &mut [u8]); } impl Payload for &[u8] { fn len(&self) -> usize { <[u8]>::len(self) } fn slice(self, Range { start, end }: Range<u32>) -> Self { // The following `unwrap`s are ok because: // `usize::try_from(x)` fails when `x > usize::MAX`; given that // `self.len() <= usize::MAX`, panic would be expected because `range` // exceeds the bound of `self`. let start = usize::try_from(start).unwrap_or_else(|TryFromIntError { .. }| { panic!("range start index {} out of range for slice of length {}", start, self.len()) }); let end = usize::try_from(end).unwrap_or_else(|TryFromIntError { .. }| { panic!("range end index {} out of range for slice of length {}", end, self.len()) }); &self[start..end] } fn partial_copy(&self, offset: usize, dst: &mut [u8]) { dst.copy_from_slice(&self[offset..offset + dst.len()]) } } impl Payload for () { fn len(&self) -> usize { 0 } fn slice(self, Range { start, end }: Range<u32>) -> Self { if start != 0 { panic!("range start index {} out of range for slice of length 0", start); } if end != 0 { panic!("range end index {} out of range for slice of length 0", end); } () } fn partial_copy(&self, offset: usize, dst: &mut [u8]) { if dst.len() != 0 || offset != 0 { panic!( "source slice length (0) does not match destination slice length ({})", dst.len() ); } } } impl From<Segment<()>> for Segment<&'static [u8]> { fn from( Segment { seq, ack, wnd, contents: Contents { control, data: () } }: Segment<()>, ) -> Self { Segment { seq, ack, wnd, contents: Contents { control, data: &[] } } } } impl From<Segment<()>> for Segment<SendPayload<'static>> { fn from( Segment { seq, ack, wnd, contents: Contents { control, data: () } }: Segment<()>, ) -> Self { Segment { seq, ack, wnd, contents: Contents { control, data: SendPayload::Contiguous(&[]) }, } } } #[cfg(test)] mod test { use test_case::test_case; use super::*; #[test_case(None, &[][..] => (0, &[][..]); "empty")] #[test_case(None, &[1][..] => (1, &[1][..]); "no control")] #[test_case(Some(Control::SYN), &[][..] => (1, &[][..]); "empty slice with syn")] #[test_case(Some(Control::SYN), &[1][..] => (2, &[1][..]); "non-empty slice with syn")] #[test_case(Some(Control::FIN), &[][..] => (1, &[][..]); "empty slice with fin")] #[test_case(Some(Control::FIN), &[1][..] => (2, &[1][..]); "non-empty slice with fin")] #[test_case(Some(Control::RST), &[][..] => (0, &[][..]); "empty slice with rst")] #[test_case(Some(Control::RST), &[1][..] => (1, &[1][..]); "non-empty slice with rst")] fn segment_len(control: Option<Control>, data: &[u8]) -> (u32, &[u8]) { let (seg, truncated) = Segment::with_data( SeqNum::new(1), Some(SeqNum::new(1)), control, WindowSize::ZERO, data, ); assert_eq!(truncated, 0); (seg.contents.len(), seg.contents.data) } #[test_case(&[1, 2, 3, 4, 5][..], 0..4 => [1, 2, 3, 4])] #[test_case((), 0..0 => [0, 0, 0, 0])] fn payload_slice_copy(data: impl Payload, range: Range<u32>) -> [u8; 4] { let sliced = data.slice(range); let mut buffer = [0; 4]; sliced.partial_copy(0, &mut buffer[..sliced.len()]); buffer } #[derive(Debug, PartialEq, Eq)] struct TestPayload(Range<u32>); impl TestPayload { fn new(len: usize) -> Self { Self(0..u32::try_from(len).unwrap()) } } impl Payload for TestPayload { fn len(&self) -> usize { self.0.len() } fn slice(self, range: Range<u32>) -> Self { let Self(this) = self; assert!(range.start >= this.start && range.end <= this.end); TestPayload(range) } fn partial_copy(&self, _offset: usize, _dst: &mut [u8]) { unimplemented!("TestPayload doesn't carry any data"); } } #[test_case(100, Some(Control::SYN) => (100, Some(Control::SYN), 0))] #[test_case(100, Some(Control::FIN) => (100, Some(Control::FIN), 0))] #[test_case(100, Some(Control::RST) => (100, Some(Control::RST), 0))] #[test_case(100, None => (100, None, 0))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN - 1, Some(Control::SYN) => (MAX_PAYLOAD_AND_CONTROL_LEN - 1, Some(Control::SYN), 0))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN - 1, Some(Control::FIN) => (MAX_PAYLOAD_AND_CONTROL_LEN - 1, Some(Control::FIN), 0))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN - 1, Some(Control::RST) => (MAX_PAYLOAD_AND_CONTROL_LEN - 1, Some(Control::RST), 0))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN - 1, None => (MAX_PAYLOAD_AND_CONTROL_LEN - 1, None, 0))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN, Some(Control::SYN) => (MAX_PAYLOAD_AND_CONTROL_LEN - 1, Some(Control::SYN), 1))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN, Some(Control::FIN) => (MAX_PAYLOAD_AND_CONTROL_LEN, None, 1))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN, Some(Control::RST) => (MAX_PAYLOAD_AND_CONTROL_LEN, Some(Control::RST), 0))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN, None => (MAX_PAYLOAD_AND_CONTROL_LEN, None, 0))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN + 1, Some(Control::SYN) => (MAX_PAYLOAD_AND_CONTROL_LEN - 1, Some(Control::SYN), 2))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN + 1, Some(Control::FIN) => (MAX_PAYLOAD_AND_CONTROL_LEN, None, 2))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN + 1, Some(Control::RST) => (MAX_PAYLOAD_AND_CONTROL_LEN, Some(Control::RST), 1))] #[test_case(MAX_PAYLOAD_AND_CONTROL_LEN + 1, None => (MAX_PAYLOAD_AND_CONTROL_LEN, None, 1))] #[test_case(u32::MAX as usize, Some(Control::SYN) => (MAX_PAYLOAD_AND_CONTROL_LEN - 1, Some(Control::SYN), 1 << 31))] fn segment_truncate(len: usize, control: Option<Control>) -> (usize, Option<Control>, usize) { let (seg, truncated) = Segment::with_data( SeqNum::new(0), None, control, WindowSize::ZERO, TestPayload::new(len), ); (seg.contents.data.len(), seg.contents.control, truncated) } struct OverlapTestArgs { seg_seq: u32, control: Option<Control>, data_len: u32, rcv_nxt: u32, rcv_wnd: usize, } #[test_case(OverlapTestArgs{ seg_seq: 1, control: None, data_len: 0, rcv_nxt: 0, rcv_wnd: 0, } => None)] #[test_case(OverlapTestArgs{ seg_seq: 1, control: None, data_len: 0, rcv_nxt: 1, rcv_wnd: 0, } => Some((SeqNum::new(1), None, 0..0)))] #[test_case(OverlapTestArgs{ seg_seq: 1, control: None, data_len: 0, rcv_nxt: 2, rcv_wnd: 0, } => None)] #[test_case(OverlapTestArgs{ seg_seq: 1, control: Some(Control::SYN), data_len: 0, rcv_nxt: 2, rcv_wnd: 0, } => None)] #[test_case(OverlapTestArgs{ seg_seq: 1, control: Some(Control::SYN), data_len: 0, rcv_nxt: 1, rcv_wnd: 0, } => None)] #[test_case(OverlapTestArgs{ seg_seq: 1, control: Some(Control::SYN), data_len: 0, rcv_nxt: 0, rcv_wnd: 0, } => None)] #[test_case(OverlapTestArgs{ seg_seq: 1, control: Some(Control::FIN), data_len: 0, rcv_nxt: 2, rcv_wnd: 0, } => None)] #[test_case(OverlapTestArgs{ seg_seq: 1, control: Some(Control::FIN), data_len: 0, rcv_nxt: 1, rcv_wnd: 0, } => None)] #[test_case(OverlapTestArgs{ seg_seq: 1, control: Some(Control::FIN), data_len: 0, rcv_nxt: 0, rcv_wnd: 0, } => None)] #[test_case(OverlapTestArgs{ seg_seq: 0, control: None, data_len: 0, rcv_nxt: 1, rcv_wnd: 1, } => None)] #[test_case(OverlapTestArgs{ seg_seq: 1, control: None, data_len: 0, rcv_nxt: 1, rcv_wnd: 1, } => Some((SeqNum::new(1), None, 0..0)))] #[test_case(OverlapTestArgs{ seg_seq: 2, control: None, data_len: 0, rcv_nxt: 1, rcv_wnd: 1, } => None)] #[test_case(OverlapTestArgs{ seg_seq: 0, control: None, data_len: 1, rcv_nxt: 1, rcv_wnd: 1, } => Some((SeqNum::new(1), None, 1..1)))] #[test_case(OverlapTestArgs{ seg_seq: 0, control: Some(Control::SYN), data_len: 0, rcv_nxt: 1, rcv_wnd: 1, } => Some((SeqNum::new(1), None, 0..0)))] #[test_case(OverlapTestArgs{ seg_seq: 2, control: None, data_len: 1, rcv_nxt: 1, rcv_wnd: 1, } => None)] #[test_case(OverlapTestArgs{ seg_seq: 0, control: None, data_len: 2, rcv_nxt: 1, rcv_wnd: 1, } => Some((SeqNum::new(1), None, 1..2)))] #[test_case(OverlapTestArgs{ seg_seq: 1, control: None, data_len: 2, rcv_nxt: 1, rcv_wnd: 1, } => Some((SeqNum::new(1), None, 0..1)))] #[test_case(OverlapTestArgs{ seg_seq: 0, control: Some(Control::SYN), data_len: 1, rcv_nxt: 1, rcv_wnd: 1, } => Some((SeqNum::new(1), None, 0..1)))] #[test_case(OverlapTestArgs{ seg_seq: 1, control: Some(Control::SYN), data_len: 1, rcv_nxt: 1, rcv_wnd: 1, } => Some((SeqNum::new(1), Some(Control::SYN), 0..0)))] #[test_case(OverlapTestArgs{ seg_seq: 0, control: Some(Control::FIN), data_len: 1, rcv_nxt: 1, rcv_wnd: 1, } => Some((SeqNum::new(1), Some(Control::FIN), 1..1)))] #[test_case(OverlapTestArgs{ seg_seq: 1, control: Some(Control::FIN), data_len: 1, rcv_nxt: 1, rcv_wnd: 1, } => Some((SeqNum::new(1), None, 0..1)))] #[test_case(OverlapTestArgs{ seg_seq: 1, control: None, data_len: MAX_PAYLOAD_AND_CONTROL_LEN_U32, rcv_nxt: 1, rcv_wnd: 10, } => Some((SeqNum::new(1), None, 0..10)))] #[test_case(OverlapTestArgs{ seg_seq: 10, control: None, data_len: MAX_PAYLOAD_AND_CONTROL_LEN_U32, rcv_nxt: 1, rcv_wnd: 10, } => Some((SeqNum::new(10), None, 0..1)))] #[test_case(OverlapTestArgs{ seg_seq: 1, control: None, data_len: 10, rcv_nxt: 1, rcv_wnd: 1 << 30 - 1, } => Some((SeqNum::new(1), None, 0..10)))] #[test_case(OverlapTestArgs{ seg_seq: 10, control: None, data_len: 10, rcv_nxt: 1, rcv_wnd: 1 << 30 - 1, } => Some((SeqNum::new(10), None, 0..10)))] fn segment_overlap( OverlapTestArgs { seg_seq, control, data_len, rcv_nxt, rcv_wnd }: OverlapTestArgs, ) -> Option<(SeqNum, Option<Control>, Range<u32>)> { let (seg, discarded) = Segment::with_data( SeqNum::new(seg_seq), None, control, WindowSize::ZERO, TestPayload(0..data_len), ); assert_eq!(discarded, 0); seg.overlap(SeqNum::new(rcv_nxt), WindowSize::new(rcv_wnd).unwrap()).map( |Segment { seq, ack: _, wnd: _, contents: Contents { control, data: TestPayload(range) }, }| { (seq, control, range) }, ) } }
35.323855
100
0.538014
1d9fbcc834aba3e09dc62ad17c0c0df505edecac
2,912
#![allow(dead_code)] // Simple tests to ensure macro generated fns compile ioctl!(do_bad with 0x1234); ioctl!(none do_none with 0, 0); ioctl!(read read_test with 0, 0; u32); ioctl!(write write_test with 0, 0; u64); ioctl!(readwrite readwrite_test with 0, 0; u64); ioctl!(read buf readbuf_test with 0, 0; u32); ioctl!(write buf writebuf_test with 0, 0; u32); ioctl!(readwrite buf readwritebuf_test with 0, 0; u32); // See C code for source of values for op calculations: // https://gist.github.com/posborne/83ea6880770a1aef332e #[cfg(any(target_os = "linux", target_os = "android"))] mod linux { #[test] fn test_op_none() { assert_eq!(io!(b'q', 10), 0x0000710A); assert_eq!(io!(b'a', 255), 0x000061FF); } #[test] fn test_op_write() { assert_eq!(iow!(b'z', 10, 1), 0x40017A0A); assert_eq!(iow!(b'z', 10, 512), 0x42007A0A); } #[cfg(target_pointer_width = "64")] #[test] fn test_op_write_64() { assert_eq!(iow!(b'z', 10, (1 as u64) << 32), 0x40007A0A); } #[test] fn test_op_read() { assert_eq!(ior!(b'z', 10, 1), 0x80017A0A); assert_eq!(ior!(b'z', 10, 512), 0x82007A0A); } #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_64() { assert_eq!(ior!(b'z', 10, (1 as u64) << 32), 0x80007A0A); } #[test] fn test_op_read_write() { assert_eq!(iorw!(b'z', 10, 1), 0xC0017A0A); assert_eq!(iorw!(b'z', 10, 512), 0xC2007A0A); } #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_write_64() { assert_eq!(iorw!(b'z', 10, (1 as u64) << 32), 0xC0007A0A); } } #[cfg(any(target_os = "macos", target_os = "ios", target_os = "netbsd", target_os = "openbsd", target_os = "freebsd", target_os = "dragonfly"))] mod bsd { #[test] fn test_op_none() { assert_eq!(io!(b'q', 10), 0x2000710A); assert_eq!(io!(b'a', 255), 0x200061FF); } #[test] fn test_op_write() { assert_eq!(iow!(b'z', 10, 1), 0x80017A0A); assert_eq!(iow!(b'z', 10, 512), 0x82007A0A); } #[cfg(target_pointer_width = "64")] #[test] fn test_op_write_64() { assert_eq!(iow!(b'z', 10, (1 as u64) << 32), 0x80007A0A); } #[test] fn test_op_read() { assert_eq!(ior!(b'z', 10, 1), 0x40017A0A); assert_eq!(ior!(b'z', 10, 512), 0x42007A0A); } #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_64() { assert_eq!(ior!(b'z', 10, (1 as u64) << 32), 0x40007A0A); } #[test] fn test_op_read_write() { assert_eq!(iorw!(b'z', 10, 1), 0xC0017A0A); assert_eq!(iorw!(b'z', 10, 512), 0xC2007A0A); } #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_write_64() { assert_eq!(iorw!(b'z', 10, (1 as u64) << 32), 0xC0007A0A); } }
26.472727
66
0.56147
01374e57707c4bfd1acd79955b96144c6cd9063f
2,891
// Copyright 2020 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use common_datavalues::prelude::*; use common_exception::Result; use common_functions::scalars::*; use pretty_assertions::assert_eq; #[test] fn test_to_type_name_function() -> Result<()> { #[allow(dead_code)] struct Test { name: &'static str, display: &'static str, nullable: bool, arg_names: Vec<&'static str>, columns: Vec<DataColumn>, expect: DataColumn, error: &'static str, func: Box<dyn Function>, } let schema = DataSchemaRefExt::create(vec![DataField::new("a", DataType::Boolean, false)]); let tests = vec![Test { name: "to_type_name-example-passed", display: "toTypeName", nullable: false, arg_names: vec!["a"], func: ToTypeNameFunction::try_create("toTypeName")?, columns: vec![Series::new(vec![true, true, true, false]).into()], expect: Series::new(vec!["Boolean", "Boolean", "Boolean", "Boolean"]).into(), error: "", }]; for t in tests { let rows = t.columns[0].len(); let func = t.func; // Type check. let mut args = vec![]; let mut fields = vec![]; for name in t.arg_names { args.push(schema.field_with_name(name)?.data_type().clone()); fields.push(schema.field_with_name(name)?.clone()); } let columns: Vec<DataColumnWithField> = t .columns .iter() .zip(fields.iter()) .map(|(c, f)| DataColumnWithField::new(c.clone(), f.clone())) .collect(); if let Err(e) = func.eval(&columns, rows) { assert_eq!(t.error, e.to_string()); } // Display check. let expect_display = t.display.to_string(); let actual_display = format!("{}", func); assert_eq!(expect_display, actual_display); // Nullable check. let expect_null = t.nullable; let actual_null = func.nullable(&schema)?; assert_eq!(expect_null, actual_null); let v = &(func.eval(&columns, rows)?); let expect_type = func.return_type(&args)?; let actual_type = v.data_type(); assert_eq!(expect_type, actual_type); assert!(v.to_array()?.series_equal(&t.expect.to_array()?)); } Ok(()) }
32.122222
95
0.601522
9bc911b405d49f0f05c14255c748b4161d91eda9
14,027
//! The `gossip_service` module implements the network control plane. use { crate::{cluster_info::ClusterInfo, contact_info::ContactInfo}, crossbeam_channel::{unbounded, Sender}, rand::{thread_rng, Rng}, solana_client::{connection_cache::ConnectionCache, thin_client::ThinClient}, solana_perf::recycler::Recycler, solana_runtime::bank_forks::BankForks, solana_sdk::{ pubkey::Pubkey, signature::{Keypair, Signer}, }, solana_streamer::{ socket::SocketAddrSpace, streamer::{self, StreamerReceiveStats}, }, std::{ collections::HashSet, net::{SocketAddr, TcpListener, UdpSocket}, sync::{ atomic::{AtomicBool, Ordering}, Arc, RwLock, }, thread::{self, sleep, JoinHandle}, time::{Duration, Instant}, }, }; pub struct GossipService { thread_hdls: Vec<JoinHandle<()>>, } impl GossipService { pub fn new( cluster_info: &Arc<ClusterInfo>, bank_forks: Option<Arc<RwLock<BankForks>>>, gossip_socket: UdpSocket, gossip_validators: Option<HashSet<Pubkey>>, should_check_duplicate_instance: bool, stats_reporter_sender: Option<Sender<Box<dyn FnOnce() + Send>>>, exit: &Arc<AtomicBool>, ) -> Self { let (request_sender, request_receiver) = unbounded(); let gossip_socket = Arc::new(gossip_socket); trace!( "GossipService: id: {}, listening on: {:?}", &cluster_info.id(), gossip_socket.local_addr().unwrap() ); let socket_addr_space = *cluster_info.socket_addr_space(); let t_receiver = streamer::receiver( gossip_socket.clone(), exit.clone(), request_sender, Recycler::default(), Arc::new(StreamerReceiveStats::new("gossip_receiver")), 1, false, None, ); let (consume_sender, listen_receiver) = unbounded(); let t_socket_consume = cluster_info.clone().start_socket_consume_thread( request_receiver, consume_sender, exit.clone(), ); let (response_sender, response_receiver) = unbounded(); let t_listen = cluster_info.clone().listen( bank_forks.clone(), listen_receiver, response_sender.clone(), should_check_duplicate_instance, exit.clone(), ); let t_gossip = cluster_info.clone().gossip( bank_forks, response_sender, gossip_validators, exit.clone(), ); let t_responder = streamer::responder( "gossip", gossip_socket, response_receiver, socket_addr_space, stats_reporter_sender, ); let thread_hdls = vec![ t_receiver, t_responder, t_socket_consume, t_listen, t_gossip, ]; Self { thread_hdls } } pub fn join(self) -> thread::Result<()> { for thread_hdl in self.thread_hdls { thread_hdl.join()?; } Ok(()) } } /// Discover Validators in a cluster pub fn discover_cluster( entrypoint: &SocketAddr, num_nodes: usize, socket_addr_space: SocketAddrSpace, ) -> std::io::Result<Vec<ContactInfo>> { const DISCOVER_CLUSTER_TIMEOUT: Duration = Duration::from_secs(120); let (_all_peers, validators) = discover( None, // keypair Some(entrypoint), Some(num_nodes), DISCOVER_CLUSTER_TIMEOUT, None, // find_node_by_pubkey None, // find_node_by_gossip_addr None, // my_gossip_addr 0, // my_shred_version socket_addr_space, )?; Ok(validators) } pub fn discover( keypair: Option<Keypair>, entrypoint: Option<&SocketAddr>, num_nodes: Option<usize>, // num_nodes only counts validators, excludes spy nodes timeout: Duration, find_node_by_pubkey: Option<Pubkey>, find_node_by_gossip_addr: Option<&SocketAddr>, my_gossip_addr: Option<&SocketAddr>, my_shred_version: u16, socket_addr_space: SocketAddrSpace, ) -> std::io::Result<( Vec<ContactInfo>, // all gossip peers Vec<ContactInfo>, // tvu peers (validators) )> { let keypair = keypair.unwrap_or_else(Keypair::new); let exit = Arc::new(AtomicBool::new(false)); let (gossip_service, ip_echo, spy_ref) = make_gossip_node( keypair, entrypoint, &exit, my_gossip_addr, my_shred_version, true, // should_check_duplicate_instance, socket_addr_space, ); let id = spy_ref.id(); info!("Entrypoint: {:?}", entrypoint); info!("Node Id: {:?}", id); if let Some(my_gossip_addr) = my_gossip_addr { info!("Gossip Address: {:?}", my_gossip_addr); } let _ip_echo_server = ip_echo .map(|tcp_listener| solana_net_utils::ip_echo_server(tcp_listener, Some(my_shred_version))); let (met_criteria, elapsed, all_peers, tvu_peers) = spy( spy_ref.clone(), num_nodes, timeout, find_node_by_pubkey, find_node_by_gossip_addr, ); exit.store(true, Ordering::Relaxed); gossip_service.join().unwrap(); if met_criteria { info!( "discover success in {}s...\n{}", elapsed.as_secs(), spy_ref.contact_info_trace() ); return Ok((all_peers, tvu_peers)); } if !tvu_peers.is_empty() { info!( "discover failed to match criteria by timeout...\n{}", spy_ref.contact_info_trace() ); return Ok((all_peers, tvu_peers)); } info!("discover failed...\n{}", spy_ref.contact_info_trace()); Err(std::io::Error::new( std::io::ErrorKind::Other, "Discover failed", )) } /// Creates a ThinClient by selecting a valid node at random pub fn get_client( nodes: &[ContactInfo], socket_addr_space: &SocketAddrSpace, connection_cache: Arc<ConnectionCache>, ) -> ThinClient { let nodes: Vec<_> = nodes .iter() .filter_map(|node| ContactInfo::valid_client_facing_addr(node, socket_addr_space)) .collect(); let select = thread_rng().gen_range(0, nodes.len()); let (rpc, tpu) = nodes[select]; ThinClient::new(rpc, tpu, connection_cache) } pub fn get_multi_client( nodes: &[ContactInfo], socket_addr_space: &SocketAddrSpace, connection_cache: Arc<ConnectionCache>, ) -> (ThinClient, usize) { let addrs: Vec<_> = nodes .iter() .filter_map(|node| ContactInfo::valid_client_facing_addr(node, socket_addr_space)) .collect(); let rpc_addrs: Vec<_> = addrs.iter().map(|addr| addr.0).collect(); let tpu_addrs: Vec<_> = addrs.iter().map(|addr| addr.1).collect(); let num_nodes = tpu_addrs.len(); ( ThinClient::new_from_addrs(rpc_addrs, tpu_addrs, connection_cache), num_nodes, ) } fn spy( spy_ref: Arc<ClusterInfo>, num_nodes: Option<usize>, timeout: Duration, find_node_by_pubkey: Option<Pubkey>, find_node_by_gossip_addr: Option<&SocketAddr>, ) -> ( bool, // if found the specified nodes Duration, // elapsed time until found the nodes or timed-out Vec<ContactInfo>, // all gossip peers Vec<ContactInfo>, // tvu peers (validators) ) { let now = Instant::now(); let mut met_criteria = false; let mut all_peers: Vec<ContactInfo> = Vec::new(); let mut tvu_peers: Vec<ContactInfo> = Vec::new(); let mut i = 1; while !met_criteria && now.elapsed() < timeout { all_peers = spy_ref .all_peers() .into_iter() .map(|x| x.0) .collect::<Vec<_>>(); tvu_peers = spy_ref.all_tvu_peers(); let found_node_by_pubkey = if let Some(pubkey) = find_node_by_pubkey { all_peers.iter().any(|x| x.id == pubkey) } else { false }; let found_node_by_gossip_addr = if let Some(gossip_addr) = find_node_by_gossip_addr { all_peers.iter().any(|x| x.gossip == *gossip_addr) } else { false }; if let Some(num) = num_nodes { // Only consider validators and archives for `num_nodes` let mut nodes: Vec<_> = tvu_peers.iter().collect(); nodes.sort(); nodes.dedup(); if nodes.len() >= num { if found_node_by_pubkey || found_node_by_gossip_addr { met_criteria = true; } if find_node_by_pubkey.is_none() && find_node_by_gossip_addr.is_none() { met_criteria = true; } } } else if found_node_by_pubkey || found_node_by_gossip_addr { met_criteria = true; } if i % 20 == 0 { info!("discovering...\n{}", spy_ref.contact_info_trace()); } sleep(Duration::from_millis( crate::cluster_info::GOSSIP_SLEEP_MILLIS, )); i += 1; } (met_criteria, now.elapsed(), all_peers, tvu_peers) } /// Makes a spy or gossip node based on whether or not a gossip_addr was passed in /// Pass in a gossip addr to fully participate in gossip instead of relying on just pulls pub fn make_gossip_node( keypair: Keypair, entrypoint: Option<&SocketAddr>, exit: &Arc<AtomicBool>, gossip_addr: Option<&SocketAddr>, shred_version: u16, should_check_duplicate_instance: bool, socket_addr_space: SocketAddrSpace, ) -> (GossipService, Option<TcpListener>, Arc<ClusterInfo>) { let (node, gossip_socket, ip_echo) = if let Some(gossip_addr) = gossip_addr { ClusterInfo::gossip_node(keypair.pubkey(), gossip_addr, shred_version) } else { ClusterInfo::spy_node(keypair.pubkey(), shred_version) }; let cluster_info = ClusterInfo::new(node, Arc::new(keypair), socket_addr_space); if let Some(entrypoint) = entrypoint { cluster_info.set_entrypoint(ContactInfo::new_gossip_entry_point(entrypoint)); } let cluster_info = Arc::new(cluster_info); let gossip_service = GossipService::new( &cluster_info, None, gossip_socket, None, should_check_duplicate_instance, None, exit, ); (gossip_service, ip_echo, cluster_info) } #[cfg(test)] mod tests { use { super::*, crate::cluster_info::{ClusterInfo, Node}, std::sync::{atomic::AtomicBool, Arc}, }; #[test] #[ignore] // test that stage will exit when flag is set fn test_exit() { let exit = Arc::new(AtomicBool::new(false)); let tn = Node::new_localhost(); let cluster_info = ClusterInfo::new( tn.info.clone(), Arc::new(Keypair::new()), SocketAddrSpace::Unspecified, ); let c = Arc::new(cluster_info); let d = GossipService::new( &c, None, tn.sockets.gossip, None, true, // should_check_duplicate_instance None, &exit, ); exit.store(true, Ordering::Relaxed); d.join().unwrap(); } #[test] fn test_gossip_services_spy() { const TIMEOUT: Duration = Duration::from_secs(5); let keypair = Keypair::new(); let peer0 = solana_sdk::pubkey::new_rand(); let peer1 = solana_sdk::pubkey::new_rand(); let contact_info = ContactInfo::new_localhost(&keypair.pubkey(), 0); let peer0_info = ContactInfo::new_localhost(&peer0, 0); let peer1_info = ContactInfo::new_localhost(&peer1, 0); let cluster_info = ClusterInfo::new( contact_info, Arc::new(keypair), SocketAddrSpace::Unspecified, ); cluster_info.insert_info(peer0_info.clone()); cluster_info.insert_info(peer1_info); let spy_ref = Arc::new(cluster_info); let (met_criteria, elapsed, _, tvu_peers) = spy(spy_ref.clone(), None, TIMEOUT, None, None); assert!(!met_criteria); assert!((TIMEOUT..TIMEOUT + Duration::from_secs(1)).contains(&elapsed)); assert_eq!(tvu_peers, spy_ref.tvu_peers()); // Find num_nodes let (met_criteria, _, _, _) = spy(spy_ref.clone(), Some(1), TIMEOUT, None, None); assert!(met_criteria); let (met_criteria, _, _, _) = spy(spy_ref.clone(), Some(2), TIMEOUT, None, None); assert!(met_criteria); // Find specific node by pubkey let (met_criteria, _, _, _) = spy(spy_ref.clone(), None, TIMEOUT, Some(peer0), None); assert!(met_criteria); let (met_criteria, _, _, _) = spy( spy_ref.clone(), None, TIMEOUT, Some(solana_sdk::pubkey::new_rand()), None, ); assert!(!met_criteria); // Find num_nodes *and* specific node by pubkey let (met_criteria, _, _, _) = spy(spy_ref.clone(), Some(1), TIMEOUT, Some(peer0), None); assert!(met_criteria); let (met_criteria, _, _, _) = spy(spy_ref.clone(), Some(3), TIMEOUT, Some(peer0), None); assert!(!met_criteria); let (met_criteria, _, _, _) = spy( spy_ref.clone(), Some(1), TIMEOUT, Some(solana_sdk::pubkey::new_rand()), None, ); assert!(!met_criteria); // Find specific node by gossip address let (met_criteria, _, _, _) = spy( spy_ref.clone(), None, TIMEOUT, None, Some(&peer0_info.gossip), ); assert!(met_criteria); let (met_criteria, _, _, _) = spy( spy_ref, None, TIMEOUT, None, Some(&"1.1.1.1:1234".parse().unwrap()), ); assert!(!met_criteria); } }
31.952164
100
0.583874
263769e758ee22965601e6e0f796a4b2dc7c70d6
9,095
// Copyright 2019 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::error::{Error, ErrorKind}; use crate::util; use crate::shamir::Share; use hmac::{Hmac, Mac}; use sha2::Sha256; use crate::field::gf256::Gf256; use crate::field::lagrange; // Create alias for HMAC-SHA256 type HmacSha256 = Hmac<Sha256>; /// Share split configuration values #[derive(Debug, Clone, PartialEq, Eq)] pub struct SplitterConfig { /// The length of the random Identifier in bits // TODO: Redundant with ShareConfig value pub id_length_bits: u8, /// The maximum number of shares that can be created pub max_share_count: u8, /// The length of the digest of the shared secret in bytes pub digest_length_bytes: u8, /// The index of the share containing the shared secret pub secret_index: u8, /// The index of the share containing the digest of the shared secret pub digest_index: u8, } impl Default for SplitterConfig { fn default() -> Self { let id_length_bits = 15; let max_share_count = 16; let digest_length_bytes = 4; let secret_index = 255; let digest_index = 254; SplitterConfig { id_length_bits, max_share_count, digest_length_bytes, secret_index, digest_index, } } } impl SplitterConfig { /// Just use defaults for now pub fn new() -> Self { SplitterConfig { ..Default::default() } } } /// Main Struct pub struct Splitter { /// Configuration values config: SplitterConfig, } impl Splitter { /// Create new pub fn new(config: Option<&SplitterConfig>) -> Splitter { Splitter { config: match config { Some(c) => c.to_owned(), None => SplitterConfig::new(), }, } } /// split secret /// member_threshold, share_count, shared_secret at least 128 bits and a multiple of 16 /// returns shares pub fn split_secret( &self, proto_share: &Share, threshold: u8, share_count: u8, shared_secret: &[u8], ) -> Result<Vec<Share>, Error> { if threshold == 0 || threshold > self.config.max_share_count { return Err(ErrorKind::Argument(format!( "Threshold must be between 1 and {}", self.config.max_share_count )))?; } if share_count < threshold || share_count > self.config.max_share_count { return Err(ErrorKind::Argument(format!( "Share count with given member threshold must be between {} and {}", threshold, self.config.max_share_count )))?; } if shared_secret.len() < 16 || shared_secret.len() % 2 != 0 { return Err(ErrorKind::Argument("Secret must be at least 16 bytes in length and a multiple of 2".to_string()))?; } let mut shares = vec![]; // if the threshold is 1, then the digest of the shared secret is not used if threshold == 1 { for i in 0..share_count { let mut s = proto_share.clone(); s.member_index = i; s.member_threshold = threshold; s.share_value = shared_secret.to_owned(); shares.push(s); } return Ok(shares); } let random_share_count = threshold - 2; for i in 0..random_share_count { let mut s = proto_share.clone(); s.member_index = i; s.member_threshold = threshold; s.share_value = util::fill_vec_rand(shared_secret.len()); shares.push(s); } let random_part = util::fill_vec_rand(shared_secret.len() - self.config.digest_length_bytes as usize); let mut digest = self.create_digest(&random_part.to_vec(), &shared_secret); digest.append(&mut random_part.to_vec()); let mut base_shares = shares.clone(); let mut s = proto_share.clone(); s.member_index = self.config.digest_index; s.member_threshold = threshold; s.share_value = digest; base_shares.push(s); let mut s = proto_share.clone(); s.member_index = self.config.secret_index; s.member_threshold = threshold; s.share_value = shared_secret.to_owned(); base_shares.push(s); for i in random_share_count..share_count { let mut r = self.interpolate(&base_shares, i, proto_share)?; r.member_index = i; r.member_threshold = threshold; shares.push(r); } //self.check_digest(&shares, &shared_secret, &proto_share)?; Ok(shares) } /// recover a secret pub fn recover_secret(&self, shares: &[Share], threshold: u8) -> Result<Share, Error> { if shares.is_empty() { return Err(ErrorKind::Value("Share set must not be empty.".to_string()))?; } let mut proto_share = shares[0].clone(); proto_share.share_value = vec![]; let shared_secret = self.interpolate(&shares, self.config.secret_index, &proto_share)?; if threshold != 1 { self.check_digest(&shares, &shared_secret, &proto_share)?; } Ok(shared_secret) } fn interpolate(&self, shares: &[Share], x: u8, proto_share: &Share) -> Result<Share, Error> { let x_coords: Vec<u8> = shares.iter().map(|s| s.member_index).collect(); if x_coords.contains(&x) { for s in shares { if s.member_index == x { let mut ret_s = proto_share.clone(); ret_s.member_index = x; ret_s.share_value = s.share_value.clone(); return Ok(ret_s); } } } let share_value_lengths = shares[0].share_value.len(); for s in shares { if s.share_value.len() != share_value_lengths { return Err(ErrorKind::Mnemonic("Invalid set of shares. All share values must have the same length".to_string()))?; } } let mut ret_share = proto_share.clone(); ret_share.member_index = x; for i in 0..share_value_lengths { let points: Vec<(Gf256, Gf256)> = shares .iter() .map(|s| { ( Gf256::from_byte(s.member_index), Gf256::from_byte(s.share_value[i]), ) }) .collect(); let poly = lagrange::interpolate(&points); let y = poly.evaluate_at(Gf256::from_byte(x)); ret_share.share_value.push(y.to_byte()); } Ok(ret_share) } fn create_digest(&self, random_data: &[u8], shared_secret: &[u8]) -> Vec<u8> { let mut mac = HmacSha256::new_varkey(random_data).expect("HMAC error"); mac.input(shared_secret); let mut result = [0u8; 32]; result.copy_from_slice(mac.result().code().as_slice()); let mut ret_vec = result.to_vec(); ret_vec.split_off(4); ret_vec } fn check_digest( &self, shares: &[Share], shared_secret: &Share, proto_share: &Share, ) -> Result<(), Error> { let digest_share = self.interpolate(shares, self.config.digest_index, proto_share)?; let mut digest = digest_share.share_value.clone(); let random_part = digest.split_off(self.config.digest_length_bytes as usize); if digest != self.create_digest(&random_part, &shared_secret.share_value) { return Err(ErrorKind::Digest("Invalid digest of the shared secret".to_string()))?; } Ok(()) } } #[cfg(test)] mod tests { use super::*; use rand::{thread_rng, Rng}; // run split and recover given shares and thresholds, then check random combinations of threshold // shares reconstruct the secret fn split_recover_impl( secret_length_bytes: usize, threshold: u8, total_shares: u8, ) -> Result<(), Error> { let sp = Splitter::new(None); let secret = util::fill_vec_rand(secret_length_bytes); println!("Secret is: {:?}", secret); let proto_share = Share::new()?; let mut shares = sp.split_secret(&proto_share, threshold, total_shares, &secret)?; println!("Shares: {:?}", shares); for _ in threshold..total_shares { let recovered_secret = sp.recover_secret(&shares, threshold)?; println!("Recovered secret is: {:?}", secret); assert_eq!(secret, recovered_secret.share_value); if threshold == 1 { return Ok(()); } // randomly remove a share till we're at threshold let remove_index = thread_rng().gen_range(0, shares.len()); shares.remove(remove_index); } // now remove one more, and recovery should fail if shares.len() > 1 { let remove_index = thread_rng().gen_range(0, shares.len()); shares.remove(remove_index); assert!(sp.recover_secret(&shares, threshold).is_err()); } Ok(()) } #[test] fn split_recover() -> Result<(), Error> { // test invalid inputs assert!(split_recover_impl(14, 3, 5).is_err()); assert!(split_recover_impl(2047, 10, 12).is_err()); assert!(split_recover_impl(16, 0, 5).is_err()); assert!(split_recover_impl(16, 5, 3).is_err()); assert!(split_recover_impl(16, 5, 0).is_err()); // test a range of thresholds let config = SplitterConfig::new(); for sc in 1..=config.max_share_count { for t in 1..=sc { split_recover_impl(16, t, sc)?; } } // test a range of lengths for sl in (16..32).step_by(2) { split_recover_impl(sl, 3, 5)?; split_recover_impl(sl, 2, 3)?; } // test a couple of nice long lengths split_recover_impl(2048, 3, 5)?; split_recover_impl(4096, 10, 16)?; Ok(()) } }
28.690852
118
0.682463
e84d42f64b98bb83f9cae890df36392dc7402e3f
740,155
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// Error type for the `AssociateApprovedOrigin` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct AssociateApprovedOriginError { /// Kind of error that occurred. pub kind: AssociateApprovedOriginErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `AssociateApprovedOrigin` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum AssociateApprovedOriginErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>A resource already has that name.</p> ResourceConflictException(crate::error::ResourceConflictException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The service quota has been exceeded.</p> ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for AssociateApprovedOriginError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { AssociateApprovedOriginErrorKind::InternalServiceException(_inner) => _inner.fmt(f), AssociateApprovedOriginErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), AssociateApprovedOriginErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), AssociateApprovedOriginErrorKind::ResourceConflictException(_inner) => _inner.fmt(f), AssociateApprovedOriginErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), AssociateApprovedOriginErrorKind::ServiceQuotaExceededException(_inner) => { _inner.fmt(f) } AssociateApprovedOriginErrorKind::ThrottlingException(_inner) => _inner.fmt(f), AssociateApprovedOriginErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for AssociateApprovedOriginError { fn code(&self) -> Option<&str> { AssociateApprovedOriginError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl AssociateApprovedOriginError { /// Creates a new `AssociateApprovedOriginError`. pub fn new(kind: AssociateApprovedOriginErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `AssociateApprovedOriginError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: AssociateApprovedOriginErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `AssociateApprovedOriginError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: AssociateApprovedOriginErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `AssociateApprovedOriginErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, AssociateApprovedOriginErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `AssociateApprovedOriginErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, AssociateApprovedOriginErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `AssociateApprovedOriginErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, AssociateApprovedOriginErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `AssociateApprovedOriginErrorKind::ResourceConflictException`. pub fn is_resource_conflict_exception(&self) -> bool { matches!( &self.kind, AssociateApprovedOriginErrorKind::ResourceConflictException(_) ) } /// Returns `true` if the error kind is `AssociateApprovedOriginErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, AssociateApprovedOriginErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `AssociateApprovedOriginErrorKind::ServiceQuotaExceededException`. pub fn is_service_quota_exceeded_exception(&self) -> bool { matches!( &self.kind, AssociateApprovedOriginErrorKind::ServiceQuotaExceededException(_) ) } /// Returns `true` if the error kind is `AssociateApprovedOriginErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, AssociateApprovedOriginErrorKind::ThrottlingException(_) ) } } impl std::error::Error for AssociateApprovedOriginError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { AssociateApprovedOriginErrorKind::InternalServiceException(_inner) => Some(_inner), AssociateApprovedOriginErrorKind::InvalidParameterException(_inner) => Some(_inner), AssociateApprovedOriginErrorKind::InvalidRequestException(_inner) => Some(_inner), AssociateApprovedOriginErrorKind::ResourceConflictException(_inner) => Some(_inner), AssociateApprovedOriginErrorKind::ResourceNotFoundException(_inner) => Some(_inner), AssociateApprovedOriginErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner), AssociateApprovedOriginErrorKind::ThrottlingException(_inner) => Some(_inner), AssociateApprovedOriginErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `AssociateBot` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct AssociateBotError { /// Kind of error that occurred. pub kind: AssociateBotErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `AssociateBot` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum AssociateBotErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>A resource already has that name.</p> ResourceConflictException(crate::error::ResourceConflictException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The service quota has been exceeded.</p> ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for AssociateBotError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { AssociateBotErrorKind::InternalServiceException(_inner) => _inner.fmt(f), AssociateBotErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), AssociateBotErrorKind::LimitExceededException(_inner) => _inner.fmt(f), AssociateBotErrorKind::ResourceConflictException(_inner) => _inner.fmt(f), AssociateBotErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), AssociateBotErrorKind::ServiceQuotaExceededException(_inner) => _inner.fmt(f), AssociateBotErrorKind::ThrottlingException(_inner) => _inner.fmt(f), AssociateBotErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for AssociateBotError { fn code(&self) -> Option<&str> { AssociateBotError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl AssociateBotError { /// Creates a new `AssociateBotError`. pub fn new(kind: AssociateBotErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `AssociateBotError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: AssociateBotErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `AssociateBotError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: AssociateBotErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `AssociateBotErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, AssociateBotErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `AssociateBotErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, AssociateBotErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `AssociateBotErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!(&self.kind, AssociateBotErrorKind::LimitExceededException(_)) } /// Returns `true` if the error kind is `AssociateBotErrorKind::ResourceConflictException`. pub fn is_resource_conflict_exception(&self) -> bool { matches!( &self.kind, AssociateBotErrorKind::ResourceConflictException(_) ) } /// Returns `true` if the error kind is `AssociateBotErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, AssociateBotErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `AssociateBotErrorKind::ServiceQuotaExceededException`. pub fn is_service_quota_exceeded_exception(&self) -> bool { matches!( &self.kind, AssociateBotErrorKind::ServiceQuotaExceededException(_) ) } /// Returns `true` if the error kind is `AssociateBotErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, AssociateBotErrorKind::ThrottlingException(_)) } } impl std::error::Error for AssociateBotError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { AssociateBotErrorKind::InternalServiceException(_inner) => Some(_inner), AssociateBotErrorKind::InvalidRequestException(_inner) => Some(_inner), AssociateBotErrorKind::LimitExceededException(_inner) => Some(_inner), AssociateBotErrorKind::ResourceConflictException(_inner) => Some(_inner), AssociateBotErrorKind::ResourceNotFoundException(_inner) => Some(_inner), AssociateBotErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner), AssociateBotErrorKind::ThrottlingException(_inner) => Some(_inner), AssociateBotErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `AssociateInstanceStorageConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct AssociateInstanceStorageConfigError { /// Kind of error that occurred. pub kind: AssociateInstanceStorageConfigErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `AssociateInstanceStorageConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum AssociateInstanceStorageConfigErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>A resource already has that name.</p> ResourceConflictException(crate::error::ResourceConflictException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for AssociateInstanceStorageConfigError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { AssociateInstanceStorageConfigErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } AssociateInstanceStorageConfigErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } AssociateInstanceStorageConfigErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } AssociateInstanceStorageConfigErrorKind::ResourceConflictException(_inner) => { _inner.fmt(f) } AssociateInstanceStorageConfigErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } AssociateInstanceStorageConfigErrorKind::ThrottlingException(_inner) => _inner.fmt(f), AssociateInstanceStorageConfigErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for AssociateInstanceStorageConfigError { fn code(&self) -> Option<&str> { AssociateInstanceStorageConfigError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl AssociateInstanceStorageConfigError { /// Creates a new `AssociateInstanceStorageConfigError`. pub fn new( kind: AssociateInstanceStorageConfigErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `AssociateInstanceStorageConfigError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: AssociateInstanceStorageConfigErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `AssociateInstanceStorageConfigError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: AssociateInstanceStorageConfigErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `AssociateInstanceStorageConfigErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, AssociateInstanceStorageConfigErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `AssociateInstanceStorageConfigErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, AssociateInstanceStorageConfigErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `AssociateInstanceStorageConfigErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, AssociateInstanceStorageConfigErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `AssociateInstanceStorageConfigErrorKind::ResourceConflictException`. pub fn is_resource_conflict_exception(&self) -> bool { matches!( &self.kind, AssociateInstanceStorageConfigErrorKind::ResourceConflictException(_) ) } /// Returns `true` if the error kind is `AssociateInstanceStorageConfigErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, AssociateInstanceStorageConfigErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `AssociateInstanceStorageConfigErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, AssociateInstanceStorageConfigErrorKind::ThrottlingException(_) ) } } impl std::error::Error for AssociateInstanceStorageConfigError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { AssociateInstanceStorageConfigErrorKind::InternalServiceException(_inner) => { Some(_inner) } AssociateInstanceStorageConfigErrorKind::InvalidParameterException(_inner) => { Some(_inner) } AssociateInstanceStorageConfigErrorKind::InvalidRequestException(_inner) => { Some(_inner) } AssociateInstanceStorageConfigErrorKind::ResourceConflictException(_inner) => { Some(_inner) } AssociateInstanceStorageConfigErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } AssociateInstanceStorageConfigErrorKind::ThrottlingException(_inner) => Some(_inner), AssociateInstanceStorageConfigErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `AssociateLambdaFunction` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct AssociateLambdaFunctionError { /// Kind of error that occurred. pub kind: AssociateLambdaFunctionErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `AssociateLambdaFunction` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum AssociateLambdaFunctionErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>A resource already has that name.</p> ResourceConflictException(crate::error::ResourceConflictException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The service quota has been exceeded.</p> ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for AssociateLambdaFunctionError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { AssociateLambdaFunctionErrorKind::InternalServiceException(_inner) => _inner.fmt(f), AssociateLambdaFunctionErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), AssociateLambdaFunctionErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), AssociateLambdaFunctionErrorKind::ResourceConflictException(_inner) => _inner.fmt(f), AssociateLambdaFunctionErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), AssociateLambdaFunctionErrorKind::ServiceQuotaExceededException(_inner) => { _inner.fmt(f) } AssociateLambdaFunctionErrorKind::ThrottlingException(_inner) => _inner.fmt(f), AssociateLambdaFunctionErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for AssociateLambdaFunctionError { fn code(&self) -> Option<&str> { AssociateLambdaFunctionError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl AssociateLambdaFunctionError { /// Creates a new `AssociateLambdaFunctionError`. pub fn new(kind: AssociateLambdaFunctionErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `AssociateLambdaFunctionError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: AssociateLambdaFunctionErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `AssociateLambdaFunctionError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: AssociateLambdaFunctionErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `AssociateLambdaFunctionErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, AssociateLambdaFunctionErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `AssociateLambdaFunctionErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, AssociateLambdaFunctionErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `AssociateLambdaFunctionErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, AssociateLambdaFunctionErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `AssociateLambdaFunctionErrorKind::ResourceConflictException`. pub fn is_resource_conflict_exception(&self) -> bool { matches!( &self.kind, AssociateLambdaFunctionErrorKind::ResourceConflictException(_) ) } /// Returns `true` if the error kind is `AssociateLambdaFunctionErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, AssociateLambdaFunctionErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `AssociateLambdaFunctionErrorKind::ServiceQuotaExceededException`. pub fn is_service_quota_exceeded_exception(&self) -> bool { matches!( &self.kind, AssociateLambdaFunctionErrorKind::ServiceQuotaExceededException(_) ) } /// Returns `true` if the error kind is `AssociateLambdaFunctionErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, AssociateLambdaFunctionErrorKind::ThrottlingException(_) ) } } impl std::error::Error for AssociateLambdaFunctionError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { AssociateLambdaFunctionErrorKind::InternalServiceException(_inner) => Some(_inner), AssociateLambdaFunctionErrorKind::InvalidParameterException(_inner) => Some(_inner), AssociateLambdaFunctionErrorKind::InvalidRequestException(_inner) => Some(_inner), AssociateLambdaFunctionErrorKind::ResourceConflictException(_inner) => Some(_inner), AssociateLambdaFunctionErrorKind::ResourceNotFoundException(_inner) => Some(_inner), AssociateLambdaFunctionErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner), AssociateLambdaFunctionErrorKind::ThrottlingException(_inner) => Some(_inner), AssociateLambdaFunctionErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `AssociateLexBot` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct AssociateLexBotError { /// Kind of error that occurred. pub kind: AssociateLexBotErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `AssociateLexBot` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum AssociateLexBotErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>A resource already has that name.</p> ResourceConflictException(crate::error::ResourceConflictException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The service quota has been exceeded.</p> ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for AssociateLexBotError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { AssociateLexBotErrorKind::InternalServiceException(_inner) => _inner.fmt(f), AssociateLexBotErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), AssociateLexBotErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), AssociateLexBotErrorKind::ResourceConflictException(_inner) => _inner.fmt(f), AssociateLexBotErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), AssociateLexBotErrorKind::ServiceQuotaExceededException(_inner) => _inner.fmt(f), AssociateLexBotErrorKind::ThrottlingException(_inner) => _inner.fmt(f), AssociateLexBotErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for AssociateLexBotError { fn code(&self) -> Option<&str> { AssociateLexBotError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl AssociateLexBotError { /// Creates a new `AssociateLexBotError`. pub fn new(kind: AssociateLexBotErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `AssociateLexBotError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: AssociateLexBotErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `AssociateLexBotError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: AssociateLexBotErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `AssociateLexBotErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, AssociateLexBotErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `AssociateLexBotErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, AssociateLexBotErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `AssociateLexBotErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, AssociateLexBotErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `AssociateLexBotErrorKind::ResourceConflictException`. pub fn is_resource_conflict_exception(&self) -> bool { matches!( &self.kind, AssociateLexBotErrorKind::ResourceConflictException(_) ) } /// Returns `true` if the error kind is `AssociateLexBotErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, AssociateLexBotErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `AssociateLexBotErrorKind::ServiceQuotaExceededException`. pub fn is_service_quota_exceeded_exception(&self) -> bool { matches!( &self.kind, AssociateLexBotErrorKind::ServiceQuotaExceededException(_) ) } /// Returns `true` if the error kind is `AssociateLexBotErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, AssociateLexBotErrorKind::ThrottlingException(_)) } } impl std::error::Error for AssociateLexBotError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { AssociateLexBotErrorKind::InternalServiceException(_inner) => Some(_inner), AssociateLexBotErrorKind::InvalidParameterException(_inner) => Some(_inner), AssociateLexBotErrorKind::InvalidRequestException(_inner) => Some(_inner), AssociateLexBotErrorKind::ResourceConflictException(_inner) => Some(_inner), AssociateLexBotErrorKind::ResourceNotFoundException(_inner) => Some(_inner), AssociateLexBotErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner), AssociateLexBotErrorKind::ThrottlingException(_inner) => Some(_inner), AssociateLexBotErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `AssociateQueueQuickConnects` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct AssociateQueueQuickConnectsError { /// Kind of error that occurred. pub kind: AssociateQueueQuickConnectsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `AssociateQueueQuickConnects` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum AssociateQueueQuickConnectsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for AssociateQueueQuickConnectsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { AssociateQueueQuickConnectsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), AssociateQueueQuickConnectsErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } AssociateQueueQuickConnectsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), AssociateQueueQuickConnectsErrorKind::LimitExceededException(_inner) => _inner.fmt(f), AssociateQueueQuickConnectsErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } AssociateQueueQuickConnectsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), AssociateQueueQuickConnectsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for AssociateQueueQuickConnectsError { fn code(&self) -> Option<&str> { AssociateQueueQuickConnectsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl AssociateQueueQuickConnectsError { /// Creates a new `AssociateQueueQuickConnectsError`. pub fn new(kind: AssociateQueueQuickConnectsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `AssociateQueueQuickConnectsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: AssociateQueueQuickConnectsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `AssociateQueueQuickConnectsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: AssociateQueueQuickConnectsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `AssociateQueueQuickConnectsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, AssociateQueueQuickConnectsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `AssociateQueueQuickConnectsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, AssociateQueueQuickConnectsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `AssociateQueueQuickConnectsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, AssociateQueueQuickConnectsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `AssociateQueueQuickConnectsErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, AssociateQueueQuickConnectsErrorKind::LimitExceededException(_) ) } /// Returns `true` if the error kind is `AssociateQueueQuickConnectsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, AssociateQueueQuickConnectsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `AssociateQueueQuickConnectsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, AssociateQueueQuickConnectsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for AssociateQueueQuickConnectsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { AssociateQueueQuickConnectsErrorKind::InternalServiceException(_inner) => Some(_inner), AssociateQueueQuickConnectsErrorKind::InvalidParameterException(_inner) => Some(_inner), AssociateQueueQuickConnectsErrorKind::InvalidRequestException(_inner) => Some(_inner), AssociateQueueQuickConnectsErrorKind::LimitExceededException(_inner) => Some(_inner), AssociateQueueQuickConnectsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), AssociateQueueQuickConnectsErrorKind::ThrottlingException(_inner) => Some(_inner), AssociateQueueQuickConnectsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `AssociateRoutingProfileQueues` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct AssociateRoutingProfileQueuesError { /// Kind of error that occurred. pub kind: AssociateRoutingProfileQueuesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `AssociateRoutingProfileQueues` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum AssociateRoutingProfileQueuesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for AssociateRoutingProfileQueuesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { AssociateRoutingProfileQueuesErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } AssociateRoutingProfileQueuesErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } AssociateRoutingProfileQueuesErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } AssociateRoutingProfileQueuesErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } AssociateRoutingProfileQueuesErrorKind::ThrottlingException(_inner) => _inner.fmt(f), AssociateRoutingProfileQueuesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for AssociateRoutingProfileQueuesError { fn code(&self) -> Option<&str> { AssociateRoutingProfileQueuesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl AssociateRoutingProfileQueuesError { /// Creates a new `AssociateRoutingProfileQueuesError`. pub fn new( kind: AssociateRoutingProfileQueuesErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `AssociateRoutingProfileQueuesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: AssociateRoutingProfileQueuesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `AssociateRoutingProfileQueuesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: AssociateRoutingProfileQueuesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `AssociateRoutingProfileQueuesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, AssociateRoutingProfileQueuesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `AssociateRoutingProfileQueuesErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, AssociateRoutingProfileQueuesErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `AssociateRoutingProfileQueuesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, AssociateRoutingProfileQueuesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `AssociateRoutingProfileQueuesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, AssociateRoutingProfileQueuesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `AssociateRoutingProfileQueuesErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, AssociateRoutingProfileQueuesErrorKind::ThrottlingException(_) ) } } impl std::error::Error for AssociateRoutingProfileQueuesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { AssociateRoutingProfileQueuesErrorKind::InternalServiceException(_inner) => { Some(_inner) } AssociateRoutingProfileQueuesErrorKind::InvalidParameterException(_inner) => { Some(_inner) } AssociateRoutingProfileQueuesErrorKind::InvalidRequestException(_inner) => Some(_inner), AssociateRoutingProfileQueuesErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } AssociateRoutingProfileQueuesErrorKind::ThrottlingException(_inner) => Some(_inner), AssociateRoutingProfileQueuesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `AssociateSecurityKey` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct AssociateSecurityKeyError { /// Kind of error that occurred. pub kind: AssociateSecurityKeyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `AssociateSecurityKey` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum AssociateSecurityKeyErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>A resource already has that name.</p> ResourceConflictException(crate::error::ResourceConflictException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The service quota has been exceeded.</p> ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for AssociateSecurityKeyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { AssociateSecurityKeyErrorKind::InternalServiceException(_inner) => _inner.fmt(f), AssociateSecurityKeyErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), AssociateSecurityKeyErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), AssociateSecurityKeyErrorKind::ResourceConflictException(_inner) => _inner.fmt(f), AssociateSecurityKeyErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), AssociateSecurityKeyErrorKind::ServiceQuotaExceededException(_inner) => _inner.fmt(f), AssociateSecurityKeyErrorKind::ThrottlingException(_inner) => _inner.fmt(f), AssociateSecurityKeyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for AssociateSecurityKeyError { fn code(&self) -> Option<&str> { AssociateSecurityKeyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl AssociateSecurityKeyError { /// Creates a new `AssociateSecurityKeyError`. pub fn new(kind: AssociateSecurityKeyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `AssociateSecurityKeyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: AssociateSecurityKeyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `AssociateSecurityKeyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: AssociateSecurityKeyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `AssociateSecurityKeyErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, AssociateSecurityKeyErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `AssociateSecurityKeyErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, AssociateSecurityKeyErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `AssociateSecurityKeyErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, AssociateSecurityKeyErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `AssociateSecurityKeyErrorKind::ResourceConflictException`. pub fn is_resource_conflict_exception(&self) -> bool { matches!( &self.kind, AssociateSecurityKeyErrorKind::ResourceConflictException(_) ) } /// Returns `true` if the error kind is `AssociateSecurityKeyErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, AssociateSecurityKeyErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `AssociateSecurityKeyErrorKind::ServiceQuotaExceededException`. pub fn is_service_quota_exceeded_exception(&self) -> bool { matches!( &self.kind, AssociateSecurityKeyErrorKind::ServiceQuotaExceededException(_) ) } /// Returns `true` if the error kind is `AssociateSecurityKeyErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, AssociateSecurityKeyErrorKind::ThrottlingException(_) ) } } impl std::error::Error for AssociateSecurityKeyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { AssociateSecurityKeyErrorKind::InternalServiceException(_inner) => Some(_inner), AssociateSecurityKeyErrorKind::InvalidParameterException(_inner) => Some(_inner), AssociateSecurityKeyErrorKind::InvalidRequestException(_inner) => Some(_inner), AssociateSecurityKeyErrorKind::ResourceConflictException(_inner) => Some(_inner), AssociateSecurityKeyErrorKind::ResourceNotFoundException(_inner) => Some(_inner), AssociateSecurityKeyErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner), AssociateSecurityKeyErrorKind::ThrottlingException(_inner) => Some(_inner), AssociateSecurityKeyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `CreateAgentStatus` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateAgentStatusError { /// Kind of error that occurred. pub kind: CreateAgentStatusErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateAgentStatus` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateAgentStatusErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateAgentStatusError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateAgentStatusErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), CreateAgentStatusErrorKind::InternalServiceException(_inner) => _inner.fmt(f), CreateAgentStatusErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), CreateAgentStatusErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateAgentStatusErrorKind::LimitExceededException(_inner) => _inner.fmt(f), CreateAgentStatusErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), CreateAgentStatusErrorKind::ThrottlingException(_inner) => _inner.fmt(f), CreateAgentStatusErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateAgentStatusError { fn code(&self) -> Option<&str> { CreateAgentStatusError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateAgentStatusError { /// Creates a new `CreateAgentStatusError`. pub fn new(kind: CreateAgentStatusErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateAgentStatusError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateAgentStatusErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateAgentStatusError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateAgentStatusErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateAgentStatusErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, CreateAgentStatusErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `CreateAgentStatusErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, CreateAgentStatusErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `CreateAgentStatusErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, CreateAgentStatusErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `CreateAgentStatusErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, CreateAgentStatusErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `CreateAgentStatusErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, CreateAgentStatusErrorKind::LimitExceededException(_) ) } /// Returns `true` if the error kind is `CreateAgentStatusErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateAgentStatusErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateAgentStatusErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, CreateAgentStatusErrorKind::ThrottlingException(_) ) } } impl std::error::Error for CreateAgentStatusError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateAgentStatusErrorKind::DuplicateResourceException(_inner) => Some(_inner), CreateAgentStatusErrorKind::InternalServiceException(_inner) => Some(_inner), CreateAgentStatusErrorKind::InvalidParameterException(_inner) => Some(_inner), CreateAgentStatusErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateAgentStatusErrorKind::LimitExceededException(_inner) => Some(_inner), CreateAgentStatusErrorKind::ResourceNotFoundException(_inner) => Some(_inner), CreateAgentStatusErrorKind::ThrottlingException(_inner) => Some(_inner), CreateAgentStatusErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `CreateContactFlow` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateContactFlowError { /// Kind of error that occurred. pub kind: CreateContactFlowErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateContactFlow` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateContactFlowErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The contact flow is not valid.</p> InvalidContactFlowException(crate::error::InvalidContactFlowException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateContactFlowError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateContactFlowErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), CreateContactFlowErrorKind::InternalServiceException(_inner) => _inner.fmt(f), CreateContactFlowErrorKind::InvalidContactFlowException(_inner) => _inner.fmt(f), CreateContactFlowErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), CreateContactFlowErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateContactFlowErrorKind::LimitExceededException(_inner) => _inner.fmt(f), CreateContactFlowErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), CreateContactFlowErrorKind::ThrottlingException(_inner) => _inner.fmt(f), CreateContactFlowErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateContactFlowError { fn code(&self) -> Option<&str> { CreateContactFlowError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateContactFlowError { /// Creates a new `CreateContactFlowError`. pub fn new(kind: CreateContactFlowErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateContactFlowError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateContactFlowErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateContactFlowError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateContactFlowErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateContactFlowErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, CreateContactFlowErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `CreateContactFlowErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, CreateContactFlowErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `CreateContactFlowErrorKind::InvalidContactFlowException`. pub fn is_invalid_contact_flow_exception(&self) -> bool { matches!( &self.kind, CreateContactFlowErrorKind::InvalidContactFlowException(_) ) } /// Returns `true` if the error kind is `CreateContactFlowErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, CreateContactFlowErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `CreateContactFlowErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, CreateContactFlowErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `CreateContactFlowErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, CreateContactFlowErrorKind::LimitExceededException(_) ) } /// Returns `true` if the error kind is `CreateContactFlowErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateContactFlowErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateContactFlowErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, CreateContactFlowErrorKind::ThrottlingException(_) ) } } impl std::error::Error for CreateContactFlowError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateContactFlowErrorKind::DuplicateResourceException(_inner) => Some(_inner), CreateContactFlowErrorKind::InternalServiceException(_inner) => Some(_inner), CreateContactFlowErrorKind::InvalidContactFlowException(_inner) => Some(_inner), CreateContactFlowErrorKind::InvalidParameterException(_inner) => Some(_inner), CreateContactFlowErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateContactFlowErrorKind::LimitExceededException(_inner) => Some(_inner), CreateContactFlowErrorKind::ResourceNotFoundException(_inner) => Some(_inner), CreateContactFlowErrorKind::ThrottlingException(_inner) => Some(_inner), CreateContactFlowErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `CreateHoursOfOperation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateHoursOfOperationError { /// Kind of error that occurred. pub kind: CreateHoursOfOperationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateHoursOfOperation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateHoursOfOperationErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateHoursOfOperationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateHoursOfOperationErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), CreateHoursOfOperationErrorKind::InternalServiceException(_inner) => _inner.fmt(f), CreateHoursOfOperationErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), CreateHoursOfOperationErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateHoursOfOperationErrorKind::LimitExceededException(_inner) => _inner.fmt(f), CreateHoursOfOperationErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), CreateHoursOfOperationErrorKind::ThrottlingException(_inner) => _inner.fmt(f), CreateHoursOfOperationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateHoursOfOperationError { fn code(&self) -> Option<&str> { CreateHoursOfOperationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateHoursOfOperationError { /// Creates a new `CreateHoursOfOperationError`. pub fn new(kind: CreateHoursOfOperationErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateHoursOfOperationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateHoursOfOperationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateHoursOfOperationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateHoursOfOperationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateHoursOfOperationErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, CreateHoursOfOperationErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `CreateHoursOfOperationErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, CreateHoursOfOperationErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `CreateHoursOfOperationErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, CreateHoursOfOperationErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `CreateHoursOfOperationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, CreateHoursOfOperationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `CreateHoursOfOperationErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, CreateHoursOfOperationErrorKind::LimitExceededException(_) ) } /// Returns `true` if the error kind is `CreateHoursOfOperationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateHoursOfOperationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateHoursOfOperationErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, CreateHoursOfOperationErrorKind::ThrottlingException(_) ) } } impl std::error::Error for CreateHoursOfOperationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateHoursOfOperationErrorKind::DuplicateResourceException(_inner) => Some(_inner), CreateHoursOfOperationErrorKind::InternalServiceException(_inner) => Some(_inner), CreateHoursOfOperationErrorKind::InvalidParameterException(_inner) => Some(_inner), CreateHoursOfOperationErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateHoursOfOperationErrorKind::LimitExceededException(_inner) => Some(_inner), CreateHoursOfOperationErrorKind::ResourceNotFoundException(_inner) => Some(_inner), CreateHoursOfOperationErrorKind::ThrottlingException(_inner) => Some(_inner), CreateHoursOfOperationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `CreateInstance` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateInstanceError { /// Kind of error that occurred. pub kind: CreateInstanceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateInstance` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateInstanceErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The service quota has been exceeded.</p> ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateInstanceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateInstanceErrorKind::InternalServiceException(_inner) => _inner.fmt(f), CreateInstanceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateInstanceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), CreateInstanceErrorKind::ServiceQuotaExceededException(_inner) => _inner.fmt(f), CreateInstanceErrorKind::ThrottlingException(_inner) => _inner.fmt(f), CreateInstanceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateInstanceError { fn code(&self) -> Option<&str> { CreateInstanceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateInstanceError { /// Creates a new `CreateInstanceError`. pub fn new(kind: CreateInstanceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateInstanceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateInstanceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateInstanceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateInstanceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateInstanceErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, CreateInstanceErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `CreateInstanceErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, CreateInstanceErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `CreateInstanceErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateInstanceErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateInstanceErrorKind::ServiceQuotaExceededException`. pub fn is_service_quota_exceeded_exception(&self) -> bool { matches!( &self.kind, CreateInstanceErrorKind::ServiceQuotaExceededException(_) ) } /// Returns `true` if the error kind is `CreateInstanceErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, CreateInstanceErrorKind::ThrottlingException(_)) } } impl std::error::Error for CreateInstanceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateInstanceErrorKind::InternalServiceException(_inner) => Some(_inner), CreateInstanceErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateInstanceErrorKind::ResourceNotFoundException(_inner) => Some(_inner), CreateInstanceErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner), CreateInstanceErrorKind::ThrottlingException(_inner) => Some(_inner), CreateInstanceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `CreateIntegrationAssociation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateIntegrationAssociationError { /// Kind of error that occurred. pub kind: CreateIntegrationAssociationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateIntegrationAssociation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateIntegrationAssociationErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateIntegrationAssociationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateIntegrationAssociationErrorKind::DuplicateResourceException(_inner) => { _inner.fmt(f) } CreateIntegrationAssociationErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } CreateIntegrationAssociationErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateIntegrationAssociationErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } CreateIntegrationAssociationErrorKind::ThrottlingException(_inner) => _inner.fmt(f), CreateIntegrationAssociationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateIntegrationAssociationError { fn code(&self) -> Option<&str> { CreateIntegrationAssociationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateIntegrationAssociationError { /// Creates a new `CreateIntegrationAssociationError`. pub fn new(kind: CreateIntegrationAssociationErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateIntegrationAssociationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateIntegrationAssociationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateIntegrationAssociationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateIntegrationAssociationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateIntegrationAssociationErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, CreateIntegrationAssociationErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `CreateIntegrationAssociationErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, CreateIntegrationAssociationErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `CreateIntegrationAssociationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, CreateIntegrationAssociationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `CreateIntegrationAssociationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateIntegrationAssociationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateIntegrationAssociationErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, CreateIntegrationAssociationErrorKind::ThrottlingException(_) ) } } impl std::error::Error for CreateIntegrationAssociationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateIntegrationAssociationErrorKind::DuplicateResourceException(_inner) => { Some(_inner) } CreateIntegrationAssociationErrorKind::InternalServiceException(_inner) => Some(_inner), CreateIntegrationAssociationErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateIntegrationAssociationErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } CreateIntegrationAssociationErrorKind::ThrottlingException(_inner) => Some(_inner), CreateIntegrationAssociationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `CreateQueue` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateQueueError { /// Kind of error that occurred. pub kind: CreateQueueErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateQueue` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateQueueErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateQueueError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateQueueErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), CreateQueueErrorKind::InternalServiceException(_inner) => _inner.fmt(f), CreateQueueErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), CreateQueueErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateQueueErrorKind::LimitExceededException(_inner) => _inner.fmt(f), CreateQueueErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), CreateQueueErrorKind::ThrottlingException(_inner) => _inner.fmt(f), CreateQueueErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateQueueError { fn code(&self) -> Option<&str> { CreateQueueError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateQueueError { /// Creates a new `CreateQueueError`. pub fn new(kind: CreateQueueErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateQueueError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateQueueErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateQueueError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateQueueErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateQueueErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, CreateQueueErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `CreateQueueErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, CreateQueueErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `CreateQueueErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, CreateQueueErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `CreateQueueErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, CreateQueueErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `CreateQueueErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!(&self.kind, CreateQueueErrorKind::LimitExceededException(_)) } /// Returns `true` if the error kind is `CreateQueueErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateQueueErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateQueueErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, CreateQueueErrorKind::ThrottlingException(_)) } } impl std::error::Error for CreateQueueError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateQueueErrorKind::DuplicateResourceException(_inner) => Some(_inner), CreateQueueErrorKind::InternalServiceException(_inner) => Some(_inner), CreateQueueErrorKind::InvalidParameterException(_inner) => Some(_inner), CreateQueueErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateQueueErrorKind::LimitExceededException(_inner) => Some(_inner), CreateQueueErrorKind::ResourceNotFoundException(_inner) => Some(_inner), CreateQueueErrorKind::ThrottlingException(_inner) => Some(_inner), CreateQueueErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `CreateQuickConnect` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateQuickConnectError { /// Kind of error that occurred. pub kind: CreateQuickConnectErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateQuickConnect` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateQuickConnectErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateQuickConnectError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateQuickConnectErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), CreateQuickConnectErrorKind::InternalServiceException(_inner) => _inner.fmt(f), CreateQuickConnectErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), CreateQuickConnectErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateQuickConnectErrorKind::LimitExceededException(_inner) => _inner.fmt(f), CreateQuickConnectErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), CreateQuickConnectErrorKind::ThrottlingException(_inner) => _inner.fmt(f), CreateQuickConnectErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateQuickConnectError { fn code(&self) -> Option<&str> { CreateQuickConnectError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateQuickConnectError { /// Creates a new `CreateQuickConnectError`. pub fn new(kind: CreateQuickConnectErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateQuickConnectError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateQuickConnectErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateQuickConnectError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateQuickConnectErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateQuickConnectErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, CreateQuickConnectErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `CreateQuickConnectErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, CreateQuickConnectErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `CreateQuickConnectErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, CreateQuickConnectErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `CreateQuickConnectErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, CreateQuickConnectErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `CreateQuickConnectErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, CreateQuickConnectErrorKind::LimitExceededException(_) ) } /// Returns `true` if the error kind is `CreateQuickConnectErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateQuickConnectErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateQuickConnectErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, CreateQuickConnectErrorKind::ThrottlingException(_) ) } } impl std::error::Error for CreateQuickConnectError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateQuickConnectErrorKind::DuplicateResourceException(_inner) => Some(_inner), CreateQuickConnectErrorKind::InternalServiceException(_inner) => Some(_inner), CreateQuickConnectErrorKind::InvalidParameterException(_inner) => Some(_inner), CreateQuickConnectErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateQuickConnectErrorKind::LimitExceededException(_inner) => Some(_inner), CreateQuickConnectErrorKind::ResourceNotFoundException(_inner) => Some(_inner), CreateQuickConnectErrorKind::ThrottlingException(_inner) => Some(_inner), CreateQuickConnectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `CreateRoutingProfile` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateRoutingProfileError { /// Kind of error that occurred. pub kind: CreateRoutingProfileErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateRoutingProfile` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateRoutingProfileErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateRoutingProfileError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateRoutingProfileErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), CreateRoutingProfileErrorKind::InternalServiceException(_inner) => _inner.fmt(f), CreateRoutingProfileErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), CreateRoutingProfileErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateRoutingProfileErrorKind::LimitExceededException(_inner) => _inner.fmt(f), CreateRoutingProfileErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), CreateRoutingProfileErrorKind::ThrottlingException(_inner) => _inner.fmt(f), CreateRoutingProfileErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateRoutingProfileError { fn code(&self) -> Option<&str> { CreateRoutingProfileError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateRoutingProfileError { /// Creates a new `CreateRoutingProfileError`. pub fn new(kind: CreateRoutingProfileErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateRoutingProfileError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateRoutingProfileErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateRoutingProfileError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateRoutingProfileErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateRoutingProfileErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, CreateRoutingProfileErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `CreateRoutingProfileErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, CreateRoutingProfileErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `CreateRoutingProfileErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, CreateRoutingProfileErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `CreateRoutingProfileErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, CreateRoutingProfileErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `CreateRoutingProfileErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, CreateRoutingProfileErrorKind::LimitExceededException(_) ) } /// Returns `true` if the error kind is `CreateRoutingProfileErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateRoutingProfileErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateRoutingProfileErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, CreateRoutingProfileErrorKind::ThrottlingException(_) ) } } impl std::error::Error for CreateRoutingProfileError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateRoutingProfileErrorKind::DuplicateResourceException(_inner) => Some(_inner), CreateRoutingProfileErrorKind::InternalServiceException(_inner) => Some(_inner), CreateRoutingProfileErrorKind::InvalidParameterException(_inner) => Some(_inner), CreateRoutingProfileErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateRoutingProfileErrorKind::LimitExceededException(_inner) => Some(_inner), CreateRoutingProfileErrorKind::ResourceNotFoundException(_inner) => Some(_inner), CreateRoutingProfileErrorKind::ThrottlingException(_inner) => Some(_inner), CreateRoutingProfileErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `CreateUseCase` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateUseCaseError { /// Kind of error that occurred. pub kind: CreateUseCaseErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateUseCase` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateUseCaseErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateUseCaseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateUseCaseErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), CreateUseCaseErrorKind::InternalServiceException(_inner) => _inner.fmt(f), CreateUseCaseErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateUseCaseErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), CreateUseCaseErrorKind::ThrottlingException(_inner) => _inner.fmt(f), CreateUseCaseErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateUseCaseError { fn code(&self) -> Option<&str> { CreateUseCaseError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateUseCaseError { /// Creates a new `CreateUseCaseError`. pub fn new(kind: CreateUseCaseErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateUseCaseError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateUseCaseErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateUseCaseError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateUseCaseErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateUseCaseErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, CreateUseCaseErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `CreateUseCaseErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, CreateUseCaseErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `CreateUseCaseErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, CreateUseCaseErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `CreateUseCaseErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateUseCaseErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateUseCaseErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, CreateUseCaseErrorKind::ThrottlingException(_)) } } impl std::error::Error for CreateUseCaseError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateUseCaseErrorKind::DuplicateResourceException(_inner) => Some(_inner), CreateUseCaseErrorKind::InternalServiceException(_inner) => Some(_inner), CreateUseCaseErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateUseCaseErrorKind::ResourceNotFoundException(_inner) => Some(_inner), CreateUseCaseErrorKind::ThrottlingException(_inner) => Some(_inner), CreateUseCaseErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `CreateUser` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateUserError { /// Kind of error that occurred. pub kind: CreateUserErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateUser` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateUserErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateUserError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateUserErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), CreateUserErrorKind::InternalServiceException(_inner) => _inner.fmt(f), CreateUserErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), CreateUserErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateUserErrorKind::LimitExceededException(_inner) => _inner.fmt(f), CreateUserErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), CreateUserErrorKind::ThrottlingException(_inner) => _inner.fmt(f), CreateUserErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateUserError { fn code(&self) -> Option<&str> { CreateUserError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateUserError { /// Creates a new `CreateUserError`. pub fn new(kind: CreateUserErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateUserError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateUserErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateUserError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateUserErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateUserErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, CreateUserErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `CreateUserErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!(&self.kind, CreateUserErrorKind::InternalServiceException(_)) } /// Returns `true` if the error kind is `CreateUserErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, CreateUserErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `CreateUserErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, CreateUserErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `CreateUserErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!(&self.kind, CreateUserErrorKind::LimitExceededException(_)) } /// Returns `true` if the error kind is `CreateUserErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateUserErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateUserErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, CreateUserErrorKind::ThrottlingException(_)) } } impl std::error::Error for CreateUserError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateUserErrorKind::DuplicateResourceException(_inner) => Some(_inner), CreateUserErrorKind::InternalServiceException(_inner) => Some(_inner), CreateUserErrorKind::InvalidParameterException(_inner) => Some(_inner), CreateUserErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateUserErrorKind::LimitExceededException(_inner) => Some(_inner), CreateUserErrorKind::ResourceNotFoundException(_inner) => Some(_inner), CreateUserErrorKind::ThrottlingException(_inner) => Some(_inner), CreateUserErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `CreateUserHierarchyGroup` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct CreateUserHierarchyGroupError { /// Kind of error that occurred. pub kind: CreateUserHierarchyGroupErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `CreateUserHierarchyGroup` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum CreateUserHierarchyGroupErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for CreateUserHierarchyGroupError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { CreateUserHierarchyGroupErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), CreateUserHierarchyGroupErrorKind::InternalServiceException(_inner) => _inner.fmt(f), CreateUserHierarchyGroupErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), CreateUserHierarchyGroupErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), CreateUserHierarchyGroupErrorKind::LimitExceededException(_inner) => _inner.fmt(f), CreateUserHierarchyGroupErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), CreateUserHierarchyGroupErrorKind::ThrottlingException(_inner) => _inner.fmt(f), CreateUserHierarchyGroupErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for CreateUserHierarchyGroupError { fn code(&self) -> Option<&str> { CreateUserHierarchyGroupError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl CreateUserHierarchyGroupError { /// Creates a new `CreateUserHierarchyGroupError`. pub fn new(kind: CreateUserHierarchyGroupErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `CreateUserHierarchyGroupError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: CreateUserHierarchyGroupErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `CreateUserHierarchyGroupError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: CreateUserHierarchyGroupErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `CreateUserHierarchyGroupErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, CreateUserHierarchyGroupErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `CreateUserHierarchyGroupErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, CreateUserHierarchyGroupErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `CreateUserHierarchyGroupErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, CreateUserHierarchyGroupErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `CreateUserHierarchyGroupErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, CreateUserHierarchyGroupErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `CreateUserHierarchyGroupErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, CreateUserHierarchyGroupErrorKind::LimitExceededException(_) ) } /// Returns `true` if the error kind is `CreateUserHierarchyGroupErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, CreateUserHierarchyGroupErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `CreateUserHierarchyGroupErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, CreateUserHierarchyGroupErrorKind::ThrottlingException(_) ) } } impl std::error::Error for CreateUserHierarchyGroupError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { CreateUserHierarchyGroupErrorKind::DuplicateResourceException(_inner) => Some(_inner), CreateUserHierarchyGroupErrorKind::InternalServiceException(_inner) => Some(_inner), CreateUserHierarchyGroupErrorKind::InvalidParameterException(_inner) => Some(_inner), CreateUserHierarchyGroupErrorKind::InvalidRequestException(_inner) => Some(_inner), CreateUserHierarchyGroupErrorKind::LimitExceededException(_inner) => Some(_inner), CreateUserHierarchyGroupErrorKind::ResourceNotFoundException(_inner) => Some(_inner), CreateUserHierarchyGroupErrorKind::ThrottlingException(_inner) => Some(_inner), CreateUserHierarchyGroupErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteHoursOfOperation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteHoursOfOperationError { /// Kind of error that occurred. pub kind: DeleteHoursOfOperationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteHoursOfOperation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteHoursOfOperationErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteHoursOfOperationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteHoursOfOperationErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DeleteHoursOfOperationErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DeleteHoursOfOperationErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DeleteHoursOfOperationErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DeleteHoursOfOperationErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DeleteHoursOfOperationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteHoursOfOperationError { fn code(&self) -> Option<&str> { DeleteHoursOfOperationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteHoursOfOperationError { /// Creates a new `DeleteHoursOfOperationError`. pub fn new(kind: DeleteHoursOfOperationErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteHoursOfOperationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteHoursOfOperationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteHoursOfOperationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteHoursOfOperationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteHoursOfOperationErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DeleteHoursOfOperationErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DeleteHoursOfOperationErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DeleteHoursOfOperationErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DeleteHoursOfOperationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DeleteHoursOfOperationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DeleteHoursOfOperationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteHoursOfOperationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteHoursOfOperationErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DeleteHoursOfOperationErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DeleteHoursOfOperationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteHoursOfOperationErrorKind::InternalServiceException(_inner) => Some(_inner), DeleteHoursOfOperationErrorKind::InvalidParameterException(_inner) => Some(_inner), DeleteHoursOfOperationErrorKind::InvalidRequestException(_inner) => Some(_inner), DeleteHoursOfOperationErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DeleteHoursOfOperationErrorKind::ThrottlingException(_inner) => Some(_inner), DeleteHoursOfOperationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteInstance` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteInstanceError { /// Kind of error that occurred. pub kind: DeleteInstanceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteInstance` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteInstanceErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteInstanceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteInstanceErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DeleteInstanceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DeleteInstanceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DeleteInstanceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteInstanceError { fn code(&self) -> Option<&str> { DeleteInstanceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteInstanceError { /// Creates a new `DeleteInstanceError`. pub fn new(kind: DeleteInstanceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteInstanceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteInstanceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteInstanceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteInstanceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteInstanceErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DeleteInstanceErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DeleteInstanceErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DeleteInstanceErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DeleteInstanceErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteInstanceErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for DeleteInstanceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteInstanceErrorKind::InternalServiceException(_inner) => Some(_inner), DeleteInstanceErrorKind::InvalidRequestException(_inner) => Some(_inner), DeleteInstanceErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DeleteInstanceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteIntegrationAssociation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteIntegrationAssociationError { /// Kind of error that occurred. pub kind: DeleteIntegrationAssociationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteIntegrationAssociation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteIntegrationAssociationErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteIntegrationAssociationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteIntegrationAssociationErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } DeleteIntegrationAssociationErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DeleteIntegrationAssociationErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DeleteIntegrationAssociationErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DeleteIntegrationAssociationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteIntegrationAssociationError { fn code(&self) -> Option<&str> { DeleteIntegrationAssociationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteIntegrationAssociationError { /// Creates a new `DeleteIntegrationAssociationError`. pub fn new(kind: DeleteIntegrationAssociationErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteIntegrationAssociationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteIntegrationAssociationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteIntegrationAssociationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteIntegrationAssociationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteIntegrationAssociationErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DeleteIntegrationAssociationErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DeleteIntegrationAssociationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DeleteIntegrationAssociationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DeleteIntegrationAssociationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteIntegrationAssociationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteIntegrationAssociationErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DeleteIntegrationAssociationErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DeleteIntegrationAssociationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteIntegrationAssociationErrorKind::InternalServiceException(_inner) => Some(_inner), DeleteIntegrationAssociationErrorKind::InvalidRequestException(_inner) => Some(_inner), DeleteIntegrationAssociationErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DeleteIntegrationAssociationErrorKind::ThrottlingException(_inner) => Some(_inner), DeleteIntegrationAssociationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteQuickConnect` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteQuickConnectError { /// Kind of error that occurred. pub kind: DeleteQuickConnectErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteQuickConnect` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteQuickConnectErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteQuickConnectError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteQuickConnectErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DeleteQuickConnectErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DeleteQuickConnectErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DeleteQuickConnectErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DeleteQuickConnectErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DeleteQuickConnectErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteQuickConnectError { fn code(&self) -> Option<&str> { DeleteQuickConnectError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteQuickConnectError { /// Creates a new `DeleteQuickConnectError`. pub fn new(kind: DeleteQuickConnectErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteQuickConnectError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteQuickConnectErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteQuickConnectError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteQuickConnectErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteQuickConnectErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DeleteQuickConnectErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DeleteQuickConnectErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DeleteQuickConnectErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DeleteQuickConnectErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DeleteQuickConnectErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DeleteQuickConnectErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteQuickConnectErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteQuickConnectErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DeleteQuickConnectErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DeleteQuickConnectError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteQuickConnectErrorKind::InternalServiceException(_inner) => Some(_inner), DeleteQuickConnectErrorKind::InvalidParameterException(_inner) => Some(_inner), DeleteQuickConnectErrorKind::InvalidRequestException(_inner) => Some(_inner), DeleteQuickConnectErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DeleteQuickConnectErrorKind::ThrottlingException(_inner) => Some(_inner), DeleteQuickConnectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteUseCase` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteUseCaseError { /// Kind of error that occurred. pub kind: DeleteUseCaseErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteUseCase` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteUseCaseErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteUseCaseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteUseCaseErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DeleteUseCaseErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DeleteUseCaseErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DeleteUseCaseErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DeleteUseCaseErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteUseCaseError { fn code(&self) -> Option<&str> { DeleteUseCaseError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteUseCaseError { /// Creates a new `DeleteUseCaseError`. pub fn new(kind: DeleteUseCaseErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteUseCaseError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteUseCaseErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteUseCaseError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteUseCaseErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteUseCaseErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DeleteUseCaseErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DeleteUseCaseErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DeleteUseCaseErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DeleteUseCaseErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteUseCaseErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteUseCaseErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, DeleteUseCaseErrorKind::ThrottlingException(_)) } } impl std::error::Error for DeleteUseCaseError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteUseCaseErrorKind::InternalServiceException(_inner) => Some(_inner), DeleteUseCaseErrorKind::InvalidRequestException(_inner) => Some(_inner), DeleteUseCaseErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DeleteUseCaseErrorKind::ThrottlingException(_inner) => Some(_inner), DeleteUseCaseErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteUser` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteUserError { /// Kind of error that occurred. pub kind: DeleteUserErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteUser` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteUserErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteUserError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteUserErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DeleteUserErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DeleteUserErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DeleteUserErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DeleteUserErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DeleteUserErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteUserError { fn code(&self) -> Option<&str> { DeleteUserError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteUserError { /// Creates a new `DeleteUserError`. pub fn new(kind: DeleteUserErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteUserError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteUserErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteUserError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteUserErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteUserErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!(&self.kind, DeleteUserErrorKind::InternalServiceException(_)) } /// Returns `true` if the error kind is `DeleteUserErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DeleteUserErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DeleteUserErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, DeleteUserErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `DeleteUserErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteUserErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteUserErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, DeleteUserErrorKind::ThrottlingException(_)) } } impl std::error::Error for DeleteUserError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteUserErrorKind::InternalServiceException(_inner) => Some(_inner), DeleteUserErrorKind::InvalidParameterException(_inner) => Some(_inner), DeleteUserErrorKind::InvalidRequestException(_inner) => Some(_inner), DeleteUserErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DeleteUserErrorKind::ThrottlingException(_inner) => Some(_inner), DeleteUserErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DeleteUserHierarchyGroup` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DeleteUserHierarchyGroupError { /// Kind of error that occurred. pub kind: DeleteUserHierarchyGroupErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DeleteUserHierarchyGroup` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DeleteUserHierarchyGroupErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>That resource is already in use. Please try another.</p> ResourceInUseException(crate::error::ResourceInUseException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DeleteUserHierarchyGroupError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DeleteUserHierarchyGroupErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DeleteUserHierarchyGroupErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DeleteUserHierarchyGroupErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DeleteUserHierarchyGroupErrorKind::ResourceInUseException(_inner) => _inner.fmt(f), DeleteUserHierarchyGroupErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DeleteUserHierarchyGroupErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DeleteUserHierarchyGroupErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DeleteUserHierarchyGroupError { fn code(&self) -> Option<&str> { DeleteUserHierarchyGroupError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DeleteUserHierarchyGroupError { /// Creates a new `DeleteUserHierarchyGroupError`. pub fn new(kind: DeleteUserHierarchyGroupErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DeleteUserHierarchyGroupError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DeleteUserHierarchyGroupErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DeleteUserHierarchyGroupError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DeleteUserHierarchyGroupErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DeleteUserHierarchyGroupErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DeleteUserHierarchyGroupErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DeleteUserHierarchyGroupErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DeleteUserHierarchyGroupErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DeleteUserHierarchyGroupErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DeleteUserHierarchyGroupErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DeleteUserHierarchyGroupErrorKind::ResourceInUseException`. pub fn is_resource_in_use_exception(&self) -> bool { matches!( &self.kind, DeleteUserHierarchyGroupErrorKind::ResourceInUseException(_) ) } /// Returns `true` if the error kind is `DeleteUserHierarchyGroupErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DeleteUserHierarchyGroupErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DeleteUserHierarchyGroupErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DeleteUserHierarchyGroupErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DeleteUserHierarchyGroupError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DeleteUserHierarchyGroupErrorKind::InternalServiceException(_inner) => Some(_inner), DeleteUserHierarchyGroupErrorKind::InvalidParameterException(_inner) => Some(_inner), DeleteUserHierarchyGroupErrorKind::InvalidRequestException(_inner) => Some(_inner), DeleteUserHierarchyGroupErrorKind::ResourceInUseException(_inner) => Some(_inner), DeleteUserHierarchyGroupErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DeleteUserHierarchyGroupErrorKind::ThrottlingException(_inner) => Some(_inner), DeleteUserHierarchyGroupErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeAgentStatus` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeAgentStatusError { /// Kind of error that occurred. pub kind: DescribeAgentStatusErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeAgentStatus` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeAgentStatusErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeAgentStatusError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeAgentStatusErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DescribeAgentStatusErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DescribeAgentStatusErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeAgentStatusErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeAgentStatusErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DescribeAgentStatusErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeAgentStatusError { fn code(&self) -> Option<&str> { DescribeAgentStatusError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeAgentStatusError { /// Creates a new `DescribeAgentStatusError`. pub fn new(kind: DescribeAgentStatusErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeAgentStatusError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeAgentStatusErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeAgentStatusError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeAgentStatusErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeAgentStatusErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeAgentStatusErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeAgentStatusErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DescribeAgentStatusErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DescribeAgentStatusErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeAgentStatusErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeAgentStatusErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeAgentStatusErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeAgentStatusErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DescribeAgentStatusErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DescribeAgentStatusError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeAgentStatusErrorKind::InternalServiceException(_inner) => Some(_inner), DescribeAgentStatusErrorKind::InvalidParameterException(_inner) => Some(_inner), DescribeAgentStatusErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeAgentStatusErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeAgentStatusErrorKind::ThrottlingException(_inner) => Some(_inner), DescribeAgentStatusErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeContactFlow` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeContactFlowError { /// Kind of error that occurred. pub kind: DescribeContactFlowErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeContactFlow` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeContactFlowErrorKind { /// <p>The contact flow has not been published.</p> ContactFlowNotPublishedException(crate::error::ContactFlowNotPublishedException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeContactFlowError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeContactFlowErrorKind::ContactFlowNotPublishedException(_inner) => _inner.fmt(f), DescribeContactFlowErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DescribeContactFlowErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DescribeContactFlowErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeContactFlowErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeContactFlowErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DescribeContactFlowErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeContactFlowError { fn code(&self) -> Option<&str> { DescribeContactFlowError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeContactFlowError { /// Creates a new `DescribeContactFlowError`. pub fn new(kind: DescribeContactFlowErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeContactFlowError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeContactFlowErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeContactFlowError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeContactFlowErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeContactFlowErrorKind::ContactFlowNotPublishedException`. pub fn is_contact_flow_not_published_exception(&self) -> bool { matches!( &self.kind, DescribeContactFlowErrorKind::ContactFlowNotPublishedException(_) ) } /// Returns `true` if the error kind is `DescribeContactFlowErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeContactFlowErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeContactFlowErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DescribeContactFlowErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DescribeContactFlowErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeContactFlowErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeContactFlowErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeContactFlowErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeContactFlowErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DescribeContactFlowErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DescribeContactFlowError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeContactFlowErrorKind::ContactFlowNotPublishedException(_inner) => Some(_inner), DescribeContactFlowErrorKind::InternalServiceException(_inner) => Some(_inner), DescribeContactFlowErrorKind::InvalidParameterException(_inner) => Some(_inner), DescribeContactFlowErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeContactFlowErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeContactFlowErrorKind::ThrottlingException(_inner) => Some(_inner), DescribeContactFlowErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeHoursOfOperation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeHoursOfOperationError { /// Kind of error that occurred. pub kind: DescribeHoursOfOperationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeHoursOfOperation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeHoursOfOperationErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeHoursOfOperationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeHoursOfOperationErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DescribeHoursOfOperationErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DescribeHoursOfOperationErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeHoursOfOperationErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeHoursOfOperationErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DescribeHoursOfOperationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeHoursOfOperationError { fn code(&self) -> Option<&str> { DescribeHoursOfOperationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeHoursOfOperationError { /// Creates a new `DescribeHoursOfOperationError`. pub fn new(kind: DescribeHoursOfOperationErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeHoursOfOperationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeHoursOfOperationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeHoursOfOperationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeHoursOfOperationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeHoursOfOperationErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeHoursOfOperationErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeHoursOfOperationErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DescribeHoursOfOperationErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DescribeHoursOfOperationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeHoursOfOperationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeHoursOfOperationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeHoursOfOperationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeHoursOfOperationErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DescribeHoursOfOperationErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DescribeHoursOfOperationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeHoursOfOperationErrorKind::InternalServiceException(_inner) => Some(_inner), DescribeHoursOfOperationErrorKind::InvalidParameterException(_inner) => Some(_inner), DescribeHoursOfOperationErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeHoursOfOperationErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeHoursOfOperationErrorKind::ThrottlingException(_inner) => Some(_inner), DescribeHoursOfOperationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeInstance` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeInstanceError { /// Kind of error that occurred. pub kind: DescribeInstanceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeInstance` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeInstanceErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeInstanceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeInstanceErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DescribeInstanceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeInstanceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeInstanceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeInstanceError { fn code(&self) -> Option<&str> { DescribeInstanceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeInstanceError { /// Creates a new `DescribeInstanceError`. pub fn new(kind: DescribeInstanceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeInstanceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeInstanceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeInstanceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeInstanceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeInstanceErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeInstanceErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeInstanceErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for DescribeInstanceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeInstanceErrorKind::InternalServiceException(_inner) => Some(_inner), DescribeInstanceErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeInstanceErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeInstanceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeInstanceAttribute` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeInstanceAttributeError { /// Kind of error that occurred. pub kind: DescribeInstanceAttributeErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeInstanceAttribute` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeInstanceAttributeErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeInstanceAttributeError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeInstanceAttributeErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DescribeInstanceAttributeErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DescribeInstanceAttributeErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeInstanceAttributeErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeInstanceAttributeErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DescribeInstanceAttributeErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeInstanceAttributeError { fn code(&self) -> Option<&str> { DescribeInstanceAttributeError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeInstanceAttributeError { /// Creates a new `DescribeInstanceAttributeError`. pub fn new(kind: DescribeInstanceAttributeErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeInstanceAttributeError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeInstanceAttributeErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeInstanceAttributeError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeInstanceAttributeErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeInstanceAttributeErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceAttributeErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeInstanceAttributeErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceAttributeErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DescribeInstanceAttributeErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceAttributeErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeInstanceAttributeErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceAttributeErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeInstanceAttributeErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceAttributeErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DescribeInstanceAttributeError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeInstanceAttributeErrorKind::InternalServiceException(_inner) => Some(_inner), DescribeInstanceAttributeErrorKind::InvalidParameterException(_inner) => Some(_inner), DescribeInstanceAttributeErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeInstanceAttributeErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeInstanceAttributeErrorKind::ThrottlingException(_inner) => Some(_inner), DescribeInstanceAttributeErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeInstanceStorageConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeInstanceStorageConfigError { /// Kind of error that occurred. pub kind: DescribeInstanceStorageConfigErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeInstanceStorageConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeInstanceStorageConfigErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeInstanceStorageConfigError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeInstanceStorageConfigErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } DescribeInstanceStorageConfigErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } DescribeInstanceStorageConfigErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DescribeInstanceStorageConfigErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DescribeInstanceStorageConfigErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DescribeInstanceStorageConfigErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeInstanceStorageConfigError { fn code(&self) -> Option<&str> { DescribeInstanceStorageConfigError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeInstanceStorageConfigError { /// Creates a new `DescribeInstanceStorageConfigError`. pub fn new( kind: DescribeInstanceStorageConfigErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DescribeInstanceStorageConfigError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeInstanceStorageConfigErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeInstanceStorageConfigError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeInstanceStorageConfigErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeInstanceStorageConfigErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceStorageConfigErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeInstanceStorageConfigErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceStorageConfigErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DescribeInstanceStorageConfigErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceStorageConfigErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeInstanceStorageConfigErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceStorageConfigErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeInstanceStorageConfigErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DescribeInstanceStorageConfigErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DescribeInstanceStorageConfigError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeInstanceStorageConfigErrorKind::InternalServiceException(_inner) => { Some(_inner) } DescribeInstanceStorageConfigErrorKind::InvalidParameterException(_inner) => { Some(_inner) } DescribeInstanceStorageConfigErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeInstanceStorageConfigErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DescribeInstanceStorageConfigErrorKind::ThrottlingException(_inner) => Some(_inner), DescribeInstanceStorageConfigErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeQueue` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeQueueError { /// Kind of error that occurred. pub kind: DescribeQueueErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeQueue` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeQueueErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeQueueError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeQueueErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DescribeQueueErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DescribeQueueErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeQueueErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeQueueErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DescribeQueueErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeQueueError { fn code(&self) -> Option<&str> { DescribeQueueError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeQueueError { /// Creates a new `DescribeQueueError`. pub fn new(kind: DescribeQueueErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeQueueError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeQueueErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeQueueError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeQueueErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeQueueErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeQueueErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeQueueErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DescribeQueueErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DescribeQueueErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeQueueErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeQueueErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeQueueErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeQueueErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, DescribeQueueErrorKind::ThrottlingException(_)) } } impl std::error::Error for DescribeQueueError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeQueueErrorKind::InternalServiceException(_inner) => Some(_inner), DescribeQueueErrorKind::InvalidParameterException(_inner) => Some(_inner), DescribeQueueErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeQueueErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeQueueErrorKind::ThrottlingException(_inner) => Some(_inner), DescribeQueueErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeQuickConnect` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeQuickConnectError { /// Kind of error that occurred. pub kind: DescribeQuickConnectErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeQuickConnect` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeQuickConnectErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeQuickConnectError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeQuickConnectErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DescribeQuickConnectErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DescribeQuickConnectErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeQuickConnectErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeQuickConnectErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DescribeQuickConnectErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeQuickConnectError { fn code(&self) -> Option<&str> { DescribeQuickConnectError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeQuickConnectError { /// Creates a new `DescribeQuickConnectError`. pub fn new(kind: DescribeQuickConnectErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeQuickConnectError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeQuickConnectErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeQuickConnectError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeQuickConnectErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeQuickConnectErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeQuickConnectErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeQuickConnectErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DescribeQuickConnectErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DescribeQuickConnectErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeQuickConnectErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeQuickConnectErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeQuickConnectErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeQuickConnectErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DescribeQuickConnectErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DescribeQuickConnectError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeQuickConnectErrorKind::InternalServiceException(_inner) => Some(_inner), DescribeQuickConnectErrorKind::InvalidParameterException(_inner) => Some(_inner), DescribeQuickConnectErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeQuickConnectErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeQuickConnectErrorKind::ThrottlingException(_inner) => Some(_inner), DescribeQuickConnectErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeRoutingProfile` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeRoutingProfileError { /// Kind of error that occurred. pub kind: DescribeRoutingProfileErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeRoutingProfile` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeRoutingProfileErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeRoutingProfileError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeRoutingProfileErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DescribeRoutingProfileErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DescribeRoutingProfileErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeRoutingProfileErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeRoutingProfileErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DescribeRoutingProfileErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeRoutingProfileError { fn code(&self) -> Option<&str> { DescribeRoutingProfileError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeRoutingProfileError { /// Creates a new `DescribeRoutingProfileError`. pub fn new(kind: DescribeRoutingProfileErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeRoutingProfileError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeRoutingProfileErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeRoutingProfileError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeRoutingProfileErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeRoutingProfileErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeRoutingProfileErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeRoutingProfileErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DescribeRoutingProfileErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DescribeRoutingProfileErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeRoutingProfileErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeRoutingProfileErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeRoutingProfileErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeRoutingProfileErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DescribeRoutingProfileErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DescribeRoutingProfileError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeRoutingProfileErrorKind::InternalServiceException(_inner) => Some(_inner), DescribeRoutingProfileErrorKind::InvalidParameterException(_inner) => Some(_inner), DescribeRoutingProfileErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeRoutingProfileErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeRoutingProfileErrorKind::ThrottlingException(_inner) => Some(_inner), DescribeRoutingProfileErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeUser` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeUserError { /// Kind of error that occurred. pub kind: DescribeUserErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeUser` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeUserErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeUserError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeUserErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DescribeUserErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DescribeUserErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeUserErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeUserErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DescribeUserErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeUserError { fn code(&self) -> Option<&str> { DescribeUserError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeUserError { /// Creates a new `DescribeUserError`. pub fn new(kind: DescribeUserErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeUserError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeUserErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeUserError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeUserErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeUserErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeUserErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeUserErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DescribeUserErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DescribeUserErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeUserErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeUserErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeUserErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeUserErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, DescribeUserErrorKind::ThrottlingException(_)) } } impl std::error::Error for DescribeUserError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeUserErrorKind::InternalServiceException(_inner) => Some(_inner), DescribeUserErrorKind::InvalidParameterException(_inner) => Some(_inner), DescribeUserErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeUserErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeUserErrorKind::ThrottlingException(_inner) => Some(_inner), DescribeUserErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeUserHierarchyGroup` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeUserHierarchyGroupError { /// Kind of error that occurred. pub kind: DescribeUserHierarchyGroupErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeUserHierarchyGroup` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeUserHierarchyGroupErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeUserHierarchyGroupError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeUserHierarchyGroupErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DescribeUserHierarchyGroupErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DescribeUserHierarchyGroupErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DescribeUserHierarchyGroupErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DescribeUserHierarchyGroupErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DescribeUserHierarchyGroupErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeUserHierarchyGroupError { fn code(&self) -> Option<&str> { DescribeUserHierarchyGroupError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeUserHierarchyGroupError { /// Creates a new `DescribeUserHierarchyGroupError`. pub fn new(kind: DescribeUserHierarchyGroupErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DescribeUserHierarchyGroupError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeUserHierarchyGroupErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeUserHierarchyGroupError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeUserHierarchyGroupErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeUserHierarchyGroupErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeUserHierarchyGroupErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeUserHierarchyGroupErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DescribeUserHierarchyGroupErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DescribeUserHierarchyGroupErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeUserHierarchyGroupErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeUserHierarchyGroupErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeUserHierarchyGroupErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeUserHierarchyGroupErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DescribeUserHierarchyGroupErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DescribeUserHierarchyGroupError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeUserHierarchyGroupErrorKind::InternalServiceException(_inner) => Some(_inner), DescribeUserHierarchyGroupErrorKind::InvalidParameterException(_inner) => Some(_inner), DescribeUserHierarchyGroupErrorKind::InvalidRequestException(_inner) => Some(_inner), DescribeUserHierarchyGroupErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DescribeUserHierarchyGroupErrorKind::ThrottlingException(_inner) => Some(_inner), DescribeUserHierarchyGroupErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DescribeUserHierarchyStructure` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DescribeUserHierarchyStructureError { /// Kind of error that occurred. pub kind: DescribeUserHierarchyStructureErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DescribeUserHierarchyStructure` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DescribeUserHierarchyStructureErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DescribeUserHierarchyStructureError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DescribeUserHierarchyStructureErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } DescribeUserHierarchyStructureErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } DescribeUserHierarchyStructureErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DescribeUserHierarchyStructureErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DescribeUserHierarchyStructureErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DescribeUserHierarchyStructureErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DescribeUserHierarchyStructureError { fn code(&self) -> Option<&str> { DescribeUserHierarchyStructureError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DescribeUserHierarchyStructureError { /// Creates a new `DescribeUserHierarchyStructureError`. pub fn new( kind: DescribeUserHierarchyStructureErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DescribeUserHierarchyStructureError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DescribeUserHierarchyStructureErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DescribeUserHierarchyStructureError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DescribeUserHierarchyStructureErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DescribeUserHierarchyStructureErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DescribeUserHierarchyStructureErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DescribeUserHierarchyStructureErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DescribeUserHierarchyStructureErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DescribeUserHierarchyStructureErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DescribeUserHierarchyStructureErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DescribeUserHierarchyStructureErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DescribeUserHierarchyStructureErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DescribeUserHierarchyStructureErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DescribeUserHierarchyStructureErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DescribeUserHierarchyStructureError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DescribeUserHierarchyStructureErrorKind::InternalServiceException(_inner) => { Some(_inner) } DescribeUserHierarchyStructureErrorKind::InvalidParameterException(_inner) => { Some(_inner) } DescribeUserHierarchyStructureErrorKind::InvalidRequestException(_inner) => { Some(_inner) } DescribeUserHierarchyStructureErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DescribeUserHierarchyStructureErrorKind::ThrottlingException(_inner) => Some(_inner), DescribeUserHierarchyStructureErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DisassociateApprovedOrigin` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DisassociateApprovedOriginError { /// Kind of error that occurred. pub kind: DisassociateApprovedOriginErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DisassociateApprovedOrigin` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DisassociateApprovedOriginErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DisassociateApprovedOriginError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DisassociateApprovedOriginErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DisassociateApprovedOriginErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DisassociateApprovedOriginErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DisassociateApprovedOriginErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DisassociateApprovedOriginErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DisassociateApprovedOriginErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DisassociateApprovedOriginError { fn code(&self) -> Option<&str> { DisassociateApprovedOriginError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DisassociateApprovedOriginError { /// Creates a new `DisassociateApprovedOriginError`. pub fn new(kind: DisassociateApprovedOriginErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DisassociateApprovedOriginError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DisassociateApprovedOriginErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DisassociateApprovedOriginError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DisassociateApprovedOriginErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DisassociateApprovedOriginErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DisassociateApprovedOriginErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DisassociateApprovedOriginErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DisassociateApprovedOriginErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DisassociateApprovedOriginErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DisassociateApprovedOriginErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DisassociateApprovedOriginErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DisassociateApprovedOriginErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DisassociateApprovedOriginErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DisassociateApprovedOriginErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DisassociateApprovedOriginError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DisassociateApprovedOriginErrorKind::InternalServiceException(_inner) => Some(_inner), DisassociateApprovedOriginErrorKind::InvalidParameterException(_inner) => Some(_inner), DisassociateApprovedOriginErrorKind::InvalidRequestException(_inner) => Some(_inner), DisassociateApprovedOriginErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DisassociateApprovedOriginErrorKind::ThrottlingException(_inner) => Some(_inner), DisassociateApprovedOriginErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DisassociateBot` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DisassociateBotError { /// Kind of error that occurred. pub kind: DisassociateBotErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DisassociateBot` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DisassociateBotErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DisassociateBotError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DisassociateBotErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DisassociateBotErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DisassociateBotErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DisassociateBotErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DisassociateBotErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DisassociateBotError { fn code(&self) -> Option<&str> { DisassociateBotError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DisassociateBotError { /// Creates a new `DisassociateBotError`. pub fn new(kind: DisassociateBotErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DisassociateBotError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DisassociateBotErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DisassociateBotError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DisassociateBotErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DisassociateBotErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DisassociateBotErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DisassociateBotErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DisassociateBotErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DisassociateBotErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DisassociateBotErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DisassociateBotErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, DisassociateBotErrorKind::ThrottlingException(_)) } } impl std::error::Error for DisassociateBotError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DisassociateBotErrorKind::InternalServiceException(_inner) => Some(_inner), DisassociateBotErrorKind::InvalidRequestException(_inner) => Some(_inner), DisassociateBotErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DisassociateBotErrorKind::ThrottlingException(_inner) => Some(_inner), DisassociateBotErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DisassociateInstanceStorageConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DisassociateInstanceStorageConfigError { /// Kind of error that occurred. pub kind: DisassociateInstanceStorageConfigErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DisassociateInstanceStorageConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DisassociateInstanceStorageConfigErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DisassociateInstanceStorageConfigError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DisassociateInstanceStorageConfigErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } DisassociateInstanceStorageConfigErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } DisassociateInstanceStorageConfigErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DisassociateInstanceStorageConfigErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DisassociateInstanceStorageConfigErrorKind::ThrottlingException(_inner) => { _inner.fmt(f) } DisassociateInstanceStorageConfigErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DisassociateInstanceStorageConfigError { fn code(&self) -> Option<&str> { DisassociateInstanceStorageConfigError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DisassociateInstanceStorageConfigError { /// Creates a new `DisassociateInstanceStorageConfigError`. pub fn new( kind: DisassociateInstanceStorageConfigErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DisassociateInstanceStorageConfigError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DisassociateInstanceStorageConfigErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DisassociateInstanceStorageConfigError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DisassociateInstanceStorageConfigErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DisassociateInstanceStorageConfigErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DisassociateInstanceStorageConfigErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DisassociateInstanceStorageConfigErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DisassociateInstanceStorageConfigErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DisassociateInstanceStorageConfigErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DisassociateInstanceStorageConfigErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DisassociateInstanceStorageConfigErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DisassociateInstanceStorageConfigErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DisassociateInstanceStorageConfigErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DisassociateInstanceStorageConfigErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DisassociateInstanceStorageConfigError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DisassociateInstanceStorageConfigErrorKind::InternalServiceException(_inner) => { Some(_inner) } DisassociateInstanceStorageConfigErrorKind::InvalidParameterException(_inner) => { Some(_inner) } DisassociateInstanceStorageConfigErrorKind::InvalidRequestException(_inner) => { Some(_inner) } DisassociateInstanceStorageConfigErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DisassociateInstanceStorageConfigErrorKind::ThrottlingException(_inner) => Some(_inner), DisassociateInstanceStorageConfigErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DisassociateLambdaFunction` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DisassociateLambdaFunctionError { /// Kind of error that occurred. pub kind: DisassociateLambdaFunctionErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DisassociateLambdaFunction` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DisassociateLambdaFunctionErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DisassociateLambdaFunctionError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DisassociateLambdaFunctionErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DisassociateLambdaFunctionErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DisassociateLambdaFunctionErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DisassociateLambdaFunctionErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DisassociateLambdaFunctionErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DisassociateLambdaFunctionErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DisassociateLambdaFunctionError { fn code(&self) -> Option<&str> { DisassociateLambdaFunctionError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DisassociateLambdaFunctionError { /// Creates a new `DisassociateLambdaFunctionError`. pub fn new(kind: DisassociateLambdaFunctionErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DisassociateLambdaFunctionError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DisassociateLambdaFunctionErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DisassociateLambdaFunctionError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DisassociateLambdaFunctionErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DisassociateLambdaFunctionErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DisassociateLambdaFunctionErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DisassociateLambdaFunctionErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DisassociateLambdaFunctionErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DisassociateLambdaFunctionErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DisassociateLambdaFunctionErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DisassociateLambdaFunctionErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DisassociateLambdaFunctionErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DisassociateLambdaFunctionErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DisassociateLambdaFunctionErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DisassociateLambdaFunctionError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DisassociateLambdaFunctionErrorKind::InternalServiceException(_inner) => Some(_inner), DisassociateLambdaFunctionErrorKind::InvalidParameterException(_inner) => Some(_inner), DisassociateLambdaFunctionErrorKind::InvalidRequestException(_inner) => Some(_inner), DisassociateLambdaFunctionErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DisassociateLambdaFunctionErrorKind::ThrottlingException(_inner) => Some(_inner), DisassociateLambdaFunctionErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DisassociateLexBot` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DisassociateLexBotError { /// Kind of error that occurred. pub kind: DisassociateLexBotErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DisassociateLexBot` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DisassociateLexBotErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DisassociateLexBotError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DisassociateLexBotErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DisassociateLexBotErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DisassociateLexBotErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DisassociateLexBotErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DisassociateLexBotErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DisassociateLexBotErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DisassociateLexBotError { fn code(&self) -> Option<&str> { DisassociateLexBotError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DisassociateLexBotError { /// Creates a new `DisassociateLexBotError`. pub fn new(kind: DisassociateLexBotErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DisassociateLexBotError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DisassociateLexBotErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DisassociateLexBotError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DisassociateLexBotErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DisassociateLexBotErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DisassociateLexBotErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DisassociateLexBotErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DisassociateLexBotErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DisassociateLexBotErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DisassociateLexBotErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DisassociateLexBotErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DisassociateLexBotErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DisassociateLexBotErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DisassociateLexBotErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DisassociateLexBotError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DisassociateLexBotErrorKind::InternalServiceException(_inner) => Some(_inner), DisassociateLexBotErrorKind::InvalidParameterException(_inner) => Some(_inner), DisassociateLexBotErrorKind::InvalidRequestException(_inner) => Some(_inner), DisassociateLexBotErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DisassociateLexBotErrorKind::ThrottlingException(_inner) => Some(_inner), DisassociateLexBotErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DisassociateQueueQuickConnects` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DisassociateQueueQuickConnectsError { /// Kind of error that occurred. pub kind: DisassociateQueueQuickConnectsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DisassociateQueueQuickConnects` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DisassociateQueueQuickConnectsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DisassociateQueueQuickConnectsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DisassociateQueueQuickConnectsErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } DisassociateQueueQuickConnectsErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } DisassociateQueueQuickConnectsErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DisassociateQueueQuickConnectsErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DisassociateQueueQuickConnectsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DisassociateQueueQuickConnectsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DisassociateQueueQuickConnectsError { fn code(&self) -> Option<&str> { DisassociateQueueQuickConnectsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DisassociateQueueQuickConnectsError { /// Creates a new `DisassociateQueueQuickConnectsError`. pub fn new( kind: DisassociateQueueQuickConnectsErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DisassociateQueueQuickConnectsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DisassociateQueueQuickConnectsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DisassociateQueueQuickConnectsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DisassociateQueueQuickConnectsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DisassociateQueueQuickConnectsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DisassociateQueueQuickConnectsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DisassociateQueueQuickConnectsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DisassociateQueueQuickConnectsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DisassociateQueueQuickConnectsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DisassociateQueueQuickConnectsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DisassociateQueueQuickConnectsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DisassociateQueueQuickConnectsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DisassociateQueueQuickConnectsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DisassociateQueueQuickConnectsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DisassociateQueueQuickConnectsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DisassociateQueueQuickConnectsErrorKind::InternalServiceException(_inner) => { Some(_inner) } DisassociateQueueQuickConnectsErrorKind::InvalidParameterException(_inner) => { Some(_inner) } DisassociateQueueQuickConnectsErrorKind::InvalidRequestException(_inner) => { Some(_inner) } DisassociateQueueQuickConnectsErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DisassociateQueueQuickConnectsErrorKind::ThrottlingException(_inner) => Some(_inner), DisassociateQueueQuickConnectsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DisassociateRoutingProfileQueues` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DisassociateRoutingProfileQueuesError { /// Kind of error that occurred. pub kind: DisassociateRoutingProfileQueuesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DisassociateRoutingProfileQueues` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DisassociateRoutingProfileQueuesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DisassociateRoutingProfileQueuesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DisassociateRoutingProfileQueuesErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } DisassociateRoutingProfileQueuesErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } DisassociateRoutingProfileQueuesErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } DisassociateRoutingProfileQueuesErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } DisassociateRoutingProfileQueuesErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DisassociateRoutingProfileQueuesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DisassociateRoutingProfileQueuesError { fn code(&self) -> Option<&str> { DisassociateRoutingProfileQueuesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DisassociateRoutingProfileQueuesError { /// Creates a new `DisassociateRoutingProfileQueuesError`. pub fn new( kind: DisassociateRoutingProfileQueuesErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `DisassociateRoutingProfileQueuesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DisassociateRoutingProfileQueuesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DisassociateRoutingProfileQueuesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DisassociateRoutingProfileQueuesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DisassociateRoutingProfileQueuesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DisassociateRoutingProfileQueuesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DisassociateRoutingProfileQueuesErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DisassociateRoutingProfileQueuesErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DisassociateRoutingProfileQueuesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DisassociateRoutingProfileQueuesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DisassociateRoutingProfileQueuesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DisassociateRoutingProfileQueuesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DisassociateRoutingProfileQueuesErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DisassociateRoutingProfileQueuesErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DisassociateRoutingProfileQueuesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DisassociateRoutingProfileQueuesErrorKind::InternalServiceException(_inner) => { Some(_inner) } DisassociateRoutingProfileQueuesErrorKind::InvalidParameterException(_inner) => { Some(_inner) } DisassociateRoutingProfileQueuesErrorKind::InvalidRequestException(_inner) => { Some(_inner) } DisassociateRoutingProfileQueuesErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } DisassociateRoutingProfileQueuesErrorKind::ThrottlingException(_inner) => Some(_inner), DisassociateRoutingProfileQueuesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `DisassociateSecurityKey` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct DisassociateSecurityKeyError { /// Kind of error that occurred. pub kind: DisassociateSecurityKeyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `DisassociateSecurityKey` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum DisassociateSecurityKeyErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for DisassociateSecurityKeyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { DisassociateSecurityKeyErrorKind::InternalServiceException(_inner) => _inner.fmt(f), DisassociateSecurityKeyErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), DisassociateSecurityKeyErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), DisassociateSecurityKeyErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), DisassociateSecurityKeyErrorKind::ThrottlingException(_inner) => _inner.fmt(f), DisassociateSecurityKeyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for DisassociateSecurityKeyError { fn code(&self) -> Option<&str> { DisassociateSecurityKeyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl DisassociateSecurityKeyError { /// Creates a new `DisassociateSecurityKeyError`. pub fn new(kind: DisassociateSecurityKeyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `DisassociateSecurityKeyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: DisassociateSecurityKeyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `DisassociateSecurityKeyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: DisassociateSecurityKeyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `DisassociateSecurityKeyErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, DisassociateSecurityKeyErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `DisassociateSecurityKeyErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, DisassociateSecurityKeyErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `DisassociateSecurityKeyErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, DisassociateSecurityKeyErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `DisassociateSecurityKeyErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, DisassociateSecurityKeyErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `DisassociateSecurityKeyErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, DisassociateSecurityKeyErrorKind::ThrottlingException(_) ) } } impl std::error::Error for DisassociateSecurityKeyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { DisassociateSecurityKeyErrorKind::InternalServiceException(_inner) => Some(_inner), DisassociateSecurityKeyErrorKind::InvalidParameterException(_inner) => Some(_inner), DisassociateSecurityKeyErrorKind::InvalidRequestException(_inner) => Some(_inner), DisassociateSecurityKeyErrorKind::ResourceNotFoundException(_inner) => Some(_inner), DisassociateSecurityKeyErrorKind::ThrottlingException(_inner) => Some(_inner), DisassociateSecurityKeyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `GetContactAttributes` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct GetContactAttributesError { /// Kind of error that occurred. pub kind: GetContactAttributesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `GetContactAttributes` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum GetContactAttributesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for GetContactAttributesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { GetContactAttributesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), GetContactAttributesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), GetContactAttributesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), GetContactAttributesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for GetContactAttributesError { fn code(&self) -> Option<&str> { GetContactAttributesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl GetContactAttributesError { /// Creates a new `GetContactAttributesError`. pub fn new(kind: GetContactAttributesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `GetContactAttributesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: GetContactAttributesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `GetContactAttributesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: GetContactAttributesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `GetContactAttributesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, GetContactAttributesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `GetContactAttributesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, GetContactAttributesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `GetContactAttributesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, GetContactAttributesErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for GetContactAttributesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { GetContactAttributesErrorKind::InternalServiceException(_inner) => Some(_inner), GetContactAttributesErrorKind::InvalidRequestException(_inner) => Some(_inner), GetContactAttributesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), GetContactAttributesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `GetCurrentMetricData` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct GetCurrentMetricDataError { /// Kind of error that occurred. pub kind: GetCurrentMetricDataErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `GetCurrentMetricData` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum GetCurrentMetricDataErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for GetCurrentMetricDataError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { GetCurrentMetricDataErrorKind::InternalServiceException(_inner) => _inner.fmt(f), GetCurrentMetricDataErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), GetCurrentMetricDataErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), GetCurrentMetricDataErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), GetCurrentMetricDataErrorKind::ThrottlingException(_inner) => _inner.fmt(f), GetCurrentMetricDataErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for GetCurrentMetricDataError { fn code(&self) -> Option<&str> { GetCurrentMetricDataError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl GetCurrentMetricDataError { /// Creates a new `GetCurrentMetricDataError`. pub fn new(kind: GetCurrentMetricDataErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `GetCurrentMetricDataError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: GetCurrentMetricDataErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `GetCurrentMetricDataError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: GetCurrentMetricDataErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `GetCurrentMetricDataErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, GetCurrentMetricDataErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `GetCurrentMetricDataErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, GetCurrentMetricDataErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `GetCurrentMetricDataErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, GetCurrentMetricDataErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `GetCurrentMetricDataErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, GetCurrentMetricDataErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `GetCurrentMetricDataErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, GetCurrentMetricDataErrorKind::ThrottlingException(_) ) } } impl std::error::Error for GetCurrentMetricDataError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { GetCurrentMetricDataErrorKind::InternalServiceException(_inner) => Some(_inner), GetCurrentMetricDataErrorKind::InvalidParameterException(_inner) => Some(_inner), GetCurrentMetricDataErrorKind::InvalidRequestException(_inner) => Some(_inner), GetCurrentMetricDataErrorKind::ResourceNotFoundException(_inner) => Some(_inner), GetCurrentMetricDataErrorKind::ThrottlingException(_inner) => Some(_inner), GetCurrentMetricDataErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `GetFederationToken` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct GetFederationTokenError { /// Kind of error that occurred. pub kind: GetFederationTokenErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `GetFederationToken` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum GetFederationTokenErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>No user with the specified credentials was found in the Amazon Connect instance.</p> UserNotFoundException(crate::error::UserNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for GetFederationTokenError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { GetFederationTokenErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), GetFederationTokenErrorKind::InternalServiceException(_inner) => _inner.fmt(f), GetFederationTokenErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), GetFederationTokenErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), GetFederationTokenErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), GetFederationTokenErrorKind::UserNotFoundException(_inner) => _inner.fmt(f), GetFederationTokenErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for GetFederationTokenError { fn code(&self) -> Option<&str> { GetFederationTokenError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl GetFederationTokenError { /// Creates a new `GetFederationTokenError`. pub fn new(kind: GetFederationTokenErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `GetFederationTokenError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: GetFederationTokenErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `GetFederationTokenError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: GetFederationTokenErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `GetFederationTokenErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, GetFederationTokenErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `GetFederationTokenErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, GetFederationTokenErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `GetFederationTokenErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, GetFederationTokenErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `GetFederationTokenErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, GetFederationTokenErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `GetFederationTokenErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, GetFederationTokenErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `GetFederationTokenErrorKind::UserNotFoundException`. pub fn is_user_not_found_exception(&self) -> bool { matches!( &self.kind, GetFederationTokenErrorKind::UserNotFoundException(_) ) } } impl std::error::Error for GetFederationTokenError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { GetFederationTokenErrorKind::DuplicateResourceException(_inner) => Some(_inner), GetFederationTokenErrorKind::InternalServiceException(_inner) => Some(_inner), GetFederationTokenErrorKind::InvalidParameterException(_inner) => Some(_inner), GetFederationTokenErrorKind::InvalidRequestException(_inner) => Some(_inner), GetFederationTokenErrorKind::ResourceNotFoundException(_inner) => Some(_inner), GetFederationTokenErrorKind::UserNotFoundException(_inner) => Some(_inner), GetFederationTokenErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `GetMetricData` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct GetMetricDataError { /// Kind of error that occurred. pub kind: GetMetricDataErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `GetMetricData` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum GetMetricDataErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for GetMetricDataError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { GetMetricDataErrorKind::InternalServiceException(_inner) => _inner.fmt(f), GetMetricDataErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), GetMetricDataErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), GetMetricDataErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), GetMetricDataErrorKind::ThrottlingException(_inner) => _inner.fmt(f), GetMetricDataErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for GetMetricDataError { fn code(&self) -> Option<&str> { GetMetricDataError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl GetMetricDataError { /// Creates a new `GetMetricDataError`. pub fn new(kind: GetMetricDataErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `GetMetricDataError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: GetMetricDataErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `GetMetricDataError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: GetMetricDataErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `GetMetricDataErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, GetMetricDataErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `GetMetricDataErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, GetMetricDataErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `GetMetricDataErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, GetMetricDataErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `GetMetricDataErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, GetMetricDataErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `GetMetricDataErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, GetMetricDataErrorKind::ThrottlingException(_)) } } impl std::error::Error for GetMetricDataError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { GetMetricDataErrorKind::InternalServiceException(_inner) => Some(_inner), GetMetricDataErrorKind::InvalidParameterException(_inner) => Some(_inner), GetMetricDataErrorKind::InvalidRequestException(_inner) => Some(_inner), GetMetricDataErrorKind::ResourceNotFoundException(_inner) => Some(_inner), GetMetricDataErrorKind::ThrottlingException(_inner) => Some(_inner), GetMetricDataErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListAgentStatuses` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListAgentStatusesError { /// Kind of error that occurred. pub kind: ListAgentStatusesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListAgentStatuses` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListAgentStatusesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListAgentStatusesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListAgentStatusesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListAgentStatusesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListAgentStatusesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListAgentStatusesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListAgentStatusesErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListAgentStatusesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListAgentStatusesError { fn code(&self) -> Option<&str> { ListAgentStatusesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListAgentStatusesError { /// Creates a new `ListAgentStatusesError`. pub fn new(kind: ListAgentStatusesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListAgentStatusesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListAgentStatusesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListAgentStatusesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListAgentStatusesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListAgentStatusesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListAgentStatusesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListAgentStatusesErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListAgentStatusesErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListAgentStatusesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListAgentStatusesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListAgentStatusesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListAgentStatusesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListAgentStatusesErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListAgentStatusesErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListAgentStatusesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListAgentStatusesErrorKind::InternalServiceException(_inner) => Some(_inner), ListAgentStatusesErrorKind::InvalidParameterException(_inner) => Some(_inner), ListAgentStatusesErrorKind::InvalidRequestException(_inner) => Some(_inner), ListAgentStatusesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListAgentStatusesErrorKind::ThrottlingException(_inner) => Some(_inner), ListAgentStatusesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListApprovedOrigins` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListApprovedOriginsError { /// Kind of error that occurred. pub kind: ListApprovedOriginsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListApprovedOrigins` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListApprovedOriginsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListApprovedOriginsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListApprovedOriginsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListApprovedOriginsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListApprovedOriginsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListApprovedOriginsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListApprovedOriginsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListApprovedOriginsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListApprovedOriginsError { fn code(&self) -> Option<&str> { ListApprovedOriginsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListApprovedOriginsError { /// Creates a new `ListApprovedOriginsError`. pub fn new(kind: ListApprovedOriginsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListApprovedOriginsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListApprovedOriginsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListApprovedOriginsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListApprovedOriginsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListApprovedOriginsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListApprovedOriginsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListApprovedOriginsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListApprovedOriginsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListApprovedOriginsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListApprovedOriginsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListApprovedOriginsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListApprovedOriginsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListApprovedOriginsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListApprovedOriginsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListApprovedOriginsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListApprovedOriginsErrorKind::InternalServiceException(_inner) => Some(_inner), ListApprovedOriginsErrorKind::InvalidParameterException(_inner) => Some(_inner), ListApprovedOriginsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListApprovedOriginsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListApprovedOriginsErrorKind::ThrottlingException(_inner) => Some(_inner), ListApprovedOriginsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListBots` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListBotsError { /// Kind of error that occurred. pub kind: ListBotsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListBots` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListBotsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListBotsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListBotsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListBotsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListBotsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListBotsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListBotsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListBotsError { fn code(&self) -> Option<&str> { ListBotsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListBotsError { /// Creates a new `ListBotsError`. pub fn new(kind: ListBotsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListBotsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListBotsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListBotsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListBotsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListBotsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!(&self.kind, ListBotsErrorKind::InternalServiceException(_)) } /// Returns `true` if the error kind is `ListBotsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, ListBotsErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `ListBotsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!(&self.kind, ListBotsErrorKind::ResourceNotFoundException(_)) } /// Returns `true` if the error kind is `ListBotsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, ListBotsErrorKind::ThrottlingException(_)) } } impl std::error::Error for ListBotsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListBotsErrorKind::InternalServiceException(_inner) => Some(_inner), ListBotsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListBotsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListBotsErrorKind::ThrottlingException(_inner) => Some(_inner), ListBotsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListContactFlows` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListContactFlowsError { /// Kind of error that occurred. pub kind: ListContactFlowsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListContactFlows` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListContactFlowsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListContactFlowsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListContactFlowsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListContactFlowsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListContactFlowsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListContactFlowsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListContactFlowsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListContactFlowsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListContactFlowsError { fn code(&self) -> Option<&str> { ListContactFlowsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListContactFlowsError { /// Creates a new `ListContactFlowsError`. pub fn new(kind: ListContactFlowsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListContactFlowsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListContactFlowsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListContactFlowsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListContactFlowsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListContactFlowsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListContactFlowsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListContactFlowsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListContactFlowsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListContactFlowsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListContactFlowsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListContactFlowsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListContactFlowsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListContactFlowsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListContactFlowsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListContactFlowsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListContactFlowsErrorKind::InternalServiceException(_inner) => Some(_inner), ListContactFlowsErrorKind::InvalidParameterException(_inner) => Some(_inner), ListContactFlowsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListContactFlowsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListContactFlowsErrorKind::ThrottlingException(_inner) => Some(_inner), ListContactFlowsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListHoursOfOperations` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListHoursOfOperationsError { /// Kind of error that occurred. pub kind: ListHoursOfOperationsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListHoursOfOperations` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListHoursOfOperationsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListHoursOfOperationsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListHoursOfOperationsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListHoursOfOperationsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListHoursOfOperationsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListHoursOfOperationsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListHoursOfOperationsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListHoursOfOperationsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListHoursOfOperationsError { fn code(&self) -> Option<&str> { ListHoursOfOperationsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListHoursOfOperationsError { /// Creates a new `ListHoursOfOperationsError`. pub fn new(kind: ListHoursOfOperationsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListHoursOfOperationsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListHoursOfOperationsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListHoursOfOperationsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListHoursOfOperationsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListHoursOfOperationsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListHoursOfOperationsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListHoursOfOperationsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListHoursOfOperationsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListHoursOfOperationsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListHoursOfOperationsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListHoursOfOperationsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListHoursOfOperationsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListHoursOfOperationsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListHoursOfOperationsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListHoursOfOperationsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListHoursOfOperationsErrorKind::InternalServiceException(_inner) => Some(_inner), ListHoursOfOperationsErrorKind::InvalidParameterException(_inner) => Some(_inner), ListHoursOfOperationsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListHoursOfOperationsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListHoursOfOperationsErrorKind::ThrottlingException(_inner) => Some(_inner), ListHoursOfOperationsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListInstanceAttributes` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListInstanceAttributesError { /// Kind of error that occurred. pub kind: ListInstanceAttributesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListInstanceAttributes` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListInstanceAttributesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListInstanceAttributesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListInstanceAttributesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListInstanceAttributesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListInstanceAttributesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListInstanceAttributesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListInstanceAttributesErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListInstanceAttributesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListInstanceAttributesError { fn code(&self) -> Option<&str> { ListInstanceAttributesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListInstanceAttributesError { /// Creates a new `ListInstanceAttributesError`. pub fn new(kind: ListInstanceAttributesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListInstanceAttributesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListInstanceAttributesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListInstanceAttributesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListInstanceAttributesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListInstanceAttributesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListInstanceAttributesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListInstanceAttributesErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListInstanceAttributesErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListInstanceAttributesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListInstanceAttributesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListInstanceAttributesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListInstanceAttributesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListInstanceAttributesErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListInstanceAttributesErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListInstanceAttributesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListInstanceAttributesErrorKind::InternalServiceException(_inner) => Some(_inner), ListInstanceAttributesErrorKind::InvalidParameterException(_inner) => Some(_inner), ListInstanceAttributesErrorKind::InvalidRequestException(_inner) => Some(_inner), ListInstanceAttributesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListInstanceAttributesErrorKind::ThrottlingException(_inner) => Some(_inner), ListInstanceAttributesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListInstances` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListInstancesError { /// Kind of error that occurred. pub kind: ListInstancesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListInstances` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListInstancesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListInstancesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListInstancesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListInstancesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListInstancesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListInstancesError { fn code(&self) -> Option<&str> { ListInstancesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListInstancesError { /// Creates a new `ListInstancesError`. pub fn new(kind: ListInstancesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListInstancesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListInstancesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListInstancesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListInstancesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListInstancesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListInstancesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListInstancesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListInstancesErrorKind::InvalidRequestException(_) ) } } impl std::error::Error for ListInstancesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListInstancesErrorKind::InternalServiceException(_inner) => Some(_inner), ListInstancesErrorKind::InvalidRequestException(_inner) => Some(_inner), ListInstancesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListInstanceStorageConfigs` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListInstanceStorageConfigsError { /// Kind of error that occurred. pub kind: ListInstanceStorageConfigsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListInstanceStorageConfigs` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListInstanceStorageConfigsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListInstanceStorageConfigsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListInstanceStorageConfigsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListInstanceStorageConfigsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListInstanceStorageConfigsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListInstanceStorageConfigsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListInstanceStorageConfigsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListInstanceStorageConfigsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListInstanceStorageConfigsError { fn code(&self) -> Option<&str> { ListInstanceStorageConfigsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListInstanceStorageConfigsError { /// Creates a new `ListInstanceStorageConfigsError`. pub fn new(kind: ListInstanceStorageConfigsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListInstanceStorageConfigsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListInstanceStorageConfigsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListInstanceStorageConfigsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListInstanceStorageConfigsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListInstanceStorageConfigsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListInstanceStorageConfigsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListInstanceStorageConfigsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListInstanceStorageConfigsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListInstanceStorageConfigsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListInstanceStorageConfigsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListInstanceStorageConfigsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListInstanceStorageConfigsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListInstanceStorageConfigsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListInstanceStorageConfigsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListInstanceStorageConfigsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListInstanceStorageConfigsErrorKind::InternalServiceException(_inner) => Some(_inner), ListInstanceStorageConfigsErrorKind::InvalidParameterException(_inner) => Some(_inner), ListInstanceStorageConfigsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListInstanceStorageConfigsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListInstanceStorageConfigsErrorKind::ThrottlingException(_inner) => Some(_inner), ListInstanceStorageConfigsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListIntegrationAssociations` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListIntegrationAssociationsError { /// Kind of error that occurred. pub kind: ListIntegrationAssociationsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListIntegrationAssociations` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListIntegrationAssociationsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListIntegrationAssociationsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListIntegrationAssociationsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListIntegrationAssociationsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListIntegrationAssociationsErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } ListIntegrationAssociationsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListIntegrationAssociationsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListIntegrationAssociationsError { fn code(&self) -> Option<&str> { ListIntegrationAssociationsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListIntegrationAssociationsError { /// Creates a new `ListIntegrationAssociationsError`. pub fn new(kind: ListIntegrationAssociationsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListIntegrationAssociationsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListIntegrationAssociationsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListIntegrationAssociationsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListIntegrationAssociationsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListIntegrationAssociationsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListIntegrationAssociationsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListIntegrationAssociationsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListIntegrationAssociationsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListIntegrationAssociationsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListIntegrationAssociationsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListIntegrationAssociationsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListIntegrationAssociationsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListIntegrationAssociationsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListIntegrationAssociationsErrorKind::InternalServiceException(_inner) => Some(_inner), ListIntegrationAssociationsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListIntegrationAssociationsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListIntegrationAssociationsErrorKind::ThrottlingException(_inner) => Some(_inner), ListIntegrationAssociationsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListLambdaFunctions` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListLambdaFunctionsError { /// Kind of error that occurred. pub kind: ListLambdaFunctionsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListLambdaFunctions` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListLambdaFunctionsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListLambdaFunctionsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListLambdaFunctionsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListLambdaFunctionsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListLambdaFunctionsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListLambdaFunctionsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListLambdaFunctionsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListLambdaFunctionsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListLambdaFunctionsError { fn code(&self) -> Option<&str> { ListLambdaFunctionsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListLambdaFunctionsError { /// Creates a new `ListLambdaFunctionsError`. pub fn new(kind: ListLambdaFunctionsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListLambdaFunctionsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListLambdaFunctionsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListLambdaFunctionsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListLambdaFunctionsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListLambdaFunctionsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListLambdaFunctionsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListLambdaFunctionsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListLambdaFunctionsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListLambdaFunctionsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListLambdaFunctionsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListLambdaFunctionsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListLambdaFunctionsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListLambdaFunctionsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListLambdaFunctionsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListLambdaFunctionsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListLambdaFunctionsErrorKind::InternalServiceException(_inner) => Some(_inner), ListLambdaFunctionsErrorKind::InvalidParameterException(_inner) => Some(_inner), ListLambdaFunctionsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListLambdaFunctionsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListLambdaFunctionsErrorKind::ThrottlingException(_inner) => Some(_inner), ListLambdaFunctionsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListLexBots` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListLexBotsError { /// Kind of error that occurred. pub kind: ListLexBotsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListLexBots` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListLexBotsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListLexBotsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListLexBotsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListLexBotsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListLexBotsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListLexBotsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListLexBotsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListLexBotsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListLexBotsError { fn code(&self) -> Option<&str> { ListLexBotsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListLexBotsError { /// Creates a new `ListLexBotsError`. pub fn new(kind: ListLexBotsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListLexBotsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListLexBotsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListLexBotsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListLexBotsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListLexBotsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListLexBotsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListLexBotsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListLexBotsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListLexBotsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, ListLexBotsErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `ListLexBotsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListLexBotsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListLexBotsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, ListLexBotsErrorKind::ThrottlingException(_)) } } impl std::error::Error for ListLexBotsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListLexBotsErrorKind::InternalServiceException(_inner) => Some(_inner), ListLexBotsErrorKind::InvalidParameterException(_inner) => Some(_inner), ListLexBotsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListLexBotsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListLexBotsErrorKind::ThrottlingException(_inner) => Some(_inner), ListLexBotsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListPhoneNumbers` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListPhoneNumbersError { /// Kind of error that occurred. pub kind: ListPhoneNumbersErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListPhoneNumbers` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListPhoneNumbersErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListPhoneNumbersError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListPhoneNumbersErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListPhoneNumbersErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListPhoneNumbersErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListPhoneNumbersErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListPhoneNumbersErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListPhoneNumbersErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListPhoneNumbersError { fn code(&self) -> Option<&str> { ListPhoneNumbersError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListPhoneNumbersError { /// Creates a new `ListPhoneNumbersError`. pub fn new(kind: ListPhoneNumbersErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListPhoneNumbersError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListPhoneNumbersErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListPhoneNumbersError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListPhoneNumbersErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListPhoneNumbersErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListPhoneNumbersErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListPhoneNumbersErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListPhoneNumbersErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListPhoneNumbersErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListPhoneNumbersErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListPhoneNumbersErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListPhoneNumbersErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListPhoneNumbersErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListPhoneNumbersErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListPhoneNumbersError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListPhoneNumbersErrorKind::InternalServiceException(_inner) => Some(_inner), ListPhoneNumbersErrorKind::InvalidParameterException(_inner) => Some(_inner), ListPhoneNumbersErrorKind::InvalidRequestException(_inner) => Some(_inner), ListPhoneNumbersErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListPhoneNumbersErrorKind::ThrottlingException(_inner) => Some(_inner), ListPhoneNumbersErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListPrompts` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListPromptsError { /// Kind of error that occurred. pub kind: ListPromptsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListPrompts` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListPromptsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListPromptsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListPromptsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListPromptsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListPromptsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListPromptsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListPromptsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListPromptsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListPromptsError { fn code(&self) -> Option<&str> { ListPromptsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListPromptsError { /// Creates a new `ListPromptsError`. pub fn new(kind: ListPromptsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListPromptsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListPromptsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListPromptsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListPromptsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListPromptsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListPromptsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListPromptsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListPromptsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListPromptsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, ListPromptsErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `ListPromptsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListPromptsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListPromptsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, ListPromptsErrorKind::ThrottlingException(_)) } } impl std::error::Error for ListPromptsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListPromptsErrorKind::InternalServiceException(_inner) => Some(_inner), ListPromptsErrorKind::InvalidParameterException(_inner) => Some(_inner), ListPromptsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListPromptsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListPromptsErrorKind::ThrottlingException(_inner) => Some(_inner), ListPromptsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListQueueQuickConnects` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListQueueQuickConnectsError { /// Kind of error that occurred. pub kind: ListQueueQuickConnectsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListQueueQuickConnects` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListQueueQuickConnectsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListQueueQuickConnectsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListQueueQuickConnectsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListQueueQuickConnectsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListQueueQuickConnectsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListQueueQuickConnectsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListQueueQuickConnectsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListQueueQuickConnectsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListQueueQuickConnectsError { fn code(&self) -> Option<&str> { ListQueueQuickConnectsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListQueueQuickConnectsError { /// Creates a new `ListQueueQuickConnectsError`. pub fn new(kind: ListQueueQuickConnectsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListQueueQuickConnectsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListQueueQuickConnectsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListQueueQuickConnectsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListQueueQuickConnectsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListQueueQuickConnectsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListQueueQuickConnectsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListQueueQuickConnectsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListQueueQuickConnectsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListQueueQuickConnectsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListQueueQuickConnectsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListQueueQuickConnectsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListQueueQuickConnectsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListQueueQuickConnectsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListQueueQuickConnectsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListQueueQuickConnectsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListQueueQuickConnectsErrorKind::InternalServiceException(_inner) => Some(_inner), ListQueueQuickConnectsErrorKind::InvalidParameterException(_inner) => Some(_inner), ListQueueQuickConnectsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListQueueQuickConnectsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListQueueQuickConnectsErrorKind::ThrottlingException(_inner) => Some(_inner), ListQueueQuickConnectsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListQueues` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListQueuesError { /// Kind of error that occurred. pub kind: ListQueuesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListQueues` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListQueuesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListQueuesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListQueuesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListQueuesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListQueuesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListQueuesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListQueuesErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListQueuesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListQueuesError { fn code(&self) -> Option<&str> { ListQueuesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListQueuesError { /// Creates a new `ListQueuesError`. pub fn new(kind: ListQueuesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListQueuesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListQueuesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListQueuesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListQueuesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListQueuesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!(&self.kind, ListQueuesErrorKind::InternalServiceException(_)) } /// Returns `true` if the error kind is `ListQueuesErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListQueuesErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListQueuesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, ListQueuesErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `ListQueuesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListQueuesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListQueuesErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, ListQueuesErrorKind::ThrottlingException(_)) } } impl std::error::Error for ListQueuesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListQueuesErrorKind::InternalServiceException(_inner) => Some(_inner), ListQueuesErrorKind::InvalidParameterException(_inner) => Some(_inner), ListQueuesErrorKind::InvalidRequestException(_inner) => Some(_inner), ListQueuesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListQueuesErrorKind::ThrottlingException(_inner) => Some(_inner), ListQueuesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListQuickConnects` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListQuickConnectsError { /// Kind of error that occurred. pub kind: ListQuickConnectsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListQuickConnects` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListQuickConnectsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListQuickConnectsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListQuickConnectsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListQuickConnectsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListQuickConnectsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListQuickConnectsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListQuickConnectsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListQuickConnectsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListQuickConnectsError { fn code(&self) -> Option<&str> { ListQuickConnectsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListQuickConnectsError { /// Creates a new `ListQuickConnectsError`. pub fn new(kind: ListQuickConnectsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListQuickConnectsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListQuickConnectsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListQuickConnectsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListQuickConnectsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListQuickConnectsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListQuickConnectsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListQuickConnectsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListQuickConnectsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListQuickConnectsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListQuickConnectsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListQuickConnectsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListQuickConnectsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListQuickConnectsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListQuickConnectsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListQuickConnectsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListQuickConnectsErrorKind::InternalServiceException(_inner) => Some(_inner), ListQuickConnectsErrorKind::InvalidParameterException(_inner) => Some(_inner), ListQuickConnectsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListQuickConnectsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListQuickConnectsErrorKind::ThrottlingException(_inner) => Some(_inner), ListQuickConnectsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListRoutingProfileQueues` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListRoutingProfileQueuesError { /// Kind of error that occurred. pub kind: ListRoutingProfileQueuesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListRoutingProfileQueues` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListRoutingProfileQueuesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListRoutingProfileQueuesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListRoutingProfileQueuesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListRoutingProfileQueuesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListRoutingProfileQueuesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListRoutingProfileQueuesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListRoutingProfileQueuesErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListRoutingProfileQueuesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListRoutingProfileQueuesError { fn code(&self) -> Option<&str> { ListRoutingProfileQueuesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListRoutingProfileQueuesError { /// Creates a new `ListRoutingProfileQueuesError`. pub fn new(kind: ListRoutingProfileQueuesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListRoutingProfileQueuesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListRoutingProfileQueuesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListRoutingProfileQueuesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListRoutingProfileQueuesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListRoutingProfileQueuesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListRoutingProfileQueuesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListRoutingProfileQueuesErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListRoutingProfileQueuesErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListRoutingProfileQueuesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListRoutingProfileQueuesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListRoutingProfileQueuesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListRoutingProfileQueuesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListRoutingProfileQueuesErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListRoutingProfileQueuesErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListRoutingProfileQueuesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListRoutingProfileQueuesErrorKind::InternalServiceException(_inner) => Some(_inner), ListRoutingProfileQueuesErrorKind::InvalidParameterException(_inner) => Some(_inner), ListRoutingProfileQueuesErrorKind::InvalidRequestException(_inner) => Some(_inner), ListRoutingProfileQueuesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListRoutingProfileQueuesErrorKind::ThrottlingException(_inner) => Some(_inner), ListRoutingProfileQueuesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListRoutingProfiles` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListRoutingProfilesError { /// Kind of error that occurred. pub kind: ListRoutingProfilesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListRoutingProfiles` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListRoutingProfilesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListRoutingProfilesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListRoutingProfilesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListRoutingProfilesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListRoutingProfilesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListRoutingProfilesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListRoutingProfilesErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListRoutingProfilesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListRoutingProfilesError { fn code(&self) -> Option<&str> { ListRoutingProfilesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListRoutingProfilesError { /// Creates a new `ListRoutingProfilesError`. pub fn new(kind: ListRoutingProfilesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListRoutingProfilesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListRoutingProfilesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListRoutingProfilesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListRoutingProfilesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListRoutingProfilesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListRoutingProfilesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListRoutingProfilesErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListRoutingProfilesErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListRoutingProfilesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListRoutingProfilesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListRoutingProfilesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListRoutingProfilesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListRoutingProfilesErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListRoutingProfilesErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListRoutingProfilesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListRoutingProfilesErrorKind::InternalServiceException(_inner) => Some(_inner), ListRoutingProfilesErrorKind::InvalidParameterException(_inner) => Some(_inner), ListRoutingProfilesErrorKind::InvalidRequestException(_inner) => Some(_inner), ListRoutingProfilesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListRoutingProfilesErrorKind::ThrottlingException(_inner) => Some(_inner), ListRoutingProfilesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListSecurityKeys` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListSecurityKeysError { /// Kind of error that occurred. pub kind: ListSecurityKeysErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListSecurityKeys` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListSecurityKeysErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListSecurityKeysError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListSecurityKeysErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListSecurityKeysErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListSecurityKeysErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListSecurityKeysErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListSecurityKeysErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListSecurityKeysErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListSecurityKeysError { fn code(&self) -> Option<&str> { ListSecurityKeysError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListSecurityKeysError { /// Creates a new `ListSecurityKeysError`. pub fn new(kind: ListSecurityKeysErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListSecurityKeysError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListSecurityKeysErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListSecurityKeysError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListSecurityKeysErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListSecurityKeysErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListSecurityKeysErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListSecurityKeysErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListSecurityKeysErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListSecurityKeysErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListSecurityKeysErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListSecurityKeysErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListSecurityKeysErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListSecurityKeysErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListSecurityKeysErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListSecurityKeysError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListSecurityKeysErrorKind::InternalServiceException(_inner) => Some(_inner), ListSecurityKeysErrorKind::InvalidParameterException(_inner) => Some(_inner), ListSecurityKeysErrorKind::InvalidRequestException(_inner) => Some(_inner), ListSecurityKeysErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListSecurityKeysErrorKind::ThrottlingException(_inner) => Some(_inner), ListSecurityKeysErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListSecurityProfiles` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListSecurityProfilesError { /// Kind of error that occurred. pub kind: ListSecurityProfilesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListSecurityProfiles` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListSecurityProfilesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListSecurityProfilesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListSecurityProfilesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListSecurityProfilesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListSecurityProfilesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListSecurityProfilesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListSecurityProfilesErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListSecurityProfilesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListSecurityProfilesError { fn code(&self) -> Option<&str> { ListSecurityProfilesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListSecurityProfilesError { /// Creates a new `ListSecurityProfilesError`. pub fn new(kind: ListSecurityProfilesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListSecurityProfilesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListSecurityProfilesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListSecurityProfilesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListSecurityProfilesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListSecurityProfilesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListSecurityProfilesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListSecurityProfilesErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListSecurityProfilesErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListSecurityProfilesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListSecurityProfilesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListSecurityProfilesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListSecurityProfilesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListSecurityProfilesErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListSecurityProfilesErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListSecurityProfilesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListSecurityProfilesErrorKind::InternalServiceException(_inner) => Some(_inner), ListSecurityProfilesErrorKind::InvalidParameterException(_inner) => Some(_inner), ListSecurityProfilesErrorKind::InvalidRequestException(_inner) => Some(_inner), ListSecurityProfilesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListSecurityProfilesErrorKind::ThrottlingException(_inner) => Some(_inner), ListSecurityProfilesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListTagsForResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListTagsForResourceError { /// Kind of error that occurred. pub kind: ListTagsForResourceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListTagsForResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListTagsForResourceErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListTagsForResourceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListTagsForResourceErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListTagsForResourceErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListTagsForResourceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListTagsForResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListTagsForResourceErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListTagsForResourceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListTagsForResourceError { fn code(&self) -> Option<&str> { ListTagsForResourceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListTagsForResourceError { /// Creates a new `ListTagsForResourceError`. pub fn new(kind: ListTagsForResourceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListTagsForResourceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListTagsForResourceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListTagsForResourceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListTagsForResourceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListTagsForResourceErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListTagsForResourceErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListTagsForResourceErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListTagsForResourceErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListTagsForResourceErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListTagsForResourceErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListTagsForResourceErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListTagsForResourceErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListTagsForResourceErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListTagsForResourceErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListTagsForResourceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListTagsForResourceErrorKind::InternalServiceException(_inner) => Some(_inner), ListTagsForResourceErrorKind::InvalidParameterException(_inner) => Some(_inner), ListTagsForResourceErrorKind::InvalidRequestException(_inner) => Some(_inner), ListTagsForResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListTagsForResourceErrorKind::ThrottlingException(_inner) => Some(_inner), ListTagsForResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListUseCases` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListUseCasesError { /// Kind of error that occurred. pub kind: ListUseCasesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListUseCases` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListUseCasesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListUseCasesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListUseCasesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListUseCasesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListUseCasesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListUseCasesErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListUseCasesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListUseCasesError { fn code(&self) -> Option<&str> { ListUseCasesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListUseCasesError { /// Creates a new `ListUseCasesError`. pub fn new(kind: ListUseCasesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListUseCasesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListUseCasesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListUseCasesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListUseCasesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListUseCasesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListUseCasesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListUseCasesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListUseCasesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListUseCasesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListUseCasesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListUseCasesErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, ListUseCasesErrorKind::ThrottlingException(_)) } } impl std::error::Error for ListUseCasesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListUseCasesErrorKind::InternalServiceException(_inner) => Some(_inner), ListUseCasesErrorKind::InvalidRequestException(_inner) => Some(_inner), ListUseCasesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListUseCasesErrorKind::ThrottlingException(_inner) => Some(_inner), ListUseCasesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListUserHierarchyGroups` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListUserHierarchyGroupsError { /// Kind of error that occurred. pub kind: ListUserHierarchyGroupsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListUserHierarchyGroups` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListUserHierarchyGroupsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListUserHierarchyGroupsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListUserHierarchyGroupsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListUserHierarchyGroupsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListUserHierarchyGroupsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListUserHierarchyGroupsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListUserHierarchyGroupsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListUserHierarchyGroupsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListUserHierarchyGroupsError { fn code(&self) -> Option<&str> { ListUserHierarchyGroupsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListUserHierarchyGroupsError { /// Creates a new `ListUserHierarchyGroupsError`. pub fn new(kind: ListUserHierarchyGroupsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListUserHierarchyGroupsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListUserHierarchyGroupsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListUserHierarchyGroupsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListUserHierarchyGroupsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListUserHierarchyGroupsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ListUserHierarchyGroupsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ListUserHierarchyGroupsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, ListUserHierarchyGroupsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `ListUserHierarchyGroupsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ListUserHierarchyGroupsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ListUserHierarchyGroupsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ListUserHierarchyGroupsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `ListUserHierarchyGroupsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, ListUserHierarchyGroupsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for ListUserHierarchyGroupsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListUserHierarchyGroupsErrorKind::InternalServiceException(_inner) => Some(_inner), ListUserHierarchyGroupsErrorKind::InvalidParameterException(_inner) => Some(_inner), ListUserHierarchyGroupsErrorKind::InvalidRequestException(_inner) => Some(_inner), ListUserHierarchyGroupsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListUserHierarchyGroupsErrorKind::ThrottlingException(_inner) => Some(_inner), ListUserHierarchyGroupsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ListUsers` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ListUsersError { /// Kind of error that occurred. pub kind: ListUsersErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ListUsers` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ListUsersErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ListUsersError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ListUsersErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ListUsersErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), ListUsersErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ListUsersErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ListUsersErrorKind::ThrottlingException(_inner) => _inner.fmt(f), ListUsersErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ListUsersError { fn code(&self) -> Option<&str> { ListUsersError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ListUsersError { /// Creates a new `ListUsersError`. pub fn new(kind: ListUsersErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ListUsersError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ListUsersErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ListUsersError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ListUsersErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ListUsersErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!(&self.kind, ListUsersErrorKind::InternalServiceException(_)) } /// Returns `true` if the error kind is `ListUsersErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!(&self.kind, ListUsersErrorKind::InvalidParameterException(_)) } /// Returns `true` if the error kind is `ListUsersErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, ListUsersErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `ListUsersErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!(&self.kind, ListUsersErrorKind::ResourceNotFoundException(_)) } /// Returns `true` if the error kind is `ListUsersErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, ListUsersErrorKind::ThrottlingException(_)) } } impl std::error::Error for ListUsersError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ListUsersErrorKind::InternalServiceException(_inner) => Some(_inner), ListUsersErrorKind::InvalidParameterException(_inner) => Some(_inner), ListUsersErrorKind::InvalidRequestException(_inner) => Some(_inner), ListUsersErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ListUsersErrorKind::ThrottlingException(_inner) => Some(_inner), ListUsersErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `ResumeContactRecording` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct ResumeContactRecordingError { /// Kind of error that occurred. pub kind: ResumeContactRecordingErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `ResumeContactRecording` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum ResumeContactRecordingErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for ResumeContactRecordingError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { ResumeContactRecordingErrorKind::InternalServiceException(_inner) => _inner.fmt(f), ResumeContactRecordingErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), ResumeContactRecordingErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), ResumeContactRecordingErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for ResumeContactRecordingError { fn code(&self) -> Option<&str> { ResumeContactRecordingError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl ResumeContactRecordingError { /// Creates a new `ResumeContactRecordingError`. pub fn new(kind: ResumeContactRecordingErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `ResumeContactRecordingError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: ResumeContactRecordingErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `ResumeContactRecordingError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: ResumeContactRecordingErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `ResumeContactRecordingErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, ResumeContactRecordingErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `ResumeContactRecordingErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, ResumeContactRecordingErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `ResumeContactRecordingErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, ResumeContactRecordingErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for ResumeContactRecordingError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { ResumeContactRecordingErrorKind::InternalServiceException(_inner) => Some(_inner), ResumeContactRecordingErrorKind::InvalidRequestException(_inner) => Some(_inner), ResumeContactRecordingErrorKind::ResourceNotFoundException(_inner) => Some(_inner), ResumeContactRecordingErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `StartChatContact` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct StartChatContactError { /// Kind of error that occurred. pub kind: StartChatContactErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `StartChatContact` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum StartChatContactErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for StartChatContactError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { StartChatContactErrorKind::InternalServiceException(_inner) => _inner.fmt(f), StartChatContactErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), StartChatContactErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), StartChatContactErrorKind::LimitExceededException(_inner) => _inner.fmt(f), StartChatContactErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), StartChatContactErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for StartChatContactError { fn code(&self) -> Option<&str> { StartChatContactError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl StartChatContactError { /// Creates a new `StartChatContactError`. pub fn new(kind: StartChatContactErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `StartChatContactError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: StartChatContactErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `StartChatContactError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: StartChatContactErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `StartChatContactErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, StartChatContactErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `StartChatContactErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, StartChatContactErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `StartChatContactErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, StartChatContactErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `StartChatContactErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, StartChatContactErrorKind::LimitExceededException(_) ) } /// Returns `true` if the error kind is `StartChatContactErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, StartChatContactErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for StartChatContactError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { StartChatContactErrorKind::InternalServiceException(_inner) => Some(_inner), StartChatContactErrorKind::InvalidParameterException(_inner) => Some(_inner), StartChatContactErrorKind::InvalidRequestException(_inner) => Some(_inner), StartChatContactErrorKind::LimitExceededException(_inner) => Some(_inner), StartChatContactErrorKind::ResourceNotFoundException(_inner) => Some(_inner), StartChatContactErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `StartContactRecording` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct StartContactRecordingError { /// Kind of error that occurred. pub kind: StartContactRecordingErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `StartContactRecording` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum StartContactRecordingErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for StartContactRecordingError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { StartContactRecordingErrorKind::InternalServiceException(_inner) => _inner.fmt(f), StartContactRecordingErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), StartContactRecordingErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), StartContactRecordingErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), StartContactRecordingErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for StartContactRecordingError { fn code(&self) -> Option<&str> { StartContactRecordingError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl StartContactRecordingError { /// Creates a new `StartContactRecordingError`. pub fn new(kind: StartContactRecordingErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `StartContactRecordingError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: StartContactRecordingErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `StartContactRecordingError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: StartContactRecordingErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `StartContactRecordingErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, StartContactRecordingErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `StartContactRecordingErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, StartContactRecordingErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `StartContactRecordingErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, StartContactRecordingErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `StartContactRecordingErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, StartContactRecordingErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for StartContactRecordingError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { StartContactRecordingErrorKind::InternalServiceException(_inner) => Some(_inner), StartContactRecordingErrorKind::InvalidParameterException(_inner) => Some(_inner), StartContactRecordingErrorKind::InvalidRequestException(_inner) => Some(_inner), StartContactRecordingErrorKind::ResourceNotFoundException(_inner) => Some(_inner), StartContactRecordingErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `StartContactStreaming` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct StartContactStreamingError { /// Kind of error that occurred. pub kind: StartContactStreamingErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `StartContactStreaming` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum StartContactStreamingErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for StartContactStreamingError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { StartContactStreamingErrorKind::InternalServiceException(_inner) => _inner.fmt(f), StartContactStreamingErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), StartContactStreamingErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), StartContactStreamingErrorKind::LimitExceededException(_inner) => _inner.fmt(f), StartContactStreamingErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), StartContactStreamingErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for StartContactStreamingError { fn code(&self) -> Option<&str> { StartContactStreamingError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl StartContactStreamingError { /// Creates a new `StartContactStreamingError`. pub fn new(kind: StartContactStreamingErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `StartContactStreamingError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: StartContactStreamingErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `StartContactStreamingError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: StartContactStreamingErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `StartContactStreamingErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, StartContactStreamingErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `StartContactStreamingErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, StartContactStreamingErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `StartContactStreamingErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, StartContactStreamingErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `StartContactStreamingErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, StartContactStreamingErrorKind::LimitExceededException(_) ) } /// Returns `true` if the error kind is `StartContactStreamingErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, StartContactStreamingErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for StartContactStreamingError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { StartContactStreamingErrorKind::InternalServiceException(_inner) => Some(_inner), StartContactStreamingErrorKind::InvalidParameterException(_inner) => Some(_inner), StartContactStreamingErrorKind::InvalidRequestException(_inner) => Some(_inner), StartContactStreamingErrorKind::LimitExceededException(_inner) => Some(_inner), StartContactStreamingErrorKind::ResourceNotFoundException(_inner) => Some(_inner), StartContactStreamingErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `StartOutboundVoiceContact` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct StartOutboundVoiceContactError { /// Kind of error that occurred. pub kind: StartOutboundVoiceContactErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `StartOutboundVoiceContact` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum StartOutboundVoiceContactErrorKind { /// <p>Outbound calls to the destination number are not allowed.</p> DestinationNotAllowedException(crate::error::DestinationNotAllowedException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The contact is not permitted.</p> OutboundContactNotPermittedException(crate::error::OutboundContactNotPermittedException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for StartOutboundVoiceContactError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { StartOutboundVoiceContactErrorKind::DestinationNotAllowedException(_inner) => { _inner.fmt(f) } StartOutboundVoiceContactErrorKind::InternalServiceException(_inner) => _inner.fmt(f), StartOutboundVoiceContactErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), StartOutboundVoiceContactErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), StartOutboundVoiceContactErrorKind::LimitExceededException(_inner) => _inner.fmt(f), StartOutboundVoiceContactErrorKind::OutboundContactNotPermittedException(_inner) => { _inner.fmt(f) } StartOutboundVoiceContactErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), StartOutboundVoiceContactErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for StartOutboundVoiceContactError { fn code(&self) -> Option<&str> { StartOutboundVoiceContactError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl StartOutboundVoiceContactError { /// Creates a new `StartOutboundVoiceContactError`. pub fn new(kind: StartOutboundVoiceContactErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `StartOutboundVoiceContactError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: StartOutboundVoiceContactErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `StartOutboundVoiceContactError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: StartOutboundVoiceContactErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `StartOutboundVoiceContactErrorKind::DestinationNotAllowedException`. pub fn is_destination_not_allowed_exception(&self) -> bool { matches!( &self.kind, StartOutboundVoiceContactErrorKind::DestinationNotAllowedException(_) ) } /// Returns `true` if the error kind is `StartOutboundVoiceContactErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, StartOutboundVoiceContactErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `StartOutboundVoiceContactErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, StartOutboundVoiceContactErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `StartOutboundVoiceContactErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, StartOutboundVoiceContactErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `StartOutboundVoiceContactErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, StartOutboundVoiceContactErrorKind::LimitExceededException(_) ) } /// Returns `true` if the error kind is `StartOutboundVoiceContactErrorKind::OutboundContactNotPermittedException`. pub fn is_outbound_contact_not_permitted_exception(&self) -> bool { matches!( &self.kind, StartOutboundVoiceContactErrorKind::OutboundContactNotPermittedException(_) ) } /// Returns `true` if the error kind is `StartOutboundVoiceContactErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, StartOutboundVoiceContactErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for StartOutboundVoiceContactError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { StartOutboundVoiceContactErrorKind::DestinationNotAllowedException(_inner) => { Some(_inner) } StartOutboundVoiceContactErrorKind::InternalServiceException(_inner) => Some(_inner), StartOutboundVoiceContactErrorKind::InvalidParameterException(_inner) => Some(_inner), StartOutboundVoiceContactErrorKind::InvalidRequestException(_inner) => Some(_inner), StartOutboundVoiceContactErrorKind::LimitExceededException(_inner) => Some(_inner), StartOutboundVoiceContactErrorKind::OutboundContactNotPermittedException(_inner) => { Some(_inner) } StartOutboundVoiceContactErrorKind::ResourceNotFoundException(_inner) => Some(_inner), StartOutboundVoiceContactErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `StartTaskContact` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct StartTaskContactError { /// Kind of error that occurred. pub kind: StartTaskContactErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `StartTaskContact` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum StartTaskContactErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The service quota has been exceeded.</p> ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for StartTaskContactError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { StartTaskContactErrorKind::InternalServiceException(_inner) => _inner.fmt(f), StartTaskContactErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), StartTaskContactErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), StartTaskContactErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), StartTaskContactErrorKind::ServiceQuotaExceededException(_inner) => _inner.fmt(f), StartTaskContactErrorKind::ThrottlingException(_inner) => _inner.fmt(f), StartTaskContactErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for StartTaskContactError { fn code(&self) -> Option<&str> { StartTaskContactError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl StartTaskContactError { /// Creates a new `StartTaskContactError`. pub fn new(kind: StartTaskContactErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `StartTaskContactError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: StartTaskContactErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `StartTaskContactError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: StartTaskContactErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `StartTaskContactErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, StartTaskContactErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `StartTaskContactErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, StartTaskContactErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `StartTaskContactErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, StartTaskContactErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `StartTaskContactErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, StartTaskContactErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `StartTaskContactErrorKind::ServiceQuotaExceededException`. pub fn is_service_quota_exceeded_exception(&self) -> bool { matches!( &self.kind, StartTaskContactErrorKind::ServiceQuotaExceededException(_) ) } /// Returns `true` if the error kind is `StartTaskContactErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, StartTaskContactErrorKind::ThrottlingException(_) ) } } impl std::error::Error for StartTaskContactError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { StartTaskContactErrorKind::InternalServiceException(_inner) => Some(_inner), StartTaskContactErrorKind::InvalidParameterException(_inner) => Some(_inner), StartTaskContactErrorKind::InvalidRequestException(_inner) => Some(_inner), StartTaskContactErrorKind::ResourceNotFoundException(_inner) => Some(_inner), StartTaskContactErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner), StartTaskContactErrorKind::ThrottlingException(_inner) => Some(_inner), StartTaskContactErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `StopContact` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct StopContactError { /// Kind of error that occurred. pub kind: StopContactErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `StopContact` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum StopContactErrorKind { /// <p>The contact with the specified ID is not active or does not exist.</p> ContactNotFoundException(crate::error::ContactNotFoundException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for StopContactError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { StopContactErrorKind::ContactNotFoundException(_inner) => _inner.fmt(f), StopContactErrorKind::InternalServiceException(_inner) => _inner.fmt(f), StopContactErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), StopContactErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), StopContactErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), StopContactErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for StopContactError { fn code(&self) -> Option<&str> { StopContactError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl StopContactError { /// Creates a new `StopContactError`. pub fn new(kind: StopContactErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `StopContactError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: StopContactErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `StopContactError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: StopContactErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `StopContactErrorKind::ContactNotFoundException`. pub fn is_contact_not_found_exception(&self) -> bool { matches!( &self.kind, StopContactErrorKind::ContactNotFoundException(_) ) } /// Returns `true` if the error kind is `StopContactErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, StopContactErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `StopContactErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, StopContactErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `StopContactErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, StopContactErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `StopContactErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, StopContactErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for StopContactError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { StopContactErrorKind::ContactNotFoundException(_inner) => Some(_inner), StopContactErrorKind::InternalServiceException(_inner) => Some(_inner), StopContactErrorKind::InvalidParameterException(_inner) => Some(_inner), StopContactErrorKind::InvalidRequestException(_inner) => Some(_inner), StopContactErrorKind::ResourceNotFoundException(_inner) => Some(_inner), StopContactErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `StopContactRecording` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct StopContactRecordingError { /// Kind of error that occurred. pub kind: StopContactRecordingErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `StopContactRecording` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum StopContactRecordingErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for StopContactRecordingError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { StopContactRecordingErrorKind::InternalServiceException(_inner) => _inner.fmt(f), StopContactRecordingErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), StopContactRecordingErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), StopContactRecordingErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for StopContactRecordingError { fn code(&self) -> Option<&str> { StopContactRecordingError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl StopContactRecordingError { /// Creates a new `StopContactRecordingError`. pub fn new(kind: StopContactRecordingErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `StopContactRecordingError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: StopContactRecordingErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `StopContactRecordingError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: StopContactRecordingErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `StopContactRecordingErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, StopContactRecordingErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `StopContactRecordingErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, StopContactRecordingErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `StopContactRecordingErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, StopContactRecordingErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for StopContactRecordingError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { StopContactRecordingErrorKind::InternalServiceException(_inner) => Some(_inner), StopContactRecordingErrorKind::InvalidRequestException(_inner) => Some(_inner), StopContactRecordingErrorKind::ResourceNotFoundException(_inner) => Some(_inner), StopContactRecordingErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `StopContactStreaming` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct StopContactStreamingError { /// Kind of error that occurred. pub kind: StopContactStreamingErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `StopContactStreaming` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum StopContactStreamingErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for StopContactStreamingError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { StopContactStreamingErrorKind::InternalServiceException(_inner) => _inner.fmt(f), StopContactStreamingErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), StopContactStreamingErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), StopContactStreamingErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), StopContactStreamingErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for StopContactStreamingError { fn code(&self) -> Option<&str> { StopContactStreamingError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl StopContactStreamingError { /// Creates a new `StopContactStreamingError`. pub fn new(kind: StopContactStreamingErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `StopContactStreamingError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: StopContactStreamingErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `StopContactStreamingError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: StopContactStreamingErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `StopContactStreamingErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, StopContactStreamingErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `StopContactStreamingErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, StopContactStreamingErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `StopContactStreamingErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, StopContactStreamingErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `StopContactStreamingErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, StopContactStreamingErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for StopContactStreamingError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { StopContactStreamingErrorKind::InternalServiceException(_inner) => Some(_inner), StopContactStreamingErrorKind::InvalidParameterException(_inner) => Some(_inner), StopContactStreamingErrorKind::InvalidRequestException(_inner) => Some(_inner), StopContactStreamingErrorKind::ResourceNotFoundException(_inner) => Some(_inner), StopContactStreamingErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `SuspendContactRecording` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct SuspendContactRecordingError { /// Kind of error that occurred. pub kind: SuspendContactRecordingErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `SuspendContactRecording` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum SuspendContactRecordingErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for SuspendContactRecordingError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { SuspendContactRecordingErrorKind::InternalServiceException(_inner) => _inner.fmt(f), SuspendContactRecordingErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), SuspendContactRecordingErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), SuspendContactRecordingErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for SuspendContactRecordingError { fn code(&self) -> Option<&str> { SuspendContactRecordingError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl SuspendContactRecordingError { /// Creates a new `SuspendContactRecordingError`. pub fn new(kind: SuspendContactRecordingErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `SuspendContactRecordingError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: SuspendContactRecordingErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `SuspendContactRecordingError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: SuspendContactRecordingErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `SuspendContactRecordingErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, SuspendContactRecordingErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `SuspendContactRecordingErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, SuspendContactRecordingErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `SuspendContactRecordingErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, SuspendContactRecordingErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for SuspendContactRecordingError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { SuspendContactRecordingErrorKind::InternalServiceException(_inner) => Some(_inner), SuspendContactRecordingErrorKind::InvalidRequestException(_inner) => Some(_inner), SuspendContactRecordingErrorKind::ResourceNotFoundException(_inner) => Some(_inner), SuspendContactRecordingErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `TagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct TagResourceError { /// Kind of error that occurred. pub kind: TagResourceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `TagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum TagResourceErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for TagResourceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { TagResourceErrorKind::InternalServiceException(_inner) => _inner.fmt(f), TagResourceErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), TagResourceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), TagResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), TagResourceErrorKind::ThrottlingException(_inner) => _inner.fmt(f), TagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for TagResourceError { fn code(&self) -> Option<&str> { TagResourceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl TagResourceError { /// Creates a new `TagResourceError`. pub fn new(kind: TagResourceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `TagResourceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: TagResourceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `TagResourceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: TagResourceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `TagResourceErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, TagResourceErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `TagResourceErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, TagResourceErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `TagResourceErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!(&self.kind, TagResourceErrorKind::InvalidRequestException(_)) } /// Returns `true` if the error kind is `TagResourceErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, TagResourceErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `TagResourceErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, TagResourceErrorKind::ThrottlingException(_)) } } impl std::error::Error for TagResourceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { TagResourceErrorKind::InternalServiceException(_inner) => Some(_inner), TagResourceErrorKind::InvalidParameterException(_inner) => Some(_inner), TagResourceErrorKind::InvalidRequestException(_inner) => Some(_inner), TagResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner), TagResourceErrorKind::ThrottlingException(_inner) => Some(_inner), TagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UntagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UntagResourceError { /// Kind of error that occurred. pub kind: UntagResourceErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UntagResource` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UntagResourceErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UntagResourceError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UntagResourceErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UntagResourceErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UntagResourceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UntagResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UntagResourceErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UntagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UntagResourceError { fn code(&self) -> Option<&str> { UntagResourceError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UntagResourceError { /// Creates a new `UntagResourceError`. pub fn new(kind: UntagResourceErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UntagResourceError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UntagResourceErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UntagResourceError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UntagResourceErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UntagResourceErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UntagResourceErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UntagResourceErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UntagResourceErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UntagResourceErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UntagResourceErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UntagResourceErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UntagResourceErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UntagResourceErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, UntagResourceErrorKind::ThrottlingException(_)) } } impl std::error::Error for UntagResourceError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UntagResourceErrorKind::InternalServiceException(_inner) => Some(_inner), UntagResourceErrorKind::InvalidParameterException(_inner) => Some(_inner), UntagResourceErrorKind::InvalidRequestException(_inner) => Some(_inner), UntagResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UntagResourceErrorKind::ThrottlingException(_inner) => Some(_inner), UntagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateAgentStatus` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateAgentStatusError { /// Kind of error that occurred. pub kind: UpdateAgentStatusErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateAgentStatus` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateAgentStatusErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The allowed limit for the resource has been exceeded.</p> LimitExceededException(crate::error::LimitExceededException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateAgentStatusError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateAgentStatusErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), UpdateAgentStatusErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateAgentStatusErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateAgentStatusErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateAgentStatusErrorKind::LimitExceededException(_inner) => _inner.fmt(f), UpdateAgentStatusErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateAgentStatusErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateAgentStatusErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateAgentStatusError { fn code(&self) -> Option<&str> { UpdateAgentStatusError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateAgentStatusError { /// Creates a new `UpdateAgentStatusError`. pub fn new(kind: UpdateAgentStatusErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateAgentStatusError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateAgentStatusErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateAgentStatusError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateAgentStatusErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateAgentStatusErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, UpdateAgentStatusErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `UpdateAgentStatusErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateAgentStatusErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateAgentStatusErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateAgentStatusErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateAgentStatusErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateAgentStatusErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateAgentStatusErrorKind::LimitExceededException`. pub fn is_limit_exceeded_exception(&self) -> bool { matches!( &self.kind, UpdateAgentStatusErrorKind::LimitExceededException(_) ) } /// Returns `true` if the error kind is `UpdateAgentStatusErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateAgentStatusErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateAgentStatusErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateAgentStatusErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateAgentStatusError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateAgentStatusErrorKind::DuplicateResourceException(_inner) => Some(_inner), UpdateAgentStatusErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateAgentStatusErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateAgentStatusErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateAgentStatusErrorKind::LimitExceededException(_inner) => Some(_inner), UpdateAgentStatusErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateAgentStatusErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateAgentStatusErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateContactAttributes` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateContactAttributesError { /// Kind of error that occurred. pub kind: UpdateContactAttributesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateContactAttributes` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateContactAttributesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateContactAttributesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateContactAttributesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateContactAttributesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateContactAttributesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateContactAttributesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateContactAttributesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateContactAttributesError { fn code(&self) -> Option<&str> { UpdateContactAttributesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateContactAttributesError { /// Creates a new `UpdateContactAttributesError`. pub fn new(kind: UpdateContactAttributesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateContactAttributesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateContactAttributesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateContactAttributesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateContactAttributesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateContactAttributesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateContactAttributesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateContactAttributesErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateContactAttributesErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateContactAttributesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateContactAttributesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateContactAttributesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateContactAttributesErrorKind::ResourceNotFoundException(_) ) } } impl std::error::Error for UpdateContactAttributesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateContactAttributesErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateContactAttributesErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateContactAttributesErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateContactAttributesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateContactAttributesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateContactFlowContent` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateContactFlowContentError { /// Kind of error that occurred. pub kind: UpdateContactFlowContentErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateContactFlowContent` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateContactFlowContentErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>The contact flow is not valid.</p> InvalidContactFlowException(crate::error::InvalidContactFlowException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateContactFlowContentError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateContactFlowContentErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateContactFlowContentErrorKind::InvalidContactFlowException(_inner) => _inner.fmt(f), UpdateContactFlowContentErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateContactFlowContentErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateContactFlowContentErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateContactFlowContentErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateContactFlowContentErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateContactFlowContentError { fn code(&self) -> Option<&str> { UpdateContactFlowContentError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateContactFlowContentError { /// Creates a new `UpdateContactFlowContentError`. pub fn new(kind: UpdateContactFlowContentErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateContactFlowContentError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateContactFlowContentErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateContactFlowContentError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateContactFlowContentErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateContactFlowContentErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowContentErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateContactFlowContentErrorKind::InvalidContactFlowException`. pub fn is_invalid_contact_flow_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowContentErrorKind::InvalidContactFlowException(_) ) } /// Returns `true` if the error kind is `UpdateContactFlowContentErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowContentErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateContactFlowContentErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowContentErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateContactFlowContentErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowContentErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateContactFlowContentErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowContentErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateContactFlowContentError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateContactFlowContentErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateContactFlowContentErrorKind::InvalidContactFlowException(_inner) => Some(_inner), UpdateContactFlowContentErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateContactFlowContentErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateContactFlowContentErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateContactFlowContentErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateContactFlowContentErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateContactFlowName` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateContactFlowNameError { /// Kind of error that occurred. pub kind: UpdateContactFlowNameErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateContactFlowName` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateContactFlowNameErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateContactFlowNameError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateContactFlowNameErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), UpdateContactFlowNameErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateContactFlowNameErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateContactFlowNameErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateContactFlowNameErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateContactFlowNameErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateContactFlowNameErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateContactFlowNameError { fn code(&self) -> Option<&str> { UpdateContactFlowNameError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateContactFlowNameError { /// Creates a new `UpdateContactFlowNameError`. pub fn new(kind: UpdateContactFlowNameErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateContactFlowNameError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateContactFlowNameErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateContactFlowNameError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateContactFlowNameErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateContactFlowNameErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowNameErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `UpdateContactFlowNameErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowNameErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateContactFlowNameErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowNameErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateContactFlowNameErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowNameErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateContactFlowNameErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowNameErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateContactFlowNameErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateContactFlowNameErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateContactFlowNameError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateContactFlowNameErrorKind::DuplicateResourceException(_inner) => Some(_inner), UpdateContactFlowNameErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateContactFlowNameErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateContactFlowNameErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateContactFlowNameErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateContactFlowNameErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateContactFlowNameErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateHoursOfOperation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateHoursOfOperationError { /// Kind of error that occurred. pub kind: UpdateHoursOfOperationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateHoursOfOperation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateHoursOfOperationErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateHoursOfOperationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateHoursOfOperationErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), UpdateHoursOfOperationErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateHoursOfOperationErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateHoursOfOperationErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateHoursOfOperationErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateHoursOfOperationErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateHoursOfOperationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateHoursOfOperationError { fn code(&self) -> Option<&str> { UpdateHoursOfOperationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateHoursOfOperationError { /// Creates a new `UpdateHoursOfOperationError`. pub fn new(kind: UpdateHoursOfOperationErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateHoursOfOperationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateHoursOfOperationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateHoursOfOperationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateHoursOfOperationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateHoursOfOperationErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, UpdateHoursOfOperationErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `UpdateHoursOfOperationErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateHoursOfOperationErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateHoursOfOperationErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateHoursOfOperationErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateHoursOfOperationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateHoursOfOperationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateHoursOfOperationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateHoursOfOperationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateHoursOfOperationErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateHoursOfOperationErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateHoursOfOperationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateHoursOfOperationErrorKind::DuplicateResourceException(_inner) => Some(_inner), UpdateHoursOfOperationErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateHoursOfOperationErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateHoursOfOperationErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateHoursOfOperationErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateHoursOfOperationErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateHoursOfOperationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateInstanceAttribute` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateInstanceAttributeError { /// Kind of error that occurred. pub kind: UpdateInstanceAttributeErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateInstanceAttribute` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateInstanceAttributeErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateInstanceAttributeError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateInstanceAttributeErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateInstanceAttributeErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateInstanceAttributeErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateInstanceAttributeErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateInstanceAttributeErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateInstanceAttributeErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateInstanceAttributeError { fn code(&self) -> Option<&str> { UpdateInstanceAttributeError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateInstanceAttributeError { /// Creates a new `UpdateInstanceAttributeError`. pub fn new(kind: UpdateInstanceAttributeErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateInstanceAttributeError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateInstanceAttributeErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateInstanceAttributeError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateInstanceAttributeErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateInstanceAttributeErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateInstanceAttributeErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateInstanceAttributeErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateInstanceAttributeErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateInstanceAttributeErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateInstanceAttributeErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateInstanceAttributeErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateInstanceAttributeErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateInstanceAttributeErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateInstanceAttributeErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateInstanceAttributeError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateInstanceAttributeErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateInstanceAttributeErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateInstanceAttributeErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateInstanceAttributeErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateInstanceAttributeErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateInstanceAttributeErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateInstanceStorageConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateInstanceStorageConfigError { /// Kind of error that occurred. pub kind: UpdateInstanceStorageConfigErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateInstanceStorageConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateInstanceStorageConfigErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateInstanceStorageConfigError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateInstanceStorageConfigErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateInstanceStorageConfigErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } UpdateInstanceStorageConfigErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateInstanceStorageConfigErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } UpdateInstanceStorageConfigErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateInstanceStorageConfigErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateInstanceStorageConfigError { fn code(&self) -> Option<&str> { UpdateInstanceStorageConfigError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateInstanceStorageConfigError { /// Creates a new `UpdateInstanceStorageConfigError`. pub fn new(kind: UpdateInstanceStorageConfigErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateInstanceStorageConfigError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateInstanceStorageConfigErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateInstanceStorageConfigError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateInstanceStorageConfigErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateInstanceStorageConfigErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateInstanceStorageConfigErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateInstanceStorageConfigErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateInstanceStorageConfigErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateInstanceStorageConfigErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateInstanceStorageConfigErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateInstanceStorageConfigErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateInstanceStorageConfigErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateInstanceStorageConfigErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateInstanceStorageConfigErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateInstanceStorageConfigError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateInstanceStorageConfigErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateInstanceStorageConfigErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateInstanceStorageConfigErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateInstanceStorageConfigErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateInstanceStorageConfigErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateInstanceStorageConfigErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateQueueHoursOfOperation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateQueueHoursOfOperationError { /// Kind of error that occurred. pub kind: UpdateQueueHoursOfOperationErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateQueueHoursOfOperation` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateQueueHoursOfOperationErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateQueueHoursOfOperationError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateQueueHoursOfOperationErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateQueueHoursOfOperationErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } UpdateQueueHoursOfOperationErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateQueueHoursOfOperationErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } UpdateQueueHoursOfOperationErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateQueueHoursOfOperationErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateQueueHoursOfOperationError { fn code(&self) -> Option<&str> { UpdateQueueHoursOfOperationError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateQueueHoursOfOperationError { /// Creates a new `UpdateQueueHoursOfOperationError`. pub fn new(kind: UpdateQueueHoursOfOperationErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateQueueHoursOfOperationError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateQueueHoursOfOperationErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateQueueHoursOfOperationError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateQueueHoursOfOperationErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateQueueHoursOfOperationErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateQueueHoursOfOperationErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateQueueHoursOfOperationErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateQueueHoursOfOperationErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateQueueHoursOfOperationErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateQueueHoursOfOperationErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateQueueHoursOfOperationErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateQueueHoursOfOperationErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateQueueHoursOfOperationErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateQueueHoursOfOperationErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateQueueHoursOfOperationError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateQueueHoursOfOperationErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateQueueHoursOfOperationErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateQueueHoursOfOperationErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateQueueHoursOfOperationErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateQueueHoursOfOperationErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateQueueHoursOfOperationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateQueueMaxContacts` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateQueueMaxContactsError { /// Kind of error that occurred. pub kind: UpdateQueueMaxContactsErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateQueueMaxContacts` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateQueueMaxContactsErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateQueueMaxContactsError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateQueueMaxContactsErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateQueueMaxContactsErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateQueueMaxContactsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateQueueMaxContactsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateQueueMaxContactsErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateQueueMaxContactsErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateQueueMaxContactsError { fn code(&self) -> Option<&str> { UpdateQueueMaxContactsError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateQueueMaxContactsError { /// Creates a new `UpdateQueueMaxContactsError`. pub fn new(kind: UpdateQueueMaxContactsErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateQueueMaxContactsError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateQueueMaxContactsErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateQueueMaxContactsError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateQueueMaxContactsErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateQueueMaxContactsErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateQueueMaxContactsErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateQueueMaxContactsErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateQueueMaxContactsErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateQueueMaxContactsErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateQueueMaxContactsErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateQueueMaxContactsErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateQueueMaxContactsErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateQueueMaxContactsErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateQueueMaxContactsErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateQueueMaxContactsError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateQueueMaxContactsErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateQueueMaxContactsErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateQueueMaxContactsErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateQueueMaxContactsErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateQueueMaxContactsErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateQueueMaxContactsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateQueueName` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateQueueNameError { /// Kind of error that occurred. pub kind: UpdateQueueNameErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateQueueName` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateQueueNameErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateQueueNameError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateQueueNameErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), UpdateQueueNameErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateQueueNameErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateQueueNameErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateQueueNameErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateQueueNameErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateQueueNameErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateQueueNameError { fn code(&self) -> Option<&str> { UpdateQueueNameError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateQueueNameError { /// Creates a new `UpdateQueueNameError`. pub fn new(kind: UpdateQueueNameErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateQueueNameError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateQueueNameErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateQueueNameError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateQueueNameErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateQueueNameErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, UpdateQueueNameErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `UpdateQueueNameErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateQueueNameErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateQueueNameErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateQueueNameErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateQueueNameErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateQueueNameErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateQueueNameErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateQueueNameErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateQueueNameErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!(&self.kind, UpdateQueueNameErrorKind::ThrottlingException(_)) } } impl std::error::Error for UpdateQueueNameError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateQueueNameErrorKind::DuplicateResourceException(_inner) => Some(_inner), UpdateQueueNameErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateQueueNameErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateQueueNameErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateQueueNameErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateQueueNameErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateQueueNameErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateQueueOutboundCallerConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateQueueOutboundCallerConfigError { /// Kind of error that occurred. pub kind: UpdateQueueOutboundCallerConfigErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateQueueOutboundCallerConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateQueueOutboundCallerConfigErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateQueueOutboundCallerConfigError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateQueueOutboundCallerConfigErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } UpdateQueueOutboundCallerConfigErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } UpdateQueueOutboundCallerConfigErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } UpdateQueueOutboundCallerConfigErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } UpdateQueueOutboundCallerConfigErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateQueueOutboundCallerConfigErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateQueueOutboundCallerConfigError { fn code(&self) -> Option<&str> { UpdateQueueOutboundCallerConfigError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateQueueOutboundCallerConfigError { /// Creates a new `UpdateQueueOutboundCallerConfigError`. pub fn new( kind: UpdateQueueOutboundCallerConfigErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `UpdateQueueOutboundCallerConfigError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateQueueOutboundCallerConfigErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateQueueOutboundCallerConfigError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateQueueOutboundCallerConfigErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateQueueOutboundCallerConfigErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateQueueOutboundCallerConfigErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateQueueOutboundCallerConfigErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateQueueOutboundCallerConfigErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateQueueOutboundCallerConfigErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateQueueOutboundCallerConfigErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateQueueOutboundCallerConfigErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateQueueOutboundCallerConfigErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateQueueOutboundCallerConfigErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateQueueOutboundCallerConfigErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateQueueOutboundCallerConfigError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateQueueOutboundCallerConfigErrorKind::InternalServiceException(_inner) => { Some(_inner) } UpdateQueueOutboundCallerConfigErrorKind::InvalidParameterException(_inner) => { Some(_inner) } UpdateQueueOutboundCallerConfigErrorKind::InvalidRequestException(_inner) => { Some(_inner) } UpdateQueueOutboundCallerConfigErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } UpdateQueueOutboundCallerConfigErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateQueueOutboundCallerConfigErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateQueueStatus` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateQueueStatusError { /// Kind of error that occurred. pub kind: UpdateQueueStatusErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateQueueStatus` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateQueueStatusErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateQueueStatusError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateQueueStatusErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateQueueStatusErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateQueueStatusErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateQueueStatusErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateQueueStatusErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateQueueStatusErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateQueueStatusError { fn code(&self) -> Option<&str> { UpdateQueueStatusError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateQueueStatusError { /// Creates a new `UpdateQueueStatusError`. pub fn new(kind: UpdateQueueStatusErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateQueueStatusError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateQueueStatusErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateQueueStatusError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateQueueStatusErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateQueueStatusErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateQueueStatusErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateQueueStatusErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateQueueStatusErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateQueueStatusErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateQueueStatusErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateQueueStatusErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateQueueStatusErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateQueueStatusErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateQueueStatusErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateQueueStatusError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateQueueStatusErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateQueueStatusErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateQueueStatusErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateQueueStatusErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateQueueStatusErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateQueueStatusErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateQuickConnectConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateQuickConnectConfigError { /// Kind of error that occurred. pub kind: UpdateQuickConnectConfigErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateQuickConnectConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateQuickConnectConfigErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateQuickConnectConfigError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateQuickConnectConfigErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateQuickConnectConfigErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateQuickConnectConfigErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateQuickConnectConfigErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateQuickConnectConfigErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateQuickConnectConfigErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateQuickConnectConfigError { fn code(&self) -> Option<&str> { UpdateQuickConnectConfigError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateQuickConnectConfigError { /// Creates a new `UpdateQuickConnectConfigError`. pub fn new(kind: UpdateQuickConnectConfigErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateQuickConnectConfigError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateQuickConnectConfigErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateQuickConnectConfigError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateQuickConnectConfigErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateQuickConnectConfigErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateQuickConnectConfigErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateQuickConnectConfigErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateQuickConnectConfigErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateQuickConnectConfigErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateQuickConnectConfigErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateQuickConnectConfigErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateQuickConnectConfigErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateQuickConnectConfigErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateQuickConnectConfigErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateQuickConnectConfigError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateQuickConnectConfigErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateQuickConnectConfigErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateQuickConnectConfigErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateQuickConnectConfigErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateQuickConnectConfigErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateQuickConnectConfigErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateQuickConnectName` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateQuickConnectNameError { /// Kind of error that occurred. pub kind: UpdateQuickConnectNameErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateQuickConnectName` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateQuickConnectNameErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateQuickConnectNameError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateQuickConnectNameErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateQuickConnectNameErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateQuickConnectNameErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateQuickConnectNameErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateQuickConnectNameErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateQuickConnectNameErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateQuickConnectNameError { fn code(&self) -> Option<&str> { UpdateQuickConnectNameError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateQuickConnectNameError { /// Creates a new `UpdateQuickConnectNameError`. pub fn new(kind: UpdateQuickConnectNameErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateQuickConnectNameError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateQuickConnectNameErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateQuickConnectNameError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateQuickConnectNameErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateQuickConnectNameErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateQuickConnectNameErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateQuickConnectNameErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateQuickConnectNameErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateQuickConnectNameErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateQuickConnectNameErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateQuickConnectNameErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateQuickConnectNameErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateQuickConnectNameErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateQuickConnectNameErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateQuickConnectNameError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateQuickConnectNameErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateQuickConnectNameErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateQuickConnectNameErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateQuickConnectNameErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateQuickConnectNameErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateQuickConnectNameErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateRoutingProfileConcurrency` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateRoutingProfileConcurrencyError { /// Kind of error that occurred. pub kind: UpdateRoutingProfileConcurrencyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateRoutingProfileConcurrency` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateRoutingProfileConcurrencyErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateRoutingProfileConcurrencyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateRoutingProfileConcurrencyErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } UpdateRoutingProfileConcurrencyErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } UpdateRoutingProfileConcurrencyErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } UpdateRoutingProfileConcurrencyErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } UpdateRoutingProfileConcurrencyErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateRoutingProfileConcurrencyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateRoutingProfileConcurrencyError { fn code(&self) -> Option<&str> { UpdateRoutingProfileConcurrencyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateRoutingProfileConcurrencyError { /// Creates a new `UpdateRoutingProfileConcurrencyError`. pub fn new( kind: UpdateRoutingProfileConcurrencyErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `UpdateRoutingProfileConcurrencyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateRoutingProfileConcurrencyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateRoutingProfileConcurrencyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateRoutingProfileConcurrencyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateRoutingProfileConcurrencyErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileConcurrencyErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileConcurrencyErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileConcurrencyErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileConcurrencyErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileConcurrencyErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileConcurrencyErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileConcurrencyErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileConcurrencyErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileConcurrencyErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateRoutingProfileConcurrencyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateRoutingProfileConcurrencyErrorKind::InternalServiceException(_inner) => { Some(_inner) } UpdateRoutingProfileConcurrencyErrorKind::InvalidParameterException(_inner) => { Some(_inner) } UpdateRoutingProfileConcurrencyErrorKind::InvalidRequestException(_inner) => { Some(_inner) } UpdateRoutingProfileConcurrencyErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } UpdateRoutingProfileConcurrencyErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateRoutingProfileConcurrencyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateRoutingProfileDefaultOutboundQueue` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateRoutingProfileDefaultOutboundQueueError { /// Kind of error that occurred. pub kind: UpdateRoutingProfileDefaultOutboundQueueErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateRoutingProfileDefaultOutboundQueue` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateRoutingProfileDefaultOutboundQueueErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateRoutingProfileDefaultOutboundQueueError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateRoutingProfileDefaultOutboundQueueErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } UpdateRoutingProfileDefaultOutboundQueueErrorKind::InvalidParameterException( _inner, ) => _inner.fmt(f), UpdateRoutingProfileDefaultOutboundQueueErrorKind::InvalidRequestException(_inner) => { _inner.fmt(f) } UpdateRoutingProfileDefaultOutboundQueueErrorKind::ResourceNotFoundException( _inner, ) => _inner.fmt(f), UpdateRoutingProfileDefaultOutboundQueueErrorKind::ThrottlingException(_inner) => { _inner.fmt(f) } UpdateRoutingProfileDefaultOutboundQueueErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateRoutingProfileDefaultOutboundQueueError { fn code(&self) -> Option<&str> { UpdateRoutingProfileDefaultOutboundQueueError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateRoutingProfileDefaultOutboundQueueError { /// Creates a new `UpdateRoutingProfileDefaultOutboundQueueError`. pub fn new( kind: UpdateRoutingProfileDefaultOutboundQueueErrorKind, meta: aws_smithy_types::Error, ) -> Self { Self { kind, meta } } /// Creates the `UpdateRoutingProfileDefaultOutboundQueueError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateRoutingProfileDefaultOutboundQueueErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateRoutingProfileDefaultOutboundQueueError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateRoutingProfileDefaultOutboundQueueErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateRoutingProfileDefaultOutboundQueueErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileDefaultOutboundQueueErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileDefaultOutboundQueueErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileDefaultOutboundQueueErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileDefaultOutboundQueueErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileDefaultOutboundQueueErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileDefaultOutboundQueueErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileDefaultOutboundQueueErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileDefaultOutboundQueueErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileDefaultOutboundQueueErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateRoutingProfileDefaultOutboundQueueError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateRoutingProfileDefaultOutboundQueueErrorKind::InternalServiceException(_inner) => { Some(_inner) } UpdateRoutingProfileDefaultOutboundQueueErrorKind::InvalidParameterException( _inner, ) => Some(_inner), UpdateRoutingProfileDefaultOutboundQueueErrorKind::InvalidRequestException(_inner) => { Some(_inner) } UpdateRoutingProfileDefaultOutboundQueueErrorKind::ResourceNotFoundException( _inner, ) => Some(_inner), UpdateRoutingProfileDefaultOutboundQueueErrorKind::ThrottlingException(_inner) => { Some(_inner) } UpdateRoutingProfileDefaultOutboundQueueErrorKind::Unhandled(_inner) => { Some(_inner.as_ref()) } } } } /// Error type for the `UpdateRoutingProfileName` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateRoutingProfileNameError { /// Kind of error that occurred. pub kind: UpdateRoutingProfileNameErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateRoutingProfileName` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateRoutingProfileNameErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateRoutingProfileNameError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateRoutingProfileNameErrorKind::DuplicateResourceException(_inner) => _inner.fmt(f), UpdateRoutingProfileNameErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateRoutingProfileNameErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateRoutingProfileNameErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateRoutingProfileNameErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateRoutingProfileNameErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateRoutingProfileNameErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateRoutingProfileNameError { fn code(&self) -> Option<&str> { UpdateRoutingProfileNameError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateRoutingProfileNameError { /// Creates a new `UpdateRoutingProfileNameError`. pub fn new(kind: UpdateRoutingProfileNameErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateRoutingProfileNameError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateRoutingProfileNameErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateRoutingProfileNameError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateRoutingProfileNameErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateRoutingProfileNameErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileNameErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileNameErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileNameErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileNameErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileNameErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileNameErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileNameErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileNameErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileNameErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileNameErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileNameErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateRoutingProfileNameError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateRoutingProfileNameErrorKind::DuplicateResourceException(_inner) => Some(_inner), UpdateRoutingProfileNameErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateRoutingProfileNameErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateRoutingProfileNameErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateRoutingProfileNameErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateRoutingProfileNameErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateRoutingProfileNameErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateRoutingProfileQueues` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateRoutingProfileQueuesError { /// Kind of error that occurred. pub kind: UpdateRoutingProfileQueuesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateRoutingProfileQueues` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateRoutingProfileQueuesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateRoutingProfileQueuesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateRoutingProfileQueuesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateRoutingProfileQueuesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateRoutingProfileQueuesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateRoutingProfileQueuesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateRoutingProfileQueuesErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateRoutingProfileQueuesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateRoutingProfileQueuesError { fn code(&self) -> Option<&str> { UpdateRoutingProfileQueuesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateRoutingProfileQueuesError { /// Creates a new `UpdateRoutingProfileQueuesError`. pub fn new(kind: UpdateRoutingProfileQueuesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateRoutingProfileQueuesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateRoutingProfileQueuesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateRoutingProfileQueuesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateRoutingProfileQueuesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateRoutingProfileQueuesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileQueuesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileQueuesErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileQueuesErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileQueuesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileQueuesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileQueuesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileQueuesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateRoutingProfileQueuesErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateRoutingProfileQueuesErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateRoutingProfileQueuesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateRoutingProfileQueuesErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateRoutingProfileQueuesErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateRoutingProfileQueuesErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateRoutingProfileQueuesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateRoutingProfileQueuesErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateRoutingProfileQueuesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateUserHierarchy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateUserHierarchyError { /// Kind of error that occurred. pub kind: UpdateUserHierarchyErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateUserHierarchy` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateUserHierarchyErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateUserHierarchyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateUserHierarchyErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateUserHierarchyErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateUserHierarchyErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateUserHierarchyErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateUserHierarchyErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateUserHierarchyErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateUserHierarchyError { fn code(&self) -> Option<&str> { UpdateUserHierarchyError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateUserHierarchyError { /// Creates a new `UpdateUserHierarchyError`. pub fn new(kind: UpdateUserHierarchyErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateUserHierarchyError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateUserHierarchyErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateUserHierarchyError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateUserHierarchyErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateUserHierarchyErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateUserHierarchyError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateUserHierarchyErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateUserHierarchyErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateUserHierarchyErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateUserHierarchyErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateUserHierarchyErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateUserHierarchyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateUserHierarchyGroupName` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateUserHierarchyGroupNameError { /// Kind of error that occurred. pub kind: UpdateUserHierarchyGroupNameErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateUserHierarchyGroupName` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateUserHierarchyGroupNameErrorKind { /// <p>A resource with the specified name already exists.</p> DuplicateResourceException(crate::error::DuplicateResourceException), /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateUserHierarchyGroupNameError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateUserHierarchyGroupNameErrorKind::DuplicateResourceException(_inner) => { _inner.fmt(f) } UpdateUserHierarchyGroupNameErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } UpdateUserHierarchyGroupNameErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } UpdateUserHierarchyGroupNameErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateUserHierarchyGroupNameErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } UpdateUserHierarchyGroupNameErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateUserHierarchyGroupNameErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateUserHierarchyGroupNameError { fn code(&self) -> Option<&str> { UpdateUserHierarchyGroupNameError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateUserHierarchyGroupNameError { /// Creates a new `UpdateUserHierarchyGroupNameError`. pub fn new(kind: UpdateUserHierarchyGroupNameErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateUserHierarchyGroupNameError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateUserHierarchyGroupNameErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateUserHierarchyGroupNameError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateUserHierarchyGroupNameErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateUserHierarchyGroupNameErrorKind::DuplicateResourceException`. pub fn is_duplicate_resource_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyGroupNameErrorKind::DuplicateResourceException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyGroupNameErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyGroupNameErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyGroupNameErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyGroupNameErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyGroupNameErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyGroupNameErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyGroupNameErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyGroupNameErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyGroupNameErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyGroupNameErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateUserHierarchyGroupNameError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateUserHierarchyGroupNameErrorKind::DuplicateResourceException(_inner) => { Some(_inner) } UpdateUserHierarchyGroupNameErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateUserHierarchyGroupNameErrorKind::InvalidParameterException(_inner) => { Some(_inner) } UpdateUserHierarchyGroupNameErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateUserHierarchyGroupNameErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } UpdateUserHierarchyGroupNameErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateUserHierarchyGroupNameErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateUserHierarchyStructure` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateUserHierarchyStructureError { /// Kind of error that occurred. pub kind: UpdateUserHierarchyStructureErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateUserHierarchyStructure` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateUserHierarchyStructureErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>That resource is already in use. Please try another.</p> ResourceInUseException(crate::error::ResourceInUseException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateUserHierarchyStructureError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateUserHierarchyStructureErrorKind::InternalServiceException(_inner) => { _inner.fmt(f) } UpdateUserHierarchyStructureErrorKind::InvalidParameterException(_inner) => { _inner.fmt(f) } UpdateUserHierarchyStructureErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateUserHierarchyStructureErrorKind::ResourceInUseException(_inner) => _inner.fmt(f), UpdateUserHierarchyStructureErrorKind::ResourceNotFoundException(_inner) => { _inner.fmt(f) } UpdateUserHierarchyStructureErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateUserHierarchyStructureErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateUserHierarchyStructureError { fn code(&self) -> Option<&str> { UpdateUserHierarchyStructureError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateUserHierarchyStructureError { /// Creates a new `UpdateUserHierarchyStructureError`. pub fn new(kind: UpdateUserHierarchyStructureErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateUserHierarchyStructureError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateUserHierarchyStructureErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateUserHierarchyStructureError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateUserHierarchyStructureErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateUserHierarchyStructureErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyStructureErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyStructureErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyStructureErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyStructureErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyStructureErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyStructureErrorKind::ResourceInUseException`. pub fn is_resource_in_use_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyStructureErrorKind::ResourceInUseException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyStructureErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyStructureErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateUserHierarchyStructureErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateUserHierarchyStructureErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateUserHierarchyStructureError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateUserHierarchyStructureErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateUserHierarchyStructureErrorKind::InvalidParameterException(_inner) => { Some(_inner) } UpdateUserHierarchyStructureErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateUserHierarchyStructureErrorKind::ResourceInUseException(_inner) => Some(_inner), UpdateUserHierarchyStructureErrorKind::ResourceNotFoundException(_inner) => { Some(_inner) } UpdateUserHierarchyStructureErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateUserHierarchyStructureErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateUserIdentityInfo` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateUserIdentityInfoError { /// Kind of error that occurred. pub kind: UpdateUserIdentityInfoErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateUserIdentityInfo` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateUserIdentityInfoErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateUserIdentityInfoError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateUserIdentityInfoErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateUserIdentityInfoErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateUserIdentityInfoErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateUserIdentityInfoErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateUserIdentityInfoErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateUserIdentityInfoErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateUserIdentityInfoError { fn code(&self) -> Option<&str> { UpdateUserIdentityInfoError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateUserIdentityInfoError { /// Creates a new `UpdateUserIdentityInfoError`. pub fn new(kind: UpdateUserIdentityInfoErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateUserIdentityInfoError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateUserIdentityInfoErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateUserIdentityInfoError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateUserIdentityInfoErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateUserIdentityInfoErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateUserIdentityInfoErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateUserIdentityInfoErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateUserIdentityInfoErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateUserIdentityInfoErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateUserIdentityInfoErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateUserIdentityInfoErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateUserIdentityInfoErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateUserIdentityInfoErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateUserIdentityInfoErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateUserIdentityInfoError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateUserIdentityInfoErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateUserIdentityInfoErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateUserIdentityInfoErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateUserIdentityInfoErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateUserIdentityInfoErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateUserIdentityInfoErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateUserPhoneConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateUserPhoneConfigError { /// Kind of error that occurred. pub kind: UpdateUserPhoneConfigErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateUserPhoneConfig` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateUserPhoneConfigErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateUserPhoneConfigError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateUserPhoneConfigErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateUserPhoneConfigErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateUserPhoneConfigErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateUserPhoneConfigErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateUserPhoneConfigErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateUserPhoneConfigErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateUserPhoneConfigError { fn code(&self) -> Option<&str> { UpdateUserPhoneConfigError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateUserPhoneConfigError { /// Creates a new `UpdateUserPhoneConfigError`. pub fn new(kind: UpdateUserPhoneConfigErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateUserPhoneConfigError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateUserPhoneConfigErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateUserPhoneConfigError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateUserPhoneConfigErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateUserPhoneConfigErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateUserPhoneConfigErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateUserPhoneConfigErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateUserPhoneConfigErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateUserPhoneConfigErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateUserPhoneConfigErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateUserPhoneConfigErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateUserPhoneConfigErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateUserPhoneConfigErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateUserPhoneConfigErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateUserPhoneConfigError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateUserPhoneConfigErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateUserPhoneConfigErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateUserPhoneConfigErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateUserPhoneConfigErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateUserPhoneConfigErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateUserPhoneConfigErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateUserRoutingProfile` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateUserRoutingProfileError { /// Kind of error that occurred. pub kind: UpdateUserRoutingProfileErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateUserRoutingProfile` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateUserRoutingProfileErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateUserRoutingProfileError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateUserRoutingProfileErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateUserRoutingProfileErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateUserRoutingProfileErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateUserRoutingProfileErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateUserRoutingProfileErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateUserRoutingProfileErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateUserRoutingProfileError { fn code(&self) -> Option<&str> { UpdateUserRoutingProfileError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateUserRoutingProfileError { /// Creates a new `UpdateUserRoutingProfileError`. pub fn new(kind: UpdateUserRoutingProfileErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateUserRoutingProfileError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateUserRoutingProfileErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateUserRoutingProfileError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateUserRoutingProfileErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateUserRoutingProfileErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateUserRoutingProfileErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateUserRoutingProfileErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateUserRoutingProfileErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateUserRoutingProfileErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateUserRoutingProfileErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateUserRoutingProfileErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateUserRoutingProfileErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateUserRoutingProfileErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateUserRoutingProfileErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateUserRoutingProfileError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateUserRoutingProfileErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateUserRoutingProfileErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateUserRoutingProfileErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateUserRoutingProfileErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateUserRoutingProfileErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateUserRoutingProfileErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// Error type for the `UpdateUserSecurityProfiles` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub struct UpdateUserSecurityProfilesError { /// Kind of error that occurred. pub kind: UpdateUserSecurityProfilesErrorKind, /// Additional metadata about the error, including error code, message, and request ID. pub(crate) meta: aws_smithy_types::Error, } /// Types of errors that can occur for the `UpdateUserSecurityProfiles` operation. #[non_exhaustive] #[derive(std::fmt::Debug)] pub enum UpdateUserSecurityProfilesErrorKind { /// <p>Request processing failed because of an error or failure with the service.</p> InternalServiceException(crate::error::InternalServiceException), /// <p>One or more of the specified parameters are not valid.</p> InvalidParameterException(crate::error::InvalidParameterException), /// <p>The request is not valid.</p> InvalidRequestException(crate::error::InvalidRequestException), /// <p>The specified resource was not found.</p> ResourceNotFoundException(crate::error::ResourceNotFoundException), /// <p>The throttling limit has been exceeded.</p> ThrottlingException(crate::error::ThrottlingException), /// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>), } impl std::fmt::Display for UpdateUserSecurityProfilesError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.kind { UpdateUserSecurityProfilesErrorKind::InternalServiceException(_inner) => _inner.fmt(f), UpdateUserSecurityProfilesErrorKind::InvalidParameterException(_inner) => _inner.fmt(f), UpdateUserSecurityProfilesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f), UpdateUserSecurityProfilesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f), UpdateUserSecurityProfilesErrorKind::ThrottlingException(_inner) => _inner.fmt(f), UpdateUserSecurityProfilesErrorKind::Unhandled(_inner) => _inner.fmt(f), } } } impl aws_smithy_types::retry::ProvideErrorKind for UpdateUserSecurityProfilesError { fn code(&self) -> Option<&str> { UpdateUserSecurityProfilesError::code(self) } fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> { None } } impl UpdateUserSecurityProfilesError { /// Creates a new `UpdateUserSecurityProfilesError`. pub fn new(kind: UpdateUserSecurityProfilesErrorKind, meta: aws_smithy_types::Error) -> Self { Self { kind, meta } } /// Creates the `UpdateUserSecurityProfilesError::Unhandled` variant from any error type. pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self { Self { kind: UpdateUserSecurityProfilesErrorKind::Unhandled(err.into()), meta: Default::default(), } } /// Creates the `UpdateUserSecurityProfilesError::Unhandled` variant from a `aws_smithy_types::Error`. pub fn generic(err: aws_smithy_types::Error) -> Self { Self { meta: err.clone(), kind: UpdateUserSecurityProfilesErrorKind::Unhandled(err.into()), } } // TODO: Consider if this should actually be `Option<Cow<&str>>`. This would enable us to use display // as implemented by std::Error to generate a message in that case. /// Returns the error message if one is available. pub fn message(&self) -> Option<&str> { self.meta.message() } /// Returns error metadata, which includes the error code, message, /// request ID, and potentially additional information. pub fn meta(&self) -> &aws_smithy_types::Error { &self.meta } /// Returns the request ID if it's available. pub fn request_id(&self) -> Option<&str> { self.meta.request_id() } /// Returns the error code if it's available. pub fn code(&self) -> Option<&str> { self.meta.code() } /// Returns `true` if the error kind is `UpdateUserSecurityProfilesErrorKind::InternalServiceException`. pub fn is_internal_service_exception(&self) -> bool { matches!( &self.kind, UpdateUserSecurityProfilesErrorKind::InternalServiceException(_) ) } /// Returns `true` if the error kind is `UpdateUserSecurityProfilesErrorKind::InvalidParameterException`. pub fn is_invalid_parameter_exception(&self) -> bool { matches!( &self.kind, UpdateUserSecurityProfilesErrorKind::InvalidParameterException(_) ) } /// Returns `true` if the error kind is `UpdateUserSecurityProfilesErrorKind::InvalidRequestException`. pub fn is_invalid_request_exception(&self) -> bool { matches!( &self.kind, UpdateUserSecurityProfilesErrorKind::InvalidRequestException(_) ) } /// Returns `true` if the error kind is `UpdateUserSecurityProfilesErrorKind::ResourceNotFoundException`. pub fn is_resource_not_found_exception(&self) -> bool { matches!( &self.kind, UpdateUserSecurityProfilesErrorKind::ResourceNotFoundException(_) ) } /// Returns `true` if the error kind is `UpdateUserSecurityProfilesErrorKind::ThrottlingException`. pub fn is_throttling_exception(&self) -> bool { matches!( &self.kind, UpdateUserSecurityProfilesErrorKind::ThrottlingException(_) ) } } impl std::error::Error for UpdateUserSecurityProfilesError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { UpdateUserSecurityProfilesErrorKind::InternalServiceException(_inner) => Some(_inner), UpdateUserSecurityProfilesErrorKind::InvalidParameterException(_inner) => Some(_inner), UpdateUserSecurityProfilesErrorKind::InvalidRequestException(_inner) => Some(_inner), UpdateUserSecurityProfilesErrorKind::ResourceNotFoundException(_inner) => Some(_inner), UpdateUserSecurityProfilesErrorKind::ThrottlingException(_inner) => Some(_inner), UpdateUserSecurityProfilesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()), } } } /// <p>The throttling limit has been exceeded.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ThrottlingException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for ThrottlingException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ThrottlingException"); formatter.field("message", &self.message); formatter.finish() } } impl ThrottlingException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for ThrottlingException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ThrottlingException")?; if let Some(inner_1) = &self.message { write!(f, ": {}", inner_1)?; } Ok(()) } } impl std::error::Error for ThrottlingException {} /// See [`ThrottlingException`](crate::error::ThrottlingException) pub mod throttling_exception { /// A builder for [`ThrottlingException`](crate::error::ThrottlingException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`ThrottlingException`](crate::error::ThrottlingException) pub fn build(self) -> crate::error::ThrottlingException { crate::error::ThrottlingException { message: self.message, } } } } impl ThrottlingException { /// Creates a new builder-style object to manufacture [`ThrottlingException`](crate::error::ThrottlingException) pub fn builder() -> crate::error::throttling_exception::Builder { crate::error::throttling_exception::Builder::default() } } /// <p>The specified resource was not found.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ResourceNotFoundException { /// <p>The message about the resource.</p> pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for ResourceNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ResourceNotFoundException"); formatter.field("message", &self.message); formatter.finish() } } impl ResourceNotFoundException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for ResourceNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ResourceNotFoundException")?; if let Some(inner_2) = &self.message { write!(f, ": {}", inner_2)?; } Ok(()) } } impl std::error::Error for ResourceNotFoundException {} /// See [`ResourceNotFoundException`](crate::error::ResourceNotFoundException) pub mod resource_not_found_exception { /// A builder for [`ResourceNotFoundException`](crate::error::ResourceNotFoundException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// <p>The message about the resource.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The message about the resource.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`ResourceNotFoundException`](crate::error::ResourceNotFoundException) pub fn build(self) -> crate::error::ResourceNotFoundException { crate::error::ResourceNotFoundException { message: self.message, } } } } impl ResourceNotFoundException { /// Creates a new builder-style object to manufacture [`ResourceNotFoundException`](crate::error::ResourceNotFoundException) pub fn builder() -> crate::error::resource_not_found_exception::Builder { crate::error::resource_not_found_exception::Builder::default() } } /// <p>The request is not valid.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct InvalidRequestException { /// <p>The message about the request.</p> pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for InvalidRequestException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("InvalidRequestException"); formatter.field("message", &self.message); formatter.finish() } } impl InvalidRequestException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for InvalidRequestException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "InvalidRequestException")?; if let Some(inner_3) = &self.message { write!(f, ": {}", inner_3)?; } Ok(()) } } impl std::error::Error for InvalidRequestException {} /// See [`InvalidRequestException`](crate::error::InvalidRequestException) pub mod invalid_request_exception { /// A builder for [`InvalidRequestException`](crate::error::InvalidRequestException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// <p>The message about the request.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The message about the request.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`InvalidRequestException`](crate::error::InvalidRequestException) pub fn build(self) -> crate::error::InvalidRequestException { crate::error::InvalidRequestException { message: self.message, } } } } impl InvalidRequestException { /// Creates a new builder-style object to manufacture [`InvalidRequestException`](crate::error::InvalidRequestException) pub fn builder() -> crate::error::invalid_request_exception::Builder { crate::error::invalid_request_exception::Builder::default() } } /// <p>One or more of the specified parameters are not valid.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct InvalidParameterException { /// <p>The message about the parameters.</p> pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for InvalidParameterException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("InvalidParameterException"); formatter.field("message", &self.message); formatter.finish() } } impl InvalidParameterException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for InvalidParameterException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "InvalidParameterException")?; if let Some(inner_4) = &self.message { write!(f, ": {}", inner_4)?; } Ok(()) } } impl std::error::Error for InvalidParameterException {} /// See [`InvalidParameterException`](crate::error::InvalidParameterException) pub mod invalid_parameter_exception { /// A builder for [`InvalidParameterException`](crate::error::InvalidParameterException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// <p>The message about the parameters.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The message about the parameters.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`InvalidParameterException`](crate::error::InvalidParameterException) pub fn build(self) -> crate::error::InvalidParameterException { crate::error::InvalidParameterException { message: self.message, } } } } impl InvalidParameterException { /// Creates a new builder-style object to manufacture [`InvalidParameterException`](crate::error::InvalidParameterException) pub fn builder() -> crate::error::invalid_parameter_exception::Builder { crate::error::invalid_parameter_exception::Builder::default() } } /// <p>Request processing failed because of an error or failure with the service.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct InternalServiceException { /// <p>The message.</p> pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for InternalServiceException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("InternalServiceException"); formatter.field("message", &self.message); formatter.finish() } } impl InternalServiceException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for InternalServiceException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "InternalServiceException")?; if let Some(inner_5) = &self.message { write!(f, ": {}", inner_5)?; } Ok(()) } } impl std::error::Error for InternalServiceException {} /// See [`InternalServiceException`](crate::error::InternalServiceException) pub mod internal_service_exception { /// A builder for [`InternalServiceException`](crate::error::InternalServiceException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// <p>The message.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The message.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`InternalServiceException`](crate::error::InternalServiceException) pub fn build(self) -> crate::error::InternalServiceException { crate::error::InternalServiceException { message: self.message, } } } } impl InternalServiceException { /// Creates a new builder-style object to manufacture [`InternalServiceException`](crate::error::InternalServiceException) pub fn builder() -> crate::error::internal_service_exception::Builder { crate::error::internal_service_exception::Builder::default() } } /// <p>That resource is already in use. Please try another.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ResourceInUseException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, /// <p>The type of resource.</p> pub resource_type: std::option::Option<crate::model::ResourceType>, /// <p>The identifier for the resource.</p> pub resource_id: std::option::Option<std::string::String>, } impl ResourceInUseException { /// <p>The type of resource.</p> pub fn resource_type(&self) -> std::option::Option<&crate::model::ResourceType> { self.resource_type.as_ref() } /// <p>The identifier for the resource.</p> pub fn resource_id(&self) -> std::option::Option<&str> { self.resource_id.as_deref() } } impl std::fmt::Debug for ResourceInUseException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ResourceInUseException"); formatter.field("message", &self.message); formatter.field("resource_type", &self.resource_type); formatter.field("resource_id", &self.resource_id); formatter.finish() } } impl ResourceInUseException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for ResourceInUseException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ResourceInUseException")?; if let Some(inner_6) = &self.message { write!(f, ": {}", inner_6)?; } Ok(()) } } impl std::error::Error for ResourceInUseException {} /// See [`ResourceInUseException`](crate::error::ResourceInUseException) pub mod resource_in_use_exception { /// A builder for [`ResourceInUseException`](crate::error::ResourceInUseException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, pub(crate) resource_type: std::option::Option<crate::model::ResourceType>, pub(crate) resource_id: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// <p>The type of resource.</p> pub fn resource_type(mut self, input: crate::model::ResourceType) -> Self { self.resource_type = Some(input); self } /// <p>The type of resource.</p> pub fn set_resource_type( mut self, input: std::option::Option<crate::model::ResourceType>, ) -> Self { self.resource_type = input; self } /// <p>The identifier for the resource.</p> pub fn resource_id(mut self, input: impl Into<std::string::String>) -> Self { self.resource_id = Some(input.into()); self } /// <p>The identifier for the resource.</p> pub fn set_resource_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.resource_id = input; self } /// Consumes the builder and constructs a [`ResourceInUseException`](crate::error::ResourceInUseException) pub fn build(self) -> crate::error::ResourceInUseException { crate::error::ResourceInUseException { message: self.message, resource_type: self.resource_type, resource_id: self.resource_id, } } } } impl ResourceInUseException { /// Creates a new builder-style object to manufacture [`ResourceInUseException`](crate::error::ResourceInUseException) pub fn builder() -> crate::error::resource_in_use_exception::Builder { crate::error::resource_in_use_exception::Builder::default() } } /// <p>A resource with the specified name already exists.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DuplicateResourceException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for DuplicateResourceException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DuplicateResourceException"); formatter.field("message", &self.message); formatter.finish() } } impl DuplicateResourceException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for DuplicateResourceException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "DuplicateResourceException")?; if let Some(inner_7) = &self.message { write!(f, ": {}", inner_7)?; } Ok(()) } } impl std::error::Error for DuplicateResourceException {} /// See [`DuplicateResourceException`](crate::error::DuplicateResourceException) pub mod duplicate_resource_exception { /// A builder for [`DuplicateResourceException`](crate::error::DuplicateResourceException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`DuplicateResourceException`](crate::error::DuplicateResourceException) pub fn build(self) -> crate::error::DuplicateResourceException { crate::error::DuplicateResourceException { message: self.message, } } } } impl DuplicateResourceException { /// Creates a new builder-style object to manufacture [`DuplicateResourceException`](crate::error::DuplicateResourceException) pub fn builder() -> crate::error::duplicate_resource_exception::Builder { crate::error::duplicate_resource_exception::Builder::default() } } /// <p>The contact flow is not valid.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct InvalidContactFlowException { /// <p>The problems with the contact flow. Please fix before trying again.</p> pub problems: std::option::Option<std::vec::Vec<crate::model::ProblemDetail>>, #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl InvalidContactFlowException { /// <p>The problems with the contact flow. Please fix before trying again.</p> pub fn problems(&self) -> std::option::Option<&[crate::model::ProblemDetail]> { self.problems.as_deref() } } impl std::fmt::Debug for InvalidContactFlowException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("InvalidContactFlowException"); formatter.field("problems", &self.problems); formatter.field("message", &self.message); formatter.finish() } } impl InvalidContactFlowException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for InvalidContactFlowException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "InvalidContactFlowException")?; if let Some(inner_8) = &self.message { write!(f, ": {}", inner_8)?; } Ok(()) } } impl std::error::Error for InvalidContactFlowException {} /// See [`InvalidContactFlowException`](crate::error::InvalidContactFlowException) pub mod invalid_contact_flow_exception { /// A builder for [`InvalidContactFlowException`](crate::error::InvalidContactFlowException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) problems: std::option::Option<std::vec::Vec<crate::model::ProblemDetail>>, pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// Appends an item to `problems`. /// /// To override the contents of this collection use [`set_problems`](Self::set_problems). /// /// <p>The problems with the contact flow. Please fix before trying again.</p> pub fn problems(mut self, input: impl Into<crate::model::ProblemDetail>) -> Self { let mut v = self.problems.unwrap_or_default(); v.push(input.into()); self.problems = Some(v); self } /// <p>The problems with the contact flow. Please fix before trying again.</p> pub fn set_problems( mut self, input: std::option::Option<std::vec::Vec<crate::model::ProblemDetail>>, ) -> Self { self.problems = input; self } #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`InvalidContactFlowException`](crate::error::InvalidContactFlowException) pub fn build(self) -> crate::error::InvalidContactFlowException { crate::error::InvalidContactFlowException { problems: self.problems, message: self.message, } } } } impl InvalidContactFlowException { /// Creates a new builder-style object to manufacture [`InvalidContactFlowException`](crate::error::InvalidContactFlowException) pub fn builder() -> crate::error::invalid_contact_flow_exception::Builder { crate::error::invalid_contact_flow_exception::Builder::default() } } /// <p>The allowed limit for the resource has been exceeded.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct LimitExceededException { /// <p>The message about the limit.</p> pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for LimitExceededException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("LimitExceededException"); formatter.field("message", &self.message); formatter.finish() } } impl LimitExceededException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for LimitExceededException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "LimitExceededException")?; if let Some(inner_9) = &self.message { write!(f, ": {}", inner_9)?; } Ok(()) } } impl std::error::Error for LimitExceededException {} /// See [`LimitExceededException`](crate::error::LimitExceededException) pub mod limit_exceeded_exception { /// A builder for [`LimitExceededException`](crate::error::LimitExceededException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// <p>The message about the limit.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The message about the limit.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`LimitExceededException`](crate::error::LimitExceededException) pub fn build(self) -> crate::error::LimitExceededException { crate::error::LimitExceededException { message: self.message, } } } } impl LimitExceededException { /// Creates a new builder-style object to manufacture [`LimitExceededException`](crate::error::LimitExceededException) pub fn builder() -> crate::error::limit_exceeded_exception::Builder { crate::error::limit_exceeded_exception::Builder::default() } } /// <p>The contact with the specified ID is not active or does not exist.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ContactNotFoundException { /// <p>The message.</p> pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for ContactNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ContactNotFoundException"); formatter.field("message", &self.message); formatter.finish() } } impl ContactNotFoundException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for ContactNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ContactNotFoundException")?; if let Some(inner_10) = &self.message { write!(f, ": {}", inner_10)?; } Ok(()) } } impl std::error::Error for ContactNotFoundException {} /// See [`ContactNotFoundException`](crate::error::ContactNotFoundException) pub mod contact_not_found_exception { /// A builder for [`ContactNotFoundException`](crate::error::ContactNotFoundException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// <p>The message.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The message.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`ContactNotFoundException`](crate::error::ContactNotFoundException) pub fn build(self) -> crate::error::ContactNotFoundException { crate::error::ContactNotFoundException { message: self.message, } } } } impl ContactNotFoundException { /// Creates a new builder-style object to manufacture [`ContactNotFoundException`](crate::error::ContactNotFoundException) pub fn builder() -> crate::error::contact_not_found_exception::Builder { crate::error::contact_not_found_exception::Builder::default() } } /// <p>The service quota has been exceeded.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ServiceQuotaExceededException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for ServiceQuotaExceededException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ServiceQuotaExceededException"); formatter.field("message", &self.message); formatter.finish() } } impl ServiceQuotaExceededException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for ServiceQuotaExceededException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ServiceQuotaExceededException")?; if let Some(inner_11) = &self.message { write!(f, ": {}", inner_11)?; } Ok(()) } } impl std::error::Error for ServiceQuotaExceededException {} /// See [`ServiceQuotaExceededException`](crate::error::ServiceQuotaExceededException) pub mod service_quota_exceeded_exception { /// A builder for [`ServiceQuotaExceededException`](crate::error::ServiceQuotaExceededException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`ServiceQuotaExceededException`](crate::error::ServiceQuotaExceededException) pub fn build(self) -> crate::error::ServiceQuotaExceededException { crate::error::ServiceQuotaExceededException { message: self.message, } } } } impl ServiceQuotaExceededException { /// Creates a new builder-style object to manufacture [`ServiceQuotaExceededException`](crate::error::ServiceQuotaExceededException) pub fn builder() -> crate::error::service_quota_exceeded_exception::Builder { crate::error::service_quota_exceeded_exception::Builder::default() } } /// <p>The contact is not permitted.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct OutboundContactNotPermittedException { /// <p>The message about the contact.</p> pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for OutboundContactNotPermittedException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("OutboundContactNotPermittedException"); formatter.field("message", &self.message); formatter.finish() } } impl OutboundContactNotPermittedException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for OutboundContactNotPermittedException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "OutboundContactNotPermittedException")?; if let Some(inner_12) = &self.message { write!(f, ": {}", inner_12)?; } Ok(()) } } impl std::error::Error for OutboundContactNotPermittedException {} /// See [`OutboundContactNotPermittedException`](crate::error::OutboundContactNotPermittedException) pub mod outbound_contact_not_permitted_exception { /// A builder for [`OutboundContactNotPermittedException`](crate::error::OutboundContactNotPermittedException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// <p>The message about the contact.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The message about the contact.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`OutboundContactNotPermittedException`](crate::error::OutboundContactNotPermittedException) pub fn build(self) -> crate::error::OutboundContactNotPermittedException { crate::error::OutboundContactNotPermittedException { message: self.message, } } } } impl OutboundContactNotPermittedException { /// Creates a new builder-style object to manufacture [`OutboundContactNotPermittedException`](crate::error::OutboundContactNotPermittedException) pub fn builder() -> crate::error::outbound_contact_not_permitted_exception::Builder { crate::error::outbound_contact_not_permitted_exception::Builder::default() } } /// <p>Outbound calls to the destination number are not allowed.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DestinationNotAllowedException { /// <p>The message about the outbound calls.</p> pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for DestinationNotAllowedException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DestinationNotAllowedException"); formatter.field("message", &self.message); formatter.finish() } } impl DestinationNotAllowedException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for DestinationNotAllowedException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "DestinationNotAllowedException")?; if let Some(inner_13) = &self.message { write!(f, ": {}", inner_13)?; } Ok(()) } } impl std::error::Error for DestinationNotAllowedException {} /// See [`DestinationNotAllowedException`](crate::error::DestinationNotAllowedException) pub mod destination_not_allowed_exception { /// A builder for [`DestinationNotAllowedException`](crate::error::DestinationNotAllowedException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { /// <p>The message about the outbound calls.</p> pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } /// <p>The message about the outbound calls.</p> pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`DestinationNotAllowedException`](crate::error::DestinationNotAllowedException) pub fn build(self) -> crate::error::DestinationNotAllowedException { crate::error::DestinationNotAllowedException { message: self.message, } } } } impl DestinationNotAllowedException { /// Creates a new builder-style object to manufacture [`DestinationNotAllowedException`](crate::error::DestinationNotAllowedException) pub fn builder() -> crate::error::destination_not_allowed_exception::Builder { crate::error::destination_not_allowed_exception::Builder::default() } } /// <p>No user with the specified credentials was found in the Amazon Connect instance.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UserNotFoundException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for UserNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UserNotFoundException"); formatter.field("message", &self.message); formatter.finish() } } impl UserNotFoundException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for UserNotFoundException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "UserNotFoundException")?; if let Some(inner_14) = &self.message { write!(f, ": {}", inner_14)?; } Ok(()) } } impl std::error::Error for UserNotFoundException {} /// See [`UserNotFoundException`](crate::error::UserNotFoundException) pub mod user_not_found_exception { /// A builder for [`UserNotFoundException`](crate::error::UserNotFoundException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`UserNotFoundException`](crate::error::UserNotFoundException) pub fn build(self) -> crate::error::UserNotFoundException { crate::error::UserNotFoundException { message: self.message, } } } } impl UserNotFoundException { /// Creates a new builder-style object to manufacture [`UserNotFoundException`](crate::error::UserNotFoundException) pub fn builder() -> crate::error::user_not_found_exception::Builder { crate::error::user_not_found_exception::Builder::default() } } /// <p>The contact flow has not been published.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ContactFlowNotPublishedException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for ContactFlowNotPublishedException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ContactFlowNotPublishedException"); formatter.field("message", &self.message); formatter.finish() } } impl ContactFlowNotPublishedException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for ContactFlowNotPublishedException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ContactFlowNotPublishedException")?; if let Some(inner_15) = &self.message { write!(f, ": {}", inner_15)?; } Ok(()) } } impl std::error::Error for ContactFlowNotPublishedException {} /// See [`ContactFlowNotPublishedException`](crate::error::ContactFlowNotPublishedException) pub mod contact_flow_not_published_exception { /// A builder for [`ContactFlowNotPublishedException`](crate::error::ContactFlowNotPublishedException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`ContactFlowNotPublishedException`](crate::error::ContactFlowNotPublishedException) pub fn build(self) -> crate::error::ContactFlowNotPublishedException { crate::error::ContactFlowNotPublishedException { message: self.message, } } } } impl ContactFlowNotPublishedException { /// Creates a new builder-style object to manufacture [`ContactFlowNotPublishedException`](crate::error::ContactFlowNotPublishedException) pub fn builder() -> crate::error::contact_flow_not_published_exception::Builder { crate::error::contact_flow_not_published_exception::Builder::default() } } /// <p>A resource already has that name.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ResourceConflictException { #[allow(missing_docs)] // documentation missing in model pub message: std::option::Option<std::string::String>, } impl std::fmt::Debug for ResourceConflictException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ResourceConflictException"); formatter.field("message", &self.message); formatter.finish() } } impl ResourceConflictException { /// Returns the error message. pub fn message(&self) -> Option<&str> { self.message.as_deref() } } impl std::fmt::Display for ResourceConflictException { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "ResourceConflictException")?; if let Some(inner_16) = &self.message { write!(f, ": {}", inner_16)?; } Ok(()) } } impl std::error::Error for ResourceConflictException {} /// See [`ResourceConflictException`](crate::error::ResourceConflictException) pub mod resource_conflict_exception { /// A builder for [`ResourceConflictException`](crate::error::ResourceConflictException) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) message: std::option::Option<std::string::String>, } impl Builder { #[allow(missing_docs)] // documentation missing in model pub fn message(mut self, input: impl Into<std::string::String>) -> Self { self.message = Some(input.into()); self } #[allow(missing_docs)] // documentation missing in model pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self { self.message = input; self } /// Consumes the builder and constructs a [`ResourceConflictException`](crate::error::ResourceConflictException) pub fn build(self) -> crate::error::ResourceConflictException { crate::error::ResourceConflictException { message: self.message, } } } } impl ResourceConflictException { /// Creates a new builder-style object to manufacture [`ResourceConflictException`](crate::error::ResourceConflictException) pub fn builder() -> crate::error::resource_conflict_exception::Builder { crate::error::resource_conflict_exception::Builder::default() } }
43.835061
150
0.673762
5bc057dd158e1d5a30a8c6bf2b52117c8663c371
2,712
use std::fmt::Debug; use std::rc::Rc; use sqlparser::ast::Ident; use crate::data::{Row, Value}; #[derive(Debug)] pub struct BlendContext<'a> { table_alias: &'a str, pub columns: Rc<Vec<Ident>>, pub row: Option<Row>, next: Option<Rc<BlendContext<'a>>>, } impl<'a> BlendContext<'a> { pub fn new( table_alias: &'a str, columns: Rc<Vec<Ident>>, row: Option<Row>, next: Option<Rc<BlendContext<'a>>>, ) -> Self { Self { table_alias, columns, row, next, } } pub fn get_value(&'a self, target: &str) -> Option<&'a Value> { let get_value = || { self.columns .iter() .position(|column| column.value == target) .map(|index| self.row.as_ref().and_then(|row| row.get_value(index))) }; match get_value() { None => match &self.next { None => None, Some(context) => context.get_value(target), }, Some(value) => value, } } pub fn get_alias_value(&'a self, table_alias: &str, target: &str) -> Option<&'a Value> { let get_value = || { if self.table_alias != table_alias { return None; } self.columns .iter() .position(|column| column.value == target) .map(|index| self.row.as_ref().and_then(|row| row.get_value(index))) }; match get_value() { None => match &self.next { None => None, Some(context) => context.get_alias_value(table_alias, target), }, Some(value) => value, } } pub fn get_alias_values(&self, alias: &str) -> Option<Vec<Value>> { if self.table_alias == alias { let values = match &self.row { Some(Row(values)) => values.clone(), None => self.columns.iter().map(|_| Value::Empty).collect(), }; Some(values) } else { self.next .as_ref() .and_then(|next| next.get_alias_values(alias)) } } pub fn get_all_values(&'a self) -> Vec<Value> { let values: Vec<Value> = match &self.row { Some(Row(values)) => values.clone(), None => self.columns.iter().map(|_| Value::Empty).collect(), }; match &self.next { Some(next) => next .get_all_values() .into_iter() .chain(values.into_iter()) .collect(), None => values, } } }
27.12
92
0.468289
031edbfb20181cff025a25f38a9b6b695e35219d
22,908
// Copyright 2020-2021, The Tremor Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::{CbAction, EventId, OpMeta, SignalKind}; use std::mem::swap; use tremor_common::ids::SourceId; use tremor_common::time::nanotime; use tremor_script::prelude::*; use tremor_script::{literal, EventOriginUri, EventPayload, Value}; /// A tremor event #[derive( Debug, Clone, PartialEq, Default, simd_json_derive::Serialize, simd_json_derive::Deserialize, )] pub struct Event { /// The event ID pub id: EventId, /// The event Data pub data: EventPayload, /// Nanoseconds at when the event was ingested pub ingest_ns: u64, /// URI to identify the origin of the event pub origin_uri: Option<EventOriginUri>, /// The kind of the event pub kind: Option<SignalKind>, /// If this event is batched (containing multiple events itself) pub is_batch: bool, /// Circuit breaker action pub cb: CbAction, /// Metadata for operators pub op_meta: OpMeta, /// this needs transactional data pub transactional: bool, } impl Event { /// create a tick signal event #[must_use] pub fn signal_tick() -> Self { Self { ingest_ns: nanotime(), kind: Some(SignalKind::Tick), ..Self::default() } } /// create a drain signal event originating at the connector with the given `source_id` #[must_use] pub fn signal_drain(source_id: SourceId) -> Self { Self { ingest_ns: nanotime(), kind: Some(SignalKind::Drain(source_id)), ..Self::default() } } /// create start signal for the given `SourceId` #[must_use] pub fn signal_start(uid: SourceId) -> Self { Self { ingest_ns: nanotime(), kind: Some(SignalKind::Start(uid)), ..Self::default() } } /// turns the event in an insight given it's success #[must_use] pub fn insight(cb: CbAction, id: EventId, ingest_ns: u64, op_meta: OpMeta) -> Event { Event { id, ingest_ns, cb, op_meta, ..Event::default() } } /// Creates either a restore or trigger event #[must_use] pub fn restore_or_break(restore: bool, ingest_ns: u64) -> Self { if restore { Event::cb_restore(ingest_ns) } else { Event::cb_trigger(ingest_ns) } } /// Creates either a ack or fail event #[must_use] pub fn ack_or_fail(ack: bool, ingest_ns: u64, ids: EventId, op_meta: OpMeta) -> Self { if ack { Event::cb_ack(ingest_ns, ids, op_meta) } else { Event::cb_fail(ingest_ns, ids, op_meta) } } /// Creates a new ack insight from the event #[must_use] pub fn insight_ack(&self) -> Event { Event::cb_ack(self.ingest_ns, self.id.clone(), self.op_meta.clone()) } /// produce a `CBAction::Ack` insight event with the given time (in ms) in the metadata #[must_use] pub fn insight_ack_with_timing(&mut self, processing_time: u64) -> Event { let mut e = self.insight_ack(); e.data = (Value::null(), literal!({ "time": processing_time })).into(); e } /// Creates a new fail insight from the event, consumes the `op_meta` of the /// event #[must_use] pub fn insight_fail(&self) -> Event { Event::cb_fail(self.ingest_ns, self.id.clone(), self.op_meta.clone()) } /// Creates a restore insight from the event, consumes the `op_meta` of the /// event #[must_use] pub fn insight_restore(&mut self) -> Event { let mut e = Event::cb_restore(self.ingest_ns); swap(&mut e.op_meta, &mut self.op_meta); e } /// Creates a trigger insight from the event, consums the `op_meta` of the /// event #[must_use] pub fn insight_trigger(&mut self) -> Event { let mut e = Event::cb_trigger(self.ingest_ns); swap(&mut e.op_meta, &mut self.op_meta); e } /// Creates a new event to restore a CB #[must_use] pub fn cb_restore(ingest_ns: u64) -> Self { Event { ingest_ns, cb: CbAction::Open, ..Event::default() } } /// Creates a new event to restore/open a CB /// /// For those CB events we don't need an explicit `EventId`. /// Sources should react properly upon any CB message, no matter the `EventId` /// operators can use the `op_meta` for checking if they are affected #[must_use] pub fn cb_open(ingest_ns: u64, op_meta: OpMeta) -> Self { Self { ingest_ns, op_meta, cb: CbAction::Open, ..Event::default() } } /// Creates a new event to trigger/close a CB /// /// For those CB events we don't need an explicit `EventId`. /// Sources should react properly upon any CB message, no matter the `EventId` /// operators can use the `op_meta` for checking if they are affected #[must_use] pub fn cb_close(ingest_ns: u64, op_meta: OpMeta) -> Self { Self { ingest_ns, op_meta, cb: CbAction::Close, ..Event::default() } } /// Creates a new event to trigger a CB #[must_use] pub fn cb_trigger(ingest_ns: u64) -> Self { Event { ingest_ns, cb: CbAction::Close, ..Event::default() } } /// Creates a new contraflow event delivery acknowledge message #[must_use] pub fn cb_ack(ingest_ns: u64, id: EventId, op_meta: OpMeta) -> Self { Event { ingest_ns, id, cb: CbAction::Ack, op_meta, ..Event::default() } } /// Creates a new contraflow event delivery acknowledge message with timing in the metadata #[must_use] pub fn cb_ack_with_timing(ingest_ns: u64, id: EventId, op_meta: OpMeta, duration: u64) -> Self { Event { ingest_ns, id, cb: CbAction::Ack, op_meta, data: (Value::null(), literal!({ "time": duration })).into(), ..Event::default() } } /// Creates a new event to trigger a CB #[must_use] pub fn cb_fail(ingest_ns: u64, id: EventId, op_meta: OpMeta) -> Self { Event { ingest_ns, id, cb: CbAction::Fail, op_meta, ..Event::default() } } #[must_use] /// return the number of events contained within this event /// normally 1, but for batched events possibly > 1 pub fn len(&self) -> usize { if self.is_batch { self.data.suffix().value().as_array().map_or(0, Vec::len) } else { 1 } } /// returns true if this event is batched but has no wrapped events #[must_use] pub fn is_empty(&self) -> bool { self.is_batch && self .data .suffix() .value() .as_array() .map_or(true, Vec::is_empty) } /// Extracts the `$correlation` metadata into a `Vec` of `Option<Value<'static>>`. /// We use a `Vec` to account for possibly batched events and `Option`s because single events might not have a value there. /// We use `Value<'static>`, which requires a clone, as we need to pass the values on to another event anyways. #[must_use] pub fn correlation_metas(&self) -> Vec<Option<Value<'static>>> { let mut res = Vec::with_capacity(self.len()); for (_, meta) in self.value_meta_iter() { res.push(meta.get("correlation").map(Value::clone_static)); } res } /// get the correlation metadata as a single value, if present /// creates an array value for batched events #[must_use] pub fn correlation_meta(&self) -> Option<Value<'static>> { if self.is_batch { let cms = self.correlation_metas(); if cms.is_empty() { None } else { Some(Value::from(cms)) } } else { self.data .suffix() .meta() .get("correlation") .map(Value::clone_static) } } } impl Event { /// allows to iterate over the values and metadatas /// in an event, if it is batched this can be multiple /// otherwise it's a singular event #[must_use] pub fn value_meta_iter(&self) -> ValueMetaIter { ValueMetaIter { event: self, idx: 0, } } } /// Iterator over the event value and metadata /// if the event is a batch this will allow iterating /// over all the batched events pub struct ValueMetaIter<'value> { event: &'value Event, idx: usize, } impl<'value> ValueMetaIter<'value> { fn extract_batched_value_meta( batched_value: &'value Value<'value>, ) -> Option<(&'value Value<'value>, &'value Value<'value>)> { batched_value .get("data") .and_then(|last_data| last_data.get("value").zip(last_data.get("meta"))) } /// Split off the last value and meta in this iter and return all previous values and metas inside a slice. /// Returns `None` if there are no values in this Event, which shouldn't happen, tbh. /// /// This is efficient because all the values are in a slice already. pub fn split_last( &mut self, ) -> Option<( (&'value Value<'value>, &'value Value<'value>), impl Iterator<Item = (&'value Value<'value>, &'value Value<'value>)>, )> { if self.event.is_batch { self.event .data .suffix() .value() .as_array() .and_then(|vec| vec.split_last()) .and_then(|(last, rest)| { let last_option = Self::extract_batched_value_meta(last); let rest_option = Some(rest.iter().filter_map(Self::extract_batched_value_meta)); last_option.zip(rest_option) }) } else { let v = self.event.data.suffix(); let vs: &[Value<'value>] = &[]; Some(( (v.value(), v.meta()), // only use the extract method to end up with the same type as the if branch above vs.iter().filter_map(Self::extract_batched_value_meta), )) } } } // TODO: descend recursively into batched events in batched events ... impl<'value> Iterator for ValueMetaIter<'value> { type Item = (&'value Value<'value>, &'value Value<'value>); fn next(&mut self) -> Option<Self::Item> { if self.event.is_batch { let r = self .event .data .suffix() .value() .get_idx(self.idx) .and_then(Self::extract_batched_value_meta); self.idx += 1; r } else if self.idx == 0 { let v = self.event.data.suffix(); self.idx += 1; Some((v.value(), v.meta())) } else { None } } } impl Event { /// Iterate over the values in an event /// this will result in multiple entries /// if the event was batched otherwise /// have only a single element #[must_use] pub fn value_iter(&self) -> ValueIter { ValueIter { event: self, idx: 0, } } } /// Iterator over the values of an event pub struct ValueIter<'value> { event: &'value Event, idx: usize, } impl<'value> ValueIter<'value> { fn extract_batched_value( batched_value: &'value Value<'value>, ) -> Option<&'value Value<'value>> { batched_value .get("data") .and_then(|last_data| last_data.get("value")) } /// Split off the last value in this iter and return all previous values inside an iterator. /// Returns `None` if there are no values in this Event, which shouldn't happen, tbh. /// /// This is useful if we don't want to clone stuff on the last value. pub fn split_last( &mut self, ) -> Option<( &'value Value<'value>, impl Iterator<Item = &'value Value<'value>>, )> { if self.event.is_batch { self.event .data .suffix() .value() .as_array() .and_then(|vec| vec.split_last()) .and_then(|(last, rest)| { let last_option = Self::extract_batched_value(last); let rest_option = Some(rest.iter().filter_map(Self::extract_batched_value)); last_option.zip(rest_option) }) } else { let v = self.event.data.suffix().value(); let vs: &[Value<'value>] = &[]; // only use the extract method to end up with the same type as the if branch above Some((v, vs.iter().filter_map(Self::extract_batched_value))) } } } impl<'value> Iterator for ValueIter<'value> { type Item = &'value Value<'value>; fn next(&mut self) -> Option<Self::Item> { if self.event.is_batch { let r = self .event .data .suffix() .value() .get_idx(self.idx) .and_then(Self::extract_batched_value); self.idx += 1; r } else if self.idx == 0 { let v = self.event.data.suffix().value(); self.idx += 1; Some(v) } else { None } } } #[cfg(test)] mod test { use super::*; use crate::Result; use simd_json::OwnedValue; use tremor_common::ids::{Id, OperatorId}; use tremor_script::{Object, ValueAndMeta}; fn merge<'iref, 'head>( this: &'iref mut ValueAndMeta<'head>, other: ValueAndMeta<'head>, ) -> Result<()> { if let Some(ref mut a) = this.value_mut().as_array_mut() { let mut e = Object::with_capacity(7); let mut data = Object::with_capacity(2); let (value, meta) = other.into_parts(); data.insert_nocheck("value".into(), value); data.insert_nocheck("meta".into(), meta); e.insert_nocheck("data".into(), Value::from(data)); e.insert_nocheck("ingest_ns".into(), 1.into()); // kind is always null on events e.insert_nocheck("kind".into(), Value::null()); e.insert_nocheck("is_batch".into(), false.into()); a.push(Value::from(e)) }; Ok(()) } #[test] fn value_iters() { let mut b = Event { data: (Value::array(), 2).into(), is_batch: true, ..Event::default() }; let e1 = Event { data: (1, 2).into(), ..Event::default() }; let e2 = Event { data: (3, 4).into(), ..Event::default() }; assert!(b.data.consume(e1.data, merge).is_ok()); assert!(b.data.consume(e2.data, merge).is_ok()); let mut vi = b.value_iter(); assert_eq!(vi.next().unwrap(), &1); assert_eq!(vi.next().unwrap(), &3); assert!(vi.next().is_none()); let mut vmi = b.value_meta_iter(); assert_eq!(vmi.next().unwrap(), (&1.into(), &2.into())); assert_eq!(vmi.next().unwrap(), (&3.into(), &4.into())); assert!(vmi.next().is_none()); } #[test] fn value_iters_split_last() { let mut b = Event { data: (Value::array(), 2).into(), is_batch: true, ..Event::default() }; assert!(b.value_iter().split_last().is_none()); assert!(b.value_meta_iter().split_last().is_none()); let e1 = Event { data: (1, 2).into(), ..Event::default() }; { let splitted = e1.value_iter().split_last(); assert!(splitted.is_some()); let (last, mut rest) = splitted.unwrap(); assert_eq!(last, &1); assert!(rest.next().is_none()); let splitted_meta = e1.value_meta_iter().split_last(); assert!(splitted_meta.is_some()); let ((last_value, last_meta), mut rest) = splitted_meta.unwrap(); assert_eq!(last_value, &1); assert_eq!(last_meta, &2); assert!(rest.next().is_none()); } assert!(b.data.consume(e1.data, merge).is_ok()); { let splitted = b.value_iter().split_last(); assert!(splitted.is_some()); let (last, mut rest) = splitted.unwrap(); assert_eq!(last, &1); assert!(rest.next().is_none()); let splitted_meta = b.value_meta_iter().split_last(); assert!(splitted_meta.is_some()); let ((last_value, last_meta), mut rest) = splitted_meta.unwrap(); assert_eq!(last_value, &1); assert_eq!(last_meta, &2); assert!(rest.next().is_none()); } let e2 = Event { data: (3, 4).into(), ..Event::default() }; assert!(b.data.consume(e2.data, merge).is_ok()); { let splitted = b.value_iter().split_last(); assert!(splitted.is_some()); let (last, mut rest) = splitted.unwrap(); assert_eq!(last, &3); let first = rest.next(); assert!(first.is_some()); assert_eq!(first.unwrap(), &1); let splitted_meta = b.value_meta_iter().split_last(); assert!(splitted_meta.is_some()); let ((last_value, last_meta), mut rest) = splitted_meta.unwrap(); assert_eq!(last_value, &3); assert_eq!(last_meta, &4); let first = rest.next(); assert!(first.is_some()); let (value, meta) = first.unwrap(); assert_eq!(value, &1); assert_eq!(meta, &2); } } #[test] fn cb() { let e = Event::default(); assert_eq!(CbAction::from(true), CbAction::Ack); assert_eq!(CbAction::from(false), CbAction::Fail); assert_eq!( Event::ack_or_fail(true, 0, EventId::default(), OpMeta::default()).cb, CbAction::Ack ); assert_eq!( Event::cb_ack(0, EventId::default(), OpMeta::default()).cb, CbAction::Ack ); assert_eq!(e.insight_ack().cb, CbAction::Ack); assert_eq!( Event::ack_or_fail(false, 0, EventId::default(), OpMeta::default()).cb, CbAction::Fail ); assert_eq!( Event::cb_fail(0, EventId::default(), OpMeta::default()).cb, CbAction::Fail ); assert_eq!(e.insight_fail().cb, CbAction::Fail); let mut clone = e.clone(); let op_id = OperatorId::new(1); clone.op_meta.insert(op_id, OwnedValue::null()); let ack_with_timing = clone.insight_ack_with_timing(100); assert_eq!(ack_with_timing.cb, CbAction::Ack); assert!(ack_with_timing.op_meta.contains_key(op_id)); let (_, m) = ack_with_timing.data.parts(); assert_eq!(Some(100), m.get_u64("time")); let mut clone2 = e.clone(); clone2 .op_meta .insert(OperatorId::new(42), OwnedValue::null()); } #[test] fn gd() { let mut e = Event::default(); assert_eq!(Event::restore_or_break(true, 0).cb, CbAction::Open); assert_eq!(Event::cb_restore(0).cb, CbAction::Open); assert_eq!(e.insight_restore().cb, CbAction::Open); assert_eq!(Event::restore_or_break(false, 0).cb, CbAction::Close); assert_eq!(Event::cb_trigger(0).cb, CbAction::Close); assert_eq!(e.insight_trigger().cb, CbAction::Close); } #[test] fn len() -> Result<()> { // default non-batched event let mut e = Event::default(); assert_eq!(1, e.len()); // batched event with 2 elements e.is_batch = true; let mut value = Value::array_with_capacity(2); value.push(Value::from(true))?; // dummy events value.push(Value::from(false))?; e.data = (value, Value::object_with_capacity(0)).into(); assert_eq!(2, e.len()); // batched event with non-array value e.data = (Value::null(), Value::object_with_capacity(0)).into(); assert_eq!(0, e.len()); // batched array with empty array value e.data = ( Value::array_with_capacity(0), Value::object_with_capacity(0), ) .into(); assert_eq!(0, e.len()); Ok(()) } #[test] fn is_empty() -> Result<()> { let mut e = Event::default(); assert_eq!(false, e.is_empty()); e.is_batch = true; e.data = (Value::null(), Value::object()).into(); assert_eq!(true, e.is_empty()); e.data = (Value::array(), Value::object()).into(); assert_eq!(true, e.is_empty()); let mut value = Value::array_with_capacity(2); value.push(Value::from(true))?; // dummy events value.push(Value::from(false))?; e.data = (value, Value::object()).into(); assert_eq!(false, e.is_empty()); Ok(()) } #[test] fn correlation_meta() -> Result<()> { let mut e = Event::default(); assert!(e.correlation_meta().is_none()); let mut m = literal!({ "correlation": 1 }); e.data = (Value::null(), m.clone()).into(); assert_eq!(e.correlation_meta().unwrap(), 1); let mut e2 = Event::default(); e2.is_batch = true; e2.data = (Value::array(), m.clone()).into(); e2.data.consume(e.data.clone(), merge).unwrap(); m.try_insert("correlation", 2); e.data = (Value::null(), m.clone()).into(); e2.data.consume(e.data, merge).unwrap(); assert_eq!(e2.correlation_meta().unwrap(), Value::from(vec![1, 2])); Ok(()) } }
32.219409
127
0.539419
9bd7701da1feb22431b1e15031f163507428761a
67,278
use crate::hir; use crate::hir::def::{DefKind, Namespace}; use crate::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use crate::hir::map::{DefPathData, DisambiguatedDefPathData}; use crate::middle::cstore::{ExternCrate, ExternCrateSource}; use crate::middle::region; use crate::mir::interpret::{sign_extend, truncate, ConstValue, Scalar}; use crate::ty::layout::{Integer, IntegerExt, Size}; use crate::ty::subst::{GenericArg, GenericArgKind, Subst}; use crate::ty::{self, DefIdTree, ParamConst, Ty, TyCtxt, TypeFoldable}; use rustc_apfloat::ieee::{Double, Single}; use rustc_apfloat::Float; use rustc_target::spec::abi::Abi; use syntax::ast; use syntax::attr::{SignedInt, UnsignedInt}; use syntax::symbol::{kw, Symbol}; use std::cell::Cell; use std::collections::BTreeMap; use std::fmt::{self, Write as _}; use std::ops::{Deref, DerefMut}; // `pretty` is a separate module only for organization. use super::*; macro_rules! p { (@write($($data:expr),+)) => { write!(scoped_cx!(), $($data),+)? }; (@print($x:expr)) => { scoped_cx!() = $x.print(scoped_cx!())? }; (@$method:ident($($arg:expr),*)) => { scoped_cx!() = scoped_cx!().$method($($arg),*)? }; ($($kind:ident $data:tt),+) => {{ $(p!(@$kind $data);)+ }}; } macro_rules! define_scoped_cx { ($cx:ident) => { #[allow(unused_macros)] macro_rules! scoped_cx { () => { $cx }; } }; } thread_local! { static FORCE_IMPL_FILENAME_LINE: Cell<bool> = Cell::new(false); static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = Cell::new(false); static NO_QUERIES: Cell<bool> = Cell::new(false); } /// Avoids running any queries during any prints that occur /// during the closure. This may alter the appearance of some /// types (e.g. forcing verbose printing for opaque types). /// This method is used during some queries (e.g. `predicates_of` /// for opaque types), to ensure that any debug printing that /// occurs during the query computation does not end up recursively /// calling the same query. pub fn with_no_queries<F: FnOnce() -> R, R>(f: F) -> R { NO_QUERIES.with(|no_queries| { let old = no_queries.get(); no_queries.set(true); let result = f(); no_queries.set(old); result }) } /// Force us to name impls with just the filename/line number. We /// normally try to use types. But at some points, notably while printing /// cycle errors, this can result in extra or suboptimal error output, /// so this variable disables that check. pub fn with_forced_impl_filename_line<F: FnOnce() -> R, R>(f: F) -> R { FORCE_IMPL_FILENAME_LINE.with(|force| { let old = force.get(); force.set(true); let result = f(); force.set(old); result }) } /// Adds the `crate::` prefix to paths where appropriate. pub fn with_crate_prefix<F: FnOnce() -> R, R>(f: F) -> R { SHOULD_PREFIX_WITH_CRATE.with(|flag| { let old = flag.get(); flag.set(true); let result = f(); flag.set(old); result }) } /// The "region highlights" are used to control region printing during /// specific error messages. When a "region highlight" is enabled, it /// gives an alternate way to print specific regions. For now, we /// always print those regions using a number, so something like "`'0`". /// /// Regions not selected by the region highlight mode are presently /// unaffected. #[derive(Copy, Clone, Default)] pub struct RegionHighlightMode { /// If enabled, when we see the selected region, use "`'N`" /// instead of the ordinary behavior. highlight_regions: [Option<(ty::RegionKind, usize)>; 3], /// If enabled, when printing a "free region" that originated from /// the given `ty::BoundRegion`, print it as "`'1`". Free regions that would ordinarily /// have names print as normal. /// /// This is used when you have a signature like `fn foo(x: &u32, /// y: &'a u32)` and we want to give a name to the region of the /// reference `x`. highlight_bound_region: Option<(ty::BoundRegion, usize)>, } impl RegionHighlightMode { /// If `region` and `number` are both `Some`, invokes /// `highlighting_region`. pub fn maybe_highlighting_region( &mut self, region: Option<ty::Region<'_>>, number: Option<usize>, ) { if let Some(k) = region { if let Some(n) = number { self.highlighting_region(k, n); } } } /// Highlights the region inference variable `vid` as `'N`. pub fn highlighting_region(&mut self, region: ty::Region<'_>, number: usize) { let num_slots = self.highlight_regions.len(); let first_avail_slot = self.highlight_regions.iter_mut().filter(|s| s.is_none()).next().unwrap_or_else(|| { bug!("can only highlight {} placeholders at a time", num_slots,) }); *first_avail_slot = Some((*region, number)); } /// Convenience wrapper for `highlighting_region`. pub fn highlighting_region_vid(&mut self, vid: ty::RegionVid, number: usize) { self.highlighting_region(&ty::ReVar(vid), number) } /// Returns `Some(n)` with the number to use for the given region, if any. fn region_highlighted(&self, region: ty::Region<'_>) -> Option<usize> { self.highlight_regions .iter() .filter_map(|h| match h { Some((r, n)) if r == region => Some(*n), _ => None, }) .next() } /// Highlight the given bound region. /// We can only highlight one bound region at a time. See /// the field `highlight_bound_region` for more detailed notes. pub fn highlighting_bound_region(&mut self, br: ty::BoundRegion, number: usize) { assert!(self.highlight_bound_region.is_none()); self.highlight_bound_region = Some((br, number)); } } /// Trait for printers that pretty-print using `fmt::Write` to the printer. pub trait PrettyPrinter<'tcx>: Printer< 'tcx, Error = fmt::Error, Path = Self, Region = Self, Type = Self, DynExistential = Self, Const = Self, > + fmt::Write { /// Like `print_def_path` but for value paths. fn print_value_path( self, def_id: DefId, substs: &'tcx [GenericArg<'tcx>], ) -> Result<Self::Path, Self::Error> { self.print_def_path(def_id, substs) } fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error> where T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>, { value.skip_binder().print(self) } /// Prints comma-separated elements. fn comma_sep<T>(mut self, mut elems: impl Iterator<Item = T>) -> Result<Self, Self::Error> where T: Print<'tcx, Self, Output = Self, Error = Self::Error>, { if let Some(first) = elems.next() { self = first.print(self)?; for elem in elems { self.write_str(", ")?; self = elem.print(self)?; } } Ok(self) } /// Prints `<...>` around what `f` prints. fn generic_delimiters( self, f: impl FnOnce(Self) -> Result<Self, Self::Error>, ) -> Result<Self, Self::Error>; /// Returns `true` if the region should be printed in /// optional positions, e.g., `&'a T` or `dyn Tr + 'b`. /// This is typically the case for all non-`'_` regions. fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool; // Defaults (should not be overriden): /// If possible, this returns a global path resolving to `def_id` that is visible /// from at least one local module, and returns `true`. If the crate defining `def_id` is /// declared with an `extern crate`, the path is guaranteed to use the `extern crate`. fn try_print_visible_def_path(self, def_id: DefId) -> Result<(Self, bool), Self::Error> { let mut callers = Vec::new(); self.try_print_visible_def_path_recur(def_id, &mut callers) } /// Does the work of `try_print_visible_def_path`, building the /// full definition path recursively before attempting to /// post-process it into the valid and visible version that /// accounts for re-exports. /// /// This method should only be callled by itself or /// `try_print_visible_def_path`. /// /// `callers` is a chain of visible_parent's leading to `def_id`, /// to support cycle detection during recursion. fn try_print_visible_def_path_recur( mut self, def_id: DefId, callers: &mut Vec<DefId>, ) -> Result<(Self, bool), Self::Error> { define_scoped_cx!(self); debug!("try_print_visible_def_path: def_id={:?}", def_id); // If `def_id` is a direct or injected extern crate, return the // path to the crate followed by the path to the item within the crate. if def_id.index == CRATE_DEF_INDEX { let cnum = def_id.krate; if cnum == LOCAL_CRATE { return Ok((self.path_crate(cnum)?, true)); } // In local mode, when we encounter a crate other than // LOCAL_CRATE, execution proceeds in one of two ways: // // 1. For a direct dependency, where user added an // `extern crate` manually, we put the `extern // crate` as the parent. So you wind up with // something relative to the current crate. // 2. For an extern inferred from a path or an indirect crate, // where there is no explicit `extern crate`, we just prepend // the crate name. match self.tcx().extern_crate(def_id) { Some(&ExternCrate { src: ExternCrateSource::Extern(def_id), dependency_of: LOCAL_CRATE, span, .. }) => { debug!("try_print_visible_def_path: def_id={:?}", def_id); return Ok(( if !span.is_dummy() { self.print_def_path(def_id, &[])? } else { self.path_crate(cnum)? }, true, )); } None => { return Ok((self.path_crate(cnum)?, true)); } _ => {} } } if def_id.is_local() { return Ok((self, false)); } let visible_parent_map = self.tcx().visible_parent_map(LOCAL_CRATE); let mut cur_def_key = self.tcx().def_key(def_id); debug!("try_print_visible_def_path: cur_def_key={:?}", cur_def_key); // For a constructor, we want the name of its parent rather than <unnamed>. match cur_def_key.disambiguated_data.data { DefPathData::Ctor => { let parent = DefId { krate: def_id.krate, index: cur_def_key .parent .expect("`DefPathData::Ctor` / `VariantData` missing a parent"), }; cur_def_key = self.tcx().def_key(parent); } _ => {} } let visible_parent = match visible_parent_map.get(&def_id).cloned() { Some(parent) => parent, None => return Ok((self, false)), }; if callers.contains(&visible_parent) { return Ok((self, false)); } callers.push(visible_parent); // HACK(eddyb) this bypasses `path_append`'s prefix printing to avoid // knowing ahead of time whether the entire path will succeed or not. // To support printers that do not implement `PrettyPrinter`, a `Vec` or // linked list on the stack would need to be built, before any printing. match self.try_print_visible_def_path_recur(visible_parent, callers)? { (cx, false) => return Ok((cx, false)), (cx, true) => self = cx, } callers.pop(); let actual_parent = self.tcx().parent(def_id); debug!( "try_print_visible_def_path: visible_parent={:?} actual_parent={:?}", visible_parent, actual_parent, ); let mut data = cur_def_key.disambiguated_data.data; debug!( "try_print_visible_def_path: data={:?} visible_parent={:?} actual_parent={:?}", data, visible_parent, actual_parent, ); match data { // In order to output a path that could actually be imported (valid and visible), // we need to handle re-exports correctly. // // For example, take `std::os::unix::process::CommandExt`, this trait is actually // defined at `std::sys::unix::ext::process::CommandExt` (at time of writing). // // `std::os::unix` rexports the contents of `std::sys::unix::ext`. `std::sys` is // private so the "true" path to `CommandExt` isn't accessible. // // In this case, the `visible_parent_map` will look something like this: // // (child) -> (parent) // `std::sys::unix::ext::process::CommandExt` -> `std::sys::unix::ext::process` // `std::sys::unix::ext::process` -> `std::sys::unix::ext` // `std::sys::unix::ext` -> `std::os` // // This is correct, as the visible parent of `std::sys::unix::ext` is in fact // `std::os`. // // When printing the path to `CommandExt` and looking at the `cur_def_key` that // corresponds to `std::sys::unix::ext`, we would normally print `ext` and then go // to the parent - resulting in a mangled path like // `std::os::ext::process::CommandExt`. // // Instead, we must detect that there was a re-export and instead print `unix` // (which is the name `std::sys::unix::ext` was re-exported as in `std::os`). To // do this, we compare the parent of `std::sys::unix::ext` (`std::sys::unix`) with // the visible parent (`std::os`). If these do not match, then we iterate over // the children of the visible parent (as was done when computing // `visible_parent_map`), looking for the specific child we currently have and then // have access to the re-exported name. DefPathData::TypeNs(ref mut name) if Some(visible_parent) != actual_parent => { let reexport = self .tcx() .item_children(visible_parent) .iter() .find(|child| child.res.def_id() == def_id) .map(|child| child.ident.name); if let Some(reexport) = reexport { *name = reexport; } } // Re-exported `extern crate` (#43189). DefPathData::CrateRoot => { data = DefPathData::TypeNs(self.tcx().original_crate_name(def_id.krate)); } _ => {} } debug!("try_print_visible_def_path: data={:?}", data); Ok((self.path_append(Ok, &DisambiguatedDefPathData { data, disambiguator: 0 })?, true)) } fn pretty_path_qualified( self, self_ty: Ty<'tcx>, trait_ref: Option<ty::TraitRef<'tcx>>, ) -> Result<Self::Path, Self::Error> { if trait_ref.is_none() { // Inherent impls. Try to print `Foo::bar` for an inherent // impl on `Foo`, but fallback to `<Foo>::bar` if self-type is // anything other than a simple path. match self_ty.kind { ty::Adt(..) | ty::Foreign(_) | ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) => { return self_ty.print(self); } _ => {} } } self.generic_delimiters(|mut cx| { define_scoped_cx!(cx); p!(print(self_ty)); if let Some(trait_ref) = trait_ref { p!(write(" as "), print(trait_ref.print_only_trait_path())); } Ok(cx) }) } fn pretty_path_append_impl( mut self, print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>, self_ty: Ty<'tcx>, trait_ref: Option<ty::TraitRef<'tcx>>, ) -> Result<Self::Path, Self::Error> { self = print_prefix(self)?; self.generic_delimiters(|mut cx| { define_scoped_cx!(cx); p!(write("impl ")); if let Some(trait_ref) = trait_ref { p!(print(trait_ref.print_only_trait_path()), write(" for ")); } p!(print(self_ty)); Ok(cx) }) } fn pretty_print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> { define_scoped_cx!(self); match ty.kind { ty::Bool => p!(write("bool")), ty::Char => p!(write("char")), ty::Int(t) => p!(write("{}", t.name_str())), ty::Uint(t) => p!(write("{}", t.name_str())), ty::Float(t) => p!(write("{}", t.name_str())), ty::RawPtr(ref tm) => { p!(write( "*{} ", match tm.mutbl { hir::Mutability::Mut => "mut", hir::Mutability::Not => "const", } )); p!(print(tm.ty)) } ty::Ref(r, ty, mutbl) => { p!(write("&")); if self.region_should_not_be_omitted(r) { p!(print(r), write(" ")); } p!(print(ty::TypeAndMut { ty, mutbl })) } ty::Never => p!(write("!")), ty::Tuple(ref tys) => { p!(write("(")); let mut tys = tys.iter(); if let Some(&ty) = tys.next() { p!(print(ty), write(",")); if let Some(&ty) = tys.next() { p!(write(" "), print(ty)); for &ty in tys { p!(write(", "), print(ty)); } } } p!(write(")")) } ty::FnDef(def_id, substs) => { let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs); p!(print(sig), write(" {{"), print_value_path(def_id, substs), write("}}")); } ty::FnPtr(ref bare_fn) => p!(print(bare_fn)), ty::Infer(infer_ty) => { if let ty::TyVar(ty_vid) = infer_ty { if let Some(name) = self.infer_ty_name(ty_vid) { p!(write("{}", name)) } else { p!(write("{}", infer_ty)) } } else { p!(write("{}", infer_ty)) } } ty::Error => p!(write("[type error]")), ty::Param(ref param_ty) => p!(write("{}", param_ty)), ty::Bound(debruijn, bound_ty) => match bound_ty.kind { ty::BoundTyKind::Anon => { if debruijn == ty::INNERMOST { p!(write("^{}", bound_ty.var.index())) } else { p!(write("^{}_{}", debruijn.index(), bound_ty.var.index())) } } ty::BoundTyKind::Param(p) => p!(write("{}", p)), }, ty::Adt(def, substs) => { p!(print_def_path(def.did, substs)); } ty::Dynamic(data, r) => { let print_r = self.region_should_not_be_omitted(r); if print_r { p!(write("(")); } p!(write("dyn "), print(data)); if print_r { p!(write(" + "), print(r), write(")")); } } ty::Foreign(def_id) => { p!(print_def_path(def_id, &[])); } ty::Projection(ref data) => p!(print(data)), ty::UnnormalizedProjection(ref data) => { p!(write("Unnormalized("), print(data), write(")")) } ty::Placeholder(placeholder) => p!(write("Placeholder({:?})", placeholder)), ty::Opaque(def_id, substs) => { // FIXME(eddyb) print this with `print_def_path`. // We use verbose printing in 'NO_QUERIES' mode, to // avoid needing to call `predicates_of`. This should // only affect certain debug messages (e.g. messages printed // from `rustc::ty` during the computation of `tcx.predicates_of`), // and should have no effect on any compiler output. if self.tcx().sess.verbose() || NO_QUERIES.with(|q| q.get()) { p!(write("Opaque({:?}, {:?})", def_id, substs)); return Ok(self); } return Ok(with_no_queries(|| { let def_key = self.tcx().def_key(def_id); if let Some(name) = def_key.disambiguated_data.data.get_opt_name() { p!(write("{}", name)); let mut substs = substs.iter(); // FIXME(eddyb) print this with `print_def_path`. if let Some(first) = substs.next() { p!(write("::<")); p!(print(first)); for subst in substs { p!(write(", "), print(subst)); } p!(write(">")); } return Ok(self); } // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`, // by looking up the projections associated with the def_id. let bounds = self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs); let mut first = true; let mut is_sized = false; p!(write("impl")); for predicate in bounds.predicates { if let Some(trait_ref) = predicate.to_opt_poly_trait_ref() { // Don't print +Sized, but rather +?Sized if absent. if Some(trait_ref.def_id()) == self.tcx().lang_items().sized_trait() { is_sized = true; continue; } p!( write("{}", if first { " " } else { "+" }), print(trait_ref.print_only_trait_path()) ); first = false; } } if !is_sized { p!(write("{}?Sized", if first { " " } else { "+" })); } else if first { p!(write(" Sized")); } Ok(self) })?); } ty::Str => p!(write("str")), ty::Generator(did, substs, movability) => { let upvar_tys = substs.as_generator().upvar_tys(did, self.tcx()); let witness = substs.as_generator().witness(did, self.tcx()); match movability { hir::Movability::Movable => p!(write("[generator")), hir::Movability::Static => p!(write("[static generator")), } // FIXME(eddyb) should use `def_span`. if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) { p!(write("@{:?}", self.tcx().hir().span(hir_id))); let mut sep = " "; for (&var_id, upvar_ty) in self.tcx().upvars(did).as_ref().iter().flat_map(|v| v.keys()).zip(upvar_tys) { p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty)); sep = ", "; } } else { // Cross-crate closure types should only be // visible in codegen bug reports, I imagine. p!(write("@{:?}", did)); let mut sep = " "; for (index, upvar_ty) in upvar_tys.enumerate() { p!(write("{}{}:", sep, index), print(upvar_ty)); sep = ", "; } } p!(write(" "), print(witness), write("]")) } ty::GeneratorWitness(types) => { p!(in_binder(&types)); } ty::Closure(did, substs) => { let upvar_tys = substs.as_closure().upvar_tys(did, self.tcx()); p!(write("[closure")); // FIXME(eddyb) should use `def_span`. if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) { if self.tcx().sess.opts.debugging_opts.span_free_formats { p!(write("@"), print_def_path(did, substs)); } else { p!(write("@{:?}", self.tcx().hir().span(hir_id))); } let mut sep = " "; for (&var_id, upvar_ty) in self.tcx().upvars(did).as_ref().iter().flat_map(|v| v.keys()).zip(upvar_tys) { p!(write("{}{}:", sep, self.tcx().hir().name(var_id)), print(upvar_ty)); sep = ", "; } } else { // Cross-crate closure types should only be // visible in codegen bug reports, I imagine. p!(write("@{:?}", did)); let mut sep = " "; for (index, upvar_ty) in upvar_tys.enumerate() { p!(write("{}{}:", sep, index), print(upvar_ty)); sep = ", "; } } if self.tcx().sess.verbose() { p!(write( " closure_kind_ty={:?} closure_sig_ty={:?}", substs.as_closure().kind_ty(did, self.tcx()), substs.as_closure().sig_ty(did, self.tcx()) )); } p!(write("]")) } ty::Array(ty, sz) => { p!(write("["), print(ty), write("; ")); if self.tcx().sess.verbose() { p!(write("{:?}", sz)); } else if let ty::ConstKind::Unevaluated(..) = sz.val { // do not try to evalute unevaluated constants. If we are const evaluating an // array length anon const, rustc will (with debug assertions) print the // constant's path. Which will end up here again. p!(write("_")); } else if let Some(n) = sz.try_eval_usize(self.tcx(), ty::ParamEnv::empty()) { p!(write("{}", n)); } else { p!(write("_")); } p!(write("]")) } ty::Slice(ty) => p!(write("["), print(ty), write("]")), } Ok(self) } fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> { None } fn pretty_print_dyn_existential( mut self, predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>, ) -> Result<Self::DynExistential, Self::Error> { define_scoped_cx!(self); // Generate the main trait ref, including associated types. let mut first = true; if let Some(principal) = predicates.principal() { p!(print_def_path(principal.def_id, &[])); let mut resugared = false; // Special-case `Fn(...) -> ...` and resugar it. let fn_trait_kind = self.tcx().lang_items().fn_trait_kind(principal.def_id); if !self.tcx().sess.verbose() && fn_trait_kind.is_some() { if let ty::Tuple(ref args) = principal.substs.type_at(0).kind { let mut projections = predicates.projection_bounds(); if let (Some(proj), None) = (projections.next(), projections.next()) { let tys: Vec<_> = args.iter().map(|k| k.expect_ty()).collect(); p!(pretty_fn_sig(&tys, false, proj.ty)); resugared = true; } } } // HACK(eddyb) this duplicates `FmtPrinter`'s `path_generic_args`, // in order to place the projections inside the `<...>`. if !resugared { // Use a type that can't appear in defaults of type parameters. let dummy_self = self.tcx().mk_ty_infer(ty::FreshTy(0)); let principal = principal.with_self_ty(self.tcx(), dummy_self); let args = self.generic_args_to_print( self.tcx().generics_of(principal.def_id), principal.substs, ); // Don't print `'_` if there's no unerased regions. let print_regions = args.iter().any(|arg| match arg.unpack() { GenericArgKind::Lifetime(r) => *r != ty::ReErased, _ => false, }); let mut args = args.iter().cloned().filter(|arg| match arg.unpack() { GenericArgKind::Lifetime(_) => print_regions, _ => true, }); let mut projections = predicates.projection_bounds(); let arg0 = args.next(); let projection0 = projections.next(); if arg0.is_some() || projection0.is_some() { let args = arg0.into_iter().chain(args); let projections = projection0.into_iter().chain(projections); p!(generic_delimiters(|mut cx| { cx = cx.comma_sep(args)?; if arg0.is_some() && projection0.is_some() { write!(cx, ", ")?; } cx.comma_sep(projections) })); } } first = false; } // Builtin bounds. // FIXME(eddyb) avoid printing twice (needed to ensure // that the auto traits are sorted *and* printed via cx). let mut auto_traits: Vec<_> = predicates.auto_traits().map(|did| (self.tcx().def_path_str(did), did)).collect(); // The auto traits come ordered by `DefPathHash`. While // `DefPathHash` is *stable* in the sense that it depends on // neither the host nor the phase of the moon, it depends // "pseudorandomly" on the compiler version and the target. // // To avoid that causing instabilities in compiletest // output, sort the auto-traits alphabetically. auto_traits.sort(); for (_, def_id) in auto_traits { if !first { p!(write(" + ")); } first = false; p!(print_def_path(def_id, &[])); } Ok(self) } fn pretty_fn_sig( mut self, inputs: &[Ty<'tcx>], c_variadic: bool, output: Ty<'tcx>, ) -> Result<Self, Self::Error> { define_scoped_cx!(self); p!(write("(")); let mut inputs = inputs.iter(); if let Some(&ty) = inputs.next() { p!(print(ty)); for &ty in inputs { p!(write(", "), print(ty)); } if c_variadic { p!(write(", ...")); } } p!(write(")")); if !output.is_unit() { p!(write(" -> "), print(output)); } Ok(self) } fn pretty_print_const(mut self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> { define_scoped_cx!(self); if self.tcx().sess.verbose() { p!(write("Const({:?}: {:?})", ct.val, ct.ty)); return Ok(self); } match (ct.val, &ct.ty.kind) { (_, ty::FnDef(did, substs)) => p!(print_value_path(*did, substs)), (ty::ConstKind::Unevaluated(did, substs), _) => match self.tcx().def_kind(did) { Some(DefKind::Static) | Some(DefKind::Const) | Some(DefKind::AssocConst) => { p!(print_value_path(did, substs)) } _ => { if did.is_local() { let span = self.tcx().def_span(did); if let Ok(snip) = self.tcx().sess.source_map().span_to_snippet(span) { p!(write("{}", snip)) } else { p!(write("_: "), print(ct.ty)) } } else { p!(write("_: "), print(ct.ty)) } } }, (ty::ConstKind::Infer(..), _) => p!(write("_: "), print(ct.ty)), (ty::ConstKind::Param(ParamConst { name, .. }), _) => p!(write("{}", name)), (ty::ConstKind::Value(value), _) => return self.pretty_print_const_value(value, ct.ty), _ => { // fallback p!(write("{:?} : ", ct.val), print(ct.ty)) } }; Ok(self) } fn pretty_print_const_value( mut self, ct: ConstValue<'tcx>, ty: Ty<'tcx>, ) -> Result<Self::Const, Self::Error> { define_scoped_cx!(self); if self.tcx().sess.verbose() { p!(write("ConstValue({:?}: {:?})", ct, ty)); return Ok(self); } let u8 = self.tcx().types.u8; match (ct, &ty.kind) { (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Bool) => { p!(write("{}", if data == 0 { "false" } else { "true" })) } (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F32)) => { p!(write("{}f32", Single::from_bits(data))) } (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Float(ast::FloatTy::F64)) => { p!(write("{}f64", Double::from_bits(data))) } (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Uint(ui)) => { let bit_size = Integer::from_attr(&self.tcx(), UnsignedInt(*ui)).size(); let max = truncate(u128::max_value(), bit_size); let ui_str = ui.name_str(); if data == max { p!(write("std::{}::MAX", ui_str)) } else { p!(write("{}{}", data, ui_str)) }; } (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Int(i)) => { let bit_size = Integer::from_attr(&self.tcx(), SignedInt(*i)).size().bits() as u128; let min = 1u128 << (bit_size - 1); let max = min - 1; let ty = self.tcx().lift(&ty).unwrap(); let size = self.tcx().layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size; let i_str = i.name_str(); match data { d if d == min => p!(write("std::{}::MIN", i_str)), d if d == max => p!(write("std::{}::MAX", i_str)), _ => p!(write("{}{}", sign_extend(data, size) as i128, i_str)), } } (ConstValue::Scalar(Scalar::Raw { data, .. }), ty::Char) => { p!(write("{:?}", ::std::char::from_u32(data as u32).unwrap())) } (ConstValue::Scalar(_), ty::RawPtr(_)) => p!(write("{{pointer}}")), (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::FnPtr(_)) => { let instance = { let alloc_map = self.tcx().alloc_map.lock(); alloc_map.unwrap_fn(ptr.alloc_id) }; p!(print_value_path(instance.def_id(), instance.substs)); } _ => { let printed = if let ty::Ref(_, ref_ty, _) = ty.kind { let byte_str = match (ct, &ref_ty.kind) { (ConstValue::Scalar(Scalar::Ptr(ptr)), ty::Array(t, n)) if *t == u8 => { let n = n.eval_usize(self.tcx(), ty::ParamEnv::empty()); Some( self.tcx() .alloc_map .lock() .unwrap_memory(ptr.alloc_id) .get_bytes(&self.tcx(), ptr, Size::from_bytes(n)) .unwrap(), ) } (ConstValue::Slice { data, start, end }, ty::Slice(t)) if *t == u8 => { // The `inspect` here is okay since we checked the bounds, and there are // no relocations (we have an active slice reference here). We don't use // this result to affect interpreter execution. Some(data.inspect_with_undef_and_ptr_outside_interpreter(start..end)) } _ => None, }; if let Some(byte_str) = byte_str { p!(write("b\"")); for &c in byte_str { for e in std::ascii::escape_default(c) { self.write_char(e as char)?; } } p!(write("\"")); true } else if let (ConstValue::Slice { data, start, end }, ty::Str) = (ct, &ref_ty.kind) { // The `inspect` here is okay since we checked the bounds, and there are no // relocations (we have an active `str` reference here). We don't use this // result to affect interpreter execution. let slice = data.inspect_with_undef_and_ptr_outside_interpreter(start..end); let s = ::std::str::from_utf8(slice).expect("non utf8 str from miri"); p!(write("{:?}", s)); true } else { false } } else { false }; if !printed { // fallback p!(write("{:?} : ", ct), print(ty)) } } }; Ok(self) } } // HACK(eddyb) boxed to avoid moving around a large struct by-value. pub struct FmtPrinter<'a, 'tcx, F>(Box<FmtPrinterData<'a, 'tcx, F>>); pub struct FmtPrinterData<'a, 'tcx, F> { tcx: TyCtxt<'tcx>, fmt: F, empty_path: bool, in_value: bool, used_region_names: FxHashSet<Symbol>, region_index: usize, binder_depth: usize, pub region_highlight_mode: RegionHighlightMode, pub name_resolver: Option<Box<&'a dyn Fn(ty::sty::TyVid) -> Option<String>>>, } impl<F> Deref for FmtPrinter<'a, 'tcx, F> { type Target = FmtPrinterData<'a, 'tcx, F>; fn deref(&self) -> &Self::Target { &self.0 } } impl<F> DerefMut for FmtPrinter<'_, '_, F> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<F> FmtPrinter<'a, 'tcx, F> { pub fn new(tcx: TyCtxt<'tcx>, fmt: F, ns: Namespace) -> Self { FmtPrinter(Box::new(FmtPrinterData { tcx, fmt, empty_path: false, in_value: ns == Namespace::ValueNS, used_region_names: Default::default(), region_index: 0, binder_depth: 0, region_highlight_mode: RegionHighlightMode::default(), name_resolver: None, })) } } impl TyCtxt<'t> { // HACK(eddyb) get rid of `def_path_str` and/or pass `Namespace` explicitly always // (but also some things just print a `DefId` generally so maybe we need this?) fn guess_def_namespace(self, def_id: DefId) -> Namespace { match self.def_key(def_id).disambiguated_data.data { DefPathData::TypeNs(..) | DefPathData::CrateRoot | DefPathData::ImplTrait => { Namespace::TypeNS } DefPathData::ValueNs(..) | DefPathData::AnonConst | DefPathData::ClosureExpr | DefPathData::Ctor => Namespace::ValueNS, DefPathData::MacroNs(..) => Namespace::MacroNS, _ => Namespace::TypeNS, } } /// Returns a string identifying this `DefId`. This string is /// suitable for user output. pub fn def_path_str(self, def_id: DefId) -> String { self.def_path_str_with_substs(def_id, &[]) } pub fn def_path_str_with_substs(self, def_id: DefId, substs: &'t [GenericArg<'t>]) -> String { let ns = self.guess_def_namespace(def_id); debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns); let mut s = String::new(); let _ = FmtPrinter::new(self, &mut s, ns).print_def_path(def_id, substs); s } } impl<F: fmt::Write> fmt::Write for FmtPrinter<'_, '_, F> { fn write_str(&mut self, s: &str) -> fmt::Result { self.fmt.write_str(s) } } impl<F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> { type Error = fmt::Error; type Path = Self; type Region = Self; type Type = Self; type DynExistential = Self; type Const = Self; fn tcx(&'a self) -> TyCtxt<'tcx> { self.tcx } fn print_def_path( mut self, def_id: DefId, substs: &'tcx [GenericArg<'tcx>], ) -> Result<Self::Path, Self::Error> { define_scoped_cx!(self); if substs.is_empty() { match self.try_print_visible_def_path(def_id)? { (cx, true) => return Ok(cx), (cx, false) => self = cx, } } let key = self.tcx.def_key(def_id); if let DefPathData::Impl = key.disambiguated_data.data { // Always use types for non-local impls, where types are always // available, and filename/line-number is mostly uninteresting. let use_types = !def_id.is_local() || { // Otherwise, use filename/line-number if forced. let force_no_types = FORCE_IMPL_FILENAME_LINE.with(|f| f.get()); !force_no_types }; if !use_types { // If no type info is available, fall back to // pretty printing some span information. This should // only occur very early in the compiler pipeline. let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id }; let span = self.tcx.def_span(def_id); self = self.print_def_path(parent_def_id, &[])?; // HACK(eddyb) copy of `path_append` to avoid // constructing a `DisambiguatedDefPathData`. if !self.empty_path { write!(self, "::")?; } write!(self, "<impl at {:?}>", span)?; self.empty_path = false; return Ok(self); } } self.default_print_def_path(def_id, substs) } fn print_region(self, region: ty::Region<'_>) -> Result<Self::Region, Self::Error> { self.pretty_print_region(region) } fn print_type(self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> { self.pretty_print_type(ty) } fn print_dyn_existential( self, predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>, ) -> Result<Self::DynExistential, Self::Error> { self.pretty_print_dyn_existential(predicates) } fn print_const(self, ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> { self.pretty_print_const(ct) } fn path_crate(mut self, cnum: CrateNum) -> Result<Self::Path, Self::Error> { self.empty_path = true; if cnum == LOCAL_CRATE { if self.tcx.sess.rust_2018() { // We add the `crate::` keyword on Rust 2018, only when desired. if SHOULD_PREFIX_WITH_CRATE.with(|flag| flag.get()) { write!(self, "{}", kw::Crate)?; self.empty_path = false; } } } else { write!(self, "{}", self.tcx.crate_name(cnum))?; self.empty_path = false; } Ok(self) } fn path_qualified( mut self, self_ty: Ty<'tcx>, trait_ref: Option<ty::TraitRef<'tcx>>, ) -> Result<Self::Path, Self::Error> { self = self.pretty_path_qualified(self_ty, trait_ref)?; self.empty_path = false; Ok(self) } fn path_append_impl( mut self, print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>, _disambiguated_data: &DisambiguatedDefPathData, self_ty: Ty<'tcx>, trait_ref: Option<ty::TraitRef<'tcx>>, ) -> Result<Self::Path, Self::Error> { self = self.pretty_path_append_impl( |mut cx| { cx = print_prefix(cx)?; if !cx.empty_path { write!(cx, "::")?; } Ok(cx) }, self_ty, trait_ref, )?; self.empty_path = false; Ok(self) } fn path_append( mut self, print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>, disambiguated_data: &DisambiguatedDefPathData, ) -> Result<Self::Path, Self::Error> { self = print_prefix(self)?; // Skip `::{{constructor}}` on tuple/unit structs. match disambiguated_data.data { DefPathData::Ctor => return Ok(self), _ => {} } // FIXME(eddyb) `name` should never be empty, but it // currently is for `extern { ... }` "foreign modules". let name = disambiguated_data.data.as_symbol().as_str(); if !name.is_empty() { if !self.empty_path { write!(self, "::")?; } if ast::Ident::from_str(&name).is_raw_guess() { write!(self, "r#")?; } write!(self, "{}", name)?; // FIXME(eddyb) this will print e.g. `{{closure}}#3`, but it // might be nicer to use something else, e.g. `{closure#3}`. let dis = disambiguated_data.disambiguator; let print_dis = disambiguated_data.data.get_opt_name().is_none() || dis != 0 && self.tcx.sess.verbose(); if print_dis { write!(self, "#{}", dis)?; } self.empty_path = false; } Ok(self) } fn path_generic_args( mut self, print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>, args: &[GenericArg<'tcx>], ) -> Result<Self::Path, Self::Error> { self = print_prefix(self)?; // Don't print `'_` if there's no unerased regions. let print_regions = args.iter().any(|arg| match arg.unpack() { GenericArgKind::Lifetime(r) => *r != ty::ReErased, _ => false, }); let args = args.iter().cloned().filter(|arg| match arg.unpack() { GenericArgKind::Lifetime(_) => print_regions, _ => true, }); if args.clone().next().is_some() { if self.in_value { write!(self, "::")?; } self.generic_delimiters(|cx| cx.comma_sep(args)) } else { Ok(self) } } } impl<F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> { fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> { self.0.name_resolver.as_ref().and_then(|func| func(id)) } fn print_value_path( mut self, def_id: DefId, substs: &'tcx [GenericArg<'tcx>], ) -> Result<Self::Path, Self::Error> { let was_in_value = std::mem::replace(&mut self.in_value, true); self = self.print_def_path(def_id, substs)?; self.in_value = was_in_value; Ok(self) } fn in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, Self::Error> where T: Print<'tcx, Self, Output = Self, Error = Self::Error> + TypeFoldable<'tcx>, { self.pretty_in_binder(value) } fn generic_delimiters( mut self, f: impl FnOnce(Self) -> Result<Self, Self::Error>, ) -> Result<Self, Self::Error> { write!(self, "<")?; let was_in_value = std::mem::replace(&mut self.in_value, false); let mut inner = f(self)?; inner.in_value = was_in_value; write!(inner, ">")?; Ok(inner) } fn region_should_not_be_omitted(&self, region: ty::Region<'_>) -> bool { let highlight = self.region_highlight_mode; if highlight.region_highlighted(region).is_some() { return true; } if self.tcx.sess.verbose() { return true; } let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions; match *region { ty::ReEarlyBound(ref data) => { data.name != kw::Invalid && data.name != kw::UnderscoreLifetime } ty::ReLateBound(_, br) | ty::ReFree(ty::FreeRegion { bound_region: br, .. }) | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => { if let ty::BrNamed(_, name) = br { if name != kw::Invalid && name != kw::UnderscoreLifetime { return true; } } if let Some((region, _)) = highlight.highlight_bound_region { if br == region { return true; } } false } ty::ReScope(_) | ty::ReVar(_) if identify_regions => true, ty::ReVar(_) | ty::ReScope(_) | ty::ReErased => false, ty::ReStatic | ty::ReEmpty | ty::ReClosureBound(_) => true, } } } // HACK(eddyb) limited to `FmtPrinter` because of `region_highlight_mode`. impl<F: fmt::Write> FmtPrinter<'_, '_, F> { pub fn pretty_print_region(mut self, region: ty::Region<'_>) -> Result<Self, fmt::Error> { define_scoped_cx!(self); // Watch out for region highlights. let highlight = self.region_highlight_mode; if let Some(n) = highlight.region_highlighted(region) { p!(write("'{}", n)); return Ok(self); } if self.tcx.sess.verbose() { p!(write("{:?}", region)); return Ok(self); } let identify_regions = self.tcx.sess.opts.debugging_opts.identify_regions; // These printouts are concise. They do not contain all the information // the user might want to diagnose an error, but there is basically no way // to fit that into a short string. Hence the recommendation to use // `explain_region()` or `note_and_explain_region()`. match *region { ty::ReEarlyBound(ref data) => { if data.name != kw::Invalid { p!(write("{}", data.name)); return Ok(self); } } ty::ReLateBound(_, br) | ty::ReFree(ty::FreeRegion { bound_region: br, .. }) | ty::RePlaceholder(ty::Placeholder { name: br, .. }) => { if let ty::BrNamed(_, name) = br { if name != kw::Invalid && name != kw::UnderscoreLifetime { p!(write("{}", name)); return Ok(self); } } if let Some((region, counter)) = highlight.highlight_bound_region { if br == region { p!(write("'{}", counter)); return Ok(self); } } } ty::ReScope(scope) if identify_regions => { match scope.data { region::ScopeData::Node => p!(write("'{}s", scope.item_local_id().as_usize())), region::ScopeData::CallSite => { p!(write("'{}cs", scope.item_local_id().as_usize())) } region::ScopeData::Arguments => { p!(write("'{}as", scope.item_local_id().as_usize())) } region::ScopeData::Destruction => { p!(write("'{}ds", scope.item_local_id().as_usize())) } region::ScopeData::Remainder(first_statement_index) => p!(write( "'{}_{}rs", scope.item_local_id().as_usize(), first_statement_index.index() )), } return Ok(self); } ty::ReVar(region_vid) if identify_regions => { p!(write("{:?}", region_vid)); return Ok(self); } ty::ReVar(_) => {} ty::ReScope(_) | ty::ReErased => {} ty::ReStatic => { p!(write("'static")); return Ok(self); } ty::ReEmpty => { p!(write("'<empty>")); return Ok(self); } // The user should never encounter these in unsubstituted form. ty::ReClosureBound(vid) => { p!(write("{:?}", vid)); return Ok(self); } } p!(write("'_")); Ok(self) } } // HACK(eddyb) limited to `FmtPrinter` because of `binder_depth`, // `region_index` and `used_region_names`. impl<F: fmt::Write> FmtPrinter<'_, 'tcx, F> { pub fn name_all_regions<T>( mut self, value: &ty::Binder<T>, ) -> Result<(Self, (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)), fmt::Error> where T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>, { fn name_by_region_index(index: usize) -> Symbol { match index { 0 => Symbol::intern("'r"), 1 => Symbol::intern("'s"), i => Symbol::intern(&format!("'t{}", i - 2)), } } // Replace any anonymous late-bound regions with named // variants, using new unique identifiers, so that we can // clearly differentiate between named and unnamed regions in // the output. We'll probably want to tweak this over time to // decide just how much information to give. if self.binder_depth == 0 { self.prepare_late_bound_region_info(value); } let mut empty = true; let mut start_or_continue = |cx: &mut Self, start: &str, cont: &str| { write!( cx, "{}", if empty { empty = false; start } else { cont } ) }; define_scoped_cx!(self); let mut region_index = self.region_index; let new_value = self.tcx.replace_late_bound_regions(value, |br| { let _ = start_or_continue(&mut self, "for<", ", "); let br = match br { ty::BrNamed(_, name) => { let _ = write!(self, "{}", name); br } ty::BrAnon(_) | ty::BrEnv => { let name = loop { let name = name_by_region_index(region_index); region_index += 1; if !self.used_region_names.contains(&name) { break name; } }; let _ = write!(self, "{}", name); ty::BrNamed(DefId::local(CRATE_DEF_INDEX), name) } }; self.tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)) }); start_or_continue(&mut self, "", "> ")?; self.binder_depth += 1; self.region_index = region_index; Ok((self, new_value)) } pub fn pretty_in_binder<T>(self, value: &ty::Binder<T>) -> Result<Self, fmt::Error> where T: Print<'tcx, Self, Output = Self, Error = fmt::Error> + TypeFoldable<'tcx>, { let old_region_index = self.region_index; let (new, new_value) = self.name_all_regions(value)?; let mut inner = new_value.0.print(new)?; inner.region_index = old_region_index; inner.binder_depth -= 1; Ok(inner) } fn prepare_late_bound_region_info<T>(&mut self, value: &ty::Binder<T>) where T: TypeFoldable<'tcx>, { struct LateBoundRegionNameCollector<'a>(&'a mut FxHashSet<Symbol>); impl<'tcx> ty::fold::TypeVisitor<'tcx> for LateBoundRegionNameCollector<'_> { fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool { match *r { ty::ReLateBound(_, ty::BrNamed(_, name)) => { self.0.insert(name); } _ => {} } r.super_visit_with(self) } } self.used_region_names.clear(); let mut collector = LateBoundRegionNameCollector(&mut self.used_region_names); value.visit_with(&mut collector); self.region_index = 0; } } impl<'tcx, T, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::Binder<T> where T: Print<'tcx, P, Output = P, Error = P::Error> + TypeFoldable<'tcx>, { type Output = P; type Error = P::Error; fn print(&self, cx: P) -> Result<Self::Output, Self::Error> { cx.in_binder(self) } } impl<'tcx, T, U, P: PrettyPrinter<'tcx>> Print<'tcx, P> for ty::OutlivesPredicate<T, U> where T: Print<'tcx, P, Output = P, Error = P::Error>, U: Print<'tcx, P, Output = P, Error = P::Error>, { type Output = P; type Error = P::Error; fn print(&self, mut cx: P) -> Result<Self::Output, Self::Error> { define_scoped_cx!(cx); p!(print(self.0), write(" : "), print(self.1)); Ok(cx) } } macro_rules! forward_display_to_print { ($($ty:ty),+) => { $(impl fmt::Display for $ty { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { tcx.lift(self) .expect("could not lift for printing") .print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?; Ok(()) }) } })+ }; } macro_rules! define_print_and_forward_display { (($self:ident, $cx:ident): $($ty:ty $print:block)+) => { $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty { type Output = P; type Error = fmt::Error; fn print(&$self, $cx: P) -> Result<Self::Output, Self::Error> { #[allow(unused_mut)] let mut $cx = $cx; define_scoped_cx!($cx); let _: () = $print; #[allow(unreachable_code)] Ok($cx) } })+ forward_display_to_print!($($ty),+); }; } // HACK(eddyb) this is separate because `ty::RegionKind` doesn't need lifting. impl fmt::Display for ty::RegionKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { self.print(FmtPrinter::new(tcx, f, Namespace::TypeNS))?; Ok(()) }) } } /// Wrapper type for `ty::TraitRef` which opts-in to pretty printing only /// the trait path. That is, it will print `Trait<U>` instead of /// `<T as Trait<U>>`. #[derive(Copy, Clone, TypeFoldable, Lift)] pub struct TraitRefPrintOnlyTraitPath<'tcx>(ty::TraitRef<'tcx>); impl fmt::Debug for TraitRefPrintOnlyTraitPath<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(self, f) } } impl ty::TraitRef<'tcx> { pub fn print_only_trait_path(self) -> TraitRefPrintOnlyTraitPath<'tcx> { TraitRefPrintOnlyTraitPath(self) } } impl ty::Binder<ty::TraitRef<'tcx>> { pub fn print_only_trait_path(self) -> ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>> { self.map_bound(|tr| tr.print_only_trait_path()) } } forward_display_to_print! { Ty<'tcx>, &'tcx ty::List<ty::ExistentialPredicate<'tcx>>, &'tcx ty::Const<'tcx>, // HACK(eddyb) these are exhaustive instead of generic, // because `for<'tcx>` isn't possible yet. ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>, ty::Binder<ty::TraitRef<'tcx>>, ty::Binder<TraitRefPrintOnlyTraitPath<'tcx>>, ty::Binder<ty::FnSig<'tcx>>, ty::Binder<ty::TraitPredicate<'tcx>>, ty::Binder<ty::SubtypePredicate<'tcx>>, ty::Binder<ty::ProjectionPredicate<'tcx>>, ty::Binder<ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>>, ty::Binder<ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>>>, ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>>, ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>> } define_print_and_forward_display! { (self, cx): &'tcx ty::List<Ty<'tcx>> { p!(write("{{")); let mut tys = self.iter(); if let Some(&ty) = tys.next() { p!(print(ty)); for &ty in tys { p!(write(", "), print(ty)); } } p!(write("}}")) } ty::TypeAndMut<'tcx> { p!(write("{}", self.mutbl.prefix_str()), print(self.ty)) } ty::ExistentialTraitRef<'tcx> { // Use a type that can't appear in defaults of type parameters. let dummy_self = cx.tcx().mk_ty_infer(ty::FreshTy(0)); let trait_ref = self.with_self_ty(cx.tcx(), dummy_self); p!(print(trait_ref.print_only_trait_path())) } ty::ExistentialProjection<'tcx> { let name = cx.tcx().associated_item(self.item_def_id).ident; p!(write("{} = ", name), print(self.ty)) } ty::ExistentialPredicate<'tcx> { match *self { ty::ExistentialPredicate::Trait(x) => p!(print(x)), ty::ExistentialPredicate::Projection(x) => p!(print(x)), ty::ExistentialPredicate::AutoTrait(def_id) => { p!(print_def_path(def_id, &[])); } } } ty::FnSig<'tcx> { p!(write("{}", self.unsafety.prefix_str())); if self.abi != Abi::Rust { p!(write("extern {} ", self.abi)); } p!(write("fn"), pretty_fn_sig(self.inputs(), self.c_variadic, self.output())); } ty::InferTy { if cx.tcx().sess.verbose() { p!(write("{:?}", self)); return Ok(cx); } match *self { ty::TyVar(_) => p!(write("_")), ty::IntVar(_) => p!(write("{}", "{integer}")), ty::FloatVar(_) => p!(write("{}", "{float}")), ty::FreshTy(v) => p!(write("FreshTy({})", v)), ty::FreshIntTy(v) => p!(write("FreshIntTy({})", v)), ty::FreshFloatTy(v) => p!(write("FreshFloatTy({})", v)) } } ty::TraitRef<'tcx> { p!(write("<{} as {}>", self.self_ty(), self.print_only_trait_path())) } TraitRefPrintOnlyTraitPath<'tcx> { p!(print_def_path(self.0.def_id, self.0.substs)); } ty::ParamTy { p!(write("{}", self.name)) } ty::ParamConst { p!(write("{}", self.name)) } ty::SubtypePredicate<'tcx> { p!(print(self.a), write(" <: "), print(self.b)) } ty::TraitPredicate<'tcx> { p!(print(self.trait_ref.self_ty()), write(": "), print(self.trait_ref.print_only_trait_path())) } ty::ProjectionPredicate<'tcx> { p!(print(self.projection_ty), write(" == "), print(self.ty)) } ty::ProjectionTy<'tcx> { p!(print_def_path(self.item_def_id, self.substs)); } ty::ClosureKind { match *self { ty::ClosureKind::Fn => p!(write("Fn")), ty::ClosureKind::FnMut => p!(write("FnMut")), ty::ClosureKind::FnOnce => p!(write("FnOnce")), } } ty::Predicate<'tcx> { match *self { ty::Predicate::Trait(ref data) => p!(print(data)), ty::Predicate::Subtype(ref predicate) => p!(print(predicate)), ty::Predicate::RegionOutlives(ref predicate) => p!(print(predicate)), ty::Predicate::TypeOutlives(ref predicate) => p!(print(predicate)), ty::Predicate::Projection(ref predicate) => p!(print(predicate)), ty::Predicate::WellFormed(ty) => p!(print(ty), write(" well-formed")), ty::Predicate::ObjectSafe(trait_def_id) => { p!(write("the trait `"), print_def_path(trait_def_id, &[]), write("` is object-safe")) } ty::Predicate::ClosureKind(closure_def_id, _closure_substs, kind) => { p!(write("the closure `"), print_value_path(closure_def_id, &[]), write("` implements the trait `{}`", kind)) } ty::Predicate::ConstEvaluatable(def_id, substs) => { p!(write("the constant `"), print_value_path(def_id, substs), write("` can be evaluated")) } } } GenericArg<'tcx> { match self.unpack() { GenericArgKind::Lifetime(lt) => p!(print(lt)), GenericArgKind::Type(ty) => p!(print(ty)), GenericArgKind::Const(ct) => p!(print(ct)), } } }
37.006601
100
0.48854
ebbfed51f9b3d3cc5adc90f173149111fa7af2e4
26,178
//! This module exists to reduce compilation times. //! All the data types are backed by a physical type in memory e.g. Date32 -> i32, Date64 -> i64. //! //! Series lead to code implementations of all traits. Whereas there are a lot of duplicates due to //! data types being backed by the same physical type. In this module we reduce compile times by //! opting for a little more run time cost. We cast to the physical type -> apply the operation and //! (depending on the result) cast back to the original type //! use super::private; use super::IntoSeries; use super::SeriesTrait; use super::SeriesWrap; use crate::chunked_array::{comparison::*, AsSinglePtr, ChunkIdIter}; use crate::fmt::FmtList; #[cfg(feature = "pivot")] use crate::frame::groupby::pivot::*; use crate::frame::groupby::*; use crate::prelude::*; use ahash::RandomState; use arrow::array::{ArrayData, ArrayRef}; use arrow::buffer::Buffer; use std::borrow::Cow; impl<T> ChunkedArray<T> { /// get the physical memory type of a date type fn physical_type(&self) -> DataType { match self.dtype() { DataType::Duration(_) | DataType::Date64 | DataType::Time64(_) => DataType::Int64, DataType::Date32 => DataType::Int32, dt => panic!("already a physical type: {:?}", dt), } } } /// Dispatch the method call to the physical type and coerce back to logical type macro_rules! physical_dispatch { ($s: expr, $method: ident, $($args:expr),*) => {{ let dtype = $s.dtype(); let phys_type = $s.physical_type(); let s = $s.cast_with_dtype(&phys_type).unwrap(); let s = s.$method($($args),*); // if the type is unchanged we return the original type if s.dtype() == &phys_type { s.cast_with_dtype(dtype).unwrap() } // else the change of type is part of the operation. else { s } }} } macro_rules! try_physical_dispatch { ($s: expr, $method: ident, $($args:expr),*) => {{ let dtype = $s.dtype(); let phys_type = $s.physical_type(); let s = $s.cast_with_dtype(&phys_type).unwrap(); let s = s.$method($($args),*)?; // if the type is unchanged we return the original type if s.dtype() == &phys_type { s.cast_with_dtype(dtype) } // else the change of type is part of the operation. else { Ok(s) } }} } macro_rules! opt_physical_dispatch { ($s: expr, $method: ident, $($args:expr),*) => {{ let dtype = $s.dtype(); let phys_type = $s.physical_type(); let s = $s.cast_with_dtype(&phys_type).unwrap(); let s = s.$method($($args),*)?; // if the type is unchanged we return the original type if s.dtype() == &phys_type { Some(s.cast_with_dtype(dtype).unwrap()) } // else the change of type is part of the operation. else { Some(s) } }} } /// Same as physical dispatch, but doesnt care about return type macro_rules! cast_and_apply { ($s: expr, $method: ident, $($args:expr),*) => {{ let phys_type = $s.physical_type(); let s = $s.cast_with_dtype(&phys_type).unwrap(); s.$method($($args),*) }} } macro_rules! impl_dyn_series { ($ca: ident) => { impl IntoSeries for $ca { fn into_series(self) -> Series { Series(Arc::new(SeriesWrap(self))) } } impl private::PrivateSeries for SeriesWrap<$ca> { unsafe fn equal_element( &self, idx_self: usize, idx_other: usize, other: &Series, ) -> bool { self.0.equal_element(idx_self, idx_other, other) } fn zip_with_same_type(&self, mask: &BooleanChunked, other: &Series) -> Result<Series> { try_physical_dispatch!(self, zip_with_same_type, mask, other) } fn vec_hash(&self, random_state: RandomState) -> UInt64Chunked { cast_and_apply!(self, vec_hash, random_state) } fn agg_mean(&self, groups: &[(u32, Vec<u32>)]) -> Option<Series> { opt_physical_dispatch!(self, agg_mean, groups) } fn agg_min(&self, groups: &[(u32, Vec<u32>)]) -> Option<Series> { opt_physical_dispatch!(self, agg_min, groups) } fn agg_max(&self, groups: &[(u32, Vec<u32>)]) -> Option<Series> { opt_physical_dispatch!(self, agg_max, groups) } fn agg_sum(&self, groups: &[(u32, Vec<u32>)]) -> Option<Series> { opt_physical_dispatch!(self, agg_sum, groups) } fn agg_first(&self, groups: &[(u32, Vec<u32>)]) -> Series { physical_dispatch!(self, agg_first, groups) } fn agg_last(&self, groups: &[(u32, Vec<u32>)]) -> Series { physical_dispatch!(self, agg_last, groups) } fn agg_std(&self, groups: &[(u32, Vec<u32>)]) -> Option<Series> { opt_physical_dispatch!(self, agg_std, groups) } fn agg_var(&self, groups: &[(u32, Vec<u32>)]) -> Option<Series> { opt_physical_dispatch!(self, agg_var, groups) } fn agg_n_unique(&self, groups: &[(u32, Vec<u32>)]) -> Option<UInt32Chunked> { cast_and_apply!(self, agg_n_unique, groups) } fn agg_list(&self, groups: &[(u32, Vec<u32>)]) -> Option<Series> { // we cannot cast and dispatch as the inner type of the list would be incorrect self.0.agg_list(groups) } fn agg_quantile(&self, groups: &[(u32, Vec<u32>)], quantile: f64) -> Option<Series> { opt_physical_dispatch!(self, agg_quantile, groups, quantile) } fn agg_median(&self, groups: &[(u32, Vec<u32>)]) -> Option<Series> { opt_physical_dispatch!(self, agg_median, groups) } #[cfg(feature = "lazy")] fn agg_valid_count(&self, groups: &[(u32, Vec<u32>)]) -> Option<Series> { opt_physical_dispatch!(self, agg_valid_count, groups) } #[cfg(feature = "pivot")] fn pivot<'a>( &self, pivot_series: &'a (dyn SeriesTrait + 'a), keys: Vec<Series>, groups: &[(u32, Vec<u32>)], agg_type: PivotAgg, ) -> Result<DataFrame> { self.0.pivot(pivot_series, keys, groups, agg_type) } #[cfg(feature = "pivot")] fn pivot_count<'a>( &self, pivot_series: &'a (dyn SeriesTrait + 'a), keys: Vec<Series>, groups: &[(u32, Vec<u32>)], ) -> Result<DataFrame> { self.0.pivot_count(pivot_series, keys, groups) } fn hash_join_inner(&self, other: &Series) -> Vec<(u32, u32)> { let other = other.to_physical_repr(); cast_and_apply!(self, hash_join_inner, &other) } fn hash_join_left(&self, other: &Series) -> Vec<(u32, Option<u32>)> { let other = other.to_physical_repr(); cast_and_apply!(self, hash_join_left, &other) } fn hash_join_outer(&self, other: &Series) -> Vec<(Option<u32>, Option<u32>)> { let other = other.to_physical_repr(); cast_and_apply!(self, hash_join_outer, &other) } fn zip_outer_join_column( &self, right_column: &Series, opt_join_tuples: &[(Option<u32>, Option<u32>)], ) -> Series { let right_column = right_column.to_physical_repr(); physical_dispatch!(self, zip_outer_join_column, &right_column, opt_join_tuples) } fn subtract(&self, rhs: &Series) -> Result<Series> { try_physical_dispatch!(self, subtract, rhs) } fn add_to(&self, rhs: &Series) -> Result<Series> { try_physical_dispatch!(self, add_to, rhs) } fn multiply(&self, rhs: &Series) -> Result<Series> { try_physical_dispatch!(self, multiply, rhs) } fn divide(&self, rhs: &Series) -> Result<Series> { try_physical_dispatch!(self, divide, rhs) } fn remainder(&self, rhs: &Series) -> Result<Series> { try_physical_dispatch!(self, remainder, rhs) } fn group_tuples(&self, multithreaded: bool) -> GroupTuples { cast_and_apply!(self, group_tuples, multithreaded) } #[cfg(feature = "sort_multiple")] fn argsort_multiple(&self, by: &[Series], reverse: &[bool]) -> Result<UInt32Chunked> { let phys_type = self.0.physical_type(); let s = self.cast_with_dtype(&phys_type).unwrap(); self.0 .unpack_series_matching_type(&s)? .argsort_multiple(by, reverse) } fn str_value(&self, index: usize) -> Cow<str> { // get AnyValue Cow::Owned(format!("{}", self.get(index))) } } impl SeriesTrait for SeriesWrap<$ca> { fn cum_max(&self, reverse: bool) -> Series { physical_dispatch!(self, cum_max, reverse) } fn cum_min(&self, reverse: bool) -> Series { physical_dispatch!(self, cum_min, reverse) } fn cum_sum(&self, reverse: bool) -> Series { physical_dispatch!(self, cum_sum, reverse) } fn rename(&mut self, name: &str) { self.0.rename(name); } fn array_data(&self) -> Vec<&ArrayData> { self.0.array_data() } fn chunk_lengths(&self) -> ChunkIdIter { self.0.chunk_id() } fn name(&self) -> &str { self.0.name() } fn field(&self) -> &Field { self.0.ref_field() } fn chunks(&self) -> &Vec<ArrayRef> { self.0.chunks() } fn date32(&self) -> Result<&Date32Chunked> { if matches!(self.0.dtype(), DataType::Date32) { unsafe { Ok(&*(self as *const dyn SeriesTrait as *const Date32Chunked)) } } else { Err(PolarsError::DataTypeMisMatch( format!( "cannot unpack Series: {:?} of type {:?} into date32", self.name(), self.dtype(), ) .into(), )) } } fn date64(&self) -> Result<&Date64Chunked> { if matches!(self.0.dtype(), DataType::Date64) { unsafe { Ok(&*(self as *const dyn SeriesTrait as *const Date64Chunked)) } } else { Err(PolarsError::DataTypeMisMatch( format!( "cannot unpack Series: {:?} of type {:?} into date64", self.name(), self.dtype(), ) .into(), )) } } fn time64_nanosecond(&self) -> Result<&Time64NanosecondChunked> { if matches!(self.0.dtype(), DataType::Time64(TimeUnit::Nanosecond)) { unsafe { Ok(&*(self as *const dyn SeriesTrait as *const Time64NanosecondChunked)) } } else { Err(PolarsError::DataTypeMisMatch( format!( "cannot unpack Series: {:?} of type {:?} into time64", self.name(), self.dtype(), ) .into(), )) } } fn duration_nanosecond(&self) -> Result<&DurationNanosecondChunked> { if matches!(self.0.dtype(), DataType::Duration(TimeUnit::Nanosecond)) { unsafe { Ok(&*(self as *const dyn SeriesTrait as *const DurationNanosecondChunked)) } } else { Err(PolarsError::DataTypeMisMatch( format!( "cannot unpack Series: {:?} of type {:?} into duration_nanosecond", self.name(), self.dtype(), ) .into(), )) } } fn duration_millisecond(&self) -> Result<&DurationMillisecondChunked> { if matches!(self.0.dtype(), DataType::Duration(TimeUnit::Millisecond)) { unsafe { Ok(&*(self as *const dyn SeriesTrait as *const DurationMillisecondChunked)) } } else { Err(PolarsError::DataTypeMisMatch( format!( "cannot unpack Series: {:?} of type {:?} into duration_millisecond", self.name(), self.dtype(), ) .into(), )) } } fn append_array(&mut self, other: ArrayRef) -> Result<()> { self.0.append_array(other) } fn slice(&self, offset: i64, length: usize) -> Series { self.0.slice(offset, length).into_series() } fn mean(&self) -> Option<f64> { cast_and_apply!(self, mean,) } fn median(&self) -> Option<f64> { cast_and_apply!(self, median,) } fn append(&mut self, other: &Series) -> Result<()> { if self.0.dtype() == other.dtype() { // todo! add object self.0.append(other.as_ref().as_ref()); Ok(()) } else { Err(PolarsError::DataTypeMisMatch( "cannot append Series; data types don't match".into(), )) } } fn filter(&self, filter: &BooleanChunked) -> Result<Series> { try_physical_dispatch!(self, filter, filter) } fn take(&self, indices: &UInt32Chunked) -> Series { physical_dispatch!(self, take, indices) } fn take_iter(&self, iter: &mut dyn Iterator<Item = usize>) -> Series { physical_dispatch!(self, take_iter, iter) } fn take_every(&self, n: usize) -> Series { physical_dispatch!(self, take_every, n) } unsafe fn take_iter_unchecked(&self, iter: &mut dyn Iterator<Item = usize>) -> Series { physical_dispatch!(self, take_iter_unchecked, iter) } unsafe fn take_unchecked(&self, idx: &UInt32Chunked) -> Result<Series> { try_physical_dispatch!(self, take_unchecked, idx) } unsafe fn take_opt_iter_unchecked( &self, iter: &mut dyn Iterator<Item = Option<usize>>, ) -> Series { physical_dispatch!(self, take_opt_iter_unchecked, iter) } fn take_opt_iter(&self, iter: &mut dyn Iterator<Item = Option<usize>>) -> Series { physical_dispatch!(self, take_opt_iter, iter) } fn len(&self) -> usize { self.0.len() } fn rechunk(&self) -> Series { physical_dispatch!(self, rechunk,) } fn head(&self, length: Option<usize>) -> Series { self.0.head(length).into_series() } fn tail(&self, length: Option<usize>) -> Series { self.0.tail(length).into_series() } fn expand_at_index(&self, index: usize, length: usize) -> Series { physical_dispatch!(self, expand_at_index, index, length) } fn cast_with_dtype(&self, data_type: &DataType) -> Result<Series> { self.0.cast_with_dtype(data_type) } fn to_dummies(&self) -> Result<DataFrame> { cast_and_apply!(self, to_dummies,) } fn value_counts(&self) -> Result<DataFrame> { cast_and_apply!(self, value_counts,) } fn get(&self, index: usize) -> AnyValue { self.0.get_any_value(index) } #[inline] unsafe fn get_unchecked(&self, index: usize) -> AnyValue { self.0.get_any_value_unchecked(index) } fn sort_in_place(&mut self, reverse: bool) { ChunkSort::sort_in_place(&mut self.0, reverse); } fn sort(&self, reverse: bool) -> Series { physical_dispatch!(self, sort, reverse) } fn argsort(&self, reverse: bool) -> UInt32Chunked { cast_and_apply!(self, argsort, reverse) } fn null_count(&self) -> usize { self.0.null_count() } fn unique(&self) -> Result<Series> { try_physical_dispatch!(self, unique,) } fn n_unique(&self) -> Result<usize> { cast_and_apply!(self, n_unique,) } fn arg_unique(&self) -> Result<UInt32Chunked> { cast_and_apply!(self, arg_unique,) } fn arg_min(&self) -> Option<usize> { cast_and_apply!(self, arg_min,) } fn arg_max(&self) -> Option<usize> { cast_and_apply!(self, arg_max,) } fn arg_true(&self) -> Result<UInt32Chunked> { let ca: &BooleanChunked = self.bool()?; Ok(ca.arg_true()) } fn is_null(&self) -> BooleanChunked { cast_and_apply!(self, is_null,) } fn is_not_null(&self) -> BooleanChunked { cast_and_apply!(self, is_not_null,) } fn is_unique(&self) -> Result<BooleanChunked> { cast_and_apply!(self, is_unique,) } fn is_duplicated(&self) -> Result<BooleanChunked> { cast_and_apply!(self, is_duplicated,) } fn null_bits(&self) -> Vec<(usize, Option<Buffer>)> { self.0.null_bits().collect() } fn reverse(&self) -> Series { physical_dispatch!(self, reverse,) } fn as_single_ptr(&mut self) -> Result<usize> { self.0.as_single_ptr() } fn shift(&self, periods: i64) -> Series { physical_dispatch!(self, shift, periods) } fn fill_none(&self, strategy: FillNoneStrategy) -> Result<Series> { try_physical_dispatch!(self, fill_none, strategy) } fn sum_as_series(&self) -> Series { physical_dispatch!(self, sum_as_series,) } fn max_as_series(&self) -> Series { physical_dispatch!(self, max_as_series,) } fn min_as_series(&self) -> Series { physical_dispatch!(self, min_as_series,) } fn mean_as_series(&self) -> Series { physical_dispatch!(self, mean_as_series,) } fn median_as_series(&self) -> Series { physical_dispatch!(self, median_as_series,) } fn var_as_series(&self) -> Series { physical_dispatch!(self, var_as_series,) } fn std_as_series(&self) -> Series { physical_dispatch!(self, std_as_series,) } fn quantile_as_series(&self, quantile: f64) -> Result<Series> { try_physical_dispatch!(self, quantile_as_series, quantile) } fn rolling_mean( &self, window_size: u32, weight: Option<&[f64]>, ignore_null: bool, min_periods: u32, ) -> Result<Series> { try_physical_dispatch!( self, rolling_mean, window_size, weight, ignore_null, min_periods ) } fn rolling_sum( &self, window_size: u32, weight: Option<&[f64]>, ignore_null: bool, min_periods: u32, ) -> Result<Series> { try_physical_dispatch!( self, rolling_sum, window_size, weight, ignore_null, min_periods ) } fn rolling_min( &self, window_size: u32, weight: Option<&[f64]>, ignore_null: bool, min_periods: u32, ) -> Result<Series> { try_physical_dispatch!( self, rolling_min, window_size, weight, ignore_null, min_periods ) } fn rolling_max( &self, window_size: u32, weight: Option<&[f64]>, ignore_null: bool, min_periods: u32, ) -> Result<Series> { try_physical_dispatch!( self, rolling_max, window_size, weight, ignore_null, min_periods ) } fn fmt_list(&self) -> String { FmtList::fmt_list(&self.0) } fn clone_inner(&self) -> Arc<dyn SeriesTrait> { Arc::new(SeriesWrap(Clone::clone(&self.0))) } #[cfg(feature = "random")] #[cfg_attr(docsrs, doc(cfg(feature = "random")))] fn sample_n(&self, n: usize, with_replacement: bool) -> Result<Series> { try_physical_dispatch!(self, sample_n, n, with_replacement) } #[cfg(feature = "random")] #[cfg_attr(docsrs, doc(cfg(feature = "random")))] fn sample_frac(&self, frac: f64, with_replacement: bool) -> Result<Series> { try_physical_dispatch!(self, sample_frac, frac, with_replacement) } fn pow(&self, exponent: f64) -> Result<Series> { try_physical_dispatch!(self, pow, exponent) } fn peak_max(&self) -> BooleanChunked { cast_and_apply!(self, peak_max,) } fn peak_min(&self) -> BooleanChunked { cast_and_apply!(self, peak_min,) } #[cfg(feature = "is_in")] fn is_in(&self, other: &Series) -> Result<BooleanChunked> { IsIn::is_in(&self.0, other) } } }; } #[cfg(feature = "dtype-duration-ns")] impl_dyn_series!(DurationNanosecondChunked); #[cfg(feature = "dtype-duration-ms")] impl_dyn_series!(DurationMillisecondChunked); #[cfg(feature = "dtype-date32")] impl_dyn_series!(Date32Chunked); #[cfg(feature = "dtype-date64")] impl_dyn_series!(Date64Chunked); #[cfg(feature = "dtype-time64-ns")] impl_dyn_series!(Time64NanosecondChunked); #[cfg(test)] mod test { use super::*; #[test] #[cfg(feature = "dtype-date64")] fn test_agg_list_type() -> Result<()> { let s = Series::new("foo", &[1, 2, 3]); let s = s.cast_with_dtype(&DataType::Date64)?; let l = s.agg_list(&[(0, vec![0, 1, 2])]).unwrap(); assert!(matches!(l.dtype(), DataType::List(ArrowDataType::Date64))); Ok(()) } #[test] #[cfg(feature = "dtype-date64")] fn test_datelike_join() -> Result<()> { let s = Series::new("foo", &[1, 2, 3]); let mut s1 = s.cast_with_dtype(&DataType::Date64)?; s1.rename("bar"); let df = DataFrame::new(vec![s, s1])?; let out = df.left_join(&df.clone(), "bar", "bar")?; assert!(matches!(out.column("bar")?.dtype(), DataType::Date64)); let out = df.inner_join(&df.clone(), "bar", "bar")?; assert!(matches!(out.column("bar")?.dtype(), DataType::Date64)); let out = df.outer_join(&df.clone(), "bar", "bar")?; assert!(matches!(out.column("bar")?.dtype(), DataType::Date64)); Ok(()) } #[test] #[cfg(feature = "dtype-date64")] fn test_datelike_methods() -> Result<()> { let s = Series::new("foo", &[1, 2, 3]); let s = s.cast_with_dtype(&DataType::Date64)?; let out = s.subtract(&s)?; assert!(matches!(out.dtype(), DataType::Date64)); let out = s.add_to(&s)?; assert!(matches!(out.dtype(), DataType::Date64)); let out = s.multiply(&s)?; assert!(matches!(out.dtype(), DataType::Date64)); let out = s.divide(&s)?; assert!(matches!(out.dtype(), DataType::Date64)); Ok(()) } }
35.280323
99
0.481779
f8899e62e7e94c4a1826e80eaf4c3266087764dc
7,667
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. #![deny(missing_docs)] //! A safe wrapper around the kernel's KVM interface. //! //! This crate offers safe wrappers for: //! - [system ioctls](struct.Kvm.html) using the `Kvm` structure //! - [VM ioctls](struct.VmFd.html) using the `VmFd` structure //! - [vCPU ioctls](struct.VcpuFd.html) using the `VcpuFd` structure //! - [device ioctls](struct.DeviceFd.html) using the `DeviceFd` structure //! //! # Platform support //! //! - x86_64 //! - arm64 (experimental) //! //! **NOTE:** The list of available ioctls is not extensive. //! //! # Example - Running a VM on x86_64 //! //! In this example we are creating a Virtual Machine (VM) with one vCPU. //! On the vCPU we are running x86_64 specific code. This example is based on //! the [LWN article](https://lwn.net/Articles/658511/) on using the KVM API. //! //! To get code running on the vCPU we are going through the following steps: //! //! 1. Instantiate KVM. This is used for running //! [system specific ioctls](struct.Kvm.html). //! 2. Use the KVM object to create a VM. The VM is used for running //! [VM specific ioctls](struct.VmFd.html). //! 3. Initialize the guest memory for the created VM. In this dummy example we //! are adding only one memory region and write the code in one memory page. //! 4. Create a vCPU using the VM object. The vCPU is used for running //! [vCPU specific ioctls](struct.VcpuFd.html). //! 5. Setup x86 specific general purpose registers and special registers. For //! details about how and why these registers are set, please check the //! [LWN article](https://lwn.net/Articles/658511/) on which this example is //! built. //! 6. Run the vCPU code in a loop and check the //! [exit reasons](enum.VcpuExit.html). //! //! //! ```rust //! extern crate kvm_ioctls; //! extern crate kvm_bindings; //! //! use kvm_ioctls::{Kvm, VmFd, VcpuFd}; //! use kvm_ioctls::VcpuExit; //! //! #[cfg(target_arch = "x86_64")] //! fn main(){ //! use std::io::Write; //! use std::slice; //! use std::ptr::null_mut; //! //! use kvm_bindings::KVM_MEM_LOG_DIRTY_PAGES; //! use kvm_bindings::kvm_userspace_memory_region; //! //! // 1. Instantiate KVM. //! let kvm = Kvm::new().unwrap(); //! //! // 2. Create a VM. //! let vm = kvm.create_vm().unwrap(); //! //! // 3. Initialize Guest Memory. //! let mem_size = 0x4000; //! let guest_addr: u64 = 0x1000; //! let load_addr: *mut u8 = unsafe { //! libc::mmap( //! null_mut(), //! mem_size, //! libc::PROT_READ | libc::PROT_WRITE, //! libc::MAP_ANONYMOUS | libc::MAP_SHARED | libc::MAP_NORESERVE, //! -1, //! 0, //! ) as *mut u8 //! }; //! //! let slot = 0; //! // When initializing the guest memory slot specify the //! // `KVM_MEM_LOG_DIRTY_PAGES` to enable the dirty log. //! let mem_region = kvm_userspace_memory_region { //! slot, //! guest_phys_addr: guest_addr, //! memory_size: mem_size as u64, //! userspace_addr: load_addr as u64, //! flags: KVM_MEM_LOG_DIRTY_PAGES, //! }; //! unsafe { vm.set_user_memory_region(mem_region).unwrap() }; //! //! //! let x86_code = [ //! 0xba, 0xf8, 0x03, /* mov $0x3f8, %dx */ //! 0x00, 0xd8, /* add %bl, %al */ //! 0x04, b'0', /* add $'0', %al */ //! 0xee, /* out %al, %dx */ //! 0xec, /* in %dx, %al */ //! 0xc6, 0x06, 0x00, 0x80, 0x00, /* movl $0, (0x8000); This generates a MMIO Write.*/ //! 0x8a, 0x16, 0x00, 0x80, /* movl (0x8000), %dl; This generates a MMIO Read.*/ //! 0xf4, /* hlt */ //! ]; //! //! // Write the code in the guest memory. This will generate a dirty page. //! unsafe { //! let mut slice = slice::from_raw_parts_mut(load_addr, mem_size); //! slice.write(&x86_code).unwrap(); //! } //! //! // 4. Create one vCPU. //! let vcpu_fd = vm.create_vcpu(0).unwrap(); //! //! // 5. Initialize general purpose and special registers. //! let mut vcpu_sregs = vcpu_fd.get_sregs().unwrap(); //! vcpu_sregs.cs.base = 0; //! vcpu_sregs.cs.selector = 0; //! vcpu_fd.set_sregs(&vcpu_sregs).unwrap(); //! //! let mut vcpu_regs = vcpu_fd.get_regs().unwrap(); //! vcpu_regs.rip = guest_addr; //! vcpu_regs.rax = 2; //! vcpu_regs.rbx = 3; //! vcpu_regs.rflags = 2; //! vcpu_fd.set_regs(&vcpu_regs).unwrap(); //! //! // 6. Run code on the vCPU. //! loop { //! match vcpu_fd.run().expect("run failed") { //! VcpuExit::IoIn(addr, data) => { //! println!( //! "Received an I/O in exit. Address: {:#x}. Data: {:#x}", //! addr, //! data[0], //! ); //! } //! VcpuExit::IoOut(addr, data) => { //! println!( //! "Received an I/O out exit. Address: {:#x}. Data: {:#x}", //! addr, //! data[0], //! ); //! } //! VcpuExit::MmioRead(addr, data) => { //! println!( //! "Received an MMIO Read Request for the address {:#x}.", //! addr, //! ); //! } //! VcpuExit::MmioWrite(addr, data) => { //! println!( //! "Received an MMIO Write Request to the address {:#x}.", //! addr, //! ); //! } //! VcpuExit::Hlt => { //! // The code snippet dirties 1 page when it is loaded in memory //! let dirty_pages_bitmap = vm.get_dirty_log(slot, mem_size).unwrap(); //! let dirty_pages = dirty_pages_bitmap //! .into_iter() //! .map(|page| page.count_ones()) //! .fold(0, |dirty_page_count, i| dirty_page_count + i); //! assert_eq!(dirty_pages, 1); //! break; //! } //! r => panic!("Unexpected exit reason: {:?}", r), //! } //! } //! } //! //! #[cfg(not(target_arch = "x86_64"))] //! fn main() { //! println!("This code example only works on x86_64."); //! } //! ``` extern crate kvm_bindings; extern crate libc; #[macro_use] mod sys_ioctl; #[macro_use] mod kvm_ioctls; mod cap; mod ioctls; pub use cap::Cap; pub use ioctls::device::DeviceFd; pub use ioctls::system::Kvm; pub use ioctls::vcpu::{VcpuExit, VcpuFd}; pub use ioctls::vm::{IoEventAddress, NoDatamatch, VmFd}; #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub use ioctls::CpuId; // The following example is used to verify that our public // structures are exported properly. /// # Example /// /// ``` /// #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] /// use kvm_ioctls::{KvmRunWrapper, Result}; /// ``` pub use ioctls::{KvmRunWrapper, Result}; /// Maximum number of CPUID entries that can be returned by a call to KVM ioctls. /// /// This value is taken from Linux Kernel v4.14.13 (arch/x86/include/asm/kvm_host.h). /// It can be used for calls to [get_supported_cpuid](struct.Kvm.html#method.get_supported_cpuid) and /// [get_emulated_cpuid](struct.Kvm.html#method.get_emulated_cpuid). pub const MAX_KVM_CPUID_ENTRIES: usize = 80;
35.995305
101
0.560584
d9fb0a65ad50eec3078b0cf4627108ceefaf65c0
7,500
// Copyright 2017 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern crate env_logger; extern crate grin_chain as chain; extern crate grin_core as core; extern crate grin_keychain as keychain; extern crate grin_pow as pow; extern crate rand; extern crate time; use std::fs; use std::sync::Arc; use chain::Chain; use chain::types::*; use core::core::{Block, BlockHeader}; use core::core::hash::Hashed; use core::core::target::Difficulty; use core::consensus; use core::global; use core::global::ChainTypes; use keychain::Keychain; use pow::{cuckoo, types, MiningWorker}; fn clean_output_dir(dir_name: &str) { let _ = fs::remove_dir_all(dir_name); } fn setup(dir_name: &str) -> Chain { let _ = env_logger::init(); clean_output_dir(dir_name); global::set_mining_mode(ChainTypes::AutomatedTesting); let mut genesis_block = None; if !chain::Chain::chain_exists(dir_name.to_string()) { genesis_block = pow::mine_genesis_block(None); } chain::Chain::init( dir_name.to_string(), Arc::new(NoopAdapter {}), genesis_block, pow::verify_size, ).unwrap() } #[test] fn mine_empty_chain() { let chain = setup(".grin"); let keychain = Keychain::from_random_seed().unwrap(); // mine and add a few blocks let mut miner_config = types::MinerConfig { enable_mining: true, burn_reward: true, ..Default::default() }; miner_config.cuckoo_miner_plugin_dir = Some(String::from("../target/debug/deps")); let mut cuckoo_miner = cuckoo::Miner::new( consensus::EASINESS, global::sizeshift() as u32, global::proofsize(), ); for n in 1..4 { let prev = chain.head_header().unwrap(); let pk = keychain.derive_key_id(n as u32).unwrap(); let mut b = core::core::Block::new(&prev, vec![], &keychain, &pk).unwrap(); b.header.timestamp = prev.timestamp + time::Duration::seconds(60); let difficulty = consensus::next_difficulty(chain.difficulty_iter()).unwrap(); b.header.difficulty = difficulty.clone(); chain.set_sumtree_roots(&mut b).unwrap(); pow::pow_size( &mut cuckoo_miner, &mut b.header, difficulty, global::sizeshift() as u32, ).unwrap(); let bhash = b.hash(); chain.process_block(b, chain::NONE).unwrap(); // checking our new head let head = chain.head().unwrap(); assert_eq!(head.height, n); assert_eq!(head.last_block_h, bhash); // now check the block_header of the head let header = chain.head_header().unwrap(); assert_eq!(header.height, n); assert_eq!(header.hash(), bhash); // now check the block itself let block = chain.get_block(&header.hash()).unwrap(); assert_eq!(block.header.height, n); assert_eq!(block.hash(), bhash); assert_eq!(block.outputs.len(), 1); // now check the block height index let header_by_height = chain.get_header_by_height(n).unwrap(); assert_eq!(header_by_height.hash(), bhash); // now check the header output index let output = block.outputs[0]; let header_by_output_commit = chain .get_block_header_by_output_commit(&output.commitment()) .unwrap(); assert_eq!(header_by_output_commit.hash(), bhash); } } #[test] fn mine_forks() { let chain = setup(".grin2"); // add a first block to not fork genesis let prev = chain.head_header().unwrap(); let b = prepare_block(&prev, &chain, 2); chain.process_block(b, chain::SKIP_POW).unwrap(); // mine and add a few blocks for n in 1..4 { // first block for one branch let prev = chain.head_header().unwrap(); let b1 = prepare_block(&prev, &chain, 3 * n); // 2nd block with higher difficulty for other branch let b2 = prepare_block(&prev, &chain, 3 * n + 1); // process the first block to extend the chain let bhash = b1.hash(); chain.process_block(b1, chain::SKIP_POW).unwrap(); // checking our new head let head = chain.head().unwrap(); assert_eq!(head.height, (n + 1) as u64); assert_eq!(head.last_block_h, bhash); assert_eq!(head.prev_block_h, prev.hash()); // process the 2nd block to build a fork with more work let bhash = b2.hash(); chain.process_block(b2, chain::SKIP_POW).unwrap(); // checking head switch let head = chain.head().unwrap(); assert_eq!(head.height, (n + 1) as u64); assert_eq!(head.last_block_h, bhash); assert_eq!(head.prev_block_h, prev.hash()); } } #[test] fn mine_losing_fork() { let chain = setup(".grin3"); // add a first block we'll be forking from let prev = chain.head_header().unwrap(); let b1 = prepare_block(&prev, &chain, 2); let b1head = b1.header.clone(); chain.process_block(b1, chain::SKIP_POW).unwrap(); // prepare the 2 successor, sibling blocks, one with lower diff let b2 = prepare_block(&b1head, &chain, 4); let b2head = b2.header.clone(); let bfork = prepare_block(&b1head, &chain, 3); // add higher difficulty first, prepare its successor, then fork // with lower diff chain.process_block(b2, chain::SKIP_POW).unwrap(); assert_eq!(chain.head_header().unwrap().hash(), b2head.hash()); let b3 = prepare_block(&b2head, &chain, 5); chain.process_block(bfork, chain::SKIP_POW).unwrap(); // adding the successor let b3head = b3.header.clone(); chain.process_block(b3, chain::SKIP_POW).unwrap(); assert_eq!(chain.head_header().unwrap().hash(), b3head.hash()); } #[test] fn longer_fork() { // to make it easier to compute the sumtree roots in the test, we // prepare 2 chains, the 2nd will be have the forked blocks we can // then send back on the 1st let chain = setup(".grin4"); let chain_fork = setup(".grin5"); // add blocks to both chains, 20 on the main one, only the first 5 // for the forked chain let mut prev = chain.head_header().unwrap(); for n in 0..10 { let b = prepare_block(&prev, &chain, n + 2); let bh = b.header.clone(); if n < 5 { let b_fork = b.clone(); chain_fork.process_block(b_fork, chain::SKIP_POW).unwrap(); } chain.process_block(b, chain::SKIP_POW).unwrap(); prev = bh; } // check both chains are in the expected state let head = chain.head_header().unwrap(); assert_eq!(head.height, 10); assert_eq!(head.hash(), prev.hash()); let head_fork = chain_fork.head_header().unwrap(); assert_eq!(head_fork.height, 5); let mut prev_fork = head_fork.clone(); for n in 0..7 { let b_fork = prepare_block(&prev_fork, &chain_fork, n + 7); let bh_fork = b_fork.header.clone(); let b = b_fork.clone(); chain.process_block(b, chain::SKIP_POW).unwrap(); chain_fork.process_block(b_fork, chain::SKIP_POW).unwrap(); prev_fork = bh_fork; } } fn prepare_block(prev: &BlockHeader, chain: &Chain, diff: u64) -> Block { let mut b = prepare_block_nosum(prev, diff); chain.set_sumtree_roots(&mut b).unwrap(); b } fn prepare_block_nosum(prev: &BlockHeader, diff: u64) -> Block { let keychain = Keychain::from_random_seed().unwrap(); let key_id = keychain.derive_key_id(1).unwrap(); let mut b = core::core::Block::new(prev, vec![], &keychain, &key_id).unwrap(); b.header.timestamp = prev.timestamp + time::Duration::seconds(60); b.header.total_difficulty = Difficulty::from_num(diff); b }
29.527559
83
0.696933
e68d96ff3d85e6436001ec07cba88fe0eae30a42
938
// Copyright 2020 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. #[cfg(test)] mod context_test; mod index; pub(crate) mod common; pub(crate) mod context; pub(crate) mod database; pub(crate) mod table; pub(crate) mod table_engine; pub(crate) mod table_engine_registry; pub(crate) mod table_func; pub(crate) mod table_func_engine; pub(crate) mod table_func_engine_registry; pub use context::DataSourceContext;
30.258065
75
0.759062
1e5691eacdb34281c4dc90c2b669e6ef0c847065
12,209
// Copyright 2019 Parity Technologies (UK) Ltd. // This file is part of Cumulus. // Cumulus 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. // Cumulus 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 Cumulus. If not, see <http://www.gnu.org/licenses/>. use crate::{ chain_spec, cli::{Cli, RelayChainCli, Subcommand}, }; use codec::Encode; use cumulus_primitives_core::ParaId; use cumulus_client_service::genesis::generate_genesis_block; use log::info; use parachain_runtime::Block; use polkadot_parachain::primitives::AccountIdConversion; use sc_cli::{ ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli, }; use sc_service::{ config::{BasePath, PrometheusConfig}, PartialComponents, }; use sp_core::hexdisplay::HexDisplay; use sp_runtime::traits::Block as BlockT; use std::{io::Write, net::SocketAddr}; fn load_spec( id: &str, para_id: ParaId, ) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> { match id { "" | "local" => Ok(Box::new(chain_spec::get_chain_spec(para_id))), "staging" => Ok(Box::new(chain_spec::staging_test_net(para_id))), // "phala_pc1" => Ok(Box::new(chain_spec::ChainSpec::from_json_bytes( // &include_bytes!("../res/phala_pc1.json")[..], // )?)), path => Ok(Box::new(chain_spec::ChainSpec::from_json_file( path.into(), )?)), } } impl SubstrateCli for Cli { fn impl_name() -> String { "Phala Parachain Collator".into() } fn impl_version() -> String { env!("SUBSTRATE_CLI_IMPL_VERSION").into() } fn description() -> String { format!( "Phala parachain collator\n\nThe command-line arguments provided first will be \ passed to the parachain node, while the arguments provided after -- will be passed \ to the relaychain node.\n\n\ {} [parachain-args] -- [relaychain-args]", Self::executable_name() ) } fn author() -> String { env!("CARGO_PKG_AUTHORS").into() } fn support_url() -> String { "https://github.com/Phala-Network/phala-blockchain/issues/new".into() } fn copyright_start_year() -> i32 { 2018 } fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> { load_spec(id, self.run.parachain_id.unwrap_or(100).into()) } fn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion { &parachain_runtime::VERSION } } impl SubstrateCli for RelayChainCli { fn impl_name() -> String { "Phala Parachain Collator".into() } fn impl_version() -> String { env!("SUBSTRATE_CLI_IMPL_VERSION").into() } fn description() -> String { "Phala parachain collator\n\nThe command-line arguments provided first will be \ passed to the parachain node, while the arguments provided after -- will be passed \ to the relaychain node.\n\n\ rococo-collator [parachain-args] -- [relaychain-args]" .into() } fn author() -> String { env!("CARGO_PKG_AUTHORS").into() } fn support_url() -> String { "https://github.com/Phala-Network/phala-blockchain/issues/new".into() } fn copyright_start_year() -> i32 { 2018 } fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> { polkadot_cli::Cli::from_iter([RelayChainCli::executable_name().to_string()].iter()) .load_spec(id) } fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion { polkadot_cli::Cli::native_runtime_version(chain_spec) } } fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> { let mut storage = chain_spec.build_storage()?; storage .top .remove(sp_core::storage::well_known_keys::CODE) .ok_or_else(|| "Could not find wasm file in genesis state!".into()) } /// Parse command line arguments into service configuration. pub fn run() -> Result<()> { let cli = Cli::from_args(); match &cli.subcommand { Some(Subcommand::BuildSpec(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) } Some(Subcommand::CheckBlock(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { client, task_manager, import_queue, .. } = crate::service::new_partial(&config)?; Ok((cmd.run(client, import_queue), task_manager)) }) } Some(Subcommand::ExportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { client, task_manager, .. } = crate::service::new_partial(&config)?; Ok((cmd.run(client, config.database), task_manager)) }) } Some(Subcommand::ExportState(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { client, task_manager, .. } = crate::service::new_partial(&config)?; Ok((cmd.run(client, config.chain_spec), task_manager)) }) } Some(Subcommand::ImportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { client, task_manager, import_queue, .. } = crate::service::new_partial(&config)?; Ok((cmd.run(client, import_queue), task_manager)) }) } Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.database)) } Some(Subcommand::Revert(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { client, task_manager, backend, .. } = crate::service::new_partial(&config)?; Ok((cmd.run(client, backend), task_manager)) }) } Some(Subcommand::ExportGenesisState(params)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); let _ = builder.init(); let block: Block = generate_genesis_block(&load_spec( &params.chain.clone().unwrap_or_default(), params.parachain_id.into(), )?)?; let raw_header = block.header().encode(); let output_buf = if params.raw { raw_header } else { format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes() }; if let Some(output) = &params.output { std::fs::write(output, output_buf)?; } else { std::io::stdout().write_all(&output_buf)?; } Ok(()) } Some(Subcommand::ExportGenesisWasm(params)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); let _ = builder.init(); let raw_wasm_blob = extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?; let output_buf = if params.raw { raw_wasm_blob } else { format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes() }; if let Some(output) = &params.output { std::fs::write(output, output_buf)?; } else { std::io::stdout().write_all(&output_buf)?; } Ok(()) } None => { let runner = cli.create_runner(&*cli.run)?; runner.run_node_until_exit(|config| async move { // TODO let key = sp_core::Pair::generate().0; let extension = chain_spec::Extensions::try_get(&*config.chain_spec); let relay_chain_id = extension.map(|e| e.relay_chain.clone()); let para_id = extension.map(|e| e.para_id); let polkadot_cli = RelayChainCli::new( config.base_path.as_ref().map(|x| x.path().join("polkadot")), relay_chain_id, [RelayChainCli::executable_name().to_string()] .iter() .chain(cli.relaychain_args.iter()), ); let id = ParaId::from(cli.run.parachain_id.or(para_id).unwrap_or(100)); let parachain_account = AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id); let block: Block = generate_genesis_block(&config.chain_spec).map_err(|e| format!("{:?}", e))?; let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode())); let task_executor = config.task_executor.clone(); let polkadot_config = SubstrateCli::create_configuration( &polkadot_cli, &polkadot_cli, task_executor, config.telemetry_handle.clone(), ) .map_err(|err| format!("Relay chain argument error: {}", err))?; let collator = cli.run.base.validator || cli.collator; info!("Parachain id: {:?}", id); info!("Parachain Account: {}", parachain_account); info!("Parachain genesis state: {}", genesis_state); info!("Is collating: {}", if collator { "yes" } else { "no" }); crate::service::start_node(config, key, polkadot_config, id, collator) .await .map(|r| r.0) .map_err(Into::into) }) } } } impl DefaultConfigurationValues for RelayChainCli { fn p2p_listen_port() -> u16 { 30334 } fn rpc_ws_listen_port() -> u16 { 9945 } fn rpc_http_listen_port() -> u16 { 9934 } fn prometheus_listen_port() -> u16 { 9616 } } impl CliConfiguration<Self> for RelayChainCli { fn shared_params(&self) -> &SharedParams { self.base.base.shared_params() } fn import_params(&self) -> Option<&ImportParams> { self.base.base.import_params() } fn network_params(&self) -> Option<&NetworkParams> { self.base.base.network_params() } fn keystore_params(&self) -> Option<&KeystoreParams> { self.base.base.keystore_params() } fn base_path(&self) -> Result<Option<BasePath>> { Ok(self .shared_params() .base_path() .or_else(|| self.base_path.clone().map(Into::into))) } fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> { self.base.base.rpc_http(default_listen_port) } fn rpc_ipc(&self) -> Result<Option<String>> { self.base.base.rpc_ipc() } fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> { self.base.base.rpc_ws(default_listen_port) } fn prometheus_config(&self, default_listen_port: u16) -> Result<Option<PrometheusConfig>> { self.base.base.prometheus_config(default_listen_port) } fn init<C: SubstrateCli>(&self) -> Result<sc_telemetry::TelemetryWorker> { unreachable!("PolkadotCli is never initialized; qed"); } fn chain_id(&self, is_dev: bool) -> Result<String> { let chain_id = self.base.base.chain_id(is_dev)?; Ok(if chain_id.is_empty() { self.chain_id.clone().unwrap_or_default() } else { chain_id }) } fn role(&self, is_dev: bool) -> Result<sc_service::Role> { self.base.base.role(is_dev) } fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> { self.base.base.transaction_pool() } fn state_cache_child_ratio(&self) -> Result<Option<usize>> { self.base.base.state_cache_child_ratio() } fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> { self.base.base.rpc_methods() } fn rpc_ws_max_connections(&self) -> Result<Option<usize>> { self.base.base.rpc_ws_max_connections() } fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> { self.base.base.rpc_cors(is_dev) } fn telemetry_external_transport(&self) -> Result<Option<sc_service::config::ExtTransport>> { self.base.base.telemetry_external_transport() } fn default_heap_pages(&self) -> Result<Option<u64>> { self.base.base.default_heap_pages() } fn force_authoring(&self) -> Result<bool> { self.base.base.force_authoring() } fn disable_grandpa(&self) -> Result<bool> { self.base.base.disable_grandpa() } fn max_runtime_instances(&self) -> Result<Option<usize>> { self.base.base.max_runtime_instances() } fn announce_block(&self) -> Result<bool> { self.base.base.announce_block() } fn telemetry_endpoints( &self, chain_spec: &Box<dyn ChainSpec>, ) -> Result<Option<sc_telemetry::TelemetryEndpoints>> { self.base.base.telemetry_endpoints(chain_spec) } }
27.874429
95
0.682038
0862f1d446775290e12eeeac92087004adf4f3eb
197
use async_trait::async_trait; use crate::common::Result; use crate::core::UnitOfWork; #[async_trait] pub(crate) trait Middleware { async fn apply(&mut self, uow: UnitOfWork) -> Result<()>; }
19.7
61
0.705584
7954322fa5e7e9a941d8e4ee37f225cdcaa1a22d
1,497
mod atoms; mod full; mod mapped; mod parts; use super::models::{KeyAuthorization, KeysFile, KeysFileLine}; use std::str::FromStr; impl FromStr for KeyAuthorization { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { full::key_authorization(s) .map(|(_, res)| res) .map_err(|e| match e { nom::Err::Incomplete(_) => unreachable!(), nom::Err::Error(err) | nom::Err::Failure(err) => err.0.to_string(), }) } } impl FromStr for KeysFile { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let in_lines = s.lines().enumerate().collect::<Vec<_>>(); let mut lines: Vec<KeysFileLine> = Vec::with_capacity(in_lines.len()); for (line_no, line) in in_lines { let comment_indicator = line.chars().skip_while(char::is_ascii_whitespace).next(); // line was all whitespace, or first non-whitespace was comment char lines.push( if comment_indicator == None || comment_indicator == Some('#') { KeysFileLine::Comment(line.to_owned()) } else { match line.parse() { Ok(authorization) => KeysFileLine::Key(authorization), Err(e) => return Err(format!("failed to parse line {}: {}", line_no, e)), } }, ); } Ok(Self { lines }) } }
30.55102
97
0.527054
e6cc825c4439562f84cbde9df86bcd9e20787f74
1,875
use std::fs::File; use std::io::{Read, Seek, SeekFrom}; mod parser; pub enum LoaderType { Auto, #[allow(dead_code)] Hex, #[allow(dead_code)] Binary, } pub trait Loader { fn get_bytes(&mut self) -> Vec<u8>; } pub struct BinaryLoader { file: File, } impl BinaryLoader { fn new(file: File) -> Box<Loader> { Box::new(BinaryLoader { file: file }) } } impl Loader for BinaryLoader { fn get_bytes(&mut self) -> Vec<u8> { let mut program = Vec::new(); self.file.read_to_end(&mut program).unwrap(); program } } pub struct HexLoader { file: File, } impl HexLoader { fn new(file: File) -> Box<Loader> { Box::new(HexLoader { file: file }) } } impl Loader for HexLoader { fn get_bytes(&mut self) -> Vec<u8> { let mut program = Vec::new(); self.file.read_to_end(&mut program).unwrap(); let p = program.as_slice(); let result = parser::parse(p); println!("Parse Result: {:?}", result); result } } pub fn load_file(path: &str, loader_type: LoaderType) -> Vec<u8> { let file = File::open(path).unwrap(); match loader_type { LoaderType::Auto => load_autodetect(file).get_bytes(), LoaderType::Hex => HexLoader::new(file).get_bytes(), LoaderType::Binary => BinaryLoader::new(file).get_bytes(), } } fn load_autodetect(mut file: File) -> Box<Loader> { let hex_chars: Vec<u8> = "0123456789abcdefABCDEFxX[];, \r\n\t".bytes().collect(); let mut data = Vec::<u8>::new(); file.read_to_end(&mut data).unwrap(); let mut binary_data = false; for b in data { if !hex_chars.contains(&b) { binary_data = true; } } file.seek(SeekFrom::Start(0)).unwrap(); if binary_data { BinaryLoader::new(file) } else { HexLoader::new(file) } }
23.734177
85
0.582933
8f65e57ea1c1ce0153463ec2a999635dac05994f
749
use crate::language::{FindResult, OptsMultiComments, SimpleFindComments}; use crate::utils::string::contains_all; use std::io; use std::path::PathBuf; pub struct HTML<F: SimpleFindComments> { finder: F, } impl<F> HTML<F> where F: SimpleFindComments, { pub fn with_finder(finder: F) -> Self { Self { finder } } pub fn find(&self, path: PathBuf) -> io::Result<FindResult> { let multi_opts = OptsMultiComments { starts: vec!["<!--".to_string()], ends: vec!["-->".to_string()], }; self.finder .find_comments(path, &multi_opts, is_single_line_comment) } } fn is_single_line_comment(comment: &str) -> bool { contains_all(comment, vec!["<!--", "-->"]) }
22.69697
73
0.603471
912222e8db148a1c6ccdaa4709ad49a25c63d400
5,334
// Copyright (C) 2018 Víctor Jáquez <[email protected]> // // 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 glib_sys; use gst_gl_sys; use gst_sys; use gst_video_sys; use glib::translate::{from_glib, ToGlibPtr}; use gst; use gst_video::video_frame::Readable; use gst_video::*; use byteorder::{NativeEndian, ReadBytesExt}; use std::mem; pub trait VideoFrameGLExt { fn from_buffer_readable_gl( buffer: gst::Buffer, info: &VideoInfo, ) -> Result<VideoFrame<Readable>, gst::Buffer>; fn from_buffer_ref_readable_gl<'a, 'b>( buffer: &'a gst::BufferRef, info: &'b VideoInfo, ) -> Result<VideoFrameRef<&'a gst::BufferRef>, glib::error::BoolError>; fn get_texture_id(&self, idx: u32) -> Option<u32>; } impl VideoFrameGLExt for VideoFrame<Readable> { fn from_buffer_readable_gl( buffer: gst::Buffer, info: &VideoInfo, ) -> Result<VideoFrame<Readable>, gst::Buffer> { skip_assert_initialized!(); VideoFrameRef::<&gst::BufferRef>::from_buffer_readable_gl(buffer, info) } fn from_buffer_ref_readable_gl<'a, 'b>( buffer: &'a gst::BufferRef, info: &'b VideoInfo, ) -> Result<VideoFrameRef<&'a gst::BufferRef>, glib::error::BoolError> { skip_assert_initialized!(); VideoFrameRef::<&gst::BufferRef>::from_buffer_ref_readable_gl(buffer, info) } fn get_texture_id(&self, idx: u32) -> Option<u32> { self.as_video_frame_ref().get_texture_id(idx) } } impl<'a> VideoFrameGLExt for VideoFrameRef<&'a gst::BufferRef> { fn from_buffer_readable_gl( buffer: gst::Buffer, info: &VideoInfo, ) -> Result<VideoFrame<Readable>, gst::Buffer> { skip_assert_initialized!(); let n_mem = match buffer_n_gl_memory(buffer.as_ref()) { Some(n) => n, None => return Err(buffer), }; // FIXME: planes are not memories, in multiview use case, // number of memories = planes * views, but the raw memory is // not exposed in videoframe if n_mem != info.n_planes() { return Err(buffer); } unsafe { let mut frame = mem::MaybeUninit::zeroed(); let res: bool = from_glib(gst_video_sys::gst_video_frame_map( frame.as_mut_ptr(), info.to_glib_none().0 as *mut _, buffer.to_glib_none().0, gst_video_sys::GST_VIDEO_FRAME_MAP_FLAG_NO_REF | gst_sys::GST_MAP_READ | gst_gl_sys::GST_MAP_GL as u32, )); if !res { Err(buffer) } else { Ok(VideoFrame::from_glib_full(frame.assume_init())) } } } fn from_buffer_ref_readable_gl<'b, 'c>( buffer: &'b gst::BufferRef, info: &'c VideoInfo, ) -> Result<VideoFrameRef<&'b gst::BufferRef>, glib::error::BoolError> { skip_assert_initialized!(); let n_mem = match buffer_n_gl_memory(buffer) { Some(n) => n, None => return Err(glib_bool_error!("Memory is not a GstGLMemory")), }; // FIXME: planes are not memories, in multiview use case, // number of memories = planes * views, but the raw memory is // not exposed in videoframe if n_mem != info.n_planes() { return Err(glib_bool_error!( "Number of planes and memories is not matching" )); } unsafe { let mut frame = mem::MaybeUninit::zeroed(); let res: bool = from_glib(gst_video_sys::gst_video_frame_map( frame.as_mut_ptr(), info.to_glib_none().0 as *mut _, buffer.as_mut_ptr(), gst_video_sys::GST_VIDEO_FRAME_MAP_FLAG_NO_REF | gst_sys::GST_MAP_READ | gst_gl_sys::GST_MAP_GL as u32, )); if !res { Err(glib_bool_error!( "Failed to fill in the values of GstVideoFrame" )) } else { Ok(VideoFrameRef::from_glib_full(frame.assume_init())) } } } fn get_texture_id(&self, idx: u32) -> Option<u32> { let len = buffer_n_gl_memory(self.buffer())?; if idx >= len { return None; } // FIXME: planes are not memories if idx > self.n_planes() { return None; } let mut data = self.plane_data(idx).ok()?; let id = &data.read_u32::<NativeEndian>().ok()?; Some(*id) } } fn buffer_n_gl_memory(buffer: &gst::BufferRef) -> Option<u32> { skip_assert_initialized!(); unsafe { let buf = buffer.as_mut_ptr(); let num = gst_sys::gst_buffer_n_memory(buf); for i in 0..num - 1 { let mem = gst_sys::gst_buffer_peek_memory(buf, i); if gst_gl_sys::gst_is_gl_memory(mem) != glib_sys::GTRUE { return None; } } Some(num as u32) } }
31.376471
83
0.573303
91ae45ea394a311b30f3f26eb7276cf89a314046
2,716
use rand::{Rng, thread_rng}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::base_card::BaseCard; use crate::dbconfig::MySqlPooledConnection; use crate::player::Player; use crate::SakataResult; use crate::schema::player_cards; use crate::types::json_req::PlayerCardQuery; use crate::types::json_res::PlayerCardResponse; use crate::types::model::{Class, Domain, Rarity}; pub mod dao; #[derive(Queryable, Identifiable, Insertable, Associations, Serialize, Deserialize, Clone, Debug, Eq, PartialEq)] #[table_name = "player_cards"] #[belongs_to(Player, foreign_key = "id")] #[belongs_to(BaseCard, foreign_key = "id")] pub struct PlayerCard { pub id: String, pub base_card_id: u32, pub player_id: u32, pub rarity: Rarity, pub overall_power: u8, pub quantity: u8, } impl PlayerCard { pub fn new(player: &Player, base_card: &BaseCard, rarity: Rarity) -> PlayerCard { PlayerCard { id: Uuid::new_v4().to_string(), base_card_id: base_card.id.unwrap(), player_id: player.id.unwrap(), rarity, overall_power: base_card.overall_power + rarity.get_bonus(), quantity: 1, } } } fn generate_rarity() -> Rarity { let rand = thread_rng().gen_range(0, 100); if rand < 10 { Rarity::Legend } else if rand < 30 { Rarity::Epic } else if rand < 60 { Rarity::Gold } else { Rarity::Silver } } pub fn add_to_collection(player: &Player, base_card: &BaseCard, conn: &MySqlPooledConnection) -> SakataResult<PlayerCard> { let player_cards = dao::find_by(player, base_card, conn); let rarity = generate_rarity(); if let Ok(p_cards) = player_cards { for mut pc in p_cards { if pc.rarity == rarity { pc.quantity += 1; dao::update_quantity(&pc, conn)?; return Ok(pc); } } } let player = PlayerCard::new(player, base_card, rarity); dao::save(&player, conn)?; Ok(player) } pub fn query(player: Player, query: PlayerCardQuery, conn: &MySqlPooledConnection) -> SakataResult<Vec<PlayerCardResponse>> { let domain: Option<Domain> = match query.domain { None => None, Some(d) => serde_json::from_str(&d.to_string()).unwrap_or(None) }; let class: Option<Class> = match query.class { None => None, Some(d) => serde_json::from_str(&d.to_string()).unwrap_or(None) }; let cards = dao::query(player.id.unwrap(), query.page, class, domain, conn)?; let response_cards = cards.into_iter() .map(|(pc, bc)| PlayerCardResponse::new(pc, bc)) .collect(); Ok(response_cards) }
28.893617
125
0.625184
fc04434db3110a84ff70b042eb062f127bf183bf
6,809
// Rust Bitcoin Library // Written in 2014 by // Andrew Poelstra <[email protected]> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // //! Bitcoin blockdata network messages. //! //! This module describes network messages which are used for passing //! Bitcoin data (blocks and transactions) around. //! use prelude::*; use io; use hashes::sha256d; use network::constants; use consensus::encode::{self, Decodable, Encodable}; use hash_types::{BlockHash, Txid, Wtxid}; /// An inventory item. #[derive(PartialEq, Eq, Clone, Debug, Copy, Hash, PartialOrd, Ord)] pub enum Inventory { /// Error --- these inventories can be ignored Error, /// Transaction Transaction(Txid), /// Block Block(BlockHash), /// Witness Transaction by Wtxid WTx(Wtxid), /// Witness Transaction WitnessTransaction(Txid), /// Witness Block WitnessBlock(BlockHash), /// Unknown inventory type Unknown { /// The inventory item type. inv_type: u32, /// The hash of the inventory item hash: [u8; 32], } } impl Encodable for Inventory { #[inline] fn consensus_encode<S: io::Write>( &self, mut s: S, ) -> Result<usize, io::Error> { macro_rules! encode_inv { ($code:expr, $item:expr) => { u32::consensus_encode(&$code, &mut s)? + $item.consensus_encode(&mut s)? } } Ok(match *self { Inventory::Error => encode_inv!(0, sha256d::Hash::default()), Inventory::Transaction(ref t) => encode_inv!(1, t), Inventory::Block(ref b) => encode_inv!(2, b), Inventory::WTx(w) => encode_inv!(5, w), Inventory::WitnessTransaction(ref t) => encode_inv!(0x40000001, t), Inventory::WitnessBlock(ref b) => encode_inv!(0x40000002, b), Inventory::Unknown { inv_type: t, hash: ref d } => encode_inv!(t, d), }) } } impl Decodable for Inventory { #[inline] fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, encode::Error> { let inv_type: u32 = Decodable::consensus_decode(&mut d)?; Ok(match inv_type { 0 => Inventory::Error, 1 => Inventory::Transaction(Decodable::consensus_decode(&mut d)?), 2 => Inventory::Block(Decodable::consensus_decode(&mut d)?), 5 => Inventory::WTx(Decodable::consensus_decode(&mut d)?), 0x40000001 => Inventory::WitnessTransaction(Decodable::consensus_decode(&mut d)?), 0x40000002 => Inventory::WitnessBlock(Decodable::consensus_decode(&mut d)?), tp => Inventory::Unknown { inv_type: tp, hash: Decodable::consensus_decode(&mut d)?, } }) } } // Some simple messages /// The `getblocks` message #[derive(PartialEq, Eq, Clone, Debug)] pub struct GetBlocksMessage { /// The protocol version pub version: u32, /// Locator hashes --- ordered newest to oldest. The remote peer will /// reply with its longest known chain, starting from a locator hash /// if possible and block 1 otherwise. pub locator_hashes: Vec<BlockHash>, /// References the block to stop at, or zero to just fetch the maximum 500 blocks pub stop_hash: BlockHash, } /// The `getheaders` message #[derive(PartialEq, Eq, Clone, Debug)] pub struct GetHeadersMessage { /// The protocol version pub version: u32, /// Locator hashes --- ordered newest to oldest. The remote peer will /// reply with its longest known chain, starting from a locator hash /// if possible and block 1 otherwise. pub locator_hashes: Vec<BlockHash>, /// References the header to stop at, or zero to just fetch the maximum 2000 headers pub stop_hash: BlockHash } impl GetBlocksMessage { /// Construct a new `getblocks` message pub fn new(locator_hashes: Vec<BlockHash>, stop_hash: BlockHash) -> GetBlocksMessage { GetBlocksMessage { version: constants::PROTOCOL_VERSION, locator_hashes: locator_hashes, stop_hash: stop_hash } } } impl_consensus_encoding!(GetBlocksMessage, version, locator_hashes, stop_hash); impl GetHeadersMessage { /// Construct a new `getheaders` message pub fn new(locator_hashes: Vec<BlockHash>, stop_hash: BlockHash) -> GetHeadersMessage { GetHeadersMessage { version: constants::PROTOCOL_VERSION, locator_hashes: locator_hashes, stop_hash: stop_hash } } } impl_consensus_encoding!(GetHeadersMessage, version, locator_hashes, stop_hash); #[cfg(test)] mod tests { use super::{Vec, GetHeadersMessage, GetBlocksMessage}; use hashes::hex::FromHex; use consensus::encode::{deserialize, serialize}; use core::default::Default; #[test] fn getblocks_message_test() { let from_sat = Vec::from_hex("72110100014a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b0000000000000000000000000000000000000000000000000000000000000000").unwrap(); let genhash = Vec::from_hex("4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b").unwrap(); let decode: Result<GetBlocksMessage, _> = deserialize(&from_sat); assert!(decode.is_ok()); let real_decode = decode.unwrap(); assert_eq!(real_decode.version, 70002); assert_eq!(real_decode.locator_hashes.len(), 1); assert_eq!(serialize(&real_decode.locator_hashes[0]), genhash); assert_eq!(real_decode.stop_hash, Default::default()); assert_eq!(serialize(&real_decode), from_sat); } #[test] fn getheaders_message_test() { let from_sat = Vec::from_hex("72110100014a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b0000000000000000000000000000000000000000000000000000000000000000").unwrap(); let genhash = Vec::from_hex("4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b").unwrap(); let decode: Result<GetHeadersMessage, _> = deserialize(&from_sat); assert!(decode.is_ok()); let real_decode = decode.unwrap(); assert_eq!(real_decode.version, 70002); assert_eq!(real_decode.locator_hashes.len(), 1); assert_eq!(serialize(&real_decode.locator_hashes[0]), genhash); assert_eq!(real_decode.stop_hash, Default::default()); assert_eq!(serialize(&real_decode), from_sat); } }
35.097938
188
0.659568
89d51a482151ce6c8479bbc46ab3b7465dfa143e
3,987
// Change program start with test_main when running tests #![reexport_test_harness_main = "test_main"] // Don't link the Rust standard library it's dependent on the os #![no_std] #![cfg_attr(test, no_main)] // Override the testing framework runner with crate::test_runner #![feature(custom_test_frameworks)] #![test_runner(crate::test_runner)] // Enable x86 interrupt calling convention #![feature(abi_x86_interrupt)] // Provide memset, memcpy, memcmp implementation since the os usually provides thos extern crate rlibc; // Provide a panic handler implementation since the current panic is based on the os // <editor-fold desc="MACROS => TODO Find a convenient way to define macros in a separated file" use core::fmt; // <editor-fold desc="Implement panic handler dependent on above macros"> // We need to implement a new panic handler because the rust standard panic // handler is dependent on the os use core::panic::PanicInfo; use testing::Testable; // <editor-fold desc="print!, println! => Macros"> #[doc(hidden)] pub fn _print_to_vga_buffer(args: fmt::Arguments) { use core::fmt::Write; use x86_64::instructions::interrupts; interrupts::without_interrupts(|| { crate::vga_buffer::WRITER .lock() .write_fmt(args) .unwrap(); }); } // Provide global #[macro_export] macro_rules! print { ($($arg:tt)*) => ($crate::_print_to_vga_buffer(format_args!($($arg)*))); } #[macro_export] macro_rules! println { () => ($crate::print!("\n")); ($($arg:tt)*) => ($crate::print!("{}\n", format_args!($($arg)*))); } #[test_case] fn test_println_simple() { println!("test_println_simple output"); } #[test_case] fn test_println_many() { for _ in 0..200 { println!("test_println_many output"); } } // </editor-fold> // <editor-fold desc="serial_print!, serial_println! => Macros"> #[doc(hidden)] pub fn _print_to_serial_port(args: core::fmt::Arguments) { use core::fmt::Write; use x86_64::instructions::interrupts; interrupts::without_interrupts(|| { crate::serial_port_com::HOST .lock() .write_fmt(args) .expect("Printing to host serial failed"); }); } /// Prints to the host through the serial interface. #[macro_export] macro_rules! serial_print { ($($arg:tt)*) => { $crate::_print_to_serial_port(format_args!($($arg)*)); }; } /// Prints to the host through the serial interface, appending a newline. #[macro_export] macro_rules! serial_println { () => ($crate::serial_print!("\n")); ($fmt:expr) => ($crate::serial_print!(concat!($fmt, "\n"))); ($fmt:expr, $($arg:tt)*) => ($crate::serial_print!( concat!($fmt, "\n"), $($arg)*)); } // </editor-fold> // Panic handler #[allow(dead_code)] pub fn panic_handler(info: &PanicInfo) -> ! { println!("{:?}", info); hlt_loop(); } // Panic handler in test mode #[allow(dead_code)] pub fn panic_handler_test(info: &PanicInfo) -> ! { serial_println!("[failed]\n"); serial_println!("Error: {}\n", info); crate::qemu::exit(qemu::ExitCode::Failed); loop {} } // </editor-fold> // </editor-fold> // Provide testing framework mod testing; // Vga buffer implementation pub mod vga_buffer; // Qemu dependent instructions pub mod qemu; // Serial Port communication pub mod serial_port_com; // Interrupts pub mod interrupts; // Provide kernel init pub mod kernel_init; // ? pub mod gdt; // Provide implementation for the test runner pub fn test_runner(tests: &[&dyn Testable]) { println!("Running {} tests", tests.len()); for test in tests { test.run(); } qemu::exit(qemu::ExitCode::Success); } #[cfg(test)] #[panic_handler] fn panic(info: &PanicInfo) -> ! { panic_handler_test(info); } // Entry point for test #[no_mangle] #[cfg(test)] pub extern "C" fn _start() -> ! { kernel_init::run(); test_main(); hlt_loop(); } pub fn hlt_loop() -> ! { loop { x86_64::instructions::hlt(); } }
25.557692
96
0.650865
23626ddcaeb57319f5dd048b1d19bbddfd6117e0
2,315
use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; use rand_core::{OsRng, RngCore}; use chain_storage::{ test_utils::{Block, BlockId}, BlockInfo, BlockStore, }; const BLOCK_DATA_LENGTH: usize = 1024; fn criterion_benchmark(c: &mut Criterion) { let mut rng = OsRng; let mut block_data = [0; BLOCK_DATA_LENGTH]; rng.fill_bytes(&mut block_data); let genesis_block = Block::genesis(Some(Box::new(block_data))); let tempdir = tempfile::TempDir::new().unwrap(); let path = { let mut path = tempdir.path().to_path_buf(); path.push("test"); path }; let store = BlockStore::file(path, BlockId(0).serialize_as_vec()).unwrap(); let genesis_block_info = BlockInfo::new( genesis_block.id.serialize_as_vec(), genesis_block.parent.serialize_as_vec(), genesis_block.chain_length, ); store .put_block(&genesis_block.serialize_as_vec(), genesis_block_info) .unwrap(); let mut blocks = vec![genesis_block]; c.bench_function("put_block", |b| { b.iter_batched( || { let last_block = blocks.get(rng.next_u32() as usize % blocks.len()).unwrap(); rng.fill_bytes(&mut block_data); let block = last_block.make_child(Some(Box::new(block_data))); blocks.push(block.clone()); block }, |block| { let block_info = BlockInfo::new( block.id.serialize_as_vec(), block.parent.serialize_as_vec(), block.chain_length, ); store .put_block(&block.serialize_as_vec(), block_info) .unwrap() }, BatchSize::PerIteration, ) }); c.bench_function("get_block", |b| { b.iter_batched( || { blocks .get(rng.next_u32() as usize % blocks.len()) .unwrap() .id .serialize_as_vec() }, |block_id| store.get_block(&block_id).unwrap(), BatchSize::PerIteration, ) }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
30.460526
93
0.548164
abdb80f9b5f42de7481f980e2d3d1484f7814978
2,039
use std::str; use std::fmt; use std::error::Error; use std::convert::From; use base64; use actix_web::http::header; /// Possible errors while parsing `Authorization` header. /// /// Should not be used directly unless you are implementing /// your own [authentication scheme](./trait.Scheme.html). #[derive(Debug)] pub enum ParseError { /// Header value is malformed Invalid, /// Authentication scheme is missing MissingScheme, /// Required authentication field is missing MissingField(&'static str), ToStrError(header::ToStrError), Base64DecodeError(base64::DecodeError), Utf8Error(str::Utf8Error), } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.description()) } } impl Error for ParseError { fn description(&self) -> &str { match self { ParseError::Invalid => "Invalid header value", ParseError::MissingScheme => "Missing authorization scheme", ParseError::MissingField(_) => "Missing header field", ParseError::ToStrError(e) => e.description(), ParseError::Base64DecodeError(e) => e.description(), ParseError::Utf8Error(e) => e.description(), } } fn cause(&self) -> Option<&Error> { match self { ParseError::Invalid => None, ParseError::MissingScheme => None, ParseError::MissingField(_) => None, ParseError::ToStrError(e) => Some(e), ParseError::Base64DecodeError(e) => Some(e), ParseError::Utf8Error(e) => Some(e), } } } impl From<header::ToStrError> for ParseError { fn from(e: header::ToStrError) -> Self { ParseError::ToStrError(e) } } impl From<base64::DecodeError> for ParseError { fn from(e: base64::DecodeError) -> Self { ParseError::Base64DecodeError(e) } } impl From<str::Utf8Error> for ParseError { fn from(e: str::Utf8Error) -> Self { ParseError::Utf8Error(e) } }
28.71831
72
0.620402
33b625361b8386e5f4e88edda68675a675c3ea27
14,279
// Copyright 2020 Google LLC // Copyright 2020 Team Spacecat // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::{env, fs, io}; use decompiler::parser; use decompiler::lambda; use decompiler::simplified; use decompiler::expr; use decompiler::expr::Type; fn main() -> io::Result<()> { let mut env = expr::Env::new(); // The format of picture is "[size, bits...]". For each bits has 63 bits. env.insert(":1029", "Bitmap.Galaxy", None); env.insert(":1030", "Bitmap.App", None); env.insert(":1031", "Bitmap.Mul", None); env.insert(":1032", "Bitmap.Pow2", None); env.insert(":1034", "Bitmap.TotalEnergy", None); // For bomb explanation. env.insert(":1035", "Bitmap.TwoSquares", None); env.insert(":1036", "Bitmap.Define", None); env.insert(":1037", "Bitmap.Sum", None); env.insert(":1038", "Bitmap.FourDots", None); env.insert(":1039", "Bitmap.Bomb", None); env.insert(":1040", "Bitmap.Thruster", None); env.insert(":1041", "Bitmap.VarX0", None); // TODO env.insert(":1042", "Bitmap.VarX1", None); // TODO env.insert(":1043", "SparseBitmap.SymbolHuman", None); env.insert(":1044", "SparseBitmap.SymbolEndo", None); env.insert(":1045", "SparseBitmap.SymbolAlien1", None); env.insert(":1046", "SparseBitmap.SymbolAlien2", None); env.insert(":1047", "SparseBitmap.SymbolAlien3", None); env.insert(":1048", "SparseBitmap.SymbolAlien4", None); env.insert(":1049", "SparseBitmap.SymbolAlien5", None); env.insert(":1050", "SparseBitmap.SymbolAlien6", None); env.insert(":1051", "SparseBitmap.SymbolAlien7", None); env.insert(":1052", "SparseBitmap.SymbolAlien8", None); env.insert(":1053", "SparseBitmap.SymbolAlien9", None); env.insert(":1059", "SparseBitmap.PictureHuman", None); env.insert(":1060", "SparseBitmap.PictureEndo", None); env.insert(":1061", "SparseBitmap.PictureAlien1", None); env.insert(":1062", "SparseBitmap.PictureAlien2", None); env.insert(":1063", "SparseBitmap.PictureAlien3", None); env.insert(":1064", "SparseBitmap.PictureAlien4", None); env.insert(":1065", "SparseBitmap.PictureAlien5", None); env.insert(":1066", "SparseBitmap.PictureAlien6", None); env.insert(":1067", "SparseBitmap.PictureAlien7", None); env.insert(":1068", "SparseBitmap.PictureAlien8", None); env.insert(":1069", "SparseBitmap.PictureAlien9", None); env.insert(":1075", "SparseBitmap.LargeTrue", None); env.insert(":1076", "SparseBitmap.LargeFalse", None); env.insert(":1077", "SparseBitmap.LargeHeatMax", None); env.insert(":1078", "SparseBitmap.LargeThruster", None); env.insert(":1079", "Space.Aliens", None); // ID, pos, symbol, picture, (?). env.insert(":1080", "Bitmap.Laser", None); env.insert(":1081", "Bitmap.Split", None); env.insert(":1082", "Bitmap.Game", None); env.insert(":1083", "Bitmap.Attacker1", None); env.insert(":1084", "Bitmap.Attacker2", None); env.insert(":1085", "Bitmap.Attacker3", None); env.insert(":1086", "Bitmap.Attacker4", None); env.insert(":1087", "Bitmap.Defender1", None); env.insert(":1088", "Bitmap.Defender2", None); env.insert(":1089", "Bitmap.Defender3", None); env.insert(":1090", "Bitmap.Defender4", None); env.insert(":1091", "Machine.Attackers", None); env.insert(":1092", "Machine.Defenders", None); env.insert(":1093", "Bitmap.SplitClose", None); env.insert(":1097", "Bitmap.Energy", None); env.insert(":1098", "Bitmap.LaserMax", None); env.insert(":1099", "Bitmap.Cooldown", None); env.insert(":1100", "Bitmap.Life", None); env.insert(":1101", "Bitmap.Heat", None); env.insert(":1102", "Machine.Params", None); env.insert(":1103", "SparseBitmap.Space1", None); env.insert(":1104", "SparseBitmap.Space2", None); env.insert(":1105", "SparseBitmap.Space3", None); env.insert(":1107", "Print.thurster_range", None); // Position. env.insert(":1108", "Print.heat_range", None); // position. env.insert(":1109", "Msg.error", None); env.insert(":1110", "Msg.create", None); env.insert(":1111", "Msg.join", None); env.insert(":1112", "Msg.start", None); env.insert(":1113", "Msg.command", None); env.insert(":1114", "Msg.history", None); // Basic library. env.insert(":1115", "cons", None); env.insert(":1116", "List.hd", None); // Arithmetic library. env.insert(":1117", "Int.pow2", None); env.insert(":1118", "Int.log2", None); env.insert(":1119", "Int.log_x_y", None); env.insert(":1120", "Int.abs", None); env.insert(":1121", "Int.max", None); env.insert(":1122", "Int.min", None); // List library. env.insert(":1124", "List.mem", Some(Type::Func(vec!((None, None), (None, None)), Box::new(Some(Type::Bool))))); env.insert(":1126", "List.map", None); env.insert(":1127", "List.mapi", None); env.insert(":1128", "List.len", None); env.insert(":1131", "List.concat", None); env.insert(":1132", "List.foldl", None); env.insert(":1133", "List.foldr", None); env.insert(":1134", "List.flatten", None); env.insert(":1135", "List.filter", None); env.insert(":1136", "List.filteri", None); env.insert(":1137", "List.exists", None); env.insert(":1138", "IntList.make_rev", None); env.insert(":1139", "IntList.make", None); env.insert(":1141", "List.nth", None); env.insert(":1142", "List.nth_list", None); env.insert(":1143", "IntList.sum", None); env.insert(":1144", "List.replace_nth", None); env.insert(":1146", "IntList.max", None); env.insert(":1147", "List.select", None); env.insert(":1149", "IntList.min", None); env.insert(":1150", "List.map_sort", None); env.insert(":1152", "List.sort", None); env.insert(":1153", "List.filter2", None); env.insert(":1155", "IntList.unique", None); // Geometric library. env.insert(":1162", "Vec2.new", None); env.insert(":1166", "Rect.new", None); // (x, y), (h, w) env.insert(":1167", "Rect.from_vecs", None); // pos, range. env.insert(":1168", "Rect.from_center", None); // (x, y) size. env.insert(":1169", "Rect.move", None); // rect, vec2. env.insert(":1172", "Vec2.add", None); env.insert(":1173", "Vec2.add_x_y", None); env.insert(":1174", "Vec2.add_x", None); env.insert(":1175", "Vec2.x", None); env.insert(":1176", "Vec2.x_list", None); env.insert(":1178", "Vec2.y", None); env.insert(":1179", "Vec2.add_y", None); env.insert(":1180", "Vec2.mul", None); env.insert(":1181", "Vec2.distance", None); env.insert(":1183", "Vec2List.map_add", None); env.insert(":1187", "Vec2List.map_add_x", None); env.insert(":1188", "Vec2List.map_add_y", None); // Construct the result to be passed to f38 func. env.insert(":1189", "Result.no_data", None); // state -> Result. Used for scene switching. env.insert(":1190", "Result.to_render", None); // state, render_data -> Result. env.insert(":1191", "Result.to_send", None); // state, send_data -> Result. // Image rendering library. env.insert(":1193", "Image.dot_line", None); // p1, p2, freq. Dot per freq (and the end point). env.insert(":1194", "Image.line", None); env.insert(":1195", "Image.x_line", None); // x, y, len env.insert(":1196", "Image.x_dot_line", None); env.insert(":1197", "Image.y_line", None); env.insert(":1198", "Image.center_rect_bound", None); // size. env.insert(":1199", "Image.center_fill_rect", None); env.insert(":1200", "Image.rect_bound", None); // x, y, w, h env.insert(":1201", "Image.fill_rect", None); // x, y, w, h env.insert(":1202", "Image.fill_rect_aux", None); // x, y, w, (h*w) env.insert(":1203", "Int.in_range", None); env.insert(":1204", "Image.contained_rect", Some(Type::Func(vec!((None, None), (None, None)), Box::new(Some(Type::Bool))))); // p, rect (=((x, y), (w, h))) env.insert(":1205", "Image.make_bound", None); env.insert(":1206", "Image.from_uint", None); env.insert(":1207", "Bit.make", None); env.insert(":1208", "Bit.make_n", None); env.insert(":1209", "Bit.from_int", None); env.insert(":1210", "Int.ceil_sqr", None); env.insert(":1212", "Image.from_int_or_symbol", None); env.insert(":1213", "Image.from_int_or_symbol_with_size", None); env.insert(":1214", "Image.from_int", None); env.insert(":1215", "Image.from_int_left", None); env.insert(":1216", "Image.from_int_left_top", None); env.insert(":1217", "Image.from_int_with_size", None); env.insert(":1218", "Image.from_int_list", None); // Draw in x-axis with 3 pixels mergin. env.insert(":1220", "Image.from_image_list", None); // [Image] -> draw in x-axis with 3 pixels mergin. env.insert(":1221", "Image.from_image_list_with_mergin", None); // [Image], x_offset, [x_offset] env.insert(":1222", "Image.from_bitmap_list", None); env.insert(":1224", "Image.bounding_box", None); env.insert(":1225", "Image.from_bitmap", None); env.insert(":1226", "Image.from_sparse_bitmap", None); // Optning scene. env.insert(":1227", "Opening.Scene", None); // Opening.run, InitSceneState: [counter]. env.insert(":1228", "Opening.run", None); env.insert(":1229", "Opening.draw_count_down", None); // History of games. env.insert(":1231", "History.InitSceneState", None); env.insert(":1232", "History.Scene", None); // History.run, InitSceneState. env.insert(":1247", "History.HistoryList", None); // In the reverse chronological order. // [ID, game_id, top_team, bottom_team, which_team_continuted, ?] env.insert(":1253", "History.run", None); // Pelmanism game implementation. env.insert(":1305", "Pelmanism.Scene", None); // Pelmanism.run, InitSceneState. env.insert(":1306", "Pelmanism.rotation_table", None); env.insert(":1303", "Pelmanism.size", None); env.insert(":1304", "Pelmanism.tiles", None); env.insert(":1307", "Pelmanism.KindTile", None); env.insert(":1308", "Pelmanism.KindGalaxy", None); env.insert(":1309", "Pelmanism.run", None); // Takes orig: state, clicked: Vec2. env.insert(":1311", "Pelmanism.update_game", None); env.insert(":1312", "Pelmanism.solution_index", None); // Returns the rotation index or -1 (fail). env.insert(":1313", "Pelmanism.is_solved", None); // bits1, bits2, rotation. env.insert(":1314", "Pelmanism.update", None); // Takes orig: state, next: Pelmanism.state env.insert(":1315", "Pelmanism.draw", None); // Takes Pelmanism.state env.insert(":1316", "Pelmanism.draw_tile", None); // tile(int), index, offset, state. // Top level implementation. env.insert(":1328", "Garaxy.ModeOpening", None); env.insert(":1329", "Garaxy.ModeCariblation", None); env.insert(":1330", "Garaxy.ModeSpace", None); env.insert(":1331", "Garaxy.ModeTictactoe", None); env.insert(":1332", "Garaxy.ModePelmanism", None); env.insert(":1333", "Garaxy.ModeHistory", None); env.insert(":1334", "Garaxy.ModeTutorial", None); env.insert(":1335", "Garaxy.ModeError", None); env.insert(":1336", "Garaxy.Scenes", None); // List of tasks env.insert(":1337", "Error.run", None); // Print the error page. // Global entry point. env.insert(":1338", "Garaxy.run", None); env.insert(":1339", "Garaxy.next_scene", None); // state, next_mode, next_scene_state -> Result. // state, clicked, 0, instances. env.insert(":1342", "Garaxy.run_internal", None); // Takes (state, clicked, Garaxy.scenes). // Dispatch scene.run based on the given state. If the result changes its scene, // re-dispatch to the new scene. env.insert(":1343", "Garaxy.dispatch", None); // Tutorial game page. env.insert(":1344", "Tutorial.Scene", None); env.insert(":1346", "Tutorial.run", None); // Main menu. env.insert(":1420", "Space.Scene", None); env.insert(":1427", "Space.run", None); // Calibration after the opening count down. env.insert(":1445", "Cariblation.Scene", None); env.insert(":1446", "Cariblation.run", None); // Tic-Tac-Toe game implementation. env.insert(":1451", "TicTacToe.Scene", None); env.insert(":1471", "TicTacToe.run", None); env.insert(":1472", "Interact.empty", None); env.insert(":1473", "Interact.seq2", None); env.insert(":1474", "Interact.seq3", None); env.insert(":1475", "Interact.seq4", None); env.insert(":1476", "Interact.seq", None); env.insert(":1477", "Interact.find_clicked", None); env.insert(":1478", "Interact.push_image", None); env.insert(":1490", "Interact.draw_clickable_at", None); let args = env::args().collect::<Vec<_>>(); let content = fs::read_to_string(&args[1])?; for line in content.lines() { let parsed = parser::parse_line(line); eprintln!("Parsed: {:?}", parsed); let lambdified = lambda::lamdify(&parsed.value); eprintln!("Lambdified: {}", lambdified); let evaluated = lambda::eval(lambdified); eprintln!("Evaluated: {}", evaluated); let simplified = simplified::simplify(evaluated); eprintln!("Simplified: {}", simplified); let expr1 = expr::construct(&simplified, &env); eprintln!("Expr1 = {}", expr1); let expr2 = expr::simplify(&expr1); eprintln!("Expr2 = {}", expr2); let expr3 = expr::rename(&expr2, &env); let name = { if let Some(n) = env.get_name(&parsed.name) { n.clone() } else { parsed.name } }; println!("{} = {}", name, expr3) } return Ok(()); }
45.044164
160
0.618951
5bb8e2702f5f8c1bd9ff7c3f603b6df3c10011b5
143
use proc_macro2::Ident; use syn::Type; #[derive(darling::FromField)] pub struct EnumField { pub ident: Option<Ident>, pub ty: Type, }
15.888889
29
0.678322
48c9010b804a259ee90afb79857bdb80962699d1
1,260
use salvo::prelude::*; use tracing_subscriber; use tracing_subscriber::fmt::format::FmtSpan; #[fn_handler] async fn hello_world() -> &'static str { "Hello World" } #[fn_handler] async fn hello_world1() -> Result<&'static str, ()> { Ok("Hello World1") } #[fn_handler] async fn hello_world2(res: &mut Response) { res.render_plain_text("Hello World2"); } #[fn_handler] async fn hello_world3(_req: &mut Request, res: &mut Response) { res.render_plain_text("Hello World3"); } #[fn_handler] async fn hello_world4(_req: &mut Request, _depot: &mut Depot, res: &mut Response) { res.render_plain_text("Hello World4"); } #[tokio::main] async fn main() { let filter = std::env::var("RUST_LOG").unwrap_or_else(|_| "hello_world=debug,salvo=debug".to_owned()); tracing_subscriber::fmt() .with_env_filter(filter) .with_span_events(FmtSpan::CLOSE) .init(); let router = Router::new() .get(hello_world) .push(Router::new().path("hello1").get(hello_world1)) .push(Router::new().path("hello2").get(hello_world2)) .push(Router::new().path("hello3").get(hello_world3)) .push(Router::new().path("hello4").get(hello_world4)); Server::new(router).bind(([0, 0, 0, 0], 7878)).await; }
30.731707
106
0.655556
e635c6bebcd6dd80d704f1ed2d86b382b0d14600
3,967
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use deriving::generic::*; use deriving::generic::ty::*; use syntax::ast::{BinOpKind, Expr, MetaItem}; use syntax::ext::base::{Annotatable, ExtCtxt}; use syntax::ext::build::AstBuilder; use syntax::ptr::P; use syntax::symbol::Symbol; use syntax_pos::Span; pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Annotatable, push: &mut FnMut(Annotatable)) { // structures are equal if all fields are equal, and non equal, if // any fields are not equal or if the enum variants are different fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> { cs_fold(true, // use foldl |cx, span, subexpr, self_f, other_fs| { let other_f = match (other_fs.len(), other_fs.get(0)) { (1, Some(o_f)) => o_f, _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialEq)`"), }; let eq = cx.expr_binary(span, BinOpKind::Eq, self_f, other_f.clone()); cx.expr_binary(span, BinOpKind::And, subexpr, eq) }, cx.expr_bool(span, true), Box::new(|cx, span, _, _| cx.expr_bool(span, false)), cx, span, substr) } fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> { cs_fold(true, // use foldl |cx, span, subexpr, self_f, other_fs| { let other_f = match (other_fs.len(), other_fs.get(0)) { (1, Some(o_f)) => o_f, _ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialEq)`"), }; let eq = cx.expr_binary(span, BinOpKind::Ne, self_f, other_f.clone()); cx.expr_binary(span, BinOpKind::Or, subexpr, eq) }, cx.expr_bool(span, false), Box::new(|cx, span, _, _| cx.expr_bool(span, true)), cx, span, substr) } macro_rules! md { ($name:expr, $f:ident) => { { let inline = cx.meta_word(span, Symbol::intern("inline")); let attrs = vec![cx.attribute(span, inline)]; MethodDef { name: $name, generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: vec![borrowed_self()], ret_ty: Literal(path_local!(bool)), attributes: attrs, is_unsafe: false, unify_fieldless_variants: true, combine_substructure: combine_substructure(Box::new(|a, b, c| { $f(a, b, c) })) } } } } // avoid defining `ne` if we can // c-like enums, enums without any fields and structs without fields // can safely define only `eq`. let mut methods = vec![md!("eq", cs_eq)]; if !is_type_without_fields(item) { methods.push(md!("ne", cs_ne)); } let trait_def = TraitDef { span, attributes: Vec::new(), path: path_std!(cx, core::cmp::PartialEq), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), is_unsafe: false, supports_unions: false, methods, associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) }
37.424528
89
0.543232
9bc1a9f7d4f56e6d2699721fc35b159021149e9b
2,879
use std::sync::mpsc::{self, Receiver, Sender, TryRecvError}; use crate::config::Config; use ockam_message::message::{AddressType, Message as OckamMessage, MessageType, RouterAddress}; use ockam_system::commands::{OckamCommand, RouterCommand, WorkerCommand}; type WorkFn = fn(self_worker: &Worker, msg: OckamMessage); #[allow(dead_code)] pub struct Worker { router_tx: Sender<OckamCommand>, rx: Receiver<OckamCommand>, tx: Sender<OckamCommand>, addr: RouterAddress, work_fn: WorkFn, config: Config, } impl Worker { pub fn new( addr: RouterAddress, router_tx: Sender<OckamCommand>, config: Config, work_fn: WorkFn, ) -> Self { debug_assert!(matches!(addr.a_type, AddressType::Worker)); let (tx, rx) = mpsc::channel(); // register the worker with the router let cmd = OckamCommand::Router(RouterCommand::Register(AddressType::Worker, tx.clone())); router_tx.send(cmd).expect("failed to register worker"); println!("Service address: {}", addr.address.as_string()); Worker { router_tx, rx, tx, addr, config, work_fn, } } pub fn sender(&self) -> Sender<OckamCommand> { self.tx.clone() } pub fn config(&self) -> Config { self.config.clone() } pub fn poll(&self) -> bool { match self.rx.try_recv() { Ok(cmd) => match cmd { OckamCommand::Worker(WorkerCommand::ReceiveMessage(msg)) => { match msg.message_type { MessageType::Payload => { // Confirm address if self.addr != msg.onward_route.addresses[0] { println!("Received bad worker address"); return true; } (self.work_fn)(&self, msg); true } MessageType::None => true, _ => unimplemented!(), } } _ => { eprintln!("unrecognized worker command: {:?}", cmd); false } }, Err(e) => match e { TryRecvError::Empty => true, _ => { eprintln!("failed to recv worker rx: {:?}", e); false } }, } } } #[test] fn test_ockamd_worker() { let addr = RouterAddress::worker_router_address_from_str("01242020").unwrap(); let (fake_router_tx, fake_router_rx) = mpsc::channel(); Worker::new(addr, fake_router_tx, Default::default(), |_, _| {}); assert!(fake_router_rx.recv().is_ok()); }
29.680412
97
0.497742
765ff006354ecf264ee91038cb37f5a7c6bcf899
8,761
//! Parsing of DNS wire-format data. //! //! This module contains [`Parser`], the type wrapping the data of a DNS //! message for parsing, as well as the error and result types for parsing. //! You will only need to deal with parsing directly if you implement new //! record data types. Otherwise, the [`Message`] type wraps everyhing up //! in a nice, easy to use interface. //! //! [`Parser`]: struct.Parser.html //! [`Message`]: ../message/struct.Message.html use std::{error, fmt, io}; use byteorder::{BigEndian, ByteOrder}; //------------ Parser -------------------------------------------------------- /// A type wrapping DNS message data for parsing. /// /// Because of name compression, a full message needs to be available for /// parsing of DNS data. If you have received a message over the wire, you /// can use it to create a parser via the [`new()`] function. /// /// The parser then allows you to successively parse one item after the other /// out of the message via a few methods prefixed with `parse_`. Further /// methods are available to retrieve some information about the parser /// state, seek to a new position, or limit the amount of data the parser /// allows to retrieve. /// /// Parsers are `Clone`, so you can keep around a copy of a parser for later /// use. This is, for instance, done by [`ParsedDName`] in order to be able /// to rummage around the message bytes to find all its labels. /// /// [`new()`]: #method.new /// [`ParsedDName`]: ../name/struct.ParsedDName.html #[derive(Clone, Debug)] pub struct Parser<'a> { bytes: &'a [u8], pos: usize, limit: usize, } impl<'a> Parser<'a> { /// Creates a new parser atop a bytes slice. pub fn new(bytes: &'a [u8]) -> Self { Parser{limit: bytes.len(), bytes: bytes, pos: 0} } /// Limits the parser to `len` bytes from its current position. /// /// If the limit would be beyond the end of the parser, returns /// `Err(ParseError::UnexpectedEnd)`. pub fn set_limit(&mut self, len: usize) -> ParseResult<()> { let limit = self.pos + len; if len > self.bytes.len() { Err(ParseError::UnexpectedEnd) } else { self.limit = limit; Ok(()) } } /// Removes any limit from the parser. pub fn remove_limit(&mut self) { self.limit = self.bytes.len() } } impl<'a> Parser<'a> { /// Returns a reference to the complete message. /// /// The returned slice contains all bytes. It disregards the current /// position and any limit. pub fn bytes(&self) -> &'a [u8] { self.bytes } /// Returns the current parser position. /// /// This is the index in `self.bytes()` where the next octet would be /// read. pub fn pos(&self) -> usize { self.pos } /// Returns the number of bytes left to parse. /// /// If a limit is set, the returned number is up until that limit. pub fn remaining(&self) -> usize { self.limit - self.pos } /// Resets the position of the parser. /// /// The new position is relative to the beginning of the parser’s message. /// The function fails if the position is beyond the end of the message /// or, if a limit is set, beyond the limit. In either case, the /// function will return `Err(ParseError::UnexpectedEnd)`. pub fn seek(&mut self, pos: usize) -> ParseResult<()> { if pos > self.limit { Err(ParseError::UnexpectedEnd) } else { self.pos = pos; Ok(()) } } } impl<'a> Parser<'a> { /// Skips over `len` bytes. /// /// If this would go beyond the current limit or the end of the message, /// returns `Err(ParseError::UnexpectedEnd)`. pub fn skip(&mut self, len: usize) -> ParseResult<()> { self.parse_bytes(len).map(|_| ()) } /// Parses a bytes slice of the given length. /// /// The slice returned upon success references the parser’s message /// directly. The parser’s position is advanced until the end of the /// slice. /// /// The method will return `Err(ParseError::UnexpectedEnd)` if the /// length would take the parser beyond the current limit or the /// end of the message. pub fn parse_bytes(&mut self, len: usize) -> ParseResult<&'a [u8]> { let end = self.pos + len; if end > self.limit { return Err(ParseError::UnexpectedEnd) } let res = &self.bytes[self.pos..end]; self.pos = end; Ok(res) } pub fn parse_u8(&mut self) -> ParseResult<u8> { self.parse_bytes(1).map(|res| res[0]) } pub fn parse_u16(&mut self) -> ParseResult<u16> { self.parse_bytes(2).map(BigEndian::read_u16) } pub fn parse_u32(&mut self) -> ParseResult<u32> { self.parse_bytes(4).map(BigEndian::read_u32) } pub fn parse_remaining(&mut self) -> ParseResult<&'a [u8]> { let len = self.remaining(); self.parse_bytes(len) } /// Verifies that the parser is exhausted. /// /// Returns `Ok(())` if there are no remaining bytes in the parser or /// a form error otherwise. pub fn exhausted(&self) -> ParseResult<()> { if self.remaining() == 0 { Ok(()) } else { Err(ParseError::FormErr) } } } //------------ ParseError and ParseResult ----------------------------------- /// An error happening during parsing of wire-format DNS data. #[derive(Clone, Debug, PartialEq)] pub enum ParseError { /// The raw data ended unexpectedly in the middle of a structure. UnexpectedEnd, /// An unknown label type was encountered in a domain name. /// /// Several possible values for label types are not currently assigned /// (and likely never will). This is fatal since the label type defines /// how a label is parsed. UnknownLabel, /// A format error was encountered. FormErr, } impl error::Error for ParseError { fn description(&self) -> &str { use self::ParseError::*; match *self { UnexpectedEnd => "unexpected end of data", UnknownLabel => "unknown label type in domain name", FormErr => "format error", } } } impl From<ParseError> for io::Error { fn from(err: ParseError) -> io::Error { io::Error::new(io::ErrorKind::Other, Box::new(err)) } } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { error::Error::description(self).fmt(f) } } /// The result type for a `ParseError`. pub type ParseResult<T> = Result<T, ParseError>; //============ Testing ====================================================== #[cfg(test)] mod test { use super::*; fn check(parser: &Parser, pos: usize, left: &[u8]) { assert_eq!(parser.pos(), pos); assert_eq!(parser.remaining(), left.len()); assert_eq!(&parser.bytes()[pos..], left) } #[test] fn parse_bytes_ok() { let mut parser = Parser::new(b"123456"); check(&parser, 0, b"123456"); assert_eq!(parser.parse_bytes(0).unwrap(), b""); check(&parser, 0, b"123456"); assert_eq!(parser.parse_bytes(4).unwrap(), b"1234"); check(&parser, 4, b"56"); assert_eq!(parser.parse_bytes(2).unwrap(), b"56"); check(&parser, 6, b""); assert_eq!(parser.parse_bytes(0).unwrap(), b""); check(&parser, 6, b""); } #[test] fn parse_bytes_err() { let mut parser = Parser::new(b"123456"); check(&parser, 0, b"123456"); assert_eq!(parser.parse_bytes(8), Err(ParseError::UnexpectedEnd)); check(&parser, 0, b"123456"); } #[test] fn skip() { let mut parser = Parser::new(b"123456"); check(&parser, 0, b"123456"); parser.skip(2).unwrap(); check(&parser, 2, b"3456"); assert_eq!(parser.skip(6), Err(ParseError::UnexpectedEnd)); check(&parser, 2, b"3456"); } #[test] fn parse_u8() { let mut parser = Parser::new(b"123"); check(&parser, 0, b"123"); assert_eq!(parser.parse_u8().unwrap(), b'1'); check(&parser, 1, b"23"); } #[test] fn parse_u16() { let mut parser = Parser::new(b"\x12\x3456"); check(&parser, 0, b"\x12\x3456"); assert_eq!(parser.parse_u16().unwrap(), 0x1234); check(&parser, 2, b"56"); } #[test] fn parse_u32() { let mut parser = Parser::new(b"\x12\x34\x56\x7890"); check(&parser, 0, b"\x12\x34\x56\x7890"); assert_eq!(parser.parse_u32().unwrap(), 0x12345678); check(&parser, 4, b"90"); } }
30.632867
78
0.577331
613f66d7ffd7ee2422151a22fa4734ac1e82df47
8,952
use super::{InferCtxt, FixupError, FixupResult, Span}; use super::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use crate::ty::{self, Ty, Const, TyCtxt, TypeFoldable, InferConst}; use crate::ty::fold::{TypeFolder, TypeVisitor}; /////////////////////////////////////////////////////////////////////////// // OPPORTUNISTIC VAR RESOLVER /// The opportunistic resolver can be used at any time. It simply replaces /// type/const variables that have been unified with the things they have /// been unified with (similar to `shallow_resolve`, but deep). This is /// useful for printing messages etc but also required at various /// points for correctness. pub struct OpportunisticVarResolver<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, } impl<'a, 'tcx> OpportunisticVarResolver<'a, 'tcx> { #[inline] pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self { OpportunisticVarResolver { infcx } } } impl<'a, 'tcx> TypeFolder<'tcx> for OpportunisticVarResolver<'a, 'tcx> { fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.infcx.tcx } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { if !t.has_infer_types() && !t.has_infer_consts() { t // micro-optimize -- if there is nothing in this type that this fold affects... } else { let t = self.infcx.shallow_resolve(t); t.super_fold_with(self) } } fn fold_const(&mut self, ct: &'tcx Const<'tcx>) -> &'tcx Const<'tcx> { if !ct.has_infer_consts() { ct // micro-optimize -- if there is nothing in this const that this fold affects... } else { let ct = self.infcx.shallow_resolve(ct); ct.super_fold_with(self) } } } /// The opportunistic type and region resolver is similar to the /// opportunistic type resolver, but also opportunistically resolves /// regions. It is useful for canonicalization. pub struct OpportunisticTypeAndRegionResolver<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, } impl<'a, 'tcx> OpportunisticTypeAndRegionResolver<'a, 'tcx> { pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self { OpportunisticTypeAndRegionResolver { infcx } } } impl<'a, 'tcx> TypeFolder<'tcx> for OpportunisticTypeAndRegionResolver<'a, 'tcx> { fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.infcx.tcx } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { if !t.needs_infer() { t // micro-optimize -- if there is nothing in this type that this fold affects... } else { let t0 = self.infcx.shallow_resolve(t); t0.super_fold_with(self) } } fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { match *r { ty::ReVar(rid) => self.infcx.borrow_region_constraints() .opportunistic_resolve_var(self.tcx(), rid), _ => r, } } fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { if !ct.needs_infer() { ct // micro-optimize -- if there is nothing in this const that this fold affects... } else { let c0 = self.infcx.shallow_resolve(ct); c0.super_fold_with(self) } } } /////////////////////////////////////////////////////////////////////////// // UNRESOLVED TYPE FINDER /// The unresolved type **finder** walks a type searching for /// type variables that don't yet have a value. The first unresolved type is stored. /// It does not construct the fully resolved type (which might /// involve some hashing and so forth). pub struct UnresolvedTypeFinder<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, /// Used to find the type parameter name and location for error reporting. pub first_unresolved: Option<(Ty<'tcx>, Option<Span>)>, } impl<'a, 'tcx> UnresolvedTypeFinder<'a, 'tcx> { pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self { UnresolvedTypeFinder { infcx, first_unresolved: None } } } impl<'a, 'tcx> TypeVisitor<'tcx> for UnresolvedTypeFinder<'a, 'tcx> { fn visit_ty(&mut self, t: Ty<'tcx>) -> bool { let t = self.infcx.shallow_resolve(t); if t.has_infer_types() { if let ty::Infer(infer_ty) = t.kind { // Since we called `shallow_resolve` above, this must // be an (as yet...) unresolved inference variable. let ty_var_span = if let ty::TyVar(ty_vid) = infer_ty { let ty_vars = self.infcx.type_variables.borrow(); if let TypeVariableOrigin { kind: TypeVariableOriginKind::TypeParameterDefinition(_), span, } = *ty_vars.var_origin(ty_vid) { Some(span) } else { None } } else { None }; self.first_unresolved = Some((t, ty_var_span)); true // Halt visiting. } else { // Otherwise, visit its contents. t.super_visit_with(self) } } else { // All type variables in inference types must already be resolved, // - no need to visit the contents, continue visiting. false } } } /////////////////////////////////////////////////////////////////////////// // FULL TYPE RESOLUTION /// Full type resolution replaces all type and region variables with /// their concrete results. If any variable cannot be replaced (never unified, etc) /// then an `Err` result is returned. pub fn fully_resolve<'a, 'tcx, T>(infcx: &InferCtxt<'a, 'tcx>, value: &T) -> FixupResult<'tcx, T> where T: TypeFoldable<'tcx>, { let mut full_resolver = FullTypeResolver { infcx: infcx, err: None }; let result = value.fold_with(&mut full_resolver); match full_resolver.err { None => Ok(result), Some(e) => Err(e), } } // N.B. This type is not public because the protocol around checking the // `err` field is not enforcable otherwise. struct FullTypeResolver<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, err: Option<FixupError<'tcx>>, } impl<'a, 'tcx> TypeFolder<'tcx> for FullTypeResolver<'a, 'tcx> { fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.infcx.tcx } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { if !t.needs_infer() && !ty::keep_local(&t) { t // micro-optimize -- if there is nothing in this type that this fold affects... // ^ we need to have the `keep_local` check to un-default // defaulted tuples. } else { let t = self.infcx.shallow_resolve(t); match t.kind { ty::Infer(ty::TyVar(vid)) => { self.err = Some(FixupError::UnresolvedTy(vid)); self.tcx().types.err } ty::Infer(ty::IntVar(vid)) => { self.err = Some(FixupError::UnresolvedIntTy(vid)); self.tcx().types.err } ty::Infer(ty::FloatVar(vid)) => { self.err = Some(FixupError::UnresolvedFloatTy(vid)); self.tcx().types.err } ty::Infer(_) => { bug!("Unexpected type in full type resolver: {:?}", t); } _ => { t.super_fold_with(self) } } } } fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { match *r { ty::ReVar(rid) => self.infcx.lexical_region_resolutions .borrow() .as_ref() .expect("region resolution not performed") .resolve_var(rid), _ => r, } } fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { if !c.needs_infer() && !ty::keep_local(&c) { c // micro-optimize -- if there is nothing in this const that this fold affects... // ^ we need to have the `keep_local` check to un-default // defaulted tuples. } else { let c = self.infcx.shallow_resolve(c); match c.val { ty::ConstKind::Infer(InferConst::Var(vid)) => { self.err = Some(FixupError::UnresolvedConst(vid)); return self.tcx().consts.err; } ty::ConstKind::Infer(InferConst::Fresh(_)) => { bug!("Unexpected const in full const resolver: {:?}", c); } _ => {} } c.super_fold_with(self) } } }
36.538776
97
0.524911