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
|
---|---|---|---|---|---|
d635912040fcf52ae1026e54bce95d781c6d8f09 | 431,002 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
/// Error type for the `CancelImageCreation` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CancelImageCreationError {
/// Kind of error that occurred.
pub kind: CancelImageCreationErrorKind,
/// 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 `CancelImageCreation` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CancelImageCreationErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 CancelImageCreationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CancelImageCreationErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
CancelImageCreationErrorKind::ClientException(_inner) => _inner.fmt(f),
CancelImageCreationErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
CancelImageCreationErrorKind::IdempotentParameterMismatchException(_inner) => {
_inner.fmt(f)
}
CancelImageCreationErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
CancelImageCreationErrorKind::ResourceInUseException(_inner) => _inner.fmt(f),
CancelImageCreationErrorKind::ServiceException(_inner) => _inner.fmt(f),
CancelImageCreationErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
CancelImageCreationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for CancelImageCreationError {
fn code(&self) -> Option<&str> {
CancelImageCreationError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl CancelImageCreationError {
/// Creates a new `CancelImageCreationError`.
pub fn new(kind: CancelImageCreationErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `CancelImageCreationError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CancelImageCreationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `CancelImageCreationError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CancelImageCreationErrorKind::Unhandled(err.into()),
}
}
/// 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 `CancelImageCreationErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CancelImageCreationErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `CancelImageCreationErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, CancelImageCreationErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `CancelImageCreationErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
CancelImageCreationErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `CancelImageCreationErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
CancelImageCreationErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `CancelImageCreationErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
CancelImageCreationErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `CancelImageCreationErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
CancelImageCreationErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `CancelImageCreationErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
CancelImageCreationErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `CancelImageCreationErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CancelImageCreationErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for CancelImageCreationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CancelImageCreationErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
CancelImageCreationErrorKind::ClientException(_inner) => Some(_inner),
CancelImageCreationErrorKind::ForbiddenException(_inner) => Some(_inner),
CancelImageCreationErrorKind::IdempotentParameterMismatchException(_inner) => {
Some(_inner)
}
CancelImageCreationErrorKind::InvalidRequestException(_inner) => Some(_inner),
CancelImageCreationErrorKind::ResourceInUseException(_inner) => Some(_inner),
CancelImageCreationErrorKind::ServiceException(_inner) => Some(_inner),
CancelImageCreationErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
CancelImageCreationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `CreateComponent` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateComponentError {
/// Kind of error that occurred.
pub kind: CreateComponentErrorKind,
/// 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 `CreateComponent` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateComponentErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have specified two or more mutually exclusive parameters. Review the error message for details.</p>
InvalidParameterCombinationException(crate::error::InvalidParameterCombinationException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>Your version number is out of bounds or does not follow the required syntax.</p>
InvalidVersionNumberException(crate::error::InvalidVersionNumberException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>You have exceeded the number of permitted resources or operations for this service. For service quotas, see <a href="https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder">EC2 Image Builder endpoints and quotas</a>.</p>
ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 CreateComponentError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateComponentErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
CreateComponentErrorKind::ClientException(_inner) => _inner.fmt(f),
CreateComponentErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
CreateComponentErrorKind::IdempotentParameterMismatchException(_inner) => _inner.fmt(f),
CreateComponentErrorKind::InvalidParameterCombinationException(_inner) => _inner.fmt(f),
CreateComponentErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
CreateComponentErrorKind::InvalidVersionNumberException(_inner) => _inner.fmt(f),
CreateComponentErrorKind::ResourceInUseException(_inner) => _inner.fmt(f),
CreateComponentErrorKind::ServiceException(_inner) => _inner.fmt(f),
CreateComponentErrorKind::ServiceQuotaExceededException(_inner) => _inner.fmt(f),
CreateComponentErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
CreateComponentErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for CreateComponentError {
fn code(&self) -> Option<&str> {
CreateComponentError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl CreateComponentError {
/// Creates a new `CreateComponentError`.
pub fn new(kind: CreateComponentErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `CreateComponentError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateComponentErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `CreateComponentError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateComponentErrorKind::Unhandled(err.into()),
}
}
/// 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 `CreateComponentErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateComponentErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateComponentErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, CreateComponentErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `CreateComponentErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, CreateComponentErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `CreateComponentErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
CreateComponentErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `CreateComponentErrorKind::InvalidParameterCombinationException`.
pub fn is_invalid_parameter_combination_exception(&self) -> bool {
matches!(
&self.kind,
CreateComponentErrorKind::InvalidParameterCombinationException(_)
)
}
/// Returns `true` if the error kind is `CreateComponentErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
CreateComponentErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `CreateComponentErrorKind::InvalidVersionNumberException`.
pub fn is_invalid_version_number_exception(&self) -> bool {
matches!(
&self.kind,
CreateComponentErrorKind::InvalidVersionNumberException(_)
)
}
/// Returns `true` if the error kind is `CreateComponentErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
CreateComponentErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `CreateComponentErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, CreateComponentErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `CreateComponentErrorKind::ServiceQuotaExceededException`.
pub fn is_service_quota_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateComponentErrorKind::ServiceQuotaExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateComponentErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CreateComponentErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for CreateComponentError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateComponentErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
CreateComponentErrorKind::ClientException(_inner) => Some(_inner),
CreateComponentErrorKind::ForbiddenException(_inner) => Some(_inner),
CreateComponentErrorKind::IdempotentParameterMismatchException(_inner) => Some(_inner),
CreateComponentErrorKind::InvalidParameterCombinationException(_inner) => Some(_inner),
CreateComponentErrorKind::InvalidRequestException(_inner) => Some(_inner),
CreateComponentErrorKind::InvalidVersionNumberException(_inner) => Some(_inner),
CreateComponentErrorKind::ResourceInUseException(_inner) => Some(_inner),
CreateComponentErrorKind::ServiceException(_inner) => Some(_inner),
CreateComponentErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner),
CreateComponentErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
CreateComponentErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `CreateContainerRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateContainerRecipeError {
/// Kind of error that occurred.
pub kind: CreateContainerRecipeErrorKind,
/// 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 `CreateContainerRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateContainerRecipeErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>Your version number is out of bounds or does not follow the required syntax.</p>
InvalidVersionNumberException(crate::error::InvalidVersionNumberException),
/// <p>The resource that you are trying to create already exists.</p>
ResourceAlreadyExistsException(crate::error::ResourceAlreadyExistsException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>You have exceeded the number of permitted resources or operations for this service. For service quotas, see <a href="https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder">EC2 Image Builder endpoints and quotas</a>.</p>
ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 CreateContainerRecipeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateContainerRecipeErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
CreateContainerRecipeErrorKind::ClientException(_inner) => _inner.fmt(f),
CreateContainerRecipeErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
CreateContainerRecipeErrorKind::IdempotentParameterMismatchException(_inner) => {
_inner.fmt(f)
}
CreateContainerRecipeErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
CreateContainerRecipeErrorKind::InvalidVersionNumberException(_inner) => _inner.fmt(f),
CreateContainerRecipeErrorKind::ResourceAlreadyExistsException(_inner) => _inner.fmt(f),
CreateContainerRecipeErrorKind::ResourceInUseException(_inner) => _inner.fmt(f),
CreateContainerRecipeErrorKind::ServiceException(_inner) => _inner.fmt(f),
CreateContainerRecipeErrorKind::ServiceQuotaExceededException(_inner) => _inner.fmt(f),
CreateContainerRecipeErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
CreateContainerRecipeErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for CreateContainerRecipeError {
fn code(&self) -> Option<&str> {
CreateContainerRecipeError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl CreateContainerRecipeError {
/// Creates a new `CreateContainerRecipeError`.
pub fn new(kind: CreateContainerRecipeErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `CreateContainerRecipeError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateContainerRecipeErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `CreateContainerRecipeError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateContainerRecipeErrorKind::Unhandled(err.into()),
}
}
/// 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 `CreateContainerRecipeErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateContainerRecipeErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateContainerRecipeErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
CreateContainerRecipeErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `CreateContainerRecipeErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
CreateContainerRecipeErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `CreateContainerRecipeErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
CreateContainerRecipeErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `CreateContainerRecipeErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
CreateContainerRecipeErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `CreateContainerRecipeErrorKind::InvalidVersionNumberException`.
pub fn is_invalid_version_number_exception(&self) -> bool {
matches!(
&self.kind,
CreateContainerRecipeErrorKind::InvalidVersionNumberException(_)
)
}
/// Returns `true` if the error kind is `CreateContainerRecipeErrorKind::ResourceAlreadyExistsException`.
pub fn is_resource_already_exists_exception(&self) -> bool {
matches!(
&self.kind,
CreateContainerRecipeErrorKind::ResourceAlreadyExistsException(_)
)
}
/// Returns `true` if the error kind is `CreateContainerRecipeErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
CreateContainerRecipeErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `CreateContainerRecipeErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
CreateContainerRecipeErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `CreateContainerRecipeErrorKind::ServiceQuotaExceededException`.
pub fn is_service_quota_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateContainerRecipeErrorKind::ServiceQuotaExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateContainerRecipeErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CreateContainerRecipeErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for CreateContainerRecipeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateContainerRecipeErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
CreateContainerRecipeErrorKind::ClientException(_inner) => Some(_inner),
CreateContainerRecipeErrorKind::ForbiddenException(_inner) => Some(_inner),
CreateContainerRecipeErrorKind::IdempotentParameterMismatchException(_inner) => {
Some(_inner)
}
CreateContainerRecipeErrorKind::InvalidRequestException(_inner) => Some(_inner),
CreateContainerRecipeErrorKind::InvalidVersionNumberException(_inner) => Some(_inner),
CreateContainerRecipeErrorKind::ResourceAlreadyExistsException(_inner) => Some(_inner),
CreateContainerRecipeErrorKind::ResourceInUseException(_inner) => Some(_inner),
CreateContainerRecipeErrorKind::ServiceException(_inner) => Some(_inner),
CreateContainerRecipeErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner),
CreateContainerRecipeErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
CreateContainerRecipeErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `CreateDistributionConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateDistributionConfigurationError {
/// Kind of error that occurred.
pub kind: CreateDistributionConfigurationErrorKind,
/// 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 `CreateDistributionConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateDistributionConfigurationErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have specified two or more mutually exclusive parameters. Review the error message for details.</p>
InvalidParameterCombinationException(crate::error::InvalidParameterCombinationException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>The resource that you are trying to create already exists.</p>
ResourceAlreadyExistsException(crate::error::ResourceAlreadyExistsException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>You have exceeded the number of permitted resources or operations for this service. For service quotas, see <a href="https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder">EC2 Image Builder endpoints and quotas</a>.</p>
ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 CreateDistributionConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateDistributionConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
CreateDistributionConfigurationErrorKind::ClientException(_inner) => _inner.fmt(f),
CreateDistributionConfigurationErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
CreateDistributionConfigurationErrorKind::IdempotentParameterMismatchException(
_inner,
) => _inner.fmt(f),
CreateDistributionConfigurationErrorKind::InvalidParameterCombinationException(
_inner,
) => _inner.fmt(f),
CreateDistributionConfigurationErrorKind::InvalidRequestException(_inner) => {
_inner.fmt(f)
}
CreateDistributionConfigurationErrorKind::ResourceAlreadyExistsException(_inner) => {
_inner.fmt(f)
}
CreateDistributionConfigurationErrorKind::ResourceInUseException(_inner) => {
_inner.fmt(f)
}
CreateDistributionConfigurationErrorKind::ServiceException(_inner) => _inner.fmt(f),
CreateDistributionConfigurationErrorKind::ServiceQuotaExceededException(_inner) => {
_inner.fmt(f)
}
CreateDistributionConfigurationErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
CreateDistributionConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for CreateDistributionConfigurationError {
fn code(&self) -> Option<&str> {
CreateDistributionConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl CreateDistributionConfigurationError {
/// Creates a new `CreateDistributionConfigurationError`.
pub fn new(
kind: CreateDistributionConfigurationErrorKind,
meta: aws_smithy_types::Error,
) -> Self {
Self { kind, meta }
}
/// Creates the `CreateDistributionConfigurationError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateDistributionConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `CreateDistributionConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateDistributionConfigurationErrorKind::Unhandled(err.into()),
}
}
/// 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 `CreateDistributionConfigurationErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateDistributionConfigurationErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateDistributionConfigurationErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
CreateDistributionConfigurationErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `CreateDistributionConfigurationErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
CreateDistributionConfigurationErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `CreateDistributionConfigurationErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
CreateDistributionConfigurationErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `CreateDistributionConfigurationErrorKind::InvalidParameterCombinationException`.
pub fn is_invalid_parameter_combination_exception(&self) -> bool {
matches!(
&self.kind,
CreateDistributionConfigurationErrorKind::InvalidParameterCombinationException(_)
)
}
/// Returns `true` if the error kind is `CreateDistributionConfigurationErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
CreateDistributionConfigurationErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `CreateDistributionConfigurationErrorKind::ResourceAlreadyExistsException`.
pub fn is_resource_already_exists_exception(&self) -> bool {
matches!(
&self.kind,
CreateDistributionConfigurationErrorKind::ResourceAlreadyExistsException(_)
)
}
/// Returns `true` if the error kind is `CreateDistributionConfigurationErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
CreateDistributionConfigurationErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `CreateDistributionConfigurationErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
CreateDistributionConfigurationErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `CreateDistributionConfigurationErrorKind::ServiceQuotaExceededException`.
pub fn is_service_quota_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateDistributionConfigurationErrorKind::ServiceQuotaExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateDistributionConfigurationErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CreateDistributionConfigurationErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for CreateDistributionConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateDistributionConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
CreateDistributionConfigurationErrorKind::ClientException(_inner) => Some(_inner),
CreateDistributionConfigurationErrorKind::ForbiddenException(_inner) => Some(_inner),
CreateDistributionConfigurationErrorKind::IdempotentParameterMismatchException(
_inner,
) => Some(_inner),
CreateDistributionConfigurationErrorKind::InvalidParameterCombinationException(
_inner,
) => Some(_inner),
CreateDistributionConfigurationErrorKind::InvalidRequestException(_inner) => {
Some(_inner)
}
CreateDistributionConfigurationErrorKind::ResourceAlreadyExistsException(_inner) => {
Some(_inner)
}
CreateDistributionConfigurationErrorKind::ResourceInUseException(_inner) => {
Some(_inner)
}
CreateDistributionConfigurationErrorKind::ServiceException(_inner) => Some(_inner),
CreateDistributionConfigurationErrorKind::ServiceQuotaExceededException(_inner) => {
Some(_inner)
}
CreateDistributionConfigurationErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
CreateDistributionConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `CreateImage` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateImageError {
/// Kind of error that occurred.
pub kind: CreateImageErrorKind,
/// 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 `CreateImage` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateImageErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>You have exceeded the number of permitted resources or operations for this service. For service quotas, see <a href="https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder">EC2 Image Builder endpoints and quotas</a>.</p>
ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 CreateImageError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateImageErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
CreateImageErrorKind::ClientException(_inner) => _inner.fmt(f),
CreateImageErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
CreateImageErrorKind::IdempotentParameterMismatchException(_inner) => _inner.fmt(f),
CreateImageErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
CreateImageErrorKind::ResourceInUseException(_inner) => _inner.fmt(f),
CreateImageErrorKind::ServiceException(_inner) => _inner.fmt(f),
CreateImageErrorKind::ServiceQuotaExceededException(_inner) => _inner.fmt(f),
CreateImageErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
CreateImageErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for CreateImageError {
fn code(&self) -> Option<&str> {
CreateImageError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl CreateImageError {
/// Creates a new `CreateImageError`.
pub fn new(kind: CreateImageErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `CreateImageError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateImageErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `CreateImageError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateImageErrorKind::Unhandled(err.into()),
}
}
/// 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 `CreateImageErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateImageErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, CreateImageErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `CreateImageErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, CreateImageErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `CreateImageErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `CreateImageErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(&self.kind, CreateImageErrorKind::InvalidRequestException(_))
}
/// Returns `true` if the error kind is `CreateImageErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(&self.kind, CreateImageErrorKind::ResourceInUseException(_))
}
/// Returns `true` if the error kind is `CreateImageErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, CreateImageErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `CreateImageErrorKind::ServiceQuotaExceededException`.
pub fn is_service_quota_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageErrorKind::ServiceQuotaExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateImageErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for CreateImageError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateImageErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
CreateImageErrorKind::ClientException(_inner) => Some(_inner),
CreateImageErrorKind::ForbiddenException(_inner) => Some(_inner),
CreateImageErrorKind::IdempotentParameterMismatchException(_inner) => Some(_inner),
CreateImageErrorKind::InvalidRequestException(_inner) => Some(_inner),
CreateImageErrorKind::ResourceInUseException(_inner) => Some(_inner),
CreateImageErrorKind::ServiceException(_inner) => Some(_inner),
CreateImageErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner),
CreateImageErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
CreateImageErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `CreateImagePipeline` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateImagePipelineError {
/// Kind of error that occurred.
pub kind: CreateImagePipelineErrorKind,
/// 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 `CreateImagePipeline` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateImagePipelineErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>The resource that you are trying to create already exists.</p>
ResourceAlreadyExistsException(crate::error::ResourceAlreadyExistsException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>You have exceeded the number of permitted resources or operations for this service. For service quotas, see <a href="https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder">EC2 Image Builder endpoints and quotas</a>.</p>
ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 CreateImagePipelineError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateImagePipelineErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
CreateImagePipelineErrorKind::ClientException(_inner) => _inner.fmt(f),
CreateImagePipelineErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
CreateImagePipelineErrorKind::IdempotentParameterMismatchException(_inner) => {
_inner.fmt(f)
}
CreateImagePipelineErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
CreateImagePipelineErrorKind::ResourceAlreadyExistsException(_inner) => _inner.fmt(f),
CreateImagePipelineErrorKind::ResourceInUseException(_inner) => _inner.fmt(f),
CreateImagePipelineErrorKind::ServiceException(_inner) => _inner.fmt(f),
CreateImagePipelineErrorKind::ServiceQuotaExceededException(_inner) => _inner.fmt(f),
CreateImagePipelineErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
CreateImagePipelineErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for CreateImagePipelineError {
fn code(&self) -> Option<&str> {
CreateImagePipelineError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl CreateImagePipelineError {
/// Creates a new `CreateImagePipelineError`.
pub fn new(kind: CreateImagePipelineErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `CreateImagePipelineError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateImagePipelineErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `CreateImagePipelineError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateImagePipelineErrorKind::Unhandled(err.into()),
}
}
/// 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 `CreateImagePipelineErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateImagePipelineErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateImagePipelineErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, CreateImagePipelineErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `CreateImagePipelineErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
CreateImagePipelineErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `CreateImagePipelineErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
CreateImagePipelineErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `CreateImagePipelineErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
CreateImagePipelineErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `CreateImagePipelineErrorKind::ResourceAlreadyExistsException`.
pub fn is_resource_already_exists_exception(&self) -> bool {
matches!(
&self.kind,
CreateImagePipelineErrorKind::ResourceAlreadyExistsException(_)
)
}
/// Returns `true` if the error kind is `CreateImagePipelineErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
CreateImagePipelineErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `CreateImagePipelineErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
CreateImagePipelineErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `CreateImagePipelineErrorKind::ServiceQuotaExceededException`.
pub fn is_service_quota_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateImagePipelineErrorKind::ServiceQuotaExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateImagePipelineErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CreateImagePipelineErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for CreateImagePipelineError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateImagePipelineErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
CreateImagePipelineErrorKind::ClientException(_inner) => Some(_inner),
CreateImagePipelineErrorKind::ForbiddenException(_inner) => Some(_inner),
CreateImagePipelineErrorKind::IdempotentParameterMismatchException(_inner) => {
Some(_inner)
}
CreateImagePipelineErrorKind::InvalidRequestException(_inner) => Some(_inner),
CreateImagePipelineErrorKind::ResourceAlreadyExistsException(_inner) => Some(_inner),
CreateImagePipelineErrorKind::ResourceInUseException(_inner) => Some(_inner),
CreateImagePipelineErrorKind::ServiceException(_inner) => Some(_inner),
CreateImagePipelineErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner),
CreateImagePipelineErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
CreateImagePipelineErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `CreateImageRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateImageRecipeError {
/// Kind of error that occurred.
pub kind: CreateImageRecipeErrorKind,
/// 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 `CreateImageRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateImageRecipeErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>Your version number is out of bounds or does not follow the required syntax.</p>
InvalidVersionNumberException(crate::error::InvalidVersionNumberException),
/// <p>The resource that you are trying to create already exists.</p>
ResourceAlreadyExistsException(crate::error::ResourceAlreadyExistsException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>You have exceeded the number of permitted resources or operations for this service. For service quotas, see <a href="https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder">EC2 Image Builder endpoints and quotas</a>.</p>
ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 CreateImageRecipeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateImageRecipeErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
CreateImageRecipeErrorKind::ClientException(_inner) => _inner.fmt(f),
CreateImageRecipeErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
CreateImageRecipeErrorKind::IdempotentParameterMismatchException(_inner) => {
_inner.fmt(f)
}
CreateImageRecipeErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
CreateImageRecipeErrorKind::InvalidVersionNumberException(_inner) => _inner.fmt(f),
CreateImageRecipeErrorKind::ResourceAlreadyExistsException(_inner) => _inner.fmt(f),
CreateImageRecipeErrorKind::ResourceInUseException(_inner) => _inner.fmt(f),
CreateImageRecipeErrorKind::ServiceException(_inner) => _inner.fmt(f),
CreateImageRecipeErrorKind::ServiceQuotaExceededException(_inner) => _inner.fmt(f),
CreateImageRecipeErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
CreateImageRecipeErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for CreateImageRecipeError {
fn code(&self) -> Option<&str> {
CreateImageRecipeError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl CreateImageRecipeError {
/// Creates a new `CreateImageRecipeError`.
pub fn new(kind: CreateImageRecipeErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `CreateImageRecipeError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateImageRecipeErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `CreateImageRecipeError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateImageRecipeErrorKind::Unhandled(err.into()),
}
}
/// 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 `CreateImageRecipeErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageRecipeErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateImageRecipeErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, CreateImageRecipeErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `CreateImageRecipeErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageRecipeErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `CreateImageRecipeErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageRecipeErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `CreateImageRecipeErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageRecipeErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `CreateImageRecipeErrorKind::InvalidVersionNumberException`.
pub fn is_invalid_version_number_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageRecipeErrorKind::InvalidVersionNumberException(_)
)
}
/// Returns `true` if the error kind is `CreateImageRecipeErrorKind::ResourceAlreadyExistsException`.
pub fn is_resource_already_exists_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageRecipeErrorKind::ResourceAlreadyExistsException(_)
)
}
/// Returns `true` if the error kind is `CreateImageRecipeErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageRecipeErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `CreateImageRecipeErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, CreateImageRecipeErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `CreateImageRecipeErrorKind::ServiceQuotaExceededException`.
pub fn is_service_quota_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageRecipeErrorKind::ServiceQuotaExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateImageRecipeErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CreateImageRecipeErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for CreateImageRecipeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateImageRecipeErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
CreateImageRecipeErrorKind::ClientException(_inner) => Some(_inner),
CreateImageRecipeErrorKind::ForbiddenException(_inner) => Some(_inner),
CreateImageRecipeErrorKind::IdempotentParameterMismatchException(_inner) => {
Some(_inner)
}
CreateImageRecipeErrorKind::InvalidRequestException(_inner) => Some(_inner),
CreateImageRecipeErrorKind::InvalidVersionNumberException(_inner) => Some(_inner),
CreateImageRecipeErrorKind::ResourceAlreadyExistsException(_inner) => Some(_inner),
CreateImageRecipeErrorKind::ResourceInUseException(_inner) => Some(_inner),
CreateImageRecipeErrorKind::ServiceException(_inner) => Some(_inner),
CreateImageRecipeErrorKind::ServiceQuotaExceededException(_inner) => Some(_inner),
CreateImageRecipeErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
CreateImageRecipeErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `CreateInfrastructureConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateInfrastructureConfigurationError {
/// Kind of error that occurred.
pub kind: CreateInfrastructureConfigurationErrorKind,
/// 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 `CreateInfrastructureConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum CreateInfrastructureConfigurationErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>The resource that you are trying to create already exists.</p>
ResourceAlreadyExistsException(crate::error::ResourceAlreadyExistsException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>You have exceeded the number of permitted resources or operations for this service. For service quotas, see <a href="https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder">EC2 Image Builder endpoints and quotas</a>.</p>
ServiceQuotaExceededException(crate::error::ServiceQuotaExceededException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 CreateInfrastructureConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
CreateInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
CreateInfrastructureConfigurationErrorKind::ClientException(_inner) => _inner.fmt(f),
CreateInfrastructureConfigurationErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
CreateInfrastructureConfigurationErrorKind::IdempotentParameterMismatchException(
_inner,
) => _inner.fmt(f),
CreateInfrastructureConfigurationErrorKind::InvalidRequestException(_inner) => {
_inner.fmt(f)
}
CreateInfrastructureConfigurationErrorKind::ResourceAlreadyExistsException(_inner) => {
_inner.fmt(f)
}
CreateInfrastructureConfigurationErrorKind::ResourceInUseException(_inner) => {
_inner.fmt(f)
}
CreateInfrastructureConfigurationErrorKind::ServiceException(_inner) => _inner.fmt(f),
CreateInfrastructureConfigurationErrorKind::ServiceQuotaExceededException(_inner) => {
_inner.fmt(f)
}
CreateInfrastructureConfigurationErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
CreateInfrastructureConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for CreateInfrastructureConfigurationError {
fn code(&self) -> Option<&str> {
CreateInfrastructureConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl CreateInfrastructureConfigurationError {
/// Creates a new `CreateInfrastructureConfigurationError`.
pub fn new(
kind: CreateInfrastructureConfigurationErrorKind,
meta: aws_smithy_types::Error,
) -> Self {
Self { kind, meta }
}
/// Creates the `CreateInfrastructureConfigurationError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: CreateInfrastructureConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `CreateInfrastructureConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: CreateInfrastructureConfigurationErrorKind::Unhandled(err.into()),
}
}
/// 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 `CreateInfrastructureConfigurationErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateInfrastructureConfigurationErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
CreateInfrastructureConfigurationErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `CreateInfrastructureConfigurationErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
CreateInfrastructureConfigurationErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `CreateInfrastructureConfigurationErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
CreateInfrastructureConfigurationErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `CreateInfrastructureConfigurationErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
CreateInfrastructureConfigurationErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `CreateInfrastructureConfigurationErrorKind::ResourceAlreadyExistsException`.
pub fn is_resource_already_exists_exception(&self) -> bool {
matches!(
&self.kind,
CreateInfrastructureConfigurationErrorKind::ResourceAlreadyExistsException(_)
)
}
/// Returns `true` if the error kind is `CreateInfrastructureConfigurationErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
CreateInfrastructureConfigurationErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `CreateInfrastructureConfigurationErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
CreateInfrastructureConfigurationErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `CreateInfrastructureConfigurationErrorKind::ServiceQuotaExceededException`.
pub fn is_service_quota_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
CreateInfrastructureConfigurationErrorKind::ServiceQuotaExceededException(_)
)
}
/// Returns `true` if the error kind is `CreateInfrastructureConfigurationErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
CreateInfrastructureConfigurationErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for CreateInfrastructureConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
CreateInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
CreateInfrastructureConfigurationErrorKind::ClientException(_inner) => Some(_inner),
CreateInfrastructureConfigurationErrorKind::ForbiddenException(_inner) => Some(_inner),
CreateInfrastructureConfigurationErrorKind::IdempotentParameterMismatchException(
_inner,
) => Some(_inner),
CreateInfrastructureConfigurationErrorKind::InvalidRequestException(_inner) => {
Some(_inner)
}
CreateInfrastructureConfigurationErrorKind::ResourceAlreadyExistsException(_inner) => {
Some(_inner)
}
CreateInfrastructureConfigurationErrorKind::ResourceInUseException(_inner) => {
Some(_inner)
}
CreateInfrastructureConfigurationErrorKind::ServiceException(_inner) => Some(_inner),
CreateInfrastructureConfigurationErrorKind::ServiceQuotaExceededException(_inner) => {
Some(_inner)
}
CreateInfrastructureConfigurationErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
CreateInfrastructureConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `DeleteComponent` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteComponentError {
/// Kind of error that occurred.
pub kind: DeleteComponentErrorKind,
/// 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 `DeleteComponent` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteComponentErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>You have attempted to mutate or delete a resource with a dependency that prohibits this action. See the error message for more details.</p>
ResourceDependencyException(crate::error::ResourceDependencyException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 DeleteComponentError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteComponentErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
DeleteComponentErrorKind::ClientException(_inner) => _inner.fmt(f),
DeleteComponentErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
DeleteComponentErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
DeleteComponentErrorKind::ResourceDependencyException(_inner) => _inner.fmt(f),
DeleteComponentErrorKind::ServiceException(_inner) => _inner.fmt(f),
DeleteComponentErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
DeleteComponentErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for DeleteComponentError {
fn code(&self) -> Option<&str> {
DeleteComponentError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteComponentError {
/// Creates a new `DeleteComponentError`.
pub fn new(kind: DeleteComponentErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `DeleteComponentError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteComponentErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `DeleteComponentError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteComponentErrorKind::Unhandled(err.into()),
}
}
/// 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 `DeleteComponentErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteComponentErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `DeleteComponentErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, DeleteComponentErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `DeleteComponentErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, DeleteComponentErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `DeleteComponentErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
DeleteComponentErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `DeleteComponentErrorKind::ResourceDependencyException`.
pub fn is_resource_dependency_exception(&self) -> bool {
matches!(
&self.kind,
DeleteComponentErrorKind::ResourceDependencyException(_)
)
}
/// Returns `true` if the error kind is `DeleteComponentErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, DeleteComponentErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `DeleteComponentErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
DeleteComponentErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for DeleteComponentError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteComponentErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
DeleteComponentErrorKind::ClientException(_inner) => Some(_inner),
DeleteComponentErrorKind::ForbiddenException(_inner) => Some(_inner),
DeleteComponentErrorKind::InvalidRequestException(_inner) => Some(_inner),
DeleteComponentErrorKind::ResourceDependencyException(_inner) => Some(_inner),
DeleteComponentErrorKind::ServiceException(_inner) => Some(_inner),
DeleteComponentErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
DeleteComponentErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `DeleteContainerRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteContainerRecipeError {
/// Kind of error that occurred.
pub kind: DeleteContainerRecipeErrorKind,
/// 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 `DeleteContainerRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteContainerRecipeErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>You have attempted to mutate or delete a resource with a dependency that prohibits this action. See the error message for more details.</p>
ResourceDependencyException(crate::error::ResourceDependencyException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 DeleteContainerRecipeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteContainerRecipeErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
DeleteContainerRecipeErrorKind::ClientException(_inner) => _inner.fmt(f),
DeleteContainerRecipeErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
DeleteContainerRecipeErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
DeleteContainerRecipeErrorKind::ResourceDependencyException(_inner) => _inner.fmt(f),
DeleteContainerRecipeErrorKind::ServiceException(_inner) => _inner.fmt(f),
DeleteContainerRecipeErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
DeleteContainerRecipeErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for DeleteContainerRecipeError {
fn code(&self) -> Option<&str> {
DeleteContainerRecipeError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteContainerRecipeError {
/// Creates a new `DeleteContainerRecipeError`.
pub fn new(kind: DeleteContainerRecipeErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `DeleteContainerRecipeError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteContainerRecipeErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `DeleteContainerRecipeError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteContainerRecipeErrorKind::Unhandled(err.into()),
}
}
/// 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 `DeleteContainerRecipeErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteContainerRecipeErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `DeleteContainerRecipeErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
DeleteContainerRecipeErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `DeleteContainerRecipeErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
DeleteContainerRecipeErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `DeleteContainerRecipeErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
DeleteContainerRecipeErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `DeleteContainerRecipeErrorKind::ResourceDependencyException`.
pub fn is_resource_dependency_exception(&self) -> bool {
matches!(
&self.kind,
DeleteContainerRecipeErrorKind::ResourceDependencyException(_)
)
}
/// Returns `true` if the error kind is `DeleteContainerRecipeErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
DeleteContainerRecipeErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `DeleteContainerRecipeErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
DeleteContainerRecipeErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for DeleteContainerRecipeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteContainerRecipeErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
DeleteContainerRecipeErrorKind::ClientException(_inner) => Some(_inner),
DeleteContainerRecipeErrorKind::ForbiddenException(_inner) => Some(_inner),
DeleteContainerRecipeErrorKind::InvalidRequestException(_inner) => Some(_inner),
DeleteContainerRecipeErrorKind::ResourceDependencyException(_inner) => Some(_inner),
DeleteContainerRecipeErrorKind::ServiceException(_inner) => Some(_inner),
DeleteContainerRecipeErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
DeleteContainerRecipeErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `DeleteDistributionConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteDistributionConfigurationError {
/// Kind of error that occurred.
pub kind: DeleteDistributionConfigurationErrorKind,
/// 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 `DeleteDistributionConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteDistributionConfigurationErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>You have attempted to mutate or delete a resource with a dependency that prohibits this action. See the error message for more details.</p>
ResourceDependencyException(crate::error::ResourceDependencyException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 DeleteDistributionConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteDistributionConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
DeleteDistributionConfigurationErrorKind::ClientException(_inner) => _inner.fmt(f),
DeleteDistributionConfigurationErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
DeleteDistributionConfigurationErrorKind::InvalidRequestException(_inner) => {
_inner.fmt(f)
}
DeleteDistributionConfigurationErrorKind::ResourceDependencyException(_inner) => {
_inner.fmt(f)
}
DeleteDistributionConfigurationErrorKind::ServiceException(_inner) => _inner.fmt(f),
DeleteDistributionConfigurationErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
DeleteDistributionConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for DeleteDistributionConfigurationError {
fn code(&self) -> Option<&str> {
DeleteDistributionConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteDistributionConfigurationError {
/// Creates a new `DeleteDistributionConfigurationError`.
pub fn new(
kind: DeleteDistributionConfigurationErrorKind,
meta: aws_smithy_types::Error,
) -> Self {
Self { kind, meta }
}
/// Creates the `DeleteDistributionConfigurationError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteDistributionConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `DeleteDistributionConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteDistributionConfigurationErrorKind::Unhandled(err.into()),
}
}
/// 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 `DeleteDistributionConfigurationErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteDistributionConfigurationErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `DeleteDistributionConfigurationErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
DeleteDistributionConfigurationErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `DeleteDistributionConfigurationErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
DeleteDistributionConfigurationErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `DeleteDistributionConfigurationErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
DeleteDistributionConfigurationErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `DeleteDistributionConfigurationErrorKind::ResourceDependencyException`.
pub fn is_resource_dependency_exception(&self) -> bool {
matches!(
&self.kind,
DeleteDistributionConfigurationErrorKind::ResourceDependencyException(_)
)
}
/// Returns `true` if the error kind is `DeleteDistributionConfigurationErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
DeleteDistributionConfigurationErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `DeleteDistributionConfigurationErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
DeleteDistributionConfigurationErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for DeleteDistributionConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteDistributionConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
DeleteDistributionConfigurationErrorKind::ClientException(_inner) => Some(_inner),
DeleteDistributionConfigurationErrorKind::ForbiddenException(_inner) => Some(_inner),
DeleteDistributionConfigurationErrorKind::InvalidRequestException(_inner) => {
Some(_inner)
}
DeleteDistributionConfigurationErrorKind::ResourceDependencyException(_inner) => {
Some(_inner)
}
DeleteDistributionConfigurationErrorKind::ServiceException(_inner) => Some(_inner),
DeleteDistributionConfigurationErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
DeleteDistributionConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `DeleteImage` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteImageError {
/// Kind of error that occurred.
pub kind: DeleteImageErrorKind,
/// 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 `DeleteImage` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteImageErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>You have attempted to mutate or delete a resource with a dependency that prohibits this action. See the error message for more details.</p>
ResourceDependencyException(crate::error::ResourceDependencyException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 DeleteImageError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteImageErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
DeleteImageErrorKind::ClientException(_inner) => _inner.fmt(f),
DeleteImageErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
DeleteImageErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
DeleteImageErrorKind::ResourceDependencyException(_inner) => _inner.fmt(f),
DeleteImageErrorKind::ServiceException(_inner) => _inner.fmt(f),
DeleteImageErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
DeleteImageErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for DeleteImageError {
fn code(&self) -> Option<&str> {
DeleteImageError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteImageError {
/// Creates a new `DeleteImageError`.
pub fn new(kind: DeleteImageErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `DeleteImageError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteImageErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `DeleteImageError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteImageErrorKind::Unhandled(err.into()),
}
}
/// 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 `DeleteImageErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImageErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `DeleteImageErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, DeleteImageErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `DeleteImageErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, DeleteImageErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `DeleteImageErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(&self.kind, DeleteImageErrorKind::InvalidRequestException(_))
}
/// Returns `true` if the error kind is `DeleteImageErrorKind::ResourceDependencyException`.
pub fn is_resource_dependency_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImageErrorKind::ResourceDependencyException(_)
)
}
/// Returns `true` if the error kind is `DeleteImageErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, DeleteImageErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `DeleteImageErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImageErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for DeleteImageError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteImageErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
DeleteImageErrorKind::ClientException(_inner) => Some(_inner),
DeleteImageErrorKind::ForbiddenException(_inner) => Some(_inner),
DeleteImageErrorKind::InvalidRequestException(_inner) => Some(_inner),
DeleteImageErrorKind::ResourceDependencyException(_inner) => Some(_inner),
DeleteImageErrorKind::ServiceException(_inner) => Some(_inner),
DeleteImageErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
DeleteImageErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `DeleteImagePipeline` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteImagePipelineError {
/// Kind of error that occurred.
pub kind: DeleteImagePipelineErrorKind,
/// 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 `DeleteImagePipeline` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteImagePipelineErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>You have attempted to mutate or delete a resource with a dependency that prohibits this action. See the error message for more details.</p>
ResourceDependencyException(crate::error::ResourceDependencyException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 DeleteImagePipelineError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteImagePipelineErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
DeleteImagePipelineErrorKind::ClientException(_inner) => _inner.fmt(f),
DeleteImagePipelineErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
DeleteImagePipelineErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
DeleteImagePipelineErrorKind::ResourceDependencyException(_inner) => _inner.fmt(f),
DeleteImagePipelineErrorKind::ServiceException(_inner) => _inner.fmt(f),
DeleteImagePipelineErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
DeleteImagePipelineErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for DeleteImagePipelineError {
fn code(&self) -> Option<&str> {
DeleteImagePipelineError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteImagePipelineError {
/// Creates a new `DeleteImagePipelineError`.
pub fn new(kind: DeleteImagePipelineErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `DeleteImagePipelineError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteImagePipelineErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `DeleteImagePipelineError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteImagePipelineErrorKind::Unhandled(err.into()),
}
}
/// 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 `DeleteImagePipelineErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImagePipelineErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `DeleteImagePipelineErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, DeleteImagePipelineErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `DeleteImagePipelineErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImagePipelineErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `DeleteImagePipelineErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImagePipelineErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `DeleteImagePipelineErrorKind::ResourceDependencyException`.
pub fn is_resource_dependency_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImagePipelineErrorKind::ResourceDependencyException(_)
)
}
/// Returns `true` if the error kind is `DeleteImagePipelineErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImagePipelineErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `DeleteImagePipelineErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImagePipelineErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for DeleteImagePipelineError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteImagePipelineErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
DeleteImagePipelineErrorKind::ClientException(_inner) => Some(_inner),
DeleteImagePipelineErrorKind::ForbiddenException(_inner) => Some(_inner),
DeleteImagePipelineErrorKind::InvalidRequestException(_inner) => Some(_inner),
DeleteImagePipelineErrorKind::ResourceDependencyException(_inner) => Some(_inner),
DeleteImagePipelineErrorKind::ServiceException(_inner) => Some(_inner),
DeleteImagePipelineErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
DeleteImagePipelineErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `DeleteImageRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteImageRecipeError {
/// Kind of error that occurred.
pub kind: DeleteImageRecipeErrorKind,
/// 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 `DeleteImageRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteImageRecipeErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>You have attempted to mutate or delete a resource with a dependency that prohibits this action. See the error message for more details.</p>
ResourceDependencyException(crate::error::ResourceDependencyException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 DeleteImageRecipeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteImageRecipeErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
DeleteImageRecipeErrorKind::ClientException(_inner) => _inner.fmt(f),
DeleteImageRecipeErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
DeleteImageRecipeErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
DeleteImageRecipeErrorKind::ResourceDependencyException(_inner) => _inner.fmt(f),
DeleteImageRecipeErrorKind::ServiceException(_inner) => _inner.fmt(f),
DeleteImageRecipeErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
DeleteImageRecipeErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for DeleteImageRecipeError {
fn code(&self) -> Option<&str> {
DeleteImageRecipeError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteImageRecipeError {
/// Creates a new `DeleteImageRecipeError`.
pub fn new(kind: DeleteImageRecipeErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `DeleteImageRecipeError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteImageRecipeErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `DeleteImageRecipeError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteImageRecipeErrorKind::Unhandled(err.into()),
}
}
/// 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 `DeleteImageRecipeErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImageRecipeErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `DeleteImageRecipeErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, DeleteImageRecipeErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `DeleteImageRecipeErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImageRecipeErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `DeleteImageRecipeErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImageRecipeErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `DeleteImageRecipeErrorKind::ResourceDependencyException`.
pub fn is_resource_dependency_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImageRecipeErrorKind::ResourceDependencyException(_)
)
}
/// Returns `true` if the error kind is `DeleteImageRecipeErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, DeleteImageRecipeErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `DeleteImageRecipeErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
DeleteImageRecipeErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for DeleteImageRecipeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteImageRecipeErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
DeleteImageRecipeErrorKind::ClientException(_inner) => Some(_inner),
DeleteImageRecipeErrorKind::ForbiddenException(_inner) => Some(_inner),
DeleteImageRecipeErrorKind::InvalidRequestException(_inner) => Some(_inner),
DeleteImageRecipeErrorKind::ResourceDependencyException(_inner) => Some(_inner),
DeleteImageRecipeErrorKind::ServiceException(_inner) => Some(_inner),
DeleteImageRecipeErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
DeleteImageRecipeErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `DeleteInfrastructureConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DeleteInfrastructureConfigurationError {
/// Kind of error that occurred.
pub kind: DeleteInfrastructureConfigurationErrorKind,
/// 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 `DeleteInfrastructureConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DeleteInfrastructureConfigurationErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>You have attempted to mutate or delete a resource with a dependency that prohibits this action. See the error message for more details.</p>
ResourceDependencyException(crate::error::ResourceDependencyException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 DeleteInfrastructureConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
DeleteInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
DeleteInfrastructureConfigurationErrorKind::ClientException(_inner) => _inner.fmt(f),
DeleteInfrastructureConfigurationErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
DeleteInfrastructureConfigurationErrorKind::InvalidRequestException(_inner) => {
_inner.fmt(f)
}
DeleteInfrastructureConfigurationErrorKind::ResourceDependencyException(_inner) => {
_inner.fmt(f)
}
DeleteInfrastructureConfigurationErrorKind::ServiceException(_inner) => _inner.fmt(f),
DeleteInfrastructureConfigurationErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
DeleteInfrastructureConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for DeleteInfrastructureConfigurationError {
fn code(&self) -> Option<&str> {
DeleteInfrastructureConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl DeleteInfrastructureConfigurationError {
/// Creates a new `DeleteInfrastructureConfigurationError`.
pub fn new(
kind: DeleteInfrastructureConfigurationErrorKind,
meta: aws_smithy_types::Error,
) -> Self {
Self { kind, meta }
}
/// Creates the `DeleteInfrastructureConfigurationError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DeleteInfrastructureConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `DeleteInfrastructureConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DeleteInfrastructureConfigurationErrorKind::Unhandled(err.into()),
}
}
/// 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 `DeleteInfrastructureConfigurationErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
DeleteInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `DeleteInfrastructureConfigurationErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
DeleteInfrastructureConfigurationErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `DeleteInfrastructureConfigurationErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
DeleteInfrastructureConfigurationErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `DeleteInfrastructureConfigurationErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
DeleteInfrastructureConfigurationErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `DeleteInfrastructureConfigurationErrorKind::ResourceDependencyException`.
pub fn is_resource_dependency_exception(&self) -> bool {
matches!(
&self.kind,
DeleteInfrastructureConfigurationErrorKind::ResourceDependencyException(_)
)
}
/// Returns `true` if the error kind is `DeleteInfrastructureConfigurationErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
DeleteInfrastructureConfigurationErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `DeleteInfrastructureConfigurationErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
DeleteInfrastructureConfigurationErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for DeleteInfrastructureConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DeleteInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
DeleteInfrastructureConfigurationErrorKind::ClientException(_inner) => Some(_inner),
DeleteInfrastructureConfigurationErrorKind::ForbiddenException(_inner) => Some(_inner),
DeleteInfrastructureConfigurationErrorKind::InvalidRequestException(_inner) => {
Some(_inner)
}
DeleteInfrastructureConfigurationErrorKind::ResourceDependencyException(_inner) => {
Some(_inner)
}
DeleteInfrastructureConfigurationErrorKind::ServiceException(_inner) => Some(_inner),
DeleteInfrastructureConfigurationErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
DeleteInfrastructureConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetComponent` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetComponentError {
/// Kind of error that occurred.
pub kind: GetComponentErrorKind,
/// 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 `GetComponent` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetComponentErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 GetComponentError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetComponentErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
GetComponentErrorKind::ClientException(_inner) => _inner.fmt(f),
GetComponentErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
GetComponentErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
GetComponentErrorKind::ServiceException(_inner) => _inner.fmt(f),
GetComponentErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
GetComponentErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetComponentError {
fn code(&self) -> Option<&str> {
GetComponentError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetComponentError {
/// Creates a new `GetComponentError`.
pub fn new(kind: GetComponentErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `GetComponentError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetComponentErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetComponentError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetComponentErrorKind::Unhandled(err.into()),
}
}
/// 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 `GetComponentErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetComponentErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `GetComponentErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, GetComponentErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `GetComponentErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, GetComponentErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `GetComponentErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
GetComponentErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `GetComponentErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, GetComponentErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `GetComponentErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
GetComponentErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for GetComponentError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetComponentErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
GetComponentErrorKind::ClientException(_inner) => Some(_inner),
GetComponentErrorKind::ForbiddenException(_inner) => Some(_inner),
GetComponentErrorKind::InvalidRequestException(_inner) => Some(_inner),
GetComponentErrorKind::ServiceException(_inner) => Some(_inner),
GetComponentErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
GetComponentErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetComponentPolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetComponentPolicyError {
/// Kind of error that occurred.
pub kind: GetComponentPolicyErrorKind,
/// 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 `GetComponentPolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetComponentPolicyErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 GetComponentPolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetComponentPolicyErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
GetComponentPolicyErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
GetComponentPolicyErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
GetComponentPolicyErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
GetComponentPolicyErrorKind::ServiceException(_inner) => _inner.fmt(f),
GetComponentPolicyErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
GetComponentPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetComponentPolicyError {
fn code(&self) -> Option<&str> {
GetComponentPolicyError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetComponentPolicyError {
/// Creates a new `GetComponentPolicyError`.
pub fn new(kind: GetComponentPolicyErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `GetComponentPolicyError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetComponentPolicyErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetComponentPolicyError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetComponentPolicyErrorKind::Unhandled(err.into()),
}
}
/// 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 `GetComponentPolicyErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetComponentPolicyErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `GetComponentPolicyErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
GetComponentPolicyErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `GetComponentPolicyErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
GetComponentPolicyErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `GetComponentPolicyErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetComponentPolicyErrorKind::ResourceNotFoundException(_)
)
}
/// Returns `true` if the error kind is `GetComponentPolicyErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, GetComponentPolicyErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `GetComponentPolicyErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
GetComponentPolicyErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for GetComponentPolicyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetComponentPolicyErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
GetComponentPolicyErrorKind::ForbiddenException(_inner) => Some(_inner),
GetComponentPolicyErrorKind::InvalidRequestException(_inner) => Some(_inner),
GetComponentPolicyErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
GetComponentPolicyErrorKind::ServiceException(_inner) => Some(_inner),
GetComponentPolicyErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
GetComponentPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetContainerRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetContainerRecipeError {
/// Kind of error that occurred.
pub kind: GetContainerRecipeErrorKind,
/// 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 `GetContainerRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetContainerRecipeErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 GetContainerRecipeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetContainerRecipeErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
GetContainerRecipeErrorKind::ClientException(_inner) => _inner.fmt(f),
GetContainerRecipeErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
GetContainerRecipeErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
GetContainerRecipeErrorKind::ServiceException(_inner) => _inner.fmt(f),
GetContainerRecipeErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
GetContainerRecipeErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetContainerRecipeError {
fn code(&self) -> Option<&str> {
GetContainerRecipeError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetContainerRecipeError {
/// Creates a new `GetContainerRecipeError`.
pub fn new(kind: GetContainerRecipeErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `GetContainerRecipeError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetContainerRecipeErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetContainerRecipeError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetContainerRecipeErrorKind::Unhandled(err.into()),
}
}
/// 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 `GetContainerRecipeErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetContainerRecipeErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `GetContainerRecipeErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, GetContainerRecipeErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `GetContainerRecipeErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
GetContainerRecipeErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `GetContainerRecipeErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
GetContainerRecipeErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `GetContainerRecipeErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, GetContainerRecipeErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `GetContainerRecipeErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
GetContainerRecipeErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for GetContainerRecipeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetContainerRecipeErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
GetContainerRecipeErrorKind::ClientException(_inner) => Some(_inner),
GetContainerRecipeErrorKind::ForbiddenException(_inner) => Some(_inner),
GetContainerRecipeErrorKind::InvalidRequestException(_inner) => Some(_inner),
GetContainerRecipeErrorKind::ServiceException(_inner) => Some(_inner),
GetContainerRecipeErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
GetContainerRecipeErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetContainerRecipePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetContainerRecipePolicyError {
/// Kind of error that occurred.
pub kind: GetContainerRecipePolicyErrorKind,
/// 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 `GetContainerRecipePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetContainerRecipePolicyErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 GetContainerRecipePolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetContainerRecipePolicyErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
GetContainerRecipePolicyErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
GetContainerRecipePolicyErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
GetContainerRecipePolicyErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
GetContainerRecipePolicyErrorKind::ServiceException(_inner) => _inner.fmt(f),
GetContainerRecipePolicyErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
GetContainerRecipePolicyErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetContainerRecipePolicyError {
fn code(&self) -> Option<&str> {
GetContainerRecipePolicyError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetContainerRecipePolicyError {
/// Creates a new `GetContainerRecipePolicyError`.
pub fn new(kind: GetContainerRecipePolicyErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `GetContainerRecipePolicyError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetContainerRecipePolicyErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetContainerRecipePolicyError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetContainerRecipePolicyErrorKind::Unhandled(err.into()),
}
}
/// 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 `GetContainerRecipePolicyErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetContainerRecipePolicyErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `GetContainerRecipePolicyErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
GetContainerRecipePolicyErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `GetContainerRecipePolicyErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
GetContainerRecipePolicyErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `GetContainerRecipePolicyErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetContainerRecipePolicyErrorKind::ResourceNotFoundException(_)
)
}
/// Returns `true` if the error kind is `GetContainerRecipePolicyErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
GetContainerRecipePolicyErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `GetContainerRecipePolicyErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
GetContainerRecipePolicyErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for GetContainerRecipePolicyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetContainerRecipePolicyErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
GetContainerRecipePolicyErrorKind::ForbiddenException(_inner) => Some(_inner),
GetContainerRecipePolicyErrorKind::InvalidRequestException(_inner) => Some(_inner),
GetContainerRecipePolicyErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
GetContainerRecipePolicyErrorKind::ServiceException(_inner) => Some(_inner),
GetContainerRecipePolicyErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
GetContainerRecipePolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetDistributionConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetDistributionConfigurationError {
/// Kind of error that occurred.
pub kind: GetDistributionConfigurationErrorKind,
/// 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 `GetDistributionConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetDistributionConfigurationErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 GetDistributionConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetDistributionConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
GetDistributionConfigurationErrorKind::ClientException(_inner) => _inner.fmt(f),
GetDistributionConfigurationErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
GetDistributionConfigurationErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
GetDistributionConfigurationErrorKind::ServiceException(_inner) => _inner.fmt(f),
GetDistributionConfigurationErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
GetDistributionConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetDistributionConfigurationError {
fn code(&self) -> Option<&str> {
GetDistributionConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetDistributionConfigurationError {
/// Creates a new `GetDistributionConfigurationError`.
pub fn new(kind: GetDistributionConfigurationErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `GetDistributionConfigurationError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetDistributionConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetDistributionConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetDistributionConfigurationErrorKind::Unhandled(err.into()),
}
}
/// 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 `GetDistributionConfigurationErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetDistributionConfigurationErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `GetDistributionConfigurationErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
GetDistributionConfigurationErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `GetDistributionConfigurationErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
GetDistributionConfigurationErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `GetDistributionConfigurationErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
GetDistributionConfigurationErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `GetDistributionConfigurationErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
GetDistributionConfigurationErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `GetDistributionConfigurationErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
GetDistributionConfigurationErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for GetDistributionConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetDistributionConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
GetDistributionConfigurationErrorKind::ClientException(_inner) => Some(_inner),
GetDistributionConfigurationErrorKind::ForbiddenException(_inner) => Some(_inner),
GetDistributionConfigurationErrorKind::InvalidRequestException(_inner) => Some(_inner),
GetDistributionConfigurationErrorKind::ServiceException(_inner) => Some(_inner),
GetDistributionConfigurationErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
GetDistributionConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetImage` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetImageError {
/// Kind of error that occurred.
pub kind: GetImageErrorKind,
/// 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 `GetImage` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetImageErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 GetImageError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetImageErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
GetImageErrorKind::ClientException(_inner) => _inner.fmt(f),
GetImageErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
GetImageErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
GetImageErrorKind::ServiceException(_inner) => _inner.fmt(f),
GetImageErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
GetImageErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetImageError {
fn code(&self) -> Option<&str> {
GetImageError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetImageError {
/// Creates a new `GetImageError`.
pub fn new(kind: GetImageErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `GetImageError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetImageErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetImageError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetImageErrorKind::Unhandled(err.into()),
}
}
/// 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 `GetImageErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetImageErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `GetImageErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, GetImageErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `GetImageErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, GetImageErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `GetImageErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(&self.kind, GetImageErrorKind::InvalidRequestException(_))
}
/// Returns `true` if the error kind is `GetImageErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, GetImageErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `GetImageErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
GetImageErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for GetImageError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetImageErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
GetImageErrorKind::ClientException(_inner) => Some(_inner),
GetImageErrorKind::ForbiddenException(_inner) => Some(_inner),
GetImageErrorKind::InvalidRequestException(_inner) => Some(_inner),
GetImageErrorKind::ServiceException(_inner) => Some(_inner),
GetImageErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
GetImageErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetImagePipeline` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetImagePipelineError {
/// Kind of error that occurred.
pub kind: GetImagePipelineErrorKind,
/// 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 `GetImagePipeline` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetImagePipelineErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 GetImagePipelineError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetImagePipelineErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
GetImagePipelineErrorKind::ClientException(_inner) => _inner.fmt(f),
GetImagePipelineErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
GetImagePipelineErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
GetImagePipelineErrorKind::ServiceException(_inner) => _inner.fmt(f),
GetImagePipelineErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
GetImagePipelineErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetImagePipelineError {
fn code(&self) -> Option<&str> {
GetImagePipelineError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetImagePipelineError {
/// Creates a new `GetImagePipelineError`.
pub fn new(kind: GetImagePipelineErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `GetImagePipelineError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetImagePipelineErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetImagePipelineError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetImagePipelineErrorKind::Unhandled(err.into()),
}
}
/// 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 `GetImagePipelineErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetImagePipelineErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `GetImagePipelineErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, GetImagePipelineErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `GetImagePipelineErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, GetImagePipelineErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `GetImagePipelineErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
GetImagePipelineErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `GetImagePipelineErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, GetImagePipelineErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `GetImagePipelineErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
GetImagePipelineErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for GetImagePipelineError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetImagePipelineErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
GetImagePipelineErrorKind::ClientException(_inner) => Some(_inner),
GetImagePipelineErrorKind::ForbiddenException(_inner) => Some(_inner),
GetImagePipelineErrorKind::InvalidRequestException(_inner) => Some(_inner),
GetImagePipelineErrorKind::ServiceException(_inner) => Some(_inner),
GetImagePipelineErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
GetImagePipelineErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetImagePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetImagePolicyError {
/// Kind of error that occurred.
pub kind: GetImagePolicyErrorKind,
/// 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 `GetImagePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetImagePolicyErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 GetImagePolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetImagePolicyErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
GetImagePolicyErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
GetImagePolicyErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
GetImagePolicyErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
GetImagePolicyErrorKind::ServiceException(_inner) => _inner.fmt(f),
GetImagePolicyErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
GetImagePolicyErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetImagePolicyError {
fn code(&self) -> Option<&str> {
GetImagePolicyError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetImagePolicyError {
/// Creates a new `GetImagePolicyError`.
pub fn new(kind: GetImagePolicyErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `GetImagePolicyError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetImagePolicyErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetImagePolicyError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetImagePolicyErrorKind::Unhandled(err.into()),
}
}
/// 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 `GetImagePolicyErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetImagePolicyErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `GetImagePolicyErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, GetImagePolicyErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `GetImagePolicyErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
GetImagePolicyErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `GetImagePolicyErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetImagePolicyErrorKind::ResourceNotFoundException(_)
)
}
/// Returns `true` if the error kind is `GetImagePolicyErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, GetImagePolicyErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `GetImagePolicyErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
GetImagePolicyErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for GetImagePolicyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetImagePolicyErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
GetImagePolicyErrorKind::ForbiddenException(_inner) => Some(_inner),
GetImagePolicyErrorKind::InvalidRequestException(_inner) => Some(_inner),
GetImagePolicyErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
GetImagePolicyErrorKind::ServiceException(_inner) => Some(_inner),
GetImagePolicyErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
GetImagePolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetImageRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetImageRecipeError {
/// Kind of error that occurred.
pub kind: GetImageRecipeErrorKind,
/// 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 `GetImageRecipe` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetImageRecipeErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 GetImageRecipeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetImageRecipeErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
GetImageRecipeErrorKind::ClientException(_inner) => _inner.fmt(f),
GetImageRecipeErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
GetImageRecipeErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
GetImageRecipeErrorKind::ServiceException(_inner) => _inner.fmt(f),
GetImageRecipeErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
GetImageRecipeErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetImageRecipeError {
fn code(&self) -> Option<&str> {
GetImageRecipeError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetImageRecipeError {
/// Creates a new `GetImageRecipeError`.
pub fn new(kind: GetImageRecipeErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `GetImageRecipeError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetImageRecipeErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetImageRecipeError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetImageRecipeErrorKind::Unhandled(err.into()),
}
}
/// 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 `GetImageRecipeErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetImageRecipeErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `GetImageRecipeErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, GetImageRecipeErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `GetImageRecipeErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, GetImageRecipeErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `GetImageRecipeErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
GetImageRecipeErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `GetImageRecipeErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, GetImageRecipeErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `GetImageRecipeErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
GetImageRecipeErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for GetImageRecipeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetImageRecipeErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
GetImageRecipeErrorKind::ClientException(_inner) => Some(_inner),
GetImageRecipeErrorKind::ForbiddenException(_inner) => Some(_inner),
GetImageRecipeErrorKind::InvalidRequestException(_inner) => Some(_inner),
GetImageRecipeErrorKind::ServiceException(_inner) => Some(_inner),
GetImageRecipeErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
GetImageRecipeErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetImageRecipePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetImageRecipePolicyError {
/// Kind of error that occurred.
pub kind: GetImageRecipePolicyErrorKind,
/// 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 `GetImageRecipePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetImageRecipePolicyErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 GetImageRecipePolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetImageRecipePolicyErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
GetImageRecipePolicyErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
GetImageRecipePolicyErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
GetImageRecipePolicyErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
GetImageRecipePolicyErrorKind::ServiceException(_inner) => _inner.fmt(f),
GetImageRecipePolicyErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
GetImageRecipePolicyErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetImageRecipePolicyError {
fn code(&self) -> Option<&str> {
GetImageRecipePolicyError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetImageRecipePolicyError {
/// Creates a new `GetImageRecipePolicyError`.
pub fn new(kind: GetImageRecipePolicyErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `GetImageRecipePolicyError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetImageRecipePolicyErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetImageRecipePolicyError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetImageRecipePolicyErrorKind::Unhandled(err.into()),
}
}
/// 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 `GetImageRecipePolicyErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetImageRecipePolicyErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `GetImageRecipePolicyErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
GetImageRecipePolicyErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `GetImageRecipePolicyErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
GetImageRecipePolicyErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `GetImageRecipePolicyErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetImageRecipePolicyErrorKind::ResourceNotFoundException(_)
)
}
/// Returns `true` if the error kind is `GetImageRecipePolicyErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
GetImageRecipePolicyErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `GetImageRecipePolicyErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
GetImageRecipePolicyErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for GetImageRecipePolicyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetImageRecipePolicyErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
GetImageRecipePolicyErrorKind::ForbiddenException(_inner) => Some(_inner),
GetImageRecipePolicyErrorKind::InvalidRequestException(_inner) => Some(_inner),
GetImageRecipePolicyErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
GetImageRecipePolicyErrorKind::ServiceException(_inner) => Some(_inner),
GetImageRecipePolicyErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
GetImageRecipePolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetInfrastructureConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetInfrastructureConfigurationError {
/// Kind of error that occurred.
pub kind: GetInfrastructureConfigurationErrorKind,
/// 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 `GetInfrastructureConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetInfrastructureConfigurationErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 GetInfrastructureConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
GetInfrastructureConfigurationErrorKind::ClientException(_inner) => _inner.fmt(f),
GetInfrastructureConfigurationErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
GetInfrastructureConfigurationErrorKind::InvalidRequestException(_inner) => {
_inner.fmt(f)
}
GetInfrastructureConfigurationErrorKind::ServiceException(_inner) => _inner.fmt(f),
GetInfrastructureConfigurationErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
GetInfrastructureConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetInfrastructureConfigurationError {
fn code(&self) -> Option<&str> {
GetInfrastructureConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetInfrastructureConfigurationError {
/// Creates a new `GetInfrastructureConfigurationError`.
pub fn new(
kind: GetInfrastructureConfigurationErrorKind,
meta: aws_smithy_types::Error,
) -> Self {
Self { kind, meta }
}
/// Creates the `GetInfrastructureConfigurationError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetInfrastructureConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetInfrastructureConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetInfrastructureConfigurationErrorKind::Unhandled(err.into()),
}
}
/// 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 `GetInfrastructureConfigurationErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
GetInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `GetInfrastructureConfigurationErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
GetInfrastructureConfigurationErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `GetInfrastructureConfigurationErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
GetInfrastructureConfigurationErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `GetInfrastructureConfigurationErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
GetInfrastructureConfigurationErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `GetInfrastructureConfigurationErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
GetInfrastructureConfigurationErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `GetInfrastructureConfigurationErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
GetInfrastructureConfigurationErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for GetInfrastructureConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
GetInfrastructureConfigurationErrorKind::ClientException(_inner) => Some(_inner),
GetInfrastructureConfigurationErrorKind::ForbiddenException(_inner) => Some(_inner),
GetInfrastructureConfigurationErrorKind::InvalidRequestException(_inner) => {
Some(_inner)
}
GetInfrastructureConfigurationErrorKind::ServiceException(_inner) => Some(_inner),
GetInfrastructureConfigurationErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
GetInfrastructureConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ImportComponent` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ImportComponentError {
/// Kind of error that occurred.
pub kind: ImportComponentErrorKind,
/// 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 `ImportComponent` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ImportComponentErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have specified two or more mutually exclusive parameters. Review the error message for details.</p>
InvalidParameterCombinationException(crate::error::InvalidParameterCombinationException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>Your version number is out of bounds or does not follow the required syntax.</p>
InvalidVersionNumberException(crate::error::InvalidVersionNumberException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ImportComponentError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ImportComponentErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
ImportComponentErrorKind::ClientException(_inner) => _inner.fmt(f),
ImportComponentErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ImportComponentErrorKind::IdempotentParameterMismatchException(_inner) => _inner.fmt(f),
ImportComponentErrorKind::InvalidParameterCombinationException(_inner) => _inner.fmt(f),
ImportComponentErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ImportComponentErrorKind::InvalidVersionNumberException(_inner) => _inner.fmt(f),
ImportComponentErrorKind::ResourceInUseException(_inner) => _inner.fmt(f),
ImportComponentErrorKind::ServiceException(_inner) => _inner.fmt(f),
ImportComponentErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
ImportComponentErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ImportComponentError {
fn code(&self) -> Option<&str> {
ImportComponentError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ImportComponentError {
/// Creates a new `ImportComponentError`.
pub fn new(kind: ImportComponentErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ImportComponentError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ImportComponentErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ImportComponentError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ImportComponentErrorKind::Unhandled(err.into()),
}
}
/// 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 `ImportComponentErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ImportComponentErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ImportComponentErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, ImportComponentErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `ImportComponentErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, ImportComponentErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `ImportComponentErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
ImportComponentErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `ImportComponentErrorKind::InvalidParameterCombinationException`.
pub fn is_invalid_parameter_combination_exception(&self) -> bool {
matches!(
&self.kind,
ImportComponentErrorKind::InvalidParameterCombinationException(_)
)
}
/// Returns `true` if the error kind is `ImportComponentErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ImportComponentErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ImportComponentErrorKind::InvalidVersionNumberException`.
pub fn is_invalid_version_number_exception(&self) -> bool {
matches!(
&self.kind,
ImportComponentErrorKind::InvalidVersionNumberException(_)
)
}
/// Returns `true` if the error kind is `ImportComponentErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
ImportComponentErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `ImportComponentErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, ImportComponentErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `ImportComponentErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ImportComponentErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ImportComponentError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ImportComponentErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
ImportComponentErrorKind::ClientException(_inner) => Some(_inner),
ImportComponentErrorKind::ForbiddenException(_inner) => Some(_inner),
ImportComponentErrorKind::IdempotentParameterMismatchException(_inner) => Some(_inner),
ImportComponentErrorKind::InvalidParameterCombinationException(_inner) => Some(_inner),
ImportComponentErrorKind::InvalidRequestException(_inner) => Some(_inner),
ImportComponentErrorKind::InvalidVersionNumberException(_inner) => Some(_inner),
ImportComponentErrorKind::ResourceInUseException(_inner) => Some(_inner),
ImportComponentErrorKind::ServiceException(_inner) => Some(_inner),
ImportComponentErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
ImportComponentErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ImportVmImage` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ImportVmImageError {
/// Kind of error that occurred.
pub kind: ImportVmImageErrorKind,
/// 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 `ImportVmImage` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ImportVmImageErrorKind {
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ImportVmImageError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ImportVmImageErrorKind::ClientException(_inner) => _inner.fmt(f),
ImportVmImageErrorKind::ServiceException(_inner) => _inner.fmt(f),
ImportVmImageErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
ImportVmImageErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ImportVmImageError {
fn code(&self) -> Option<&str> {
ImportVmImageError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ImportVmImageError {
/// Creates a new `ImportVmImageError`.
pub fn new(kind: ImportVmImageErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ImportVmImageError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ImportVmImageErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ImportVmImageError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ImportVmImageErrorKind::Unhandled(err.into()),
}
}
/// 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 `ImportVmImageErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, ImportVmImageErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `ImportVmImageErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, ImportVmImageErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `ImportVmImageErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ImportVmImageErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ImportVmImageError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ImportVmImageErrorKind::ClientException(_inner) => Some(_inner),
ImportVmImageErrorKind::ServiceException(_inner) => Some(_inner),
ImportVmImageErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
ImportVmImageErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListComponentBuildVersions` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListComponentBuildVersionsError {
/// Kind of error that occurred.
pub kind: ListComponentBuildVersionsErrorKind,
/// 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 `ListComponentBuildVersions` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListComponentBuildVersionsErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have provided an invalid pagination token in your request.</p>
InvalidPaginationTokenException(crate::error::InvalidPaginationTokenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ListComponentBuildVersionsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListComponentBuildVersionsErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
ListComponentBuildVersionsErrorKind::ClientException(_inner) => _inner.fmt(f),
ListComponentBuildVersionsErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ListComponentBuildVersionsErrorKind::InvalidPaginationTokenException(_inner) => {
_inner.fmt(f)
}
ListComponentBuildVersionsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ListComponentBuildVersionsErrorKind::ServiceException(_inner) => _inner.fmt(f),
ListComponentBuildVersionsErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
ListComponentBuildVersionsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListComponentBuildVersionsError {
fn code(&self) -> Option<&str> {
ListComponentBuildVersionsError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListComponentBuildVersionsError {
/// Creates a new `ListComponentBuildVersionsError`.
pub fn new(kind: ListComponentBuildVersionsErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListComponentBuildVersionsError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListComponentBuildVersionsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListComponentBuildVersionsError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListComponentBuildVersionsErrorKind::Unhandled(err.into()),
}
}
/// 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 `ListComponentBuildVersionsErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListComponentBuildVersionsErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ListComponentBuildVersionsErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
ListComponentBuildVersionsErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `ListComponentBuildVersionsErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
ListComponentBuildVersionsErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `ListComponentBuildVersionsErrorKind::InvalidPaginationTokenException`.
pub fn is_invalid_pagination_token_exception(&self) -> bool {
matches!(
&self.kind,
ListComponentBuildVersionsErrorKind::InvalidPaginationTokenException(_)
)
}
/// Returns `true` if the error kind is `ListComponentBuildVersionsErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ListComponentBuildVersionsErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ListComponentBuildVersionsErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
ListComponentBuildVersionsErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `ListComponentBuildVersionsErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ListComponentBuildVersionsErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ListComponentBuildVersionsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListComponentBuildVersionsErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
ListComponentBuildVersionsErrorKind::ClientException(_inner) => Some(_inner),
ListComponentBuildVersionsErrorKind::ForbiddenException(_inner) => Some(_inner),
ListComponentBuildVersionsErrorKind::InvalidPaginationTokenException(_inner) => {
Some(_inner)
}
ListComponentBuildVersionsErrorKind::InvalidRequestException(_inner) => Some(_inner),
ListComponentBuildVersionsErrorKind::ServiceException(_inner) => Some(_inner),
ListComponentBuildVersionsErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
ListComponentBuildVersionsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListComponents` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListComponentsError {
/// Kind of error that occurred.
pub kind: ListComponentsErrorKind,
/// 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 `ListComponents` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListComponentsErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have provided an invalid pagination token in your request.</p>
InvalidPaginationTokenException(crate::error::InvalidPaginationTokenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ListComponentsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListComponentsErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
ListComponentsErrorKind::ClientException(_inner) => _inner.fmt(f),
ListComponentsErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ListComponentsErrorKind::InvalidPaginationTokenException(_inner) => _inner.fmt(f),
ListComponentsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ListComponentsErrorKind::ServiceException(_inner) => _inner.fmt(f),
ListComponentsErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
ListComponentsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListComponentsError {
fn code(&self) -> Option<&str> {
ListComponentsError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListComponentsError {
/// Creates a new `ListComponentsError`.
pub fn new(kind: ListComponentsErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListComponentsError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListComponentsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListComponentsError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListComponentsErrorKind::Unhandled(err.into()),
}
}
/// 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 `ListComponentsErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListComponentsErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ListComponentsErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, ListComponentsErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `ListComponentsErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, ListComponentsErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `ListComponentsErrorKind::InvalidPaginationTokenException`.
pub fn is_invalid_pagination_token_exception(&self) -> bool {
matches!(
&self.kind,
ListComponentsErrorKind::InvalidPaginationTokenException(_)
)
}
/// Returns `true` if the error kind is `ListComponentsErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ListComponentsErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ListComponentsErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, ListComponentsErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `ListComponentsErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ListComponentsErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ListComponentsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListComponentsErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
ListComponentsErrorKind::ClientException(_inner) => Some(_inner),
ListComponentsErrorKind::ForbiddenException(_inner) => Some(_inner),
ListComponentsErrorKind::InvalidPaginationTokenException(_inner) => Some(_inner),
ListComponentsErrorKind::InvalidRequestException(_inner) => Some(_inner),
ListComponentsErrorKind::ServiceException(_inner) => Some(_inner),
ListComponentsErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
ListComponentsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListContainerRecipes` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListContainerRecipesError {
/// Kind of error that occurred.
pub kind: ListContainerRecipesErrorKind,
/// 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 `ListContainerRecipes` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListContainerRecipesErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have provided an invalid pagination token in your request.</p>
InvalidPaginationTokenException(crate::error::InvalidPaginationTokenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ListContainerRecipesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListContainerRecipesErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
ListContainerRecipesErrorKind::ClientException(_inner) => _inner.fmt(f),
ListContainerRecipesErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ListContainerRecipesErrorKind::InvalidPaginationTokenException(_inner) => _inner.fmt(f),
ListContainerRecipesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ListContainerRecipesErrorKind::ServiceException(_inner) => _inner.fmt(f),
ListContainerRecipesErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
ListContainerRecipesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListContainerRecipesError {
fn code(&self) -> Option<&str> {
ListContainerRecipesError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListContainerRecipesError {
/// Creates a new `ListContainerRecipesError`.
pub fn new(kind: ListContainerRecipesErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListContainerRecipesError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListContainerRecipesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListContainerRecipesError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListContainerRecipesErrorKind::Unhandled(err.into()),
}
}
/// 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 `ListContainerRecipesErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListContainerRecipesErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ListContainerRecipesErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
ListContainerRecipesErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `ListContainerRecipesErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
ListContainerRecipesErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `ListContainerRecipesErrorKind::InvalidPaginationTokenException`.
pub fn is_invalid_pagination_token_exception(&self) -> bool {
matches!(
&self.kind,
ListContainerRecipesErrorKind::InvalidPaginationTokenException(_)
)
}
/// Returns `true` if the error kind is `ListContainerRecipesErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ListContainerRecipesErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ListContainerRecipesErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
ListContainerRecipesErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `ListContainerRecipesErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ListContainerRecipesErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ListContainerRecipesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListContainerRecipesErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
ListContainerRecipesErrorKind::ClientException(_inner) => Some(_inner),
ListContainerRecipesErrorKind::ForbiddenException(_inner) => Some(_inner),
ListContainerRecipesErrorKind::InvalidPaginationTokenException(_inner) => Some(_inner),
ListContainerRecipesErrorKind::InvalidRequestException(_inner) => Some(_inner),
ListContainerRecipesErrorKind::ServiceException(_inner) => Some(_inner),
ListContainerRecipesErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
ListContainerRecipesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListDistributionConfigurations` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListDistributionConfigurationsError {
/// Kind of error that occurred.
pub kind: ListDistributionConfigurationsErrorKind,
/// 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 `ListDistributionConfigurations` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListDistributionConfigurationsErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have provided an invalid pagination token in your request.</p>
InvalidPaginationTokenException(crate::error::InvalidPaginationTokenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ListDistributionConfigurationsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListDistributionConfigurationsErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
ListDistributionConfigurationsErrorKind::ClientException(_inner) => _inner.fmt(f),
ListDistributionConfigurationsErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ListDistributionConfigurationsErrorKind::InvalidPaginationTokenException(_inner) => {
_inner.fmt(f)
}
ListDistributionConfigurationsErrorKind::InvalidRequestException(_inner) => {
_inner.fmt(f)
}
ListDistributionConfigurationsErrorKind::ServiceException(_inner) => _inner.fmt(f),
ListDistributionConfigurationsErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
ListDistributionConfigurationsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListDistributionConfigurationsError {
fn code(&self) -> Option<&str> {
ListDistributionConfigurationsError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListDistributionConfigurationsError {
/// Creates a new `ListDistributionConfigurationsError`.
pub fn new(
kind: ListDistributionConfigurationsErrorKind,
meta: aws_smithy_types::Error,
) -> Self {
Self { kind, meta }
}
/// Creates the `ListDistributionConfigurationsError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListDistributionConfigurationsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListDistributionConfigurationsError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListDistributionConfigurationsErrorKind::Unhandled(err.into()),
}
}
/// 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 `ListDistributionConfigurationsErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListDistributionConfigurationsErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ListDistributionConfigurationsErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
ListDistributionConfigurationsErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `ListDistributionConfigurationsErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
ListDistributionConfigurationsErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `ListDistributionConfigurationsErrorKind::InvalidPaginationTokenException`.
pub fn is_invalid_pagination_token_exception(&self) -> bool {
matches!(
&self.kind,
ListDistributionConfigurationsErrorKind::InvalidPaginationTokenException(_)
)
}
/// Returns `true` if the error kind is `ListDistributionConfigurationsErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ListDistributionConfigurationsErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ListDistributionConfigurationsErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
ListDistributionConfigurationsErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `ListDistributionConfigurationsErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ListDistributionConfigurationsErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ListDistributionConfigurationsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListDistributionConfigurationsErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
ListDistributionConfigurationsErrorKind::ClientException(_inner) => Some(_inner),
ListDistributionConfigurationsErrorKind::ForbiddenException(_inner) => Some(_inner),
ListDistributionConfigurationsErrorKind::InvalidPaginationTokenException(_inner) => {
Some(_inner)
}
ListDistributionConfigurationsErrorKind::InvalidRequestException(_inner) => {
Some(_inner)
}
ListDistributionConfigurationsErrorKind::ServiceException(_inner) => Some(_inner),
ListDistributionConfigurationsErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
ListDistributionConfigurationsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListImageBuildVersions` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListImageBuildVersionsError {
/// Kind of error that occurred.
pub kind: ListImageBuildVersionsErrorKind,
/// 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 `ListImageBuildVersions` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListImageBuildVersionsErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have provided an invalid pagination token in your request.</p>
InvalidPaginationTokenException(crate::error::InvalidPaginationTokenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ListImageBuildVersionsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListImageBuildVersionsErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
ListImageBuildVersionsErrorKind::ClientException(_inner) => _inner.fmt(f),
ListImageBuildVersionsErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ListImageBuildVersionsErrorKind::InvalidPaginationTokenException(_inner) => {
_inner.fmt(f)
}
ListImageBuildVersionsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ListImageBuildVersionsErrorKind::ServiceException(_inner) => _inner.fmt(f),
ListImageBuildVersionsErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
ListImageBuildVersionsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListImageBuildVersionsError {
fn code(&self) -> Option<&str> {
ListImageBuildVersionsError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListImageBuildVersionsError {
/// Creates a new `ListImageBuildVersionsError`.
pub fn new(kind: ListImageBuildVersionsErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListImageBuildVersionsError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListImageBuildVersionsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListImageBuildVersionsError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListImageBuildVersionsErrorKind::Unhandled(err.into()),
}
}
/// 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 `ListImageBuildVersionsErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListImageBuildVersionsErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ListImageBuildVersionsErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
ListImageBuildVersionsErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `ListImageBuildVersionsErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
ListImageBuildVersionsErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `ListImageBuildVersionsErrorKind::InvalidPaginationTokenException`.
pub fn is_invalid_pagination_token_exception(&self) -> bool {
matches!(
&self.kind,
ListImageBuildVersionsErrorKind::InvalidPaginationTokenException(_)
)
}
/// Returns `true` if the error kind is `ListImageBuildVersionsErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ListImageBuildVersionsErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ListImageBuildVersionsErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
ListImageBuildVersionsErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `ListImageBuildVersionsErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ListImageBuildVersionsErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ListImageBuildVersionsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListImageBuildVersionsErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
ListImageBuildVersionsErrorKind::ClientException(_inner) => Some(_inner),
ListImageBuildVersionsErrorKind::ForbiddenException(_inner) => Some(_inner),
ListImageBuildVersionsErrorKind::InvalidPaginationTokenException(_inner) => {
Some(_inner)
}
ListImageBuildVersionsErrorKind::InvalidRequestException(_inner) => Some(_inner),
ListImageBuildVersionsErrorKind::ServiceException(_inner) => Some(_inner),
ListImageBuildVersionsErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
ListImageBuildVersionsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListImagePackages` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListImagePackagesError {
/// Kind of error that occurred.
pub kind: ListImagePackagesErrorKind,
/// 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 `ListImagePackages` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListImagePackagesErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have provided an invalid pagination token in your request.</p>
InvalidPaginationTokenException(crate::error::InvalidPaginationTokenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ListImagePackagesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListImagePackagesErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
ListImagePackagesErrorKind::ClientException(_inner) => _inner.fmt(f),
ListImagePackagesErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ListImagePackagesErrorKind::InvalidPaginationTokenException(_inner) => _inner.fmt(f),
ListImagePackagesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ListImagePackagesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
ListImagePackagesErrorKind::ServiceException(_inner) => _inner.fmt(f),
ListImagePackagesErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
ListImagePackagesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListImagePackagesError {
fn code(&self) -> Option<&str> {
ListImagePackagesError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListImagePackagesError {
/// Creates a new `ListImagePackagesError`.
pub fn new(kind: ListImagePackagesErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListImagePackagesError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListImagePackagesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListImagePackagesError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListImagePackagesErrorKind::Unhandled(err.into()),
}
}
/// 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 `ListImagePackagesErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePackagesErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ListImagePackagesErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, ListImagePackagesErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `ListImagePackagesErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePackagesErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `ListImagePackagesErrorKind::InvalidPaginationTokenException`.
pub fn is_invalid_pagination_token_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePackagesErrorKind::InvalidPaginationTokenException(_)
)
}
/// Returns `true` if the error kind is `ListImagePackagesErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePackagesErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ListImagePackagesErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePackagesErrorKind::ResourceNotFoundException(_)
)
}
/// Returns `true` if the error kind is `ListImagePackagesErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, ListImagePackagesErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `ListImagePackagesErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePackagesErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ListImagePackagesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListImagePackagesErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
ListImagePackagesErrorKind::ClientException(_inner) => Some(_inner),
ListImagePackagesErrorKind::ForbiddenException(_inner) => Some(_inner),
ListImagePackagesErrorKind::InvalidPaginationTokenException(_inner) => Some(_inner),
ListImagePackagesErrorKind::InvalidRequestException(_inner) => Some(_inner),
ListImagePackagesErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
ListImagePackagesErrorKind::ServiceException(_inner) => Some(_inner),
ListImagePackagesErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
ListImagePackagesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListImagePipelineImages` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListImagePipelineImagesError {
/// Kind of error that occurred.
pub kind: ListImagePipelineImagesErrorKind,
/// 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 `ListImagePipelineImages` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListImagePipelineImagesErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have provided an invalid pagination token in your request.</p>
InvalidPaginationTokenException(crate::error::InvalidPaginationTokenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ListImagePipelineImagesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListImagePipelineImagesErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
ListImagePipelineImagesErrorKind::ClientException(_inner) => _inner.fmt(f),
ListImagePipelineImagesErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ListImagePipelineImagesErrorKind::InvalidPaginationTokenException(_inner) => {
_inner.fmt(f)
}
ListImagePipelineImagesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ListImagePipelineImagesErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
ListImagePipelineImagesErrorKind::ServiceException(_inner) => _inner.fmt(f),
ListImagePipelineImagesErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
ListImagePipelineImagesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListImagePipelineImagesError {
fn code(&self) -> Option<&str> {
ListImagePipelineImagesError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListImagePipelineImagesError {
/// Creates a new `ListImagePipelineImagesError`.
pub fn new(kind: ListImagePipelineImagesErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListImagePipelineImagesError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListImagePipelineImagesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListImagePipelineImagesError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListImagePipelineImagesErrorKind::Unhandled(err.into()),
}
}
/// 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 `ListImagePipelineImagesErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelineImagesErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ListImagePipelineImagesErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelineImagesErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `ListImagePipelineImagesErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelineImagesErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `ListImagePipelineImagesErrorKind::InvalidPaginationTokenException`.
pub fn is_invalid_pagination_token_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelineImagesErrorKind::InvalidPaginationTokenException(_)
)
}
/// Returns `true` if the error kind is `ListImagePipelineImagesErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelineImagesErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ListImagePipelineImagesErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelineImagesErrorKind::ResourceNotFoundException(_)
)
}
/// Returns `true` if the error kind is `ListImagePipelineImagesErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelineImagesErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `ListImagePipelineImagesErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelineImagesErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ListImagePipelineImagesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListImagePipelineImagesErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
ListImagePipelineImagesErrorKind::ClientException(_inner) => Some(_inner),
ListImagePipelineImagesErrorKind::ForbiddenException(_inner) => Some(_inner),
ListImagePipelineImagesErrorKind::InvalidPaginationTokenException(_inner) => {
Some(_inner)
}
ListImagePipelineImagesErrorKind::InvalidRequestException(_inner) => Some(_inner),
ListImagePipelineImagesErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
ListImagePipelineImagesErrorKind::ServiceException(_inner) => Some(_inner),
ListImagePipelineImagesErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
ListImagePipelineImagesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListImagePipelines` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListImagePipelinesError {
/// Kind of error that occurred.
pub kind: ListImagePipelinesErrorKind,
/// 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 `ListImagePipelines` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListImagePipelinesErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have provided an invalid pagination token in your request.</p>
InvalidPaginationTokenException(crate::error::InvalidPaginationTokenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ListImagePipelinesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListImagePipelinesErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
ListImagePipelinesErrorKind::ClientException(_inner) => _inner.fmt(f),
ListImagePipelinesErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ListImagePipelinesErrorKind::InvalidPaginationTokenException(_inner) => _inner.fmt(f),
ListImagePipelinesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ListImagePipelinesErrorKind::ServiceException(_inner) => _inner.fmt(f),
ListImagePipelinesErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
ListImagePipelinesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListImagePipelinesError {
fn code(&self) -> Option<&str> {
ListImagePipelinesError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListImagePipelinesError {
/// Creates a new `ListImagePipelinesError`.
pub fn new(kind: ListImagePipelinesErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListImagePipelinesError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListImagePipelinesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListImagePipelinesError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListImagePipelinesErrorKind::Unhandled(err.into()),
}
}
/// 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 `ListImagePipelinesErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelinesErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ListImagePipelinesErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, ListImagePipelinesErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `ListImagePipelinesErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelinesErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `ListImagePipelinesErrorKind::InvalidPaginationTokenException`.
pub fn is_invalid_pagination_token_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelinesErrorKind::InvalidPaginationTokenException(_)
)
}
/// Returns `true` if the error kind is `ListImagePipelinesErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelinesErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ListImagePipelinesErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, ListImagePipelinesErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `ListImagePipelinesErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ListImagePipelinesErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ListImagePipelinesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListImagePipelinesErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
ListImagePipelinesErrorKind::ClientException(_inner) => Some(_inner),
ListImagePipelinesErrorKind::ForbiddenException(_inner) => Some(_inner),
ListImagePipelinesErrorKind::InvalidPaginationTokenException(_inner) => Some(_inner),
ListImagePipelinesErrorKind::InvalidRequestException(_inner) => Some(_inner),
ListImagePipelinesErrorKind::ServiceException(_inner) => Some(_inner),
ListImagePipelinesErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
ListImagePipelinesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListImageRecipes` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListImageRecipesError {
/// Kind of error that occurred.
pub kind: ListImageRecipesErrorKind,
/// 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 `ListImageRecipes` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListImageRecipesErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have provided an invalid pagination token in your request.</p>
InvalidPaginationTokenException(crate::error::InvalidPaginationTokenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ListImageRecipesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListImageRecipesErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
ListImageRecipesErrorKind::ClientException(_inner) => _inner.fmt(f),
ListImageRecipesErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ListImageRecipesErrorKind::InvalidPaginationTokenException(_inner) => _inner.fmt(f),
ListImageRecipesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ListImageRecipesErrorKind::ServiceException(_inner) => _inner.fmt(f),
ListImageRecipesErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
ListImageRecipesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListImageRecipesError {
fn code(&self) -> Option<&str> {
ListImageRecipesError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListImageRecipesError {
/// Creates a new `ListImageRecipesError`.
pub fn new(kind: ListImageRecipesErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListImageRecipesError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListImageRecipesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListImageRecipesError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListImageRecipesErrorKind::Unhandled(err.into()),
}
}
/// 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 `ListImageRecipesErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListImageRecipesErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ListImageRecipesErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, ListImageRecipesErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `ListImageRecipesErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, ListImageRecipesErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `ListImageRecipesErrorKind::InvalidPaginationTokenException`.
pub fn is_invalid_pagination_token_exception(&self) -> bool {
matches!(
&self.kind,
ListImageRecipesErrorKind::InvalidPaginationTokenException(_)
)
}
/// Returns `true` if the error kind is `ListImageRecipesErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ListImageRecipesErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ListImageRecipesErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, ListImageRecipesErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `ListImageRecipesErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ListImageRecipesErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ListImageRecipesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListImageRecipesErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
ListImageRecipesErrorKind::ClientException(_inner) => Some(_inner),
ListImageRecipesErrorKind::ForbiddenException(_inner) => Some(_inner),
ListImageRecipesErrorKind::InvalidPaginationTokenException(_inner) => Some(_inner),
ListImageRecipesErrorKind::InvalidRequestException(_inner) => Some(_inner),
ListImageRecipesErrorKind::ServiceException(_inner) => Some(_inner),
ListImageRecipesErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
ListImageRecipesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListImages` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListImagesError {
/// Kind of error that occurred.
pub kind: ListImagesErrorKind,
/// 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 `ListImages` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListImagesErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have provided an invalid pagination token in your request.</p>
InvalidPaginationTokenException(crate::error::InvalidPaginationTokenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ListImagesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListImagesErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
ListImagesErrorKind::ClientException(_inner) => _inner.fmt(f),
ListImagesErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ListImagesErrorKind::InvalidPaginationTokenException(_inner) => _inner.fmt(f),
ListImagesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ListImagesErrorKind::ServiceException(_inner) => _inner.fmt(f),
ListImagesErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
ListImagesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListImagesError {
fn code(&self) -> Option<&str> {
ListImagesError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListImagesError {
/// Creates a new `ListImagesError`.
pub fn new(kind: ListImagesErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListImagesError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListImagesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListImagesError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListImagesErrorKind::Unhandled(err.into()),
}
}
/// 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 `ListImagesErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListImagesErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ListImagesErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, ListImagesErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `ListImagesErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, ListImagesErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `ListImagesErrorKind::InvalidPaginationTokenException`.
pub fn is_invalid_pagination_token_exception(&self) -> bool {
matches!(
&self.kind,
ListImagesErrorKind::InvalidPaginationTokenException(_)
)
}
/// Returns `true` if the error kind is `ListImagesErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(&self.kind, ListImagesErrorKind::InvalidRequestException(_))
}
/// Returns `true` if the error kind is `ListImagesErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, ListImagesErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `ListImagesErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ListImagesErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ListImagesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListImagesErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
ListImagesErrorKind::ClientException(_inner) => Some(_inner),
ListImagesErrorKind::ForbiddenException(_inner) => Some(_inner),
ListImagesErrorKind::InvalidPaginationTokenException(_inner) => Some(_inner),
ListImagesErrorKind::InvalidRequestException(_inner) => Some(_inner),
ListImagesErrorKind::ServiceException(_inner) => Some(_inner),
ListImagesErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
ListImagesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListInfrastructureConfigurations` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListInfrastructureConfigurationsError {
/// Kind of error that occurred.
pub kind: ListInfrastructureConfigurationsErrorKind,
/// 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 `ListInfrastructureConfigurations` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListInfrastructureConfigurationsErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have provided an invalid pagination token in your request.</p>
InvalidPaginationTokenException(crate::error::InvalidPaginationTokenException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 ListInfrastructureConfigurationsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListInfrastructureConfigurationsErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
ListInfrastructureConfigurationsErrorKind::ClientException(_inner) => _inner.fmt(f),
ListInfrastructureConfigurationsErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ListInfrastructureConfigurationsErrorKind::InvalidPaginationTokenException(_inner) => {
_inner.fmt(f)
}
ListInfrastructureConfigurationsErrorKind::InvalidRequestException(_inner) => {
_inner.fmt(f)
}
ListInfrastructureConfigurationsErrorKind::ServiceException(_inner) => _inner.fmt(f),
ListInfrastructureConfigurationsErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
ListInfrastructureConfigurationsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListInfrastructureConfigurationsError {
fn code(&self) -> Option<&str> {
ListInfrastructureConfigurationsError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListInfrastructureConfigurationsError {
/// Creates a new `ListInfrastructureConfigurationsError`.
pub fn new(
kind: ListInfrastructureConfigurationsErrorKind,
meta: aws_smithy_types::Error,
) -> Self {
Self { kind, meta }
}
/// Creates the `ListInfrastructureConfigurationsError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListInfrastructureConfigurationsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListInfrastructureConfigurationsError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListInfrastructureConfigurationsErrorKind::Unhandled(err.into()),
}
}
/// 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 `ListInfrastructureConfigurationsErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
ListInfrastructureConfigurationsErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `ListInfrastructureConfigurationsErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
ListInfrastructureConfigurationsErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `ListInfrastructureConfigurationsErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
ListInfrastructureConfigurationsErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `ListInfrastructureConfigurationsErrorKind::InvalidPaginationTokenException`.
pub fn is_invalid_pagination_token_exception(&self) -> bool {
matches!(
&self.kind,
ListInfrastructureConfigurationsErrorKind::InvalidPaginationTokenException(_)
)
}
/// Returns `true` if the error kind is `ListInfrastructureConfigurationsErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ListInfrastructureConfigurationsErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ListInfrastructureConfigurationsErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
ListInfrastructureConfigurationsErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `ListInfrastructureConfigurationsErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
ListInfrastructureConfigurationsErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for ListInfrastructureConfigurationsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListInfrastructureConfigurationsErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
ListInfrastructureConfigurationsErrorKind::ClientException(_inner) => Some(_inner),
ListInfrastructureConfigurationsErrorKind::ForbiddenException(_inner) => Some(_inner),
ListInfrastructureConfigurationsErrorKind::InvalidPaginationTokenException(_inner) => {
Some(_inner)
}
ListInfrastructureConfigurationsErrorKind::InvalidRequestException(_inner) => {
Some(_inner)
}
ListInfrastructureConfigurationsErrorKind::ServiceException(_inner) => Some(_inner),
ListInfrastructureConfigurationsErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
ListInfrastructureConfigurationsErrorKind::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>The specified parameter is invalid. Review the available parameters for the API request.</p>
InvalidParameterException(crate::error::InvalidParameterException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// 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::InvalidParameterException(_inner) => _inner.fmt(f),
ListTagsForResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
ListTagsForResourceErrorKind::ServiceException(_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()),
}
}
/// 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::InvalidParameterException`.
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
ListTagsForResourceErrorKind::InvalidParameterException(_)
)
}
/// 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::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
ListTagsForResourceErrorKind::ServiceException(_)
)
}
}
impl std::error::Error for ListTagsForResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListTagsForResourceErrorKind::InvalidParameterException(_inner) => Some(_inner),
ListTagsForResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
ListTagsForResourceErrorKind::ServiceException(_inner) => Some(_inner),
ListTagsForResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `PutComponentPolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct PutComponentPolicyError {
/// Kind of error that occurred.
pub kind: PutComponentPolicyErrorKind,
/// 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 `PutComponentPolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum PutComponentPolicyErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>The value that you provided for the specified parameter is invalid.</p>
InvalidParameterValueException(crate::error::InvalidParameterValueException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 PutComponentPolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
PutComponentPolicyErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
PutComponentPolicyErrorKind::ClientException(_inner) => _inner.fmt(f),
PutComponentPolicyErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
PutComponentPolicyErrorKind::InvalidParameterValueException(_inner) => _inner.fmt(f),
PutComponentPolicyErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
PutComponentPolicyErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
PutComponentPolicyErrorKind::ServiceException(_inner) => _inner.fmt(f),
PutComponentPolicyErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
PutComponentPolicyErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for PutComponentPolicyError {
fn code(&self) -> Option<&str> {
PutComponentPolicyError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl PutComponentPolicyError {
/// Creates a new `PutComponentPolicyError`.
pub fn new(kind: PutComponentPolicyErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `PutComponentPolicyError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: PutComponentPolicyErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `PutComponentPolicyError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: PutComponentPolicyErrorKind::Unhandled(err.into()),
}
}
/// 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 `PutComponentPolicyErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
PutComponentPolicyErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `PutComponentPolicyErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, PutComponentPolicyErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `PutComponentPolicyErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
PutComponentPolicyErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `PutComponentPolicyErrorKind::InvalidParameterValueException`.
pub fn is_invalid_parameter_value_exception(&self) -> bool {
matches!(
&self.kind,
PutComponentPolicyErrorKind::InvalidParameterValueException(_)
)
}
/// Returns `true` if the error kind is `PutComponentPolicyErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
PutComponentPolicyErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `PutComponentPolicyErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
PutComponentPolicyErrorKind::ResourceNotFoundException(_)
)
}
/// Returns `true` if the error kind is `PutComponentPolicyErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, PutComponentPolicyErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `PutComponentPolicyErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
PutComponentPolicyErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for PutComponentPolicyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
PutComponentPolicyErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
PutComponentPolicyErrorKind::ClientException(_inner) => Some(_inner),
PutComponentPolicyErrorKind::ForbiddenException(_inner) => Some(_inner),
PutComponentPolicyErrorKind::InvalidParameterValueException(_inner) => Some(_inner),
PutComponentPolicyErrorKind::InvalidRequestException(_inner) => Some(_inner),
PutComponentPolicyErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
PutComponentPolicyErrorKind::ServiceException(_inner) => Some(_inner),
PutComponentPolicyErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
PutComponentPolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `PutContainerRecipePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct PutContainerRecipePolicyError {
/// Kind of error that occurred.
pub kind: PutContainerRecipePolicyErrorKind,
/// 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 `PutContainerRecipePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum PutContainerRecipePolicyErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>The value that you provided for the specified parameter is invalid.</p>
InvalidParameterValueException(crate::error::InvalidParameterValueException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 PutContainerRecipePolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
PutContainerRecipePolicyErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
PutContainerRecipePolicyErrorKind::ClientException(_inner) => _inner.fmt(f),
PutContainerRecipePolicyErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
PutContainerRecipePolicyErrorKind::InvalidParameterValueException(_inner) => {
_inner.fmt(f)
}
PutContainerRecipePolicyErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
PutContainerRecipePolicyErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
PutContainerRecipePolicyErrorKind::ServiceException(_inner) => _inner.fmt(f),
PutContainerRecipePolicyErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
PutContainerRecipePolicyErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for PutContainerRecipePolicyError {
fn code(&self) -> Option<&str> {
PutContainerRecipePolicyError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl PutContainerRecipePolicyError {
/// Creates a new `PutContainerRecipePolicyError`.
pub fn new(kind: PutContainerRecipePolicyErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `PutContainerRecipePolicyError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: PutContainerRecipePolicyErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `PutContainerRecipePolicyError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: PutContainerRecipePolicyErrorKind::Unhandled(err.into()),
}
}
/// 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 `PutContainerRecipePolicyErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
PutContainerRecipePolicyErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `PutContainerRecipePolicyErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
PutContainerRecipePolicyErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `PutContainerRecipePolicyErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
PutContainerRecipePolicyErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `PutContainerRecipePolicyErrorKind::InvalidParameterValueException`.
pub fn is_invalid_parameter_value_exception(&self) -> bool {
matches!(
&self.kind,
PutContainerRecipePolicyErrorKind::InvalidParameterValueException(_)
)
}
/// Returns `true` if the error kind is `PutContainerRecipePolicyErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
PutContainerRecipePolicyErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `PutContainerRecipePolicyErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
PutContainerRecipePolicyErrorKind::ResourceNotFoundException(_)
)
}
/// Returns `true` if the error kind is `PutContainerRecipePolicyErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
PutContainerRecipePolicyErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `PutContainerRecipePolicyErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
PutContainerRecipePolicyErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for PutContainerRecipePolicyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
PutContainerRecipePolicyErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
PutContainerRecipePolicyErrorKind::ClientException(_inner) => Some(_inner),
PutContainerRecipePolicyErrorKind::ForbiddenException(_inner) => Some(_inner),
PutContainerRecipePolicyErrorKind::InvalidParameterValueException(_inner) => {
Some(_inner)
}
PutContainerRecipePolicyErrorKind::InvalidRequestException(_inner) => Some(_inner),
PutContainerRecipePolicyErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
PutContainerRecipePolicyErrorKind::ServiceException(_inner) => Some(_inner),
PutContainerRecipePolicyErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
PutContainerRecipePolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `PutImagePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct PutImagePolicyError {
/// Kind of error that occurred.
pub kind: PutImagePolicyErrorKind,
/// 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 `PutImagePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum PutImagePolicyErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>The value that you provided for the specified parameter is invalid.</p>
InvalidParameterValueException(crate::error::InvalidParameterValueException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 PutImagePolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
PutImagePolicyErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
PutImagePolicyErrorKind::ClientException(_inner) => _inner.fmt(f),
PutImagePolicyErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
PutImagePolicyErrorKind::InvalidParameterValueException(_inner) => _inner.fmt(f),
PutImagePolicyErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
PutImagePolicyErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
PutImagePolicyErrorKind::ServiceException(_inner) => _inner.fmt(f),
PutImagePolicyErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
PutImagePolicyErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for PutImagePolicyError {
fn code(&self) -> Option<&str> {
PutImagePolicyError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl PutImagePolicyError {
/// Creates a new `PutImagePolicyError`.
pub fn new(kind: PutImagePolicyErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `PutImagePolicyError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: PutImagePolicyErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `PutImagePolicyError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: PutImagePolicyErrorKind::Unhandled(err.into()),
}
}
/// 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 `PutImagePolicyErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
PutImagePolicyErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `PutImagePolicyErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, PutImagePolicyErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `PutImagePolicyErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(&self.kind, PutImagePolicyErrorKind::ForbiddenException(_))
}
/// Returns `true` if the error kind is `PutImagePolicyErrorKind::InvalidParameterValueException`.
pub fn is_invalid_parameter_value_exception(&self) -> bool {
matches!(
&self.kind,
PutImagePolicyErrorKind::InvalidParameterValueException(_)
)
}
/// Returns `true` if the error kind is `PutImagePolicyErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
PutImagePolicyErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `PutImagePolicyErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
PutImagePolicyErrorKind::ResourceNotFoundException(_)
)
}
/// Returns `true` if the error kind is `PutImagePolicyErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, PutImagePolicyErrorKind::ServiceException(_))
}
/// Returns `true` if the error kind is `PutImagePolicyErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
PutImagePolicyErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for PutImagePolicyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
PutImagePolicyErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
PutImagePolicyErrorKind::ClientException(_inner) => Some(_inner),
PutImagePolicyErrorKind::ForbiddenException(_inner) => Some(_inner),
PutImagePolicyErrorKind::InvalidParameterValueException(_inner) => Some(_inner),
PutImagePolicyErrorKind::InvalidRequestException(_inner) => Some(_inner),
PutImagePolicyErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
PutImagePolicyErrorKind::ServiceException(_inner) => Some(_inner),
PutImagePolicyErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
PutImagePolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `PutImageRecipePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct PutImageRecipePolicyError {
/// Kind of error that occurred.
pub kind: PutImageRecipePolicyErrorKind,
/// 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 `PutImageRecipePolicy` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum PutImageRecipePolicyErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>The value that you provided for the specified parameter is invalid.</p>
InvalidParameterValueException(crate::error::InvalidParameterValueException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 PutImageRecipePolicyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
PutImageRecipePolicyErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
PutImageRecipePolicyErrorKind::ClientException(_inner) => _inner.fmt(f),
PutImageRecipePolicyErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
PutImageRecipePolicyErrorKind::InvalidParameterValueException(_inner) => _inner.fmt(f),
PutImageRecipePolicyErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
PutImageRecipePolicyErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
PutImageRecipePolicyErrorKind::ServiceException(_inner) => _inner.fmt(f),
PutImageRecipePolicyErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
PutImageRecipePolicyErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for PutImageRecipePolicyError {
fn code(&self) -> Option<&str> {
PutImageRecipePolicyError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl PutImageRecipePolicyError {
/// Creates a new `PutImageRecipePolicyError`.
pub fn new(kind: PutImageRecipePolicyErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `PutImageRecipePolicyError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: PutImageRecipePolicyErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `PutImageRecipePolicyError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: PutImageRecipePolicyErrorKind::Unhandled(err.into()),
}
}
/// 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 `PutImageRecipePolicyErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
PutImageRecipePolicyErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `PutImageRecipePolicyErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
PutImageRecipePolicyErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `PutImageRecipePolicyErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
PutImageRecipePolicyErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `PutImageRecipePolicyErrorKind::InvalidParameterValueException`.
pub fn is_invalid_parameter_value_exception(&self) -> bool {
matches!(
&self.kind,
PutImageRecipePolicyErrorKind::InvalidParameterValueException(_)
)
}
/// Returns `true` if the error kind is `PutImageRecipePolicyErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
PutImageRecipePolicyErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `PutImageRecipePolicyErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
PutImageRecipePolicyErrorKind::ResourceNotFoundException(_)
)
}
/// Returns `true` if the error kind is `PutImageRecipePolicyErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
PutImageRecipePolicyErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `PutImageRecipePolicyErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
PutImageRecipePolicyErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for PutImageRecipePolicyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
PutImageRecipePolicyErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
PutImageRecipePolicyErrorKind::ClientException(_inner) => Some(_inner),
PutImageRecipePolicyErrorKind::ForbiddenException(_inner) => Some(_inner),
PutImageRecipePolicyErrorKind::InvalidParameterValueException(_inner) => Some(_inner),
PutImageRecipePolicyErrorKind::InvalidRequestException(_inner) => Some(_inner),
PutImageRecipePolicyErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
PutImageRecipePolicyErrorKind::ServiceException(_inner) => Some(_inner),
PutImageRecipePolicyErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
PutImageRecipePolicyErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `StartImagePipelineExecution` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct StartImagePipelineExecutionError {
/// Kind of error that occurred.
pub kind: StartImagePipelineExecutionErrorKind,
/// 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 `StartImagePipelineExecution` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum StartImagePipelineExecutionErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 StartImagePipelineExecutionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
StartImagePipelineExecutionErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
StartImagePipelineExecutionErrorKind::ClientException(_inner) => _inner.fmt(f),
StartImagePipelineExecutionErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
StartImagePipelineExecutionErrorKind::IdempotentParameterMismatchException(_inner) => {
_inner.fmt(f)
}
StartImagePipelineExecutionErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
StartImagePipelineExecutionErrorKind::ResourceInUseException(_inner) => _inner.fmt(f),
StartImagePipelineExecutionErrorKind::ResourceNotFoundException(_inner) => {
_inner.fmt(f)
}
StartImagePipelineExecutionErrorKind::ServiceException(_inner) => _inner.fmt(f),
StartImagePipelineExecutionErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
StartImagePipelineExecutionErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for StartImagePipelineExecutionError {
fn code(&self) -> Option<&str> {
StartImagePipelineExecutionError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl StartImagePipelineExecutionError {
/// Creates a new `StartImagePipelineExecutionError`.
pub fn new(kind: StartImagePipelineExecutionErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `StartImagePipelineExecutionError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: StartImagePipelineExecutionErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `StartImagePipelineExecutionError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: StartImagePipelineExecutionErrorKind::Unhandled(err.into()),
}
}
/// 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 `StartImagePipelineExecutionErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
StartImagePipelineExecutionErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `StartImagePipelineExecutionErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
StartImagePipelineExecutionErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `StartImagePipelineExecutionErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
StartImagePipelineExecutionErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `StartImagePipelineExecutionErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
StartImagePipelineExecutionErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `StartImagePipelineExecutionErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
StartImagePipelineExecutionErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `StartImagePipelineExecutionErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
StartImagePipelineExecutionErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `StartImagePipelineExecutionErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
StartImagePipelineExecutionErrorKind::ResourceNotFoundException(_)
)
}
/// Returns `true` if the error kind is `StartImagePipelineExecutionErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
StartImagePipelineExecutionErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `StartImagePipelineExecutionErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
StartImagePipelineExecutionErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for StartImagePipelineExecutionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
StartImagePipelineExecutionErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
StartImagePipelineExecutionErrorKind::ClientException(_inner) => Some(_inner),
StartImagePipelineExecutionErrorKind::ForbiddenException(_inner) => Some(_inner),
StartImagePipelineExecutionErrorKind::IdempotentParameterMismatchException(_inner) => {
Some(_inner)
}
StartImagePipelineExecutionErrorKind::InvalidRequestException(_inner) => Some(_inner),
StartImagePipelineExecutionErrorKind::ResourceInUseException(_inner) => Some(_inner),
StartImagePipelineExecutionErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
StartImagePipelineExecutionErrorKind::ServiceException(_inner) => Some(_inner),
StartImagePipelineExecutionErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
StartImagePipelineExecutionErrorKind::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>The specified parameter is invalid. Review the available parameters for the API request.</p>
InvalidParameterException(crate::error::InvalidParameterException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// 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::InvalidParameterException(_inner) => _inner.fmt(f),
TagResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
TagResourceErrorKind::ServiceException(_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()),
}
}
/// 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::InvalidParameterException`.
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
TagResourceErrorKind::InvalidParameterException(_)
)
}
/// 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::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, TagResourceErrorKind::ServiceException(_))
}
}
impl std::error::Error for TagResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
TagResourceErrorKind::InvalidParameterException(_inner) => Some(_inner),
TagResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
TagResourceErrorKind::ServiceException(_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>The specified parameter is invalid. Review the available parameters for the API request.</p>
InvalidParameterException(crate::error::InvalidParameterException),
/// <p>At least one of the resources referenced by your request does not exist.</p>
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// 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::InvalidParameterException(_inner) => _inner.fmt(f),
UntagResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
UntagResourceErrorKind::ServiceException(_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()),
}
}
/// 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::InvalidParameterException`.
pub fn is_invalid_parameter_exception(&self) -> bool {
matches!(
&self.kind,
UntagResourceErrorKind::InvalidParameterException(_)
)
}
/// 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::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(&self.kind, UntagResourceErrorKind::ServiceException(_))
}
}
impl std::error::Error for UntagResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UntagResourceErrorKind::InvalidParameterException(_inner) => Some(_inner),
UntagResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
UntagResourceErrorKind::ServiceException(_inner) => Some(_inner),
UntagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `UpdateDistributionConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateDistributionConfigurationError {
/// Kind of error that occurred.
pub kind: UpdateDistributionConfigurationErrorKind,
/// 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 `UpdateDistributionConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateDistributionConfigurationErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have specified two or more mutually exclusive parameters. Review the error message for details.</p>
InvalidParameterCombinationException(crate::error::InvalidParameterCombinationException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 UpdateDistributionConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateDistributionConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
UpdateDistributionConfigurationErrorKind::ClientException(_inner) => _inner.fmt(f),
UpdateDistributionConfigurationErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
UpdateDistributionConfigurationErrorKind::IdempotentParameterMismatchException(
_inner,
) => _inner.fmt(f),
UpdateDistributionConfigurationErrorKind::InvalidParameterCombinationException(
_inner,
) => _inner.fmt(f),
UpdateDistributionConfigurationErrorKind::InvalidRequestException(_inner) => {
_inner.fmt(f)
}
UpdateDistributionConfigurationErrorKind::ResourceInUseException(_inner) => {
_inner.fmt(f)
}
UpdateDistributionConfigurationErrorKind::ServiceException(_inner) => _inner.fmt(f),
UpdateDistributionConfigurationErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
UpdateDistributionConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for UpdateDistributionConfigurationError {
fn code(&self) -> Option<&str> {
UpdateDistributionConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateDistributionConfigurationError {
/// Creates a new `UpdateDistributionConfigurationError`.
pub fn new(
kind: UpdateDistributionConfigurationErrorKind,
meta: aws_smithy_types::Error,
) -> Self {
Self { kind, meta }
}
/// Creates the `UpdateDistributionConfigurationError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateDistributionConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `UpdateDistributionConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateDistributionConfigurationErrorKind::Unhandled(err.into()),
}
}
/// 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 `UpdateDistributionConfigurationErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDistributionConfigurationErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `UpdateDistributionConfigurationErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDistributionConfigurationErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `UpdateDistributionConfigurationErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDistributionConfigurationErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `UpdateDistributionConfigurationErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDistributionConfigurationErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `UpdateDistributionConfigurationErrorKind::InvalidParameterCombinationException`.
pub fn is_invalid_parameter_combination_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDistributionConfigurationErrorKind::InvalidParameterCombinationException(_)
)
}
/// Returns `true` if the error kind is `UpdateDistributionConfigurationErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDistributionConfigurationErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `UpdateDistributionConfigurationErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDistributionConfigurationErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `UpdateDistributionConfigurationErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDistributionConfigurationErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `UpdateDistributionConfigurationErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDistributionConfigurationErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for UpdateDistributionConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateDistributionConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
UpdateDistributionConfigurationErrorKind::ClientException(_inner) => Some(_inner),
UpdateDistributionConfigurationErrorKind::ForbiddenException(_inner) => Some(_inner),
UpdateDistributionConfigurationErrorKind::IdempotentParameterMismatchException(
_inner,
) => Some(_inner),
UpdateDistributionConfigurationErrorKind::InvalidParameterCombinationException(
_inner,
) => Some(_inner),
UpdateDistributionConfigurationErrorKind::InvalidRequestException(_inner) => {
Some(_inner)
}
UpdateDistributionConfigurationErrorKind::ResourceInUseException(_inner) => {
Some(_inner)
}
UpdateDistributionConfigurationErrorKind::ServiceException(_inner) => Some(_inner),
UpdateDistributionConfigurationErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
UpdateDistributionConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `UpdateImagePipeline` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateImagePipelineError {
/// Kind of error that occurred.
pub kind: UpdateImagePipelineErrorKind,
/// 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 `UpdateImagePipeline` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateImagePipelineErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 UpdateImagePipelineError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateImagePipelineErrorKind::CallRateLimitExceededException(_inner) => _inner.fmt(f),
UpdateImagePipelineErrorKind::ClientException(_inner) => _inner.fmt(f),
UpdateImagePipelineErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
UpdateImagePipelineErrorKind::IdempotentParameterMismatchException(_inner) => {
_inner.fmt(f)
}
UpdateImagePipelineErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
UpdateImagePipelineErrorKind::ResourceInUseException(_inner) => _inner.fmt(f),
UpdateImagePipelineErrorKind::ServiceException(_inner) => _inner.fmt(f),
UpdateImagePipelineErrorKind::ServiceUnavailableException(_inner) => _inner.fmt(f),
UpdateImagePipelineErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for UpdateImagePipelineError {
fn code(&self) -> Option<&str> {
UpdateImagePipelineError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateImagePipelineError {
/// Creates a new `UpdateImagePipelineError`.
pub fn new(kind: UpdateImagePipelineErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `UpdateImagePipelineError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateImagePipelineErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `UpdateImagePipelineError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateImagePipelineErrorKind::Unhandled(err.into()),
}
}
/// 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 `UpdateImagePipelineErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
UpdateImagePipelineErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `UpdateImagePipelineErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(&self.kind, UpdateImagePipelineErrorKind::ClientException(_))
}
/// Returns `true` if the error kind is `UpdateImagePipelineErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
UpdateImagePipelineErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `UpdateImagePipelineErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
UpdateImagePipelineErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `UpdateImagePipelineErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
UpdateImagePipelineErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `UpdateImagePipelineErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
UpdateImagePipelineErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `UpdateImagePipelineErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
UpdateImagePipelineErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `UpdateImagePipelineErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
UpdateImagePipelineErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for UpdateImagePipelineError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateImagePipelineErrorKind::CallRateLimitExceededException(_inner) => Some(_inner),
UpdateImagePipelineErrorKind::ClientException(_inner) => Some(_inner),
UpdateImagePipelineErrorKind::ForbiddenException(_inner) => Some(_inner),
UpdateImagePipelineErrorKind::IdempotentParameterMismatchException(_inner) => {
Some(_inner)
}
UpdateImagePipelineErrorKind::InvalidRequestException(_inner) => Some(_inner),
UpdateImagePipelineErrorKind::ResourceInUseException(_inner) => Some(_inner),
UpdateImagePipelineErrorKind::ServiceException(_inner) => Some(_inner),
UpdateImagePipelineErrorKind::ServiceUnavailableException(_inner) => Some(_inner),
UpdateImagePipelineErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `UpdateInfrastructureConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateInfrastructureConfigurationError {
/// Kind of error that occurred.
pub kind: UpdateInfrastructureConfigurationErrorKind,
/// 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 `UpdateInfrastructureConfiguration` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateInfrastructureConfigurationErrorKind {
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
CallRateLimitExceededException(crate::error::CallRateLimitExceededException),
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
ClientException(crate::error::ClientException),
/// <p>You are not authorized to perform the requested operation.</p>
ForbiddenException(crate::error::ForbiddenException),
/// <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
IdempotentParameterMismatchException(crate::error::IdempotentParameterMismatchException),
/// <p>You have made a request for an action that is not supported by the service.</p>
InvalidRequestException(crate::error::InvalidRequestException),
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
ResourceInUseException(crate::error::ResourceInUseException),
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
ServiceException(crate::error::ServiceException),
/// <p>The service is unable to process your request at this time.</p>
ServiceUnavailableException(crate::error::ServiceUnavailableException),
/// 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 UpdateInfrastructureConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
_inner.fmt(f)
}
UpdateInfrastructureConfigurationErrorKind::ClientException(_inner) => _inner.fmt(f),
UpdateInfrastructureConfigurationErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
UpdateInfrastructureConfigurationErrorKind::IdempotentParameterMismatchException(
_inner,
) => _inner.fmt(f),
UpdateInfrastructureConfigurationErrorKind::InvalidRequestException(_inner) => {
_inner.fmt(f)
}
UpdateInfrastructureConfigurationErrorKind::ResourceInUseException(_inner) => {
_inner.fmt(f)
}
UpdateInfrastructureConfigurationErrorKind::ServiceException(_inner) => _inner.fmt(f),
UpdateInfrastructureConfigurationErrorKind::ServiceUnavailableException(_inner) => {
_inner.fmt(f)
}
UpdateInfrastructureConfigurationErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for UpdateInfrastructureConfigurationError {
fn code(&self) -> Option<&str> {
UpdateInfrastructureConfigurationError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateInfrastructureConfigurationError {
/// Creates a new `UpdateInfrastructureConfigurationError`.
pub fn new(
kind: UpdateInfrastructureConfigurationErrorKind,
meta: aws_smithy_types::Error,
) -> Self {
Self { kind, meta }
}
/// Creates the `UpdateInfrastructureConfigurationError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateInfrastructureConfigurationErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `UpdateInfrastructureConfigurationError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateInfrastructureConfigurationErrorKind::Unhandled(err.into()),
}
}
/// 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 `UpdateInfrastructureConfigurationErrorKind::CallRateLimitExceededException`.
pub fn is_call_rate_limit_exceeded_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_)
)
}
/// Returns `true` if the error kind is `UpdateInfrastructureConfigurationErrorKind::ClientException`.
pub fn is_client_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInfrastructureConfigurationErrorKind::ClientException(_)
)
}
/// Returns `true` if the error kind is `UpdateInfrastructureConfigurationErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInfrastructureConfigurationErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `UpdateInfrastructureConfigurationErrorKind::IdempotentParameterMismatchException`.
pub fn is_idempotent_parameter_mismatch_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInfrastructureConfigurationErrorKind::IdempotentParameterMismatchException(_)
)
}
/// Returns `true` if the error kind is `UpdateInfrastructureConfigurationErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInfrastructureConfigurationErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `UpdateInfrastructureConfigurationErrorKind::ResourceInUseException`.
pub fn is_resource_in_use_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInfrastructureConfigurationErrorKind::ResourceInUseException(_)
)
}
/// Returns `true` if the error kind is `UpdateInfrastructureConfigurationErrorKind::ServiceException`.
pub fn is_service_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInfrastructureConfigurationErrorKind::ServiceException(_)
)
}
/// Returns `true` if the error kind is `UpdateInfrastructureConfigurationErrorKind::ServiceUnavailableException`.
pub fn is_service_unavailable_exception(&self) -> bool {
matches!(
&self.kind,
UpdateInfrastructureConfigurationErrorKind::ServiceUnavailableException(_)
)
}
}
impl std::error::Error for UpdateInfrastructureConfigurationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateInfrastructureConfigurationErrorKind::CallRateLimitExceededException(_inner) => {
Some(_inner)
}
UpdateInfrastructureConfigurationErrorKind::ClientException(_inner) => Some(_inner),
UpdateInfrastructureConfigurationErrorKind::ForbiddenException(_inner) => Some(_inner),
UpdateInfrastructureConfigurationErrorKind::IdempotentParameterMismatchException(
_inner,
) => Some(_inner),
UpdateInfrastructureConfigurationErrorKind::InvalidRequestException(_inner) => {
Some(_inner)
}
UpdateInfrastructureConfigurationErrorKind::ResourceInUseException(_inner) => {
Some(_inner)
}
UpdateInfrastructureConfigurationErrorKind::ServiceException(_inner) => Some(_inner),
UpdateInfrastructureConfigurationErrorKind::ServiceUnavailableException(_inner) => {
Some(_inner)
}
UpdateInfrastructureConfigurationErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// <p>The service is unable to process your request at this time.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServiceUnavailableException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for ServiceUnavailableException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServiceUnavailableException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ServiceUnavailableException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ServiceUnavailableException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ServiceUnavailableException")?;
if let Some(inner_1) = &self.message {
write!(f, ": {}", inner_1)?;
}
Ok(())
}
}
impl std::error::Error for ServiceUnavailableException {}
/// See [`ServiceUnavailableException`](crate::error::ServiceUnavailableException)
pub mod service_unavailable_exception {
/// A builder for [`ServiceUnavailableException`](crate::error::ServiceUnavailableException)
#[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 [`ServiceUnavailableException`](crate::error::ServiceUnavailableException)
pub fn build(self) -> crate::error::ServiceUnavailableException {
crate::error::ServiceUnavailableException {
message: self.message,
}
}
}
}
impl ServiceUnavailableException {
/// Creates a new builder-style object to manufacture [`ServiceUnavailableException`](crate::error::ServiceUnavailableException)
pub fn builder() -> crate::error::service_unavailable_exception::Builder {
crate::error::service_unavailable_exception::Builder::default()
}
}
/// <p>This exception is thrown when the service encounters an unrecoverable exception.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ServiceException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for ServiceException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServiceException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ServiceException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ServiceException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ServiceException")?;
if let Some(inner_2) = &self.message {
write!(f, ": {}", inner_2)?;
}
Ok(())
}
}
impl std::error::Error for ServiceException {}
/// See [`ServiceException`](crate::error::ServiceException)
pub mod service_exception {
/// A builder for [`ServiceException`](crate::error::ServiceException)
#[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 [`ServiceException`](crate::error::ServiceException)
pub fn build(self) -> crate::error::ServiceException {
crate::error::ServiceException {
message: self.message,
}
}
}
}
impl ServiceException {
/// Creates a new builder-style object to manufacture [`ServiceException`](crate::error::ServiceException)
pub fn builder() -> crate::error::service_exception::Builder {
crate::error::service_exception::Builder::default()
}
}
/// <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</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>,
}
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.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_3) = &self.message {
write!(f, ": {}", inner_3)?;
}
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>,
}
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 [`ResourceInUseException`](crate::error::ResourceInUseException)
pub fn build(self) -> crate::error::ResourceInUseException {
crate::error::ResourceInUseException {
message: self.message,
}
}
}
}
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>You have made a request for an action that is not supported by the service.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InvalidRequestException {
#[allow(missing_docs)] // documentation missing in model
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_4) = &self.message {
write!(f, ": {}", inner_4)?;
}
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 {
#[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 [`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>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct IdempotentParameterMismatchException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for IdempotentParameterMismatchException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("IdempotentParameterMismatchException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl IdempotentParameterMismatchException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for IdempotentParameterMismatchException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "IdempotentParameterMismatchException")?;
if let Some(inner_5) = &self.message {
write!(f, ": {}", inner_5)?;
}
Ok(())
}
}
impl std::error::Error for IdempotentParameterMismatchException {}
/// See [`IdempotentParameterMismatchException`](crate::error::IdempotentParameterMismatchException)
pub mod idempotent_parameter_mismatch_exception {
/// A builder for [`IdempotentParameterMismatchException`](crate::error::IdempotentParameterMismatchException)
#[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 [`IdempotentParameterMismatchException`](crate::error::IdempotentParameterMismatchException)
pub fn build(self) -> crate::error::IdempotentParameterMismatchException {
crate::error::IdempotentParameterMismatchException {
message: self.message,
}
}
}
}
impl IdempotentParameterMismatchException {
/// Creates a new builder-style object to manufacture [`IdempotentParameterMismatchException`](crate::error::IdempotentParameterMismatchException)
pub fn builder() -> crate::error::idempotent_parameter_mismatch_exception::Builder {
crate::error::idempotent_parameter_mismatch_exception::Builder::default()
}
}
/// <p>You are not authorized to perform the requested operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ForbiddenException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for ForbiddenException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ForbiddenException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ForbiddenException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ForbiddenException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ForbiddenException")?;
if let Some(inner_6) = &self.message {
write!(f, ": {}", inner_6)?;
}
Ok(())
}
}
impl std::error::Error for ForbiddenException {}
/// See [`ForbiddenException`](crate::error::ForbiddenException)
pub mod forbidden_exception {
/// A builder for [`ForbiddenException`](crate::error::ForbiddenException)
#[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 [`ForbiddenException`](crate::error::ForbiddenException)
pub fn build(self) -> crate::error::ForbiddenException {
crate::error::ForbiddenException {
message: self.message,
}
}
}
}
impl ForbiddenException {
/// Creates a new builder-style object to manufacture [`ForbiddenException`](crate::error::ForbiddenException)
pub fn builder() -> crate::error::forbidden_exception::Builder {
crate::error::forbidden_exception::Builder::default()
}
}
/// <p>These errors are usually caused by a client action, such as using an action or resource on behalf of a user that doesn't have permissions to use the action or resource, or specifying an invalid resource identifier.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ClientException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for ClientException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ClientException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ClientException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ClientException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ClientException")?;
if let Some(inner_7) = &self.message {
write!(f, ": {}", inner_7)?;
}
Ok(())
}
}
impl std::error::Error for ClientException {}
/// See [`ClientException`](crate::error::ClientException)
pub mod client_exception {
/// A builder for [`ClientException`](crate::error::ClientException)
#[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 [`ClientException`](crate::error::ClientException)
pub fn build(self) -> crate::error::ClientException {
crate::error::ClientException {
message: self.message,
}
}
}
}
impl ClientException {
/// Creates a new builder-style object to manufacture [`ClientException`](crate::error::ClientException)
pub fn builder() -> crate::error::client_exception::Builder {
crate::error::client_exception::Builder::default()
}
}
/// <p>You have exceeded the permitted request rate for the specific operation.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CallRateLimitExceededException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for CallRateLimitExceededException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CallRateLimitExceededException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl CallRateLimitExceededException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for CallRateLimitExceededException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "CallRateLimitExceededException")?;
if let Some(inner_8) = &self.message {
write!(f, ": {}", inner_8)?;
}
Ok(())
}
}
impl std::error::Error for CallRateLimitExceededException {}
/// See [`CallRateLimitExceededException`](crate::error::CallRateLimitExceededException)
pub mod call_rate_limit_exceeded_exception {
/// A builder for [`CallRateLimitExceededException`](crate::error::CallRateLimitExceededException)
#[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 [`CallRateLimitExceededException`](crate::error::CallRateLimitExceededException)
pub fn build(self) -> crate::error::CallRateLimitExceededException {
crate::error::CallRateLimitExceededException {
message: self.message,
}
}
}
}
impl CallRateLimitExceededException {
/// Creates a new builder-style object to manufacture [`CallRateLimitExceededException`](crate::error::CallRateLimitExceededException)
pub fn builder() -> crate::error::call_rate_limit_exceeded_exception::Builder {
crate::error::call_rate_limit_exceeded_exception::Builder::default()
}
}
/// <p>You have specified two or more mutually exclusive parameters. Review the error message for details.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InvalidParameterCombinationException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for InvalidParameterCombinationException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InvalidParameterCombinationException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl InvalidParameterCombinationException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for InvalidParameterCombinationException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InvalidParameterCombinationException")?;
if let Some(inner_9) = &self.message {
write!(f, ": {}", inner_9)?;
}
Ok(())
}
}
impl std::error::Error for InvalidParameterCombinationException {}
/// See [`InvalidParameterCombinationException`](crate::error::InvalidParameterCombinationException)
pub mod invalid_parameter_combination_exception {
/// A builder for [`InvalidParameterCombinationException`](crate::error::InvalidParameterCombinationException)
#[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 [`InvalidParameterCombinationException`](crate::error::InvalidParameterCombinationException)
pub fn build(self) -> crate::error::InvalidParameterCombinationException {
crate::error::InvalidParameterCombinationException {
message: self.message,
}
}
}
}
impl InvalidParameterCombinationException {
/// Creates a new builder-style object to manufacture [`InvalidParameterCombinationException`](crate::error::InvalidParameterCombinationException)
pub fn builder() -> crate::error::invalid_parameter_combination_exception::Builder {
crate::error::invalid_parameter_combination_exception::Builder::default()
}
}
/// <p>At least one of the resources referenced by your request does not exist.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ResourceNotFoundException {
#[allow(missing_docs)] // documentation missing in model
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_10) = &self.message {
write!(f, ": {}", inner_10)?;
}
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 {
#[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 [`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 specified parameter is invalid. Review the available parameters for the API request.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InvalidParameterException {
#[allow(missing_docs)] // documentation missing in model
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_11) = &self.message {
write!(f, ": {}", inner_11)?;
}
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 {
#[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 [`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>The value that you provided for the specified parameter is invalid.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InvalidParameterValueException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for InvalidParameterValueException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InvalidParameterValueException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl InvalidParameterValueException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for InvalidParameterValueException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InvalidParameterValueException")?;
if let Some(inner_12) = &self.message {
write!(f, ": {}", inner_12)?;
}
Ok(())
}
}
impl std::error::Error for InvalidParameterValueException {}
/// See [`InvalidParameterValueException`](crate::error::InvalidParameterValueException)
pub mod invalid_parameter_value_exception {
/// A builder for [`InvalidParameterValueException`](crate::error::InvalidParameterValueException)
#[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 [`InvalidParameterValueException`](crate::error::InvalidParameterValueException)
pub fn build(self) -> crate::error::InvalidParameterValueException {
crate::error::InvalidParameterValueException {
message: self.message,
}
}
}
}
impl InvalidParameterValueException {
/// Creates a new builder-style object to manufacture [`InvalidParameterValueException`](crate::error::InvalidParameterValueException)
pub fn builder() -> crate::error::invalid_parameter_value_exception::Builder {
crate::error::invalid_parameter_value_exception::Builder::default()
}
}
/// <p>You have provided an invalid pagination token in your request.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InvalidPaginationTokenException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for InvalidPaginationTokenException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InvalidPaginationTokenException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl InvalidPaginationTokenException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for InvalidPaginationTokenException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InvalidPaginationTokenException")?;
if let Some(inner_13) = &self.message {
write!(f, ": {}", inner_13)?;
}
Ok(())
}
}
impl std::error::Error for InvalidPaginationTokenException {}
/// See [`InvalidPaginationTokenException`](crate::error::InvalidPaginationTokenException)
pub mod invalid_pagination_token_exception {
/// A builder for [`InvalidPaginationTokenException`](crate::error::InvalidPaginationTokenException)
#[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 [`InvalidPaginationTokenException`](crate::error::InvalidPaginationTokenException)
pub fn build(self) -> crate::error::InvalidPaginationTokenException {
crate::error::InvalidPaginationTokenException {
message: self.message,
}
}
}
}
impl InvalidPaginationTokenException {
/// Creates a new builder-style object to manufacture [`InvalidPaginationTokenException`](crate::error::InvalidPaginationTokenException)
pub fn builder() -> crate::error::invalid_pagination_token_exception::Builder {
crate::error::invalid_pagination_token_exception::Builder::default()
}
}
/// <p>Your version number is out of bounds or does not follow the required syntax.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InvalidVersionNumberException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for InvalidVersionNumberException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InvalidVersionNumberException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl InvalidVersionNumberException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for InvalidVersionNumberException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InvalidVersionNumberException")?;
if let Some(inner_14) = &self.message {
write!(f, ": {}", inner_14)?;
}
Ok(())
}
}
impl std::error::Error for InvalidVersionNumberException {}
/// See [`InvalidVersionNumberException`](crate::error::InvalidVersionNumberException)
pub mod invalid_version_number_exception {
/// A builder for [`InvalidVersionNumberException`](crate::error::InvalidVersionNumberException)
#[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 [`InvalidVersionNumberException`](crate::error::InvalidVersionNumberException)
pub fn build(self) -> crate::error::InvalidVersionNumberException {
crate::error::InvalidVersionNumberException {
message: self.message,
}
}
}
}
impl InvalidVersionNumberException {
/// Creates a new builder-style object to manufacture [`InvalidVersionNumberException`](crate::error::InvalidVersionNumberException)
pub fn builder() -> crate::error::invalid_version_number_exception::Builder {
crate::error::invalid_version_number_exception::Builder::default()
}
}
/// <p>You have attempted to mutate or delete a resource with a dependency that prohibits this action. See the error message for more details.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ResourceDependencyException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for ResourceDependencyException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ResourceDependencyException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ResourceDependencyException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ResourceDependencyException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ResourceDependencyException")?;
if let Some(inner_15) = &self.message {
write!(f, ": {}", inner_15)?;
}
Ok(())
}
}
impl std::error::Error for ResourceDependencyException {}
/// See [`ResourceDependencyException`](crate::error::ResourceDependencyException)
pub mod resource_dependency_exception {
/// A builder for [`ResourceDependencyException`](crate::error::ResourceDependencyException)
#[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 [`ResourceDependencyException`](crate::error::ResourceDependencyException)
pub fn build(self) -> crate::error::ResourceDependencyException {
crate::error::ResourceDependencyException {
message: self.message,
}
}
}
}
impl ResourceDependencyException {
/// Creates a new builder-style object to manufacture [`ResourceDependencyException`](crate::error::ResourceDependencyException)
pub fn builder() -> crate::error::resource_dependency_exception::Builder {
crate::error::resource_dependency_exception::Builder::default()
}
}
/// <p>You have exceeded the number of permitted resources or operations for this service. For service quotas, see <a href="https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder">EC2 Image Builder endpoints and quotas</a>.</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_16) = &self.message {
write!(f, ": {}", inner_16)?;
}
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 resource that you are trying to create already exists.</p>
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ResourceAlreadyExistsException {
#[allow(missing_docs)] // documentation missing in model
pub message: std::option::Option<std::string::String>,
}
impl std::fmt::Debug for ResourceAlreadyExistsException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ResourceAlreadyExistsException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ResourceAlreadyExistsException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ResourceAlreadyExistsException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ResourceAlreadyExistsException")?;
if let Some(inner_17) = &self.message {
write!(f, ": {}", inner_17)?;
}
Ok(())
}
}
impl std::error::Error for ResourceAlreadyExistsException {}
/// See [`ResourceAlreadyExistsException`](crate::error::ResourceAlreadyExistsException)
pub mod resource_already_exists_exception {
/// A builder for [`ResourceAlreadyExistsException`](crate::error::ResourceAlreadyExistsException)
#[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 [`ResourceAlreadyExistsException`](crate::error::ResourceAlreadyExistsException)
pub fn build(self) -> crate::error::ResourceAlreadyExistsException {
crate::error::ResourceAlreadyExistsException {
message: self.message,
}
}
}
}
impl ResourceAlreadyExistsException {
/// Creates a new builder-style object to manufacture [`ResourceAlreadyExistsException`](crate::error::ResourceAlreadyExistsException)
pub fn builder() -> crate::error::resource_already_exists_exception::Builder {
crate::error::resource_already_exists_exception::Builder::default()
}
}
| 46.504316 | 260 | 0.680563 |
f99e076f152196272475773040c21297a28a345b | 2,982 | //! An efficient external sort implementation.
//!
//! You start by implementing the [`Sortable`] for your data, and provide your data via an
//! iterable. Then you create an [`ExtSorter`] to sort data.
//!
//! An example is provided in the `examples/` directory.
use std::fs::{File, OpenOptions};
use std::io::{BufReader, BufWriter, self};
use std::marker::PhantomData;
use std::path::Path;
use tempdir::TempDir;
mod iter;
pub use iter::{ExtSortedIterator, Sortable};
/// Sort the data
pub struct ExtSorter<T> {
buffer_n_items: usize,
tmp_dir: TempDir,
phantom: PhantomData<T>,
}
impl<T> ExtSorter<T>
where
T: Sortable<BufWriter<File>, BufReader<File>>,
T::Error: From<io::Error>,
{
/// Create an `ExtSorter` to sort your data.
///
/// It will buffer `buffer_n_items` items in memory and sort them, and then write them serialized
/// into temporary files.
pub fn new(buffer_n_items: usize) -> io::Result<Self> {
Ok(ExtSorter {
buffer_n_items,
tmp_dir: TempDir::new("extsort_lily")?,
phantom: PhantomData,
})
}
/// Same as [`new`](fn@Self::new) but provide a directory to store temporary files instead of system default.
pub fn new_in<P: AsRef<Path>>(
buffer_n_items: usize, tmp_dir: P,
) -> io::Result<Self> {
Ok(ExtSorter {
buffer_n_items,
tmp_dir: TempDir::new_in(tmp_dir, "extsort_lily")?,
phantom: PhantomData,
})
}
/// Sort the data.
///
/// It returns an iterator to produce sorted results. The sort is unstable.
pub fn sort<I>(
&self, unsorted: I,
) -> Result<iter::ExtSortedIterator<T, BufReader<File>, BufWriter<File>>, T::Error>
where
I: Iterator<Item = T>,
{
let mut chunk_count = 0;
{
let mut current_count = 0;
let mut chunk = Vec::new();
// make the initial chunks on disk
for seq in unsorted {
current_count += 1;
chunk.push(seq);
if current_count >= self.buffer_n_items {
chunk.sort_unstable();
self.write_chunk(
&self.tmp_dir.path().join(chunk_count.to_string()),
&mut chunk,
)?;
chunk.clear();
current_count = 0;
chunk_count += 1;
}
}
// write the last chunk
if !chunk.is_empty() {
chunk.sort_unstable();
self.write_chunk(
&self.tmp_dir.path().join(chunk_count.to_string()),
&mut chunk,
)?;
chunk_count += 1;
}
}
let readers = (0..chunk_count).map(|i|
File::open(self.tmp_dir.path().join(i.to_string())).map(BufReader::new)
).collect::<Result<Vec<_>, _>>()?;
iter::ExtSortedIterator::new(readers)
}
fn write_chunk(&self, file: &Path, chunk: &mut Vec<T>) -> Result<(), T::Error> {
let new_file = OpenOptions::new().create(true).write(true).truncate(true).open(file)?;
let mut w = BufWriter::new(new_file);
for s in chunk {
s.serialize(&mut w)?;
}
Ok(())
}
}
| 26.864865 | 111 | 0.606975 |
1df50a7df90843a5066244180c95eccdcc3786a8 | 2,093 | mod decode;
mod encode;
mod error;
pub use crate::decode::{
hex_check_fallback, hex_decode, hex_decode_fallback, hex_decode_unchecked,
};
pub use crate::encode::{hex_encode, hex_encode_fallback, hex_string};
pub use crate::error::Error;
#[allow(deprecated)]
pub use crate::encode::hex_to;
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub use crate::decode::hex_check_sse;
#[cfg(test)]
mod tests {
use crate::decode::hex_decode;
use crate::encode::{hex_encode, hex_string};
use proptest::proptest;
use std::str;
fn _test_hex_encode(s: &String) {
let mut buffer = vec![0; s.as_bytes().len() * 2];
hex_encode(s.as_bytes(), &mut buffer).unwrap();
let encode = unsafe { str::from_utf8_unchecked(&buffer[..s.as_bytes().len() * 2]) };
let hex_string = hex_string(s.as_bytes());
assert_eq!(encode, hex::encode(s));
assert_eq!(hex_string, hex::encode(s));
}
proptest! {
#[test]
fn test_hex_encode(ref s in ".*") {
_test_hex_encode(s);
}
}
fn _test_hex_decode(s: &String) {
let len = s.as_bytes().len();
let mut dst = Vec::with_capacity(len);
dst.resize(len, 0);
let hex_string = hex_string(s.as_bytes());
hex_decode(hex_string.as_bytes(), &mut dst).unwrap();
assert_eq!(&dst[..], s.as_bytes());
}
proptest! {
#[test]
fn test_hex_decode(ref s in ".+") {
_test_hex_decode(s);
}
}
fn _test_hex_decode_check(s: &String, ok: bool) {
let len = s.as_bytes().len();
let mut dst = Vec::with_capacity(len / 2);
dst.resize(len / 2, 0);
assert!(hex_decode(s.as_bytes(), &mut dst).is_ok() == ok);
}
proptest! {
#[test]
fn test_hex_decode_check(ref s in "([0-9a-fA-F][0-9a-fA-F])+") {
_test_hex_decode_check(s, true);
}
}
proptest! {
#[test]
fn test_hex_decode_check_odd(ref s in "[0-9a-fA-F]{11}") {
_test_hex_decode_check(s, false);
}
}
}
| 25.839506 | 92 | 0.573817 |
16243ece70aae35aa83e4b46a568caa80a656bbe | 829 | use ockam_core::Error;
/// Represents the failures that can occur in
/// an Ockam vault
#[derive(Clone, Copy, Debug)]
pub enum VaultError {
None,
SecretFromAnotherVault,
InvalidPublicKey,
Ecdh,
UnknownEcdhKeyType,
InvalidKeyType,
EntryNotFound,
InvalidAesKeyLength,
InvalidHkdfOutputType,
InvalidPrivateKeyLen,
AeadAesGcmEncrypt,
AeadAesGcmDecrypt,
InvalidSignature,
HkdfExpandError,
SecretNotFound,
}
impl VaultError {
/// Integer code associated with the error domain.
pub const DOMAIN_CODE: u32 = 12_000;
/// Descriptive name for the error domain.
pub const DOMAIN_NAME: &'static str = "OCKAM_VAULT";
}
impl Into<Error> for VaultError {
fn into(self) -> Error {
Error::new(Self::DOMAIN_CODE + (self as u32), Self::DOMAIN_NAME)
}
}
| 23.027778 | 72 | 0.689988 |
211d4f2f70a1425940a2892bc39137bd85350978 | 1,188 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::env;
fn main() {
let hermes_build = env::var("HERMES_BUILD")
.expect("HERMES_BUILD must point to a Hermes CMake build directory");
println!("cargo:rustc-link-search={}/lib/Parser", hermes_build);
println!(
"cargo:rustc-link-search={}/lib/Platform/Unicode",
hermes_build
);
println!("cargo:rustc-link-search={}/lib/SourceMap", hermes_build);
println!("cargo:rustc-link-search={}/lib/Support", hermes_build);
println!("cargo:rustc-link-search={}/external/dtoa", hermes_build);
println!(
"cargo:rustc-link-search={}/external/llvh/lib/Support",
hermes_build
);
println!("cargo:rustc-link-lib=hermesSourceMap");
println!("cargo:rustc-link-lib=hermesParser");
println!("cargo:rustc-link-lib=hermesPlatformUnicode");
println!("cargo:rustc-link-lib=hermesSupport");
println!("cargo:rustc-link-lib=LLVHSupport");
println!("cargo:rustc-link-lib=dtoa");
println!("cargo:rustc-link-lib=c++");
}
| 33.942857 | 77 | 0.672559 |
1408fe1e091c6583d217c358131de04e891df4ea | 15,376 | //! This crate provides functions to call from build and post-build scripts as part of
//! wasm32-unknown-unknown builds that rely on crates using the `embed_js` crate to write inline
//! javascript.
//!
//! See the `embed_js` repository for examples of how to use these crates together.
extern crate embed_js_common;
extern crate cpp_synmap;
extern crate cpp_syn;
extern crate serde_json;
extern crate uuid;
extern crate parity_wasm;
use cpp_synmap::SourceMap;
use cpp_syn::visit::Visitor;
use cpp_syn::{Mac, TokenTree, Delimited};
use parity_wasm::elements::{Module, Section, ExportEntry, Internal};
use std::env;
use std::path::{ PathBuf, Path };
use std::io::{ BufWriter, BufReader, Read };
use std::fs::File;
use std::process::Command;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::collections::HashMap;
use embed_js_common::{ JsMac, JsMacArg };
struct JsVisitor<'a> {
source_map: &'a mut SourceMap,
instances: &'a mut Vec<JsMac>,
included_js: &'a mut String
}
impl<'a> Visitor for JsVisitor<'a> {
fn visit_mac(&mut self, mac: &Mac) {
if mac.path.segments.len() != 1 {
return;
}
let tts = match mac.tts[0] {
TokenTree::Delimited(Delimited { ref tts, .. }, _) => &**tts,
_ => return,
};
match mac.path.segments[0].ident.as_ref() {
"js" => {
if let Ok(parsed) = embed_js_common::parse_js_mac_source_map(tts, self.source_map) {
self.instances.push(parsed);
}
}
"include_js" => {
let js_source = if let (Some(first), Some(last)) = (tts.first(), tts.last()) {
self.source_map.source_text(first.span().extend(last.span())).unwrap()
} else {
""
};
self.included_js.push_str(&js_source);
self.included_js.push_str("\n");
}
"include" => {
use cpp_syn::{ Token, Lit, LitKind };
let mut iter = tts.iter().peekable();
match iter.next() {
Some(&TokenTree::Token(Token::Literal(Lit { node: LitKind::Str(ref path, _), .. }), span)) => {
if iter.next().is_some() {
return;
}
let mut path = PathBuf::from(path);
if !path.is_absolute() {
let root = self.source_map.filename(span).unwrap();
path = root.join(path);
}
println!("cargo:warning=embed_js_build processing source in included file {}", path.display());
let krate = self.source_map.add_crate_root(path).unwrap();
self.visit_crate(&krate);
}
Some(&TokenTree::Token(Token::Ident(ref ident), span)) if ident.as_ref() == "concat" => {
match iter.next() {
Some(&TokenTree::Token(Token::Not, _)) => {}
_ => return
}
let tts = match iter.next() {
Some(&TokenTree::Delimited(Delimited { ref tts, .. }, _)) => {
tts
}
_ => return
};
let mut path = String::new();
let mut iter = tts.iter().peekable();
while let Some(t) = iter.next() {
match *t {
TokenTree::Token(Token::Literal(Lit { node: LitKind::Str(ref s, _), .. }), _) => {
path.push_str(s);
}
TokenTree::Token(Token::Comma, _) => {}
TokenTree::Token(Token::Ident(ref ident), _) if ident.as_ref() == "env" => {
match iter.next() {
Some(&TokenTree::Token(Token::Not, _)) => {}
_ => return
}
let tts = match iter.next() {
Some(&TokenTree::Delimited(Delimited { ref tts, .. }, _)) => {
tts
}
_ => return
};
if let Some(&TokenTree::Token(Token::Literal(Lit { node: LitKind::Str(ref s, _), .. }), _)) = tts.first() {
if tts.len() != 1 {
return
}
if let Ok(v) = std::env::var(s) {
path.push_str(&v);
} else {
return
}
} else {
return
}
}
_ => return
}
}
let mut path = PathBuf::from(path);
if !path.is_absolute() {
let root = self.source_map.filename(span).unwrap();
path = root.join(path);
}
println!("cargo:warning=embed_js_build processing source in included file {}", path.display());
let krate = self.source_map.add_crate_root(path).unwrap();
self.visit_crate(&krate);
}
_ => return
}
}
_ => {}
}
}
}
/// Call this once from a build script for a crate that uses `embed_js` directly.
///
/// Parameters:
///
/// * `lib_root` The path to the crate root rust file, e.g. "src/lib.rs"
///
/// Example:
///
/// ```ignore
/// extern crate embed_js_build;
/// fn main() {
/// use std::path::PathBuf;
/// let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("src/lib.rs");
/// embed_js_build::preprocess_crate(&root);
/// }
/// ```
pub fn preprocess_crate(lib_root: &Path) {
let mut source_map = SourceMap::new();
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let mut instances = Vec::new();
let mut included_js = String::new();
let krate = source_map.add_crate_root(lib_root).unwrap();
JsVisitor {
source_map: &mut source_map,
instances: &mut instances,
included_js: &mut included_js
}.visit_crate(&krate);
let js_path = out_dir.join("embed_js_data.json");
serde_json::to_writer(BufWriter::new(File::create(&js_path).unwrap()), &(instances, included_js)).unwrap();
let preamble_path = out_dir.join("embed_js_preamble.rs");
File::create(preamble_path).unwrap();
}
/// Generated from `postprocess_crate`.
pub struct PostProcessData {
/// The path to the generated wasm binary.
pub wasm_path: PathBuf,
/// The contents of the wasm binary, provided for convenience.
pub wasm: Vec<u8>,
/// The javascript that should be put as the value of the `env` field in the `importObject`
/// passed to `WebAssembly.instantiate`.
pub imports: String,
/// All javascript specified by the `include_js` macro in linked crates. This should be run
/// before the WebAssembly module is loaded.
pub included: String
}
/// Call this once **after** a wasm-unknown-unknown build has completed (i.e. from a post-build
/// script) in order to generate the javascript imports that should accompany the wasm binary.
///
/// See the `embed_js` repository for example projects using this function.
///
/// Parameters:
///
/// * `lib_name` The binary name to process, typically the name of the crate unless set otherwise
/// in `Cargo.toml`.
/// * `debug` Whether to look for the debug or release binary to process. Until wasm32-unkown-unknown
/// supports debug builds, this should always be set to `false`.
///
/// Example post-build script, taken from the "simple" example in the `embed_js` repository:
///
/// ```ignore
/// extern crate base64;
/// extern crate embed_js_build;
///
/// use std::fs::File;
/// use std::io::Write;
///
/// fn main() {
/// let pp_data = embed_js_build::postprocess_crate("simple", false).unwrap();
/// let in_base_64 = base64::encode(&pp_data.wasm);
/// let html_path = pp_data.wasm_path.with_extension("html");
/// let mut html_file = File::create(&html_path).unwrap();
/// write!(html_file, r#"<!DOCTYPE html>
/// <html lang="en">
/// <head>
/// <meta charset="utf-8">
/// <title> wasm test </title>
/// <script>
/// function _base64ToArrayBuffer(base64) {{
/// var binary_string = window.atob(base64);
/// var len = binary_string.length;
/// var bytes = new Uint8Array( len );
/// for (var i = 0; i < len; ++i) {{
/// bytes[i] = binary_string.charCodeAt(i);
/// }}
/// return bytes.buffer;
/// }}
/// var bytes = _base64ToArrayBuffer(
/// "{}"
/// );
/// WebAssembly.instantiate(bytes, {{ env: {{
/// {}
/// }}}}).then(results => {{
/// window.exports = results.instance.exports;
/// console.log(results.instance.exports.add_two(2));
/// }});
/// </script>
/// </head>
/// </html>
/// "#,
/// in_base_64,
/// pp_data.imports
/// ).unwrap();
/// }
pub fn postprocess_crate(lib_name: &str, debug: bool) -> std::io::Result<PostProcessData> {
let metadata_json = Command::new("cargo").args(&["metadata", "--format-version", "1"]).output().unwrap().stdout;
let metadata_json: serde_json::Value = serde_json::from_slice(&metadata_json).unwrap();
let target_directory = Path::new(metadata_json.as_object().unwrap().get("target_directory").unwrap().as_str().unwrap());
let bin_prefix = target_directory.join(&format!("wasm32-unknown-unknown/{}/{}", if debug { "debug" } else { "release" }, lib_name));
// collect json data from all dependency crates
let d_path = bin_prefix.with_extension("d");
let mut d_string = String::new();
File::open(&d_path)?.read_to_string(&mut d_string).unwrap();
let mut d_pieces: Vec<String> = d_string.split_whitespace().map(String::from).collect::<Vec<_>>();
{ // stick escaped spaces back together
let mut i = 0;
while i < d_pieces.len() {
while d_pieces[i].ends_with("\\") && i != d_pieces.len() - 1 {
let removed = d_pieces.remove(i+1);
d_pieces[i].push_str(&removed);
}
i += 1;
}
}
d_pieces.remove(0); // remove lib path
let mut js_macs: HashMap<String, JsMac> = HashMap::new();
let mut included_js = String::new();
for path in d_pieces {
if path.ends_with("out/embed_js_preamble.rs") || path.ends_with("out\\embed_js_preamble.rs") {
let data_path = PathBuf::from(path).with_file_name("embed_js_data.json");
let (mut crate_js_macs, crate_included_js): (Vec<JsMac>, String) = serde_json::from_reader(BufReader::new(File::open(data_path)?)).unwrap();
included_js.push_str(&crate_included_js);
for js_mac in crate_js_macs.drain(..) {
let mut hasher = DefaultHasher::new();
js_mac.hash(&mut hasher);
let mac_hash = hasher.finish();
let key = format!("__embed_js__{:x}", mac_hash);
if let Some(existing) = js_macs.get(&key) {
if *existing != js_mac {
panic!("A hash collision has occurred in the embed_js build process. Please raise a bug! Meanwhile, try making small changes to your embedded js to remove the collision.")
}
}
js_macs.insert(key, js_mac);
}
}
}
let wasm_path = bin_prefix.with_extension("wasm");
match Command::new("wasm-gc").args(&[&wasm_path, &wasm_path]).output() {
Ok(output) => {
if !output.status.success() {
panic!("wasm-gc encountered an error.\n\nstatus: {}\n\nstdout:\n\n{}\n\nstderr:\n\n{}",
output.status,
String::from_utf8(output.stdout).unwrap_or_else(|_| String::from("<error decoding stdout>")),
String::from_utf8(output.stderr).unwrap_or_else(|_| String::from("<error decoding stderr>")))
}
}
Err(e) => panic!("Error attempting to run wasm-gc. Have you got it installed? Error message: {}", e)
}
let mut wasm = Vec::new();
BufReader::new(File::open(&wasm_path)?).read_to_end(&mut wasm)?;
let mut module: Module = parity_wasm::deserialize_buffer(wasm.clone()).unwrap();
// modify the module to export the function table
let has_table_export = module.export_section()
.map(|exports| exports.entries()
.iter()
.any(|entry| entry.field() == "__table"))
.unwrap_or(false);
if !has_table_export && module.table_section().is_some() {
let sections = module.sections_mut();
for section in sections {
match *section {
Section::Export(ref mut exports) => {
exports.entries_mut().push(ExportEntry::new("__table".to_string(), Internal::Table(0)));
break;
}
_ => {}
}
}
}
parity_wasm::serialize_to_file(&wasm_path, module.clone()).unwrap();
wasm.clear();
BufReader::new(File::open(&wasm_path)?).read_to_end(&mut wasm)?;
let mut imports = String::new();
if let Some(import_section) = module.import_section() {
for entry in import_section.entries() {
if entry.module() == "env" {
if let Some(mac) = js_macs.remove(entry.field()) {
if !imports.is_empty() {
imports.push_str(",\n");
}
imports.push_str(&format!("{}:function(", entry.field()));
let mut start = true;
for arg in mac.args {
if !start {
imports.push_str(", ");
} else {
start = false;
}
match arg {
JsMacArg::Ref(_, _, name) |
JsMacArg::Primitive(_, name, _) => imports.push_str(&name)
}
}
if let Some(body) = mac.body {
imports.push_str(&format!("){{{}}}", body));
} else {
imports.push_str("){}\n");
}
}
}
}
}
// find
Ok(PostProcessData {
wasm_path,
wasm,
included: included_js,
imports
})
} | 42.358127 | 195 | 0.503057 |
4bf08096edeb8e589f25ee24760bbf721ffd9bbf | 2,385 | use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::{self, Ty, TyCtxt, TypeFlags};
pub(super) fn provide(providers: &mut ty::query::Providers<'_>) {
*providers = ty::query::Providers { erase_regions_ty, ..*providers };
}
fn erase_regions_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
// N.B., use `super_fold_with` here. If we used `fold_with`, it
// could invoke the `erase_regions_ty` query recursively.
ty.super_fold_with(&mut RegionEraserVisitor { tcx })
}
impl<'tcx> TyCtxt<'tcx> {
/// Returns an equivalent value with all free regions removed (note
/// that late-bound regions remain, because they are important for
/// subtyping, but they are anonymized and normalized as well)..
pub fn erase_regions<T>(self, value: &T) -> T
where
T: TypeFoldable<'tcx>,
{
// If there's nothing to erase avoid performing the query at all
if !value.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND | TypeFlags::HAS_FREE_REGIONS) {
return value.clone();
}
let value1 = value.fold_with(&mut RegionEraserVisitor { tcx: self });
debug!("erase_regions({:?}) = {:?}", value, value1);
value1
}
}
struct RegionEraserVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
}
impl TypeFolder<'tcx> for RegionEraserVisitor<'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
if ty.has_local_value() { ty.super_fold_with(self) } else { self.tcx.erase_regions_ty(ty) }
}
fn fold_binder<T>(&mut self, t: &ty::Binder<T>) -> ty::Binder<T>
where
T: TypeFoldable<'tcx>,
{
let u = self.tcx.anonymize_late_bound_regions(t);
u.super_fold_with(self)
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
// because late-bound regions affect subtyping, we can't
// erase the bound/free distinction, but we can replace
// all free regions with 'erased.
//
// Note that we *CAN* replace early-bound regions -- the
// type system never "sees" those, they get substituted
// away. In codegen, they will always be erased to 'erased
// whenever a substitution occurs.
match *r {
ty::ReLateBound(..) => r,
_ => self.tcx.lifetimes.re_erased,
}
}
}
| 34.565217 | 99 | 0.613417 |
715083ddca508c6abc9917a162a13ccf81206165 | 326 | use crate::{FormatElement, FormatResult, Formatter, ToFormatElement};
use rslint_parser::{ast::TsImportTypeQualifier, AstNode};
impl ToFormatElement for TsImportTypeQualifier {
fn to_format_element(&self, formatter: &Formatter) -> FormatResult<FormatElement> {
Ok(formatter.format_verbatim(self.syntax()))
}
}
| 40.75 | 87 | 0.763804 |
f530aa0fc81d41269d527f259e8f342ed7f911c9 | 73 | #pragma version(1)
#pragma rs java_package_name(foo)
long l = 1L << 32;
| 14.6 | 33 | 0.69863 |
eb15f766ac17fd4142ff73d2c52554f639ddf363 | 15,823 | #[cfg(target_os = "macos")]
use libc::getpid;
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::fs;
use std::io::{BufRead, BufReader, Cursor};
use std::path::{Path, PathBuf};
use std::process;
use failure::{Error, ResultExt};
#[cfg(target_os = "macos")]
use mac_process_info;
#[cfg(target_os = "macos")]
use osascript;
use plist::serde::deserialize;
use regex::Regex;
use serde_json;
#[cfg(target_os = "macos")]
use unix_daemonize::{daemonize_redirect, ChdirMode};
use utils::fs::{SeekRead, TempFile};
use utils::system::expand_vars;
#[derive(Deserialize, Debug)]
pub struct InfoPlist {
#[serde(rename = "CFBundleName")]
name: String,
#[serde(rename = "CFBundleIdentifier")]
bundle_id: String,
#[serde(rename = "CFBundleShortVersionString")]
version: String,
#[serde(rename = "CFBundleVersion")]
build: String,
}
#[derive(Deserialize, Debug)]
pub struct XcodeProjectInfo {
targets: Vec<String>,
schemes: Vec<String>,
configurations: Vec<String>,
name: String,
#[serde(default = "PathBuf::new")]
path: PathBuf,
}
impl fmt::Display for InfoPlist {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} ({})", self.name(), &self.version)
}
}
pub fn expand_xcodevars(s: String, vars: &HashMap<String, String>) -> String {
lazy_static! {
static ref SEP_RE: Regex = Regex::new(r"[\s/]+").unwrap();
}
expand_vars(&s, |key| {
if key == "" {
return "".into();
}
let mut iter = key.splitn(2, ':');
let value = vars
.get(iter.next().unwrap())
.map(|x| x.as_str())
.unwrap_or("");
match iter.next() {
Some("rfc1034identifier") => SEP_RE.replace_all(value, "-").into_owned(),
Some("identifier") => SEP_RE.replace_all(value, "_").into_owned(),
None | Some(_) => value.to_string(),
}
}).into_owned()
}
fn get_xcode_project_info(path: &Path) -> Result<Option<XcodeProjectInfo>, Error> {
if_chain! {
if let Some(filename_os) = path.file_name();
if let Some(filename) = filename_os.to_str();
if filename.ends_with(".xcodeproj");
then {
return Ok(Some(XcodeProjectInfo::from_path(path)?));
}
}
let mut projects = vec![];
for entry_rv in fs::read_dir(path)? {
if let Ok(entry) = entry_rv {
if let Some(filename) = entry.file_name().to_str() {
if filename.ends_with(".xcodeproj") {
projects.push(entry.path().to_path_buf());
}
}
}
}
if projects.len() == 1 {
Ok(Some(XcodeProjectInfo::from_path(&projects[0])?))
} else {
Ok(None)
}
}
impl XcodeProjectInfo {
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<XcodeProjectInfo, Error> {
#[derive(Deserialize)]
struct Output {
project: XcodeProjectInfo,
}
let p = process::Command::new("xcodebuild")
.arg("-list")
.arg("-json")
.arg("-project")
.arg(path.as_ref().as_os_str())
.output()?;
let mut rv: Output = serde_json::from_slice(&p.stdout)?;
rv.project.path = path.as_ref().canonicalize()?;
Ok(rv.project)
}
pub fn base_path(&self) -> &Path {
self.path.parent().unwrap()
}
pub fn get_build_vars(
&self,
target: &str,
configuration: &str,
) -> Result<HashMap<String, String>, Error> {
let mut rv = HashMap::new();
let p = process::Command::new("xcodebuild")
.arg("-showBuildSettings")
.arg("-project")
.arg(&self.path)
.arg("-target")
.arg(target)
.arg("-configuration")
.arg(configuration)
.output()?;
for line_rv in p.stdout.lines() {
let line = line_rv?;
if line.starts_with(" ") {
let mut sep = line[4..].splitn(2, " = ");
if_chain! {
if let Some(key) = sep.next();
if let Some(value) = sep.next();
then {
rv.insert(key.to_owned(), value.to_owned());
}
}
}
}
Ok(rv)
}
/// Return the first target
pub fn get_first_target(&self) -> Option<&str> {
if !self.targets.is_empty() {
Some(&self.targets[0])
} else {
None
}
}
/// Returns the config with a certain name
pub fn get_configuration(&self, name: &str) -> Option<&str> {
let name = name.to_lowercase();
for cfg in &self.configurations {
if cfg.to_lowercase() == name {
return Some(&cfg);
}
}
None
}
}
impl InfoPlist {
/// Loads a processed plist file.
pub fn discover_from_env() -> Result<Option<InfoPlist>, Error> {
// if we are loaded directly from xcode we can trust the os environment
// and pass those variables to the processor.
if env::var("XCODE_VERSION_ACTUAL").is_ok() {
let vars: HashMap<_, _> = env::vars().collect();
if let Some(filename) = vars.get("INFOPLIST_FILE") {
let base = vars.get("PROJECT_DIR").map(|x| x.as_str()).unwrap_or(".");
let path = env::current_dir().unwrap().join(base).join(filename);
Ok(Some(InfoPlist::load_and_process(&path, &vars)?))
} else {
Ok(None)
}
// otherwise, we discover the project info from the current path and
// invoke xcodebuild to give us the project settings for the first
// target.
} else {
if_chain! {
if let Ok(here) = env::current_dir();
if let Some(pi) = get_xcode_project_info(&here)?;
then {
InfoPlist::from_project_info(&pi)
} else {
Ok(None)
}
}
}
}
/// Lodas an info plist from a given project info
pub fn from_project_info(pi: &XcodeProjectInfo) -> Result<Option<InfoPlist>, Error> {
if_chain! {
if let Some(config) = pi.get_configuration("release")
.or_else(|| pi.get_configuration("debug"));
if let Some(target) = pi.get_first_target();
then {
let vars = pi.get_build_vars(target, config)?;
if let Some(path) = vars.get("INFOPLIST_FILE") {
let base = vars.get("PROJECT_DIR").map(|x| Path::new(x.as_str()))
.unwrap_or(pi.base_path());
let path = base.join(path);
return Ok(Some(InfoPlist::load_and_process(path, &vars)?));
}
}
}
Ok(None)
}
/// loads an info plist file from a path and processes it with the given vars
pub fn load_and_process<P: AsRef<Path>>(
path: P,
vars: &HashMap<String, String>,
) -> Result<InfoPlist, Error> {
// do we want to preprocess the plist file?
let mut rv = if vars.get("INFOPLIST_PREPROCESS").map(|x| x.as_str()) == Some("YES") {
let mut c = process::Command::new("cc");
c.arg("-xc").arg("-P").arg("-E");
if let Some(defs) = vars.get("INFOPLIST_PREPROCESSOR_DEFINITIONS") {
for token in defs.split_whitespace() {
c.arg(format!("-D{}", token));
}
}
c.arg(path.as_ref());
let p = c.output()?;
InfoPlist::from_reader(&mut Cursor::new(&p.stdout[..]))?
} else {
InfoPlist::from_path(path)?
};
// expand xcodevars here
rv.name = expand_xcodevars(rv.name, &vars);
rv.bundle_id = expand_xcodevars(rv.bundle_id, &vars);
rv.version = expand_xcodevars(rv.version, &vars);
rv.build = expand_xcodevars(rv.build, &vars);
Ok(rv)
}
/// Loads an info plist file from a path and does not process it.
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<InfoPlist, Error> {
let mut f = fs::File::open(path.as_ref()).context("Could not open Info.plist file")?;
InfoPlist::from_reader(&mut f)
}
/// Loads an info plist file from a reader.
pub fn from_reader<R: SeekRead>(rdr: R) -> Result<InfoPlist, Error> {
let mut rdr = BufReader::new(rdr);
Ok(deserialize(&mut rdr).context("Could not parse Info.plist file")?)
}
pub fn get_release_name(&self) -> String {
format!("{}-{}", self.bundle_id(), self.version())
}
pub fn version(&self) -> &str {
&self.version
}
pub fn build(&self) -> &str {
&self.build
}
pub fn name(&self) -> &str {
&self.name
}
pub fn bundle_id(&self) -> &str {
&self.bundle_id
}
}
/// Helper struct that allows the current execution to detach from
/// the xcode console and continue in the background. This becomes
/// a dummy shim for non xcode runs or platforms.
pub struct MayDetach<'a> {
output_file: Option<TempFile>,
#[allow(dead_code)]
task_name: &'a str,
}
impl<'a> MayDetach<'a> {
fn new(task_name: &'a str) -> MayDetach<'a> {
MayDetach {
output_file: None,
task_name: task_name,
}
}
/// Returns true if we are deteached from xcode
pub fn is_detached(&self) -> bool {
self.output_file.is_some()
}
/// If we are launched from xcode this detaches us from the xcode console
/// and continues execution in the background. From this moment on output
/// is captured and the user is notified with notifications.
#[cfg(target_os = "macos")]
pub fn may_detach(&mut self) -> Result<bool, Error> {
if !launched_from_xcode() {
return Ok(false);
}
println!("Continuing in background.");
show_notification("Sentry", &format!("{} starting", self.task_name))?;
let output_file = TempFile::new()?;
daemonize_redirect(
Some(output_file.path()),
Some(output_file.path()),
ChdirMode::NoChdir,
).unwrap();
self.output_file = Some(output_file);
Ok(true)
}
/// For non mac platforms this just never detaches.
#[cfg(not(target_os = "macos"))]
pub fn may_detach(&mut self) -> Result<bool, Error> {
Ok(false)
}
/// Wraps the execution of a code block. Does not detach until someone
/// calls into `may_detach`.
#[cfg(target_os = "macos")]
pub fn wrap<T, F: FnOnce(&mut MayDetach) -> Result<T, Error>>(
task_name: &'a str,
f: F,
) -> Result<T, Error> {
use open;
use std::thread;
use std::time::Duration;
use utils::system::print_error;
let mut md = MayDetach::new(task_name);
match f(&mut md) {
Ok(x) => {
md.show_done()?;
Ok(x)
}
Err(err) => {
if let Some(ref output_file) = md.output_file {
print_error(&err);
if md.show_critical_info()? {
open::that(&output_file.path())?;
thread::sleep(Duration::from_millis(5000));
}
}
Err(err)
}
}
}
/// Dummy wrap call that never detaches for non mac platforms.
#[cfg(not(target_os = "macos"))]
pub fn wrap<T, F: FnOnce(&mut MayDetach) -> Result<T, Error>>(
task_name: &'a str,
f: F,
) -> Result<T, Error> {
f(&mut MayDetach::new(task_name))
}
#[cfg(target_os = "macos")]
fn show_critical_info(&self) -> Result<bool, Error> {
show_critical_info(
&format!("{} failed", self.task_name),
"The Sentry build step failed while running in the background. \
You can ignore this error or view details to attempt to resolve \
it. Ignoring it might cause your crashes not to be handled \
properly.",
)
}
#[cfg(target_os = "macos")]
fn show_done(&self) -> Result<(), Error> {
if self.is_detached() {
show_notification("Sentry", &format!("{} finished", self.task_name))?;
}
Ok(())
}
}
/// Returns true if we were invoked from xcode
#[cfg(target_os = "macos")]
pub fn launched_from_xcode() -> bool {
if env::var("XCODE_VERSION_ACTUAL").is_err() {
return false;
}
let mut pid = unsafe { getpid() as u32 };
while let Some(parent) = mac_process_info::get_parent_pid(pid) {
if parent == 1 {
break;
}
if let Ok(name) = mac_process_info::get_process_name(parent) {
if &name == "Xcode" {
return true;
}
}
pid = parent;
}
false
}
/// Shows a dialog in xcode and blocks. The dialog will have a title and a
/// message as well as the buttons "Show details" and "Ignore". Returns
/// `true` if the `show details` button has been pressed.
#[cfg(target_os = "macos")]
pub fn show_critical_info(title: &str, msg: &str) -> Result<bool, Error> {
lazy_static! {
static ref SCRIPT: osascript::JavaScript = osascript::JavaScript::new(
"
var App = Application('XCode');
App.includeStandardAdditions = true;
return App.displayAlert($params.title, {
message: $params.message,
as: \"critical\",
buttons: [\"Show details\", \"Ignore\"]
});
"
);
}
#[derive(Serialize)]
struct AlertParams<'a> {
title: &'a str,
message: &'a str,
}
#[derive(Debug, Deserialize)]
struct AlertResult {
#[serde(rename = "buttonReturned")]
button: String,
}
let rv: AlertResult = SCRIPT
.execute_with_params(AlertParams {
title: title,
message: msg,
})
.context("Failed to display Xcode dialog")?;
Ok(&rv.button != "Ignore")
}
/// Shows a notification in xcode
#[cfg(target_os = "macos")]
pub fn show_notification(title: &str, msg: &str) -> Result<(), Error> {
use config::Config;
lazy_static! {
static ref SCRIPT: osascript::JavaScript = osascript::JavaScript::new(
"
var App = Application.currentApplication();
App.includeStandardAdditions = true;
App.displayNotification($params.message, {
withTitle: $params.title
});
"
);
}
let config = Config::get_current();
if !config.show_notifications()? {
return Ok(());
}
#[derive(Serialize)]
struct NotificationParams<'a> {
title: &'a str,
message: &'a str,
}
Ok(SCRIPT
.execute_with_params(NotificationParams {
title: title,
message: msg,
})
.context("Failed to display Xcode notification")?)
}
#[test]
fn test_expansion() {
let mut vars = HashMap::new();
vars.insert("FOO_BAR".to_string(), "foo bar baz / blah".to_string());
assert_eq!(
expand_xcodevars("A$(FOO_BAR:rfc1034identifier)B".to_string(), &vars),
"Afoo-bar-baz-blahB".to_string()
);
assert_eq!(
expand_xcodevars("A$(FOO_BAR:identifier)B".to_string(), &vars),
"Afoo_bar_baz_blahB".to_string()
);
assert_eq!(
expand_xcodevars("A${FOO_BAR:identifier}B".to_string(), &vars),
"Afoo_bar_baz_blahB".to_string()
);
}
| 30.724272 | 93 | 0.539594 |
f71bbb7c7a318889b2d0c5053b4ede89759532cd | 2,404 | use core::num::dec2flt::lemire::compute_float;
fn compute_float32(q: i64, w: u64) -> (i32, u64) {
let fp = compute_float::<f32>(q, w);
(fp.e, fp.f)
}
fn compute_float64(q: i64, w: u64) -> (i32, u64) {
let fp = compute_float::<f64>(q, w);
(fp.e, fp.f)
}
#[test]
fn compute_float_f32_rounding() {
// These test near-halfway cases for single-precision floats.
assert_eq!(compute_float32(0, 16777216), (151, 0));
assert_eq!(compute_float32(0, 16777217), (151, 0));
assert_eq!(compute_float32(0, 16777218), (151, 1));
assert_eq!(compute_float32(0, 16777219), (151, 2));
assert_eq!(compute_float32(0, 16777220), (151, 2));
// These are examples of the above tests, with
// digits from the exponent shifted to the mantissa.
assert_eq!(compute_float32(-10, 167772160000000000), (151, 0));
assert_eq!(compute_float32(-10, 167772170000000000), (151, 0));
assert_eq!(compute_float32(-10, 167772180000000000), (151, 1));
// Let's check the lines to see if anything is different in table...
assert_eq!(compute_float32(-10, 167772190000000000), (151, 2));
assert_eq!(compute_float32(-10, 167772200000000000), (151, 2));
}
#[test]
fn compute_float_f64_rounding() {
// These test near-halfway cases for double-precision floats.
assert_eq!(compute_float64(0, 9007199254740992), (1076, 0));
assert_eq!(compute_float64(0, 9007199254740993), (1076, 0));
assert_eq!(compute_float64(0, 9007199254740994), (1076, 1));
assert_eq!(compute_float64(0, 9007199254740995), (1076, 2));
assert_eq!(compute_float64(0, 9007199254740996), (1076, 2));
assert_eq!(compute_float64(0, 18014398509481984), (1077, 0));
assert_eq!(compute_float64(0, 18014398509481986), (1077, 0));
assert_eq!(compute_float64(0, 18014398509481988), (1077, 1));
assert_eq!(compute_float64(0, 18014398509481990), (1077, 2));
assert_eq!(compute_float64(0, 18014398509481992), (1077, 2));
// These are examples of the above tests, with
// digits from the exponent shifted to the mantissa.
assert_eq!(compute_float64(-3, 9007199254740992000), (1076, 0));
assert_eq!(compute_float64(-3, 9007199254740993000), (1076, 0));
assert_eq!(compute_float64(-3, 9007199254740994000), (1076, 1));
assert_eq!(compute_float64(-3, 9007199254740995000), (1076, 2));
assert_eq!(compute_float64(-3, 9007199254740996000), (1076, 2));
}
| 44.518519 | 72 | 0.688436 |
ac945680cdbd1c6d125898bed51315784f17abf9 | 811 | fn main() {
winrt::build!(
types
windows::foundation::diagnostics::*
windows::foundation::*
windows::ai::machine_learning::*
windows::storage::streams::{DataReader, DataWriter, InMemoryRandomAccessStream}
windows::ui::{Color, Colors}
windows::ui::composition::{Compositor, SpriteVisual, Visual}
windows::foundation::numerics::*
// Usage of method named `try` when `ICurrencyIdentifiersStatics` is generated
// This tests that it is escaped
windows::globalization::ICurrencyIdentifiersStatics
test_component::*
windows::ui::xaml::*
windows::data::xml::dom::*
windows::application_model::appointments::AppointmentDaysOfWeek
);
}
| 40.55 | 91 | 0.59926 |
fc674bb013be3623d585334dde8685f07b23b910 | 89,152 | use crate::{
accounts::Accounts, ancestors::Ancestors, instruction_recorder::InstructionRecorder,
log_collector::LogCollector, native_loader::NativeLoader, rent_collector::RentCollector,
};
use log::*;
use serde::{Deserialize, Serialize};
use solana_measure::measure::Measure;
use solana_sdk::{
account::{AccountSharedData, ReadableAccount, WritableAccount},
account_utils::StateMut,
bpf_loader_upgradeable::{self, UpgradeableLoaderState},
feature_set::{
instructions_sysvar_enabled, neon_evm_compute_budget, tx_wide_compute_cap,
updated_verify_policy, FeatureSet,
},
ic_logger_msg, ic_msg,
instruction::{CompiledInstruction, Instruction, InstructionError},
keyed_account::{create_keyed_accounts_unified, keyed_account_at_index, KeyedAccount},
message::Message,
native_loader,
process_instruction::{
BpfComputeBudget, ComputeMeter, Executor, InvokeContext, InvokeContextStackFrame, Logger,
ProcessInstructionWithContext,
},
pubkey::Pubkey,
rent::Rent,
system_program,
sysvar::instructions,
transaction::TransactionError,
};
use std::{
cell::{Ref, RefCell},
collections::HashMap,
rc::Rc,
sync::Arc,
};
pub struct Executors {
pub executors: HashMap<Pubkey, Arc<dyn Executor>>,
pub is_dirty: bool,
}
impl Default for Executors {
fn default() -> Self {
Self {
executors: HashMap::default(),
is_dirty: false,
}
}
}
impl Executors {
pub fn insert(&mut self, key: Pubkey, executor: Arc<dyn Executor>) {
let _ = self.executors.insert(key, executor);
self.is_dirty = true;
}
pub fn get(&self, key: &Pubkey) -> Option<Arc<dyn Executor>> {
self.executors.get(key).cloned()
}
}
#[derive(Default, Debug)]
pub struct ProgramTiming {
pub accumulated_us: u64,
pub accumulated_units: u64,
pub count: u32,
}
#[derive(Default, Debug)]
pub struct ExecuteDetailsTimings {
pub serialize_us: u64,
pub create_vm_us: u64,
pub execute_us: u64,
pub deserialize_us: u64,
pub changed_account_count: u64,
pub total_account_count: u64,
pub total_data_size: usize,
pub data_size_changed: usize,
pub per_program_timings: HashMap<Pubkey, ProgramTiming>,
}
impl ExecuteDetailsTimings {
pub fn accumulate(&mut self, other: &ExecuteDetailsTimings) {
self.serialize_us += other.serialize_us;
self.create_vm_us += other.create_vm_us;
self.execute_us += other.execute_us;
self.deserialize_us += other.deserialize_us;
self.changed_account_count += other.changed_account_count;
self.total_account_count += other.total_account_count;
self.total_data_size += other.total_data_size;
self.data_size_changed += other.data_size_changed;
for (id, other) in &other.per_program_timings {
let program_timing = self.per_program_timings.entry(*id).or_default();
program_timing.accumulated_us += other.accumulated_us;
program_timing.accumulated_units += other.accumulated_units;
program_timing.count += other.count;
}
}
}
// The relevant state of an account before an Instruction executes, used
// to verify account integrity after the Instruction completes
#[derive(Clone, Debug, Default)]
pub struct PreAccount {
key: Pubkey,
account: Rc<RefCell<AccountSharedData>>,
changed: bool,
}
impl PreAccount {
pub fn new(key: &Pubkey, account: &AccountSharedData) -> Self {
Self {
key: *key,
account: Rc::new(RefCell::new(account.clone())),
changed: false,
}
}
pub fn verify(
&self,
program_id: &Pubkey,
is_writable: bool,
rent: &Rent,
post: &AccountSharedData,
timings: &mut ExecuteDetailsTimings,
outermost_call: bool,
updated_verify_policy: bool,
) -> Result<(), InstructionError> {
let pre = self.account.borrow();
// Only the owner of the account may change owner and
// only if the account is writable and
// only if the account is not executable and
// only if the data is zero-initialized or empty
let owner_changed = pre.owner() != post.owner();
if owner_changed
&& (!is_writable // line coverage used to get branch coverage
|| pre.executable()
|| program_id != pre.owner()
|| !Self::is_zeroed(post.data()))
{
return Err(InstructionError::ModifiedProgramId);
}
// An account not assigned to the program cannot have its balance decrease.
if program_id != pre.owner() // line coverage used to get branch coverage
&& pre.lamports() > post.lamports()
{
return Err(InstructionError::ExternalAccountLamportSpend);
}
// The balance of read-only and executable accounts may not change
let lamports_changed = pre.lamports() != post.lamports();
if lamports_changed {
if !is_writable {
return Err(InstructionError::ReadonlyLamportChange);
}
if pre.executable() {
return Err(InstructionError::ExecutableLamportChange);
}
}
// Only the system program can change the size of the data
// and only if the system program owns the account
let data_len_changed = pre.data().len() != post.data().len();
if data_len_changed
&& (!system_program::check_id(program_id) // line coverage used to get branch coverage
|| !system_program::check_id(pre.owner()))
{
return Err(InstructionError::AccountDataSizeChanged);
}
// Only the owner may change account data
// and if the account is writable
// and if the account is not executable
if !(program_id == pre.owner()
&& is_writable // line coverage used to get branch coverage
&& !pre.executable())
&& pre.data() != post.data()
{
if pre.executable() {
return Err(InstructionError::ExecutableDataModified);
} else if is_writable {
return Err(InstructionError::ExternalAccountDataModified);
} else {
return Err(InstructionError::ReadonlyDataModified);
}
}
// executable is one-way (false->true) and only the account owner may set it.
let executable_changed = pre.executable() != post.executable();
if executable_changed {
if !rent.is_exempt(post.lamports(), post.data().len()) {
return Err(InstructionError::ExecutableAccountNotRentExempt);
}
let owner = if updated_verify_policy {
post.owner()
} else {
pre.owner()
};
if !is_writable // line coverage used to get branch coverage
|| pre.executable()
|| program_id != owner
{
return Err(InstructionError::ExecutableModified);
}
}
// No one modifies rent_epoch (yet).
let rent_epoch_changed = pre.rent_epoch() != post.rent_epoch();
if rent_epoch_changed {
return Err(InstructionError::RentEpochModified);
}
if outermost_call {
timings.total_account_count += 1;
timings.total_data_size += post.data().len();
if owner_changed
|| lamports_changed
|| data_len_changed
|| executable_changed
|| rent_epoch_changed
|| self.changed
{
timings.changed_account_count += 1;
timings.data_size_changed += post.data().len();
}
}
Ok(())
}
pub fn update(&mut self, account: &AccountSharedData) {
let mut pre = self.account.borrow_mut();
let rent_epoch = pre.rent_epoch();
*pre = account.clone();
pre.set_rent_epoch(rent_epoch);
self.changed = true;
}
pub fn key(&self) -> &Pubkey {
&self.key
}
pub fn lamports(&self) -> u64 {
self.account.borrow().lamports()
}
pub fn executable(&self) -> bool {
self.account.borrow().executable()
}
pub fn is_zeroed(buf: &[u8]) -> bool {
const ZEROS_LEN: usize = 1024;
static ZEROS: [u8; ZEROS_LEN] = [0; ZEROS_LEN];
let mut chunks = buf.chunks_exact(ZEROS_LEN);
chunks.all(|chunk| chunk == &ZEROS[..])
&& chunks.remainder() == &ZEROS[..chunks.remainder().len()]
}
}
pub struct ThisComputeMeter {
remaining: u64,
}
impl ComputeMeter for ThisComputeMeter {
fn consume(&mut self, amount: u64) -> Result<(), InstructionError> {
let exceeded = self.remaining < amount;
self.remaining = self.remaining.saturating_sub(amount);
if exceeded {
return Err(InstructionError::ComputationalBudgetExceeded);
}
Ok(())
}
fn get_remaining(&self) -> u64 {
self.remaining
}
}
pub struct ThisInvokeContext<'a> {
invoke_stack: Vec<InvokeContextStackFrame<'a>>,
rent: Rent,
pre_accounts: Vec<PreAccount>,
accounts: &'a [(Pubkey, Rc<RefCell<AccountSharedData>>)],
programs: &'a [(Pubkey, ProcessInstructionWithContext)],
logger: Rc<RefCell<dyn Logger>>,
bpf_compute_budget: BpfComputeBudget,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
executors: Rc<RefCell<Executors>>,
instruction_recorder: Option<InstructionRecorder>,
feature_set: Arc<FeatureSet>,
pub timings: ExecuteDetailsTimings,
account_db: Arc<Accounts>,
ancestors: &'a Ancestors,
#[allow(clippy::type_complexity)]
sysvars: RefCell<Vec<(Pubkey, Option<Rc<Vec<u8>>>)>>,
}
impl<'a> ThisInvokeContext<'a> {
#[allow(clippy::too_many_arguments)]
pub fn new(
program_id: &Pubkey,
rent: Rent,
message: &'a Message,
instruction: &'a CompiledInstruction,
executable_accounts: &'a [(Pubkey, Rc<RefCell<AccountSharedData>>)],
accounts: &'a [(Pubkey, Rc<RefCell<AccountSharedData>>)],
programs: &'a [(Pubkey, ProcessInstructionWithContext)],
log_collector: Option<Rc<LogCollector>>,
bpf_compute_budget: BpfComputeBudget,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
executors: Rc<RefCell<Executors>>,
instruction_recorder: Option<InstructionRecorder>,
feature_set: Arc<FeatureSet>,
account_db: Arc<Accounts>,
ancestors: &'a Ancestors,
) -> Self {
let pre_accounts = MessageProcessor::create_pre_accounts(message, instruction, accounts);
let keyed_accounts = MessageProcessor::create_keyed_accounts(
message,
instruction,
executable_accounts,
accounts,
);
let compute_meter = if feature_set.is_active(&tx_wide_compute_cap::id()) {
compute_meter
} else {
Rc::new(RefCell::new(ThisComputeMeter {
remaining: bpf_compute_budget.max_units,
}))
};
let mut invoke_context = Self {
invoke_stack: Vec::with_capacity(bpf_compute_budget.max_invoke_depth),
rent,
pre_accounts,
accounts,
programs,
logger: Rc::new(RefCell::new(ThisLogger { log_collector })),
bpf_compute_budget,
compute_meter,
executors,
instruction_recorder,
feature_set,
timings: ExecuteDetailsTimings::default(),
account_db,
ancestors,
sysvars: RefCell::new(vec![]),
};
invoke_context
.invoke_stack
.push(InvokeContextStackFrame::new(
*program_id,
create_keyed_accounts_unified(&keyed_accounts),
));
invoke_context
}
}
impl<'a> InvokeContext for ThisInvokeContext<'a> {
fn push(
&mut self,
key: &Pubkey,
keyed_accounts: &[(bool, bool, &Pubkey, &RefCell<AccountSharedData>)],
) -> Result<(), InstructionError> {
if self.invoke_stack.len() > self.bpf_compute_budget.max_invoke_depth {
return Err(InstructionError::CallDepth);
}
let contains = self.invoke_stack.iter().any(|frame| frame.key == *key);
let is_last = if let Some(last_frame) = self.invoke_stack.last() {
last_frame.key == *key
} else {
false
};
if contains && !is_last {
// Reentrancy not allowed unless caller is calling itself
return Err(InstructionError::ReentrancyNotAllowed);
}
// Alias the keys and account references in the provided keyed_accounts
// with the ones already existing in self, so that the lifetime 'a matches.
fn transmute_lifetime<'a, 'b, T: Sized>(value: &'a T) -> &'b T {
unsafe { std::mem::transmute(value) }
}
let keyed_accounts = keyed_accounts
.iter()
.map(|(is_signer, is_writable, search_key, account)| {
self.accounts
.iter()
.position(|(key, _account)| key == *search_key)
.map(|index| {
// TODO
// Currently we are constructing new accounts on the stack
// before calling MessageProcessor::process_cross_program_instruction
// Ideally we would recycle the existing accounts here.
(
*is_signer,
*is_writable,
&self.accounts[index].0,
// &self.accounts[index] as &RefCell<AccountSharedData>
transmute_lifetime(*account),
)
})
})
.collect::<Option<Vec<_>>>()
.ok_or(InstructionError::InvalidArgument)?;
self.invoke_stack.push(InvokeContextStackFrame::new(
*key,
create_keyed_accounts_unified(keyed_accounts.as_slice()),
));
Ok(())
}
fn pop(&mut self) {
self.invoke_stack.pop();
}
fn invoke_depth(&self) -> usize {
self.invoke_stack.len()
}
fn verify_and_update(
&mut self,
instruction: &CompiledInstruction,
accounts: &[(Pubkey, Rc<RefCell<AccountSharedData>>)],
write_privileges: &[bool],
) -> Result<(), InstructionError> {
let stack_frame = self
.invoke_stack
.last()
.ok_or(InstructionError::CallDepth)?;
let logger = self.get_logger();
MessageProcessor::verify_and_update(
instruction,
&mut self.pre_accounts,
accounts,
&stack_frame.key,
&self.rent,
write_privileges,
&mut self.timings,
logger,
self.feature_set.is_active(&updated_verify_policy::id()),
)
}
fn get_caller(&self) -> Result<&Pubkey, InstructionError> {
self.invoke_stack
.last()
.map(|frame| &frame.key)
.ok_or(InstructionError::CallDepth)
}
fn remove_first_keyed_account(&mut self) -> Result<(), InstructionError> {
let stack_frame = &mut self
.invoke_stack
.last_mut()
.ok_or(InstructionError::CallDepth)?;
stack_frame.keyed_accounts_range.start =
stack_frame.keyed_accounts_range.start.saturating_add(1);
Ok(())
}
fn get_keyed_accounts(&self) -> Result<&[KeyedAccount], InstructionError> {
self.invoke_stack
.last()
.map(|frame| &frame.keyed_accounts[frame.keyed_accounts_range.clone()])
.ok_or(InstructionError::CallDepth)
}
fn get_programs(&self) -> &[(Pubkey, ProcessInstructionWithContext)] {
self.programs
}
fn get_logger(&self) -> Rc<RefCell<dyn Logger>> {
self.logger.clone()
}
fn get_bpf_compute_budget(&self) -> &BpfComputeBudget {
&self.bpf_compute_budget
}
fn get_compute_meter(&self) -> Rc<RefCell<dyn ComputeMeter>> {
self.compute_meter.clone()
}
fn add_executor(&self, pubkey: &Pubkey, executor: Arc<dyn Executor>) {
self.executors.borrow_mut().insert(*pubkey, executor);
}
fn get_executor(&self, pubkey: &Pubkey) -> Option<Arc<dyn Executor>> {
self.executors.borrow().get(pubkey)
}
fn record_instruction(&self, instruction: &Instruction) {
if let Some(recorder) = &self.instruction_recorder {
recorder.record_instruction(instruction.clone());
}
}
fn is_feature_active(&self, feature_id: &Pubkey) -> bool {
self.feature_set.is_active(feature_id)
}
fn get_account(&self, pubkey: &Pubkey) -> Option<Rc<RefCell<AccountSharedData>>> {
self.accounts.iter().find_map(|(key, account)| {
if key == pubkey {
Some(account.clone())
} else {
None
}
})
}
fn update_timing(
&mut self,
serialize_us: u64,
create_vm_us: u64,
execute_us: u64,
deserialize_us: u64,
) {
self.timings.serialize_us += serialize_us;
self.timings.create_vm_us += create_vm_us;
self.timings.execute_us += execute_us;
self.timings.deserialize_us += deserialize_us;
}
fn get_sysvar_data(&self, id: &Pubkey) -> Option<Rc<Vec<u8>>> {
if let Ok(mut sysvars) = self.sysvars.try_borrow_mut() {
// Try share from cache
let mut result = sysvars
.iter()
.find_map(|(key, sysvar)| if id == key { sysvar.clone() } else { None });
if result.is_none() {
// Load it
result = self
.account_db
.load_with_fixed_root(self.ancestors, id)
.map(|(account, _)| Rc::new(account.data().to_vec()));
// Cache it
sysvars.push((*id, result.clone()));
}
result
} else {
None
}
}
}
pub struct ThisLogger {
log_collector: Option<Rc<LogCollector>>,
}
impl Logger for ThisLogger {
fn log_enabled(&self) -> bool {
log_enabled!(log::Level::Info) || self.log_collector.is_some()
}
fn log(&self, message: &str) {
debug!("{}", message);
if let Some(log_collector) = &self.log_collector {
log_collector.log(message);
}
}
}
#[derive(Deserialize, Serialize)]
pub struct MessageProcessor {
#[serde(skip)]
programs: Vec<(Pubkey, ProcessInstructionWithContext)>,
#[serde(skip)]
native_loader: NativeLoader,
}
impl std::fmt::Debug for MessageProcessor {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
#[derive(Debug)]
struct MessageProcessor<'a> {
programs: Vec<String>,
native_loader: &'a NativeLoader,
}
// These are just type aliases for work around of Debug-ing above pointers
type ErasedProcessInstructionWithContext = fn(
&'static Pubkey,
&'static [u8],
&'static mut dyn InvokeContext,
) -> Result<(), InstructionError>;
// rustc doesn't compile due to bug without this work around
// https://github.com/rust-lang/rust/issues/50280
// https://users.rust-lang.org/t/display-function-pointer/17073/2
let processor = MessageProcessor {
programs: self
.programs
.iter()
.map(|(pubkey, instruction)| {
let erased_instruction: ErasedProcessInstructionWithContext = *instruction;
format!("{}: {:p}", pubkey, erased_instruction)
})
.collect::<Vec<_>>(),
native_loader: &self.native_loader,
};
write!(f, "{:?}", processor)
}
}
impl Default for MessageProcessor {
fn default() -> Self {
Self {
programs: vec![],
native_loader: NativeLoader::default(),
}
}
}
impl Clone for MessageProcessor {
fn clone(&self) -> Self {
MessageProcessor {
programs: self.programs.clone(),
native_loader: NativeLoader::default(),
}
}
}
#[cfg(RUSTC_WITH_SPECIALIZATION)]
impl ::solana_frozen_abi::abi_example::AbiExample for MessageProcessor {
fn example() -> Self {
// MessageProcessor's fields are #[serde(skip)]-ed and not Serialize
// so, just rely on Default anyway.
MessageProcessor::default()
}
}
impl MessageProcessor {
/// Add a static entrypoint to intercept instructions before the dynamic loader.
pub fn add_program(
&mut self,
program_id: Pubkey,
process_instruction: ProcessInstructionWithContext,
) {
match self.programs.iter_mut().find(|(key, _)| program_id == *key) {
Some((_, processor)) => *processor = process_instruction,
None => self.programs.push((program_id, process_instruction)),
}
}
pub fn add_loader(
&mut self,
program_id: Pubkey,
process_instruction: ProcessInstructionWithContext,
) {
self.add_program(program_id, process_instruction);
}
/// Create the KeyedAccounts that will be passed to the program
fn create_keyed_accounts<'a>(
message: &'a Message,
instruction: &'a CompiledInstruction,
executable_accounts: &'a [(Pubkey, Rc<RefCell<AccountSharedData>>)],
accounts: &'a [(Pubkey, Rc<RefCell<AccountSharedData>>)],
) -> Vec<(bool, bool, &'a Pubkey, &'a RefCell<AccountSharedData>)> {
executable_accounts
.iter()
.map(|(key, account)| (false, false, key, account as &RefCell<AccountSharedData>))
.chain(instruction.accounts.iter().map(|index| {
let index = *index as usize;
(
message.is_signer(index),
message.is_writable(index),
&accounts[index].0,
&accounts[index].1 as &RefCell<AccountSharedData>,
)
}))
.collect::<Vec<_>>()
}
/// Process an instruction
/// This method calls the instruction's program entrypoint method
fn process_instruction(
&self,
program_id: &Pubkey,
instruction_data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
if let Some(root_account) = invoke_context.get_keyed_accounts()?.iter().next() {
let root_id = root_account.unsigned_key();
if native_loader::check_id(&root_account.owner()?) {
for (id, process_instruction) in &self.programs {
if id == root_id {
invoke_context.remove_first_keyed_account()?;
// Call the builtin program
return process_instruction(program_id, instruction_data, invoke_context);
}
}
// Call the program via the native loader
return self.native_loader.process_instruction(
&native_loader::id(),
instruction_data,
invoke_context,
);
} else {
let owner_id = &root_account.owner()?;
for (id, process_instruction) in &self.programs {
if id == owner_id {
// Call the program via a builtin loader
return process_instruction(program_id, instruction_data, invoke_context);
}
}
}
}
Err(InstructionError::UnsupportedProgramId)
}
pub fn create_message(
instruction: &Instruction,
keyed_accounts: &[&KeyedAccount],
signers: &[Pubkey],
invoke_context: &Ref<&mut dyn InvokeContext>,
) -> Result<(Message, Pubkey, usize), InstructionError> {
// Check for privilege escalation
for account in instruction.accounts.iter() {
let keyed_account = keyed_accounts
.iter()
.find_map(|keyed_account| {
if &account.pubkey == keyed_account.unsigned_key() {
Some(keyed_account)
} else {
None
}
})
.ok_or_else(|| {
ic_msg!(
invoke_context,
"Instruction references an unknown account {}",
account.pubkey
);
InstructionError::MissingAccount
})?;
// Readonly account cannot become writable
if account.is_writable && !keyed_account.is_writable() {
ic_msg!(
invoke_context,
"{}'s writable privilege escalated",
account.pubkey
);
return Err(InstructionError::PrivilegeEscalation);
}
if account.is_signer && // If message indicates account is signed
!( // one of the following needs to be true:
keyed_account.signer_key().is_some() // Signed in the parent instruction
|| signers.contains(&account.pubkey) // Signed by the program
) {
ic_msg!(
invoke_context,
"{}'s signer privilege escalated",
account.pubkey
);
return Err(InstructionError::PrivilegeEscalation);
}
}
// validate the caller has access to the program account and that it is executable
let program_id = instruction.program_id;
match keyed_accounts
.iter()
.find(|keyed_account| &program_id == keyed_account.unsigned_key())
{
Some(keyed_account) => {
if !keyed_account.executable()? {
ic_msg!(
invoke_context,
"Account {} is not executable",
keyed_account.unsigned_key()
);
return Err(InstructionError::AccountNotExecutable);
}
}
None => {
ic_msg!(invoke_context, "Unknown program {}", program_id);
return Err(InstructionError::MissingAccount);
}
}
let message = Message::new(&[instruction.clone()], None);
let program_id_index = message.instructions[0].program_id_index as usize;
Ok((message, program_id, program_id_index))
}
/// Entrypoint for a cross-program invocation from a native program
pub fn native_invoke(
invoke_context: &mut dyn InvokeContext,
instruction: Instruction,
keyed_account_indices: &[usize],
signers: &[Pubkey],
) -> Result<(), InstructionError> {
let invoke_context = RefCell::new(invoke_context);
let (
message,
executable_accounts,
accounts,
keyed_account_indices_reordered,
caller_write_privileges,
) = {
let invoke_context = invoke_context.borrow();
// Translate and verify caller's data
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let keyed_accounts = keyed_account_indices
.iter()
.map(|index| keyed_account_at_index(keyed_accounts, *index))
.collect::<Result<Vec<&KeyedAccount>, InstructionError>>()?;
let (message, callee_program_id, _) =
Self::create_message(&instruction, &keyed_accounts, signers, &invoke_context)?;
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let mut caller_write_privileges = keyed_account_indices
.iter()
.map(|index| keyed_accounts[*index].is_writable())
.collect::<Vec<bool>>();
caller_write_privileges.insert(0, false);
let mut accounts = vec![];
let mut keyed_account_indices_reordered = vec![];
let keyed_accounts = invoke_context.get_keyed_accounts()?;
'root: for account_key in message.account_keys.iter() {
for keyed_account_index in keyed_account_indices {
let keyed_account = &keyed_accounts[*keyed_account_index];
if account_key == keyed_account.unsigned_key() {
accounts.push((*account_key, Rc::new(keyed_account.account.clone())));
keyed_account_indices_reordered.push(*keyed_account_index);
continue 'root;
}
}
ic_msg!(
invoke_context,
"Instruction references an unknown account {}",
account_key
);
return Err(InstructionError::MissingAccount);
}
// Process instruction
invoke_context.record_instruction(&instruction);
let program_account =
invoke_context
.get_account(&callee_program_id)
.ok_or_else(|| {
ic_msg!(invoke_context, "Unknown program {}", callee_program_id);
InstructionError::MissingAccount
})?;
if !program_account.borrow().executable() {
ic_msg!(
invoke_context,
"Account {} is not executable",
callee_program_id
);
return Err(InstructionError::AccountNotExecutable);
}
let programdata = if program_account.borrow().owner() == &bpf_loader_upgradeable::id() {
if let UpgradeableLoaderState::Program {
programdata_address,
} = program_account.borrow().state()?
{
if let Some(account) = invoke_context.get_account(&programdata_address) {
Some((programdata_address, account))
} else {
ic_msg!(
invoke_context,
"Unknown upgradeable programdata account {}",
programdata_address,
);
return Err(InstructionError::MissingAccount);
}
} else {
ic_msg!(
invoke_context,
"Upgradeable program account state not valid {}",
callee_program_id,
);
return Err(InstructionError::MissingAccount);
}
} else {
None
};
let mut executable_accounts = vec![(callee_program_id, program_account)];
if let Some(programdata) = programdata {
executable_accounts.push(programdata);
}
(
message,
executable_accounts,
accounts,
keyed_account_indices_reordered,
caller_write_privileges,
)
};
#[allow(clippy::deref_addrof)]
MessageProcessor::process_cross_program_instruction(
&message,
&executable_accounts,
&accounts,
&caller_write_privileges,
*(&mut *(invoke_context.borrow_mut())),
)?;
// Copy results back to caller
{
let invoke_context = invoke_context.borrow();
let keyed_accounts = invoke_context.get_keyed_accounts()?;
for (src_keyed_account_index, ((_key, account), dst_keyed_account_index)) in accounts
.iter()
.zip(keyed_account_indices_reordered)
.enumerate()
{
let dst_keyed_account = &keyed_accounts[dst_keyed_account_index];
let src_keyed_account = account.borrow();
if message.is_writable(src_keyed_account_index) && !src_keyed_account.executable() {
if dst_keyed_account.data_len()? != src_keyed_account.data().len()
&& dst_keyed_account.data_len()? != 0
{
// Only support for `CreateAccount` at this time.
// Need a way to limit total realloc size across multiple CPI calls
ic_msg!(
invoke_context,
"Inner instructions do not support realloc, only SystemProgram::CreateAccount",
);
return Err(InstructionError::InvalidRealloc);
}
dst_keyed_account
.try_account_ref_mut()?
.set_lamports(src_keyed_account.lamports());
dst_keyed_account
.try_account_ref_mut()?
.set_owner(*src_keyed_account.owner());
dst_keyed_account
.try_account_ref_mut()?
.set_data(src_keyed_account.data().to_vec());
}
}
}
Ok(())
}
/// Process a cross-program instruction
/// This method calls the instruction's program entrypoint function
pub fn process_cross_program_instruction(
message: &Message,
executable_accounts: &[(Pubkey, Rc<RefCell<AccountSharedData>>)],
accounts: &[(Pubkey, Rc<RefCell<AccountSharedData>>)],
caller_write_privileges: &[bool],
invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
if let Some(instruction) = message.instructions.get(0) {
let program_id = instruction.program_id(&message.account_keys);
// Verify the calling program hasn't misbehaved
invoke_context.verify_and_update(instruction, accounts, caller_write_privileges)?;
// Construct keyed accounts
let keyed_accounts =
Self::create_keyed_accounts(message, instruction, executable_accounts, accounts);
// Invoke callee
invoke_context.push(program_id, &keyed_accounts)?;
let mut message_processor = MessageProcessor::default();
for (program_id, process_instruction) in invoke_context.get_programs().iter() {
message_processor.add_program(*program_id, *process_instruction);
}
let mut result = message_processor.process_instruction(
program_id,
&instruction.data,
invoke_context,
);
if result.is_ok() {
// Verify the called program has not misbehaved
let write_privileges: Vec<bool> = (0..message.account_keys.len())
.map(|i| message.is_writable(i))
.collect();
result = invoke_context.verify_and_update(instruction, accounts, &write_privileges);
}
// Restore previous state
invoke_context.pop();
result
} else {
// This function is always called with a valid instruction, if that changes return an error
Err(InstructionError::GenericError)
}
}
/// Record the initial state of the accounts so that they can be compared
/// after the instruction is processed
pub fn create_pre_accounts(
message: &Message,
instruction: &CompiledInstruction,
accounts: &[(Pubkey, Rc<RefCell<AccountSharedData>>)],
) -> Vec<PreAccount> {
let mut pre_accounts = Vec::with_capacity(instruction.accounts.len());
{
let mut work = |_unique_index: usize, account_index: usize| {
if account_index < message.account_keys.len() && account_index < accounts.len() {
let account = accounts[account_index].1.borrow();
pre_accounts.push(PreAccount::new(&accounts[account_index].0, &account));
return Ok(());
}
Err(InstructionError::MissingAccount)
};
let _ = instruction.visit_each_account(&mut work);
}
pre_accounts
}
/// Verify there are no outstanding borrows
pub fn verify_account_references(
accounts: &[(Pubkey, Rc<RefCell<AccountSharedData>>)],
) -> Result<(), InstructionError> {
for (_, account) in accounts.iter() {
account
.try_borrow_mut()
.map_err(|_| InstructionError::AccountBorrowOutstanding)?;
}
Ok(())
}
/// Verify the results of an instruction
pub fn verify(
message: &Message,
instruction: &CompiledInstruction,
pre_accounts: &[PreAccount],
executable_accounts: &[(Pubkey, Rc<RefCell<AccountSharedData>>)],
accounts: &[(Pubkey, Rc<RefCell<AccountSharedData>>)],
rent: &Rent,
timings: &mut ExecuteDetailsTimings,
logger: Rc<RefCell<dyn Logger>>,
updated_verify_policy: bool,
) -> Result<(), InstructionError> {
// Verify all executable accounts have zero outstanding refs
Self::verify_account_references(executable_accounts)?;
// Verify the per-account instruction results
let (mut pre_sum, mut post_sum) = (0_u128, 0_u128);
{
let program_id = instruction.program_id(&message.account_keys);
let mut work = |unique_index: usize, account_index: usize| {
{
// Verify account has no outstanding references
let _ = accounts[account_index]
.1
.try_borrow_mut()
.map_err(|_| InstructionError::AccountBorrowOutstanding)?;
}
let account = accounts[account_index].1.borrow();
pre_accounts[unique_index]
.verify(
program_id,
message.is_writable(account_index),
rent,
&account,
timings,
true,
updated_verify_policy,
)
.map_err(|err| {
ic_logger_msg!(
logger,
"failed to verify account {}: {}",
pre_accounts[unique_index].key,
err
);
err
})?;
pre_sum += u128::from(pre_accounts[unique_index].lamports());
post_sum += u128::from(account.lamports());
Ok(())
};
instruction.visit_each_account(&mut work)?;
}
// Verify that the total sum of all the lamports did not change
if pre_sum != post_sum {
return Err(InstructionError::UnbalancedInstruction);
}
Ok(())
}
/// Verify the results of a cross-program instruction
#[allow(clippy::too_many_arguments)]
fn verify_and_update(
instruction: &CompiledInstruction,
pre_accounts: &mut [PreAccount],
accounts: &[(Pubkey, Rc<RefCell<AccountSharedData>>)],
program_id: &Pubkey,
rent: &Rent,
write_privileges: &[bool],
timings: &mut ExecuteDetailsTimings,
logger: Rc<RefCell<dyn Logger>>,
updated_verify_policy: bool,
) -> Result<(), InstructionError> {
// Verify the per-account instruction results
let (mut pre_sum, mut post_sum) = (0_u128, 0_u128);
let mut work = |_unique_index: usize, account_index: usize| {
if account_index < write_privileges.len() && account_index < accounts.len() {
let (key, account) = &accounts[account_index];
let is_writable = write_privileges[account_index];
// Find the matching PreAccount
for pre_account in pre_accounts.iter_mut() {
if key == pre_account.key() {
{
// Verify account has no outstanding references
let _ = account
.try_borrow_mut()
.map_err(|_| InstructionError::AccountBorrowOutstanding)?;
}
let account = account.borrow();
pre_account
.verify(
program_id,
is_writable,
rent,
&account,
timings,
false,
updated_verify_policy,
)
.map_err(|err| {
ic_logger_msg!(logger, "failed to verify account {}: {}", key, err);
err
})?;
pre_sum += u128::from(pre_account.lamports());
post_sum += u128::from(account.lamports());
if is_writable && !pre_account.executable() {
pre_account.update(&account);
}
return Ok(());
}
}
}
Err(InstructionError::MissingAccount)
};
instruction.visit_each_account(&mut work)?;
// Verify that the total sum of all the lamports did not change
if pre_sum != post_sum {
return Err(InstructionError::UnbalancedInstruction);
}
Ok(())
}
/// Execute an instruction
/// This method calls the instruction's program entrypoint method and verifies that the result of
/// the call does not violate the bank's accounting rules.
/// The accounts are committed back to the bank only if this function returns Ok(_).
#[allow(clippy::too_many_arguments)]
fn execute_instruction(
&self,
message: &Message,
instruction: &CompiledInstruction,
executable_accounts: &[(Pubkey, Rc<RefCell<AccountSharedData>>)],
accounts: &[(Pubkey, Rc<RefCell<AccountSharedData>>)],
rent_collector: &RentCollector,
log_collector: Option<Rc<LogCollector>>,
executors: Rc<RefCell<Executors>>,
instruction_recorder: Option<InstructionRecorder>,
instruction_index: usize,
feature_set: Arc<FeatureSet>,
bpf_compute_budget: BpfComputeBudget,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
timings: &mut ExecuteDetailsTimings,
account_db: Arc<Accounts>,
ancestors: &Ancestors,
) -> Result<(), InstructionError> {
// Fixup the special instructions key if present
// before the account pre-values are taken care of
if feature_set.is_active(&instructions_sysvar_enabled::id()) {
for (pubkey, accont) in accounts.iter().take(message.account_keys.len()) {
if instructions::check_id(pubkey) {
let mut mut_account_ref = accont.borrow_mut();
instructions::store_current_index(
mut_account_ref.data_as_mut_slice(),
instruction_index as u16,
);
break;
}
}
}
let program_id = instruction.program_id(&message.account_keys);
let mut bpf_compute_budget = bpf_compute_budget;
if feature_set.is_active(&neon_evm_compute_budget::id())
&& *program_id == crate::neon_evm_program::id()
{
// Bump the compute budget for neon_evm
bpf_compute_budget.max_units = bpf_compute_budget.max_units.max(500_000);
bpf_compute_budget.heap_size = Some(256 * 1024);
}
let mut invoke_context = ThisInvokeContext::new(
program_id,
rent_collector.rent,
message,
instruction,
executable_accounts,
accounts,
&self.programs,
log_collector,
bpf_compute_budget,
compute_meter,
executors,
instruction_recorder,
feature_set,
account_db,
ancestors,
);
self.process_instruction(program_id, &instruction.data, &mut invoke_context)?;
Self::verify(
message,
instruction,
&invoke_context.pre_accounts,
executable_accounts,
accounts,
&rent_collector.rent,
timings,
invoke_context.get_logger(),
invoke_context.is_feature_active(&updated_verify_policy::id()),
)?;
timings.accumulate(&invoke_context.timings);
Ok(())
}
/// Process a message.
/// This method calls each instruction in the message over the set of loaded Accounts
/// The accounts are committed back to the bank only if every instruction succeeds
#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)]
pub fn process_message(
&self,
message: &Message,
loaders: &[Vec<(Pubkey, Rc<RefCell<AccountSharedData>>)>],
accounts: &[(Pubkey, Rc<RefCell<AccountSharedData>>)],
rent_collector: &RentCollector,
log_collector: Option<Rc<LogCollector>>,
executors: Rc<RefCell<Executors>>,
instruction_recorders: Option<&[InstructionRecorder]>,
feature_set: Arc<FeatureSet>,
bpf_compute_budget: BpfComputeBudget,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
timings: &mut ExecuteDetailsTimings,
account_db: Arc<Accounts>,
ancestors: &Ancestors,
) -> Result<(), TransactionError> {
for (instruction_index, instruction) in message.instructions.iter().enumerate() {
let mut time = Measure::start("execute_instruction");
let pre_remaining_units = compute_meter.borrow().get_remaining();
let instruction_recorder = instruction_recorders
.as_ref()
.map(|recorders| recorders[instruction_index].clone());
let err = self
.execute_instruction(
message,
instruction,
&loaders[instruction_index],
accounts,
rent_collector,
log_collector.clone(),
executors.clone(),
instruction_recorder,
instruction_index,
feature_set.clone(),
bpf_compute_budget,
compute_meter.clone(),
timings,
account_db.clone(),
ancestors,
)
.map_err(|err| TransactionError::InstructionError(instruction_index as u8, err));
time.stop();
let post_remaining_units = compute_meter.borrow().get_remaining();
let program_id = instruction.program_id(&message.account_keys);
let program_timing = timings.per_program_timings.entry(*program_id).or_default();
program_timing.accumulated_us += time.as_us();
program_timing.accumulated_units += pre_remaining_units - post_remaining_units;
program_timing.count += 1;
err?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use solana_sdk::{
account::Account,
instruction::{AccountMeta, Instruction, InstructionError},
message::Message,
native_loader::create_loadable_account_for_test,
process_instruction::MockComputeMeter,
};
#[test]
fn test_invoke_context() {
const MAX_DEPTH: usize = 10;
let mut invoke_stack = vec![];
let mut accounts = vec![];
let mut metas = vec![];
for i in 0..MAX_DEPTH {
invoke_stack.push(solana_sdk::pubkey::new_rand());
accounts.push((
solana_sdk::pubkey::new_rand(),
Rc::new(RefCell::new(AccountSharedData::new(
i as u64,
1,
&invoke_stack[i],
))),
));
metas.push(AccountMeta::new(accounts[i].0, false));
}
for program_id in invoke_stack.iter() {
accounts.push((
*program_id,
Rc::new(RefCell::new(AccountSharedData::new(
1,
1,
&solana_sdk::pubkey::Pubkey::default(),
))),
));
metas.push(AccountMeta::new(*program_id, false));
}
let message = Message::new(
&[Instruction::new_with_bytes(invoke_stack[0], &[0], metas)],
None,
);
let ancestors = Ancestors::default();
let mut invoke_context = ThisInvokeContext::new(
&invoke_stack[0],
Rent::default(),
&message,
&message.instructions[0],
&[],
&accounts,
&[],
None,
BpfComputeBudget::default(),
Rc::new(RefCell::new(MockComputeMeter::default())),
Rc::new(RefCell::new(Executors::default())),
None,
Arc::new(FeatureSet::all_enabled()),
Arc::new(Accounts::default()),
&ancestors,
);
// Check call depth increases and has a limit
let mut depth_reached = 1;
for program_id in invoke_stack.iter().skip(1) {
if Err(InstructionError::CallDepth) == invoke_context.push(program_id, &[]) {
break;
}
depth_reached += 1;
}
assert_ne!(depth_reached, 0);
assert!(depth_reached < MAX_DEPTH);
// Mock each invocation
for owned_index in (1..depth_reached).rev() {
let not_owned_index = owned_index - 1;
let metas = vec![
AccountMeta::new(accounts[not_owned_index].0, false),
AccountMeta::new(accounts[owned_index].0, false),
];
let message = Message::new(
&[Instruction::new_with_bytes(
invoke_stack[owned_index],
&[0],
metas,
)],
None,
);
// modify account owned by the program
accounts[owned_index].1.borrow_mut().data_as_mut_slice()[0] =
(MAX_DEPTH + owned_index) as u8;
let mut these_accounts = accounts[not_owned_index..owned_index + 1].to_vec();
these_accounts.push((
message.account_keys[2],
Rc::new(RefCell::new(AccountSharedData::new(
1,
1,
&solana_sdk::pubkey::Pubkey::default(),
))),
));
let write_privileges: Vec<bool> = (0..message.account_keys.len())
.map(|i| message.is_writable(i))
.collect();
invoke_context
.verify_and_update(&message.instructions[0], &these_accounts, &write_privileges)
.unwrap();
assert_eq!(
invoke_context.pre_accounts[owned_index]
.account
.borrow()
.data()[0],
(MAX_DEPTH + owned_index) as u8
);
// modify account not owned by the program
let data = accounts[not_owned_index].1.borrow_mut().data()[0];
accounts[not_owned_index].1.borrow_mut().data_as_mut_slice()[0] =
(MAX_DEPTH + not_owned_index) as u8;
assert_eq!(
invoke_context.verify_and_update(
&message.instructions[0],
&accounts[not_owned_index..owned_index + 1],
&write_privileges,
),
Err(InstructionError::ExternalAccountDataModified)
);
assert_eq!(
invoke_context.pre_accounts[not_owned_index]
.account
.borrow()
.data()[0],
data
);
accounts[not_owned_index].1.borrow_mut().data_as_mut_slice()[0] = data;
invoke_context.pop();
}
}
#[test]
fn test_is_zeroed() {
const ZEROS_LEN: usize = 1024;
let mut buf = [0; ZEROS_LEN];
assert!(PreAccount::is_zeroed(&buf));
buf[0] = 1;
assert!(!PreAccount::is_zeroed(&buf));
let mut buf = [0; ZEROS_LEN - 1];
assert!(PreAccount::is_zeroed(&buf));
buf[0] = 1;
assert!(!PreAccount::is_zeroed(&buf));
let mut buf = [0; ZEROS_LEN + 1];
assert!(PreAccount::is_zeroed(&buf));
buf[0] = 1;
assert!(!PreAccount::is_zeroed(&buf));
let buf = vec![];
assert!(PreAccount::is_zeroed(&buf));
}
#[test]
fn test_verify_account_references() {
let accounts = vec![(
solana_sdk::pubkey::new_rand(),
Rc::new(RefCell::new(AccountSharedData::default())),
)];
assert!(MessageProcessor::verify_account_references(&accounts).is_ok());
let mut _borrowed = accounts[0].1.borrow();
assert_eq!(
MessageProcessor::verify_account_references(&accounts),
Err(InstructionError::AccountBorrowOutstanding)
);
}
struct Change {
program_id: Pubkey,
is_writable: bool,
rent: Rent,
pre: PreAccount,
post: AccountSharedData,
}
impl Change {
pub fn new(owner: &Pubkey, program_id: &Pubkey) -> Self {
Self {
program_id: *program_id,
rent: Rent::default(),
is_writable: true,
pre: PreAccount::new(
&solana_sdk::pubkey::new_rand(),
&AccountSharedData::from(Account {
owner: *owner,
lamports: std::u64::MAX,
data: vec![],
..Account::default()
}),
),
post: AccountSharedData::from(Account {
owner: *owner,
lamports: std::u64::MAX,
..Account::default()
}),
}
}
pub fn read_only(mut self) -> Self {
self.is_writable = false;
self
}
pub fn executable(mut self, pre: bool, post: bool) -> Self {
self.pre.account.borrow_mut().set_executable(pre);
self.post.set_executable(post);
self
}
pub fn lamports(mut self, pre: u64, post: u64) -> Self {
self.pre.account.borrow_mut().set_lamports(pre);
self.post.set_lamports(post);
self
}
pub fn owner(mut self, post: &Pubkey) -> Self {
self.post.set_owner(*post);
self
}
pub fn data(mut self, pre: Vec<u8>, post: Vec<u8>) -> Self {
self.pre.account.borrow_mut().set_data(pre);
self.post.set_data(post);
self
}
pub fn rent_epoch(mut self, pre: u64, post: u64) -> Self {
self.pre.account.borrow_mut().set_rent_epoch(pre);
self.post.set_rent_epoch(post);
self
}
pub fn verify(&self) -> Result<(), InstructionError> {
self.pre.verify(
&self.program_id,
self.is_writable,
&self.rent,
&self.post,
&mut ExecuteDetailsTimings::default(),
false,
true,
)
}
}
#[test]
fn test_verify_account_changes_owner() {
let system_program_id = system_program::id();
let alice_program_id = solana_sdk::pubkey::new_rand();
let mallory_program_id = solana_sdk::pubkey::new_rand();
assert_eq!(
Change::new(&system_program_id, &system_program_id)
.owner(&alice_program_id)
.verify(),
Ok(()),
"system program should be able to change the account owner"
);
assert_eq!(
Change::new(&system_program_id, &system_program_id)
.owner(&alice_program_id)
.read_only()
.verify(),
Err(InstructionError::ModifiedProgramId),
"system program should not be able to change the account owner of a read-only account"
);
assert_eq!(
Change::new(&mallory_program_id, &system_program_id)
.owner(&alice_program_id)
.verify(),
Err(InstructionError::ModifiedProgramId),
"system program should not be able to change the account owner of a non-system account"
);
assert_eq!(
Change::new(&mallory_program_id, &mallory_program_id)
.owner(&alice_program_id)
.verify(),
Ok(()),
"mallory should be able to change the account owner, if she leaves clear data"
);
assert_eq!(
Change::new(&mallory_program_id, &mallory_program_id)
.owner(&alice_program_id)
.data(vec![42], vec![0])
.verify(),
Ok(()),
"mallory should be able to change the account owner, if she leaves clear data"
);
assert_eq!(
Change::new(&mallory_program_id, &mallory_program_id)
.owner(&alice_program_id)
.executable(true, true)
.data(vec![42], vec![0])
.verify(),
Err(InstructionError::ModifiedProgramId),
"mallory should not be able to change the account owner, if the account executable"
);
assert_eq!(
Change::new(&mallory_program_id, &mallory_program_id)
.owner(&alice_program_id)
.data(vec![42], vec![42])
.verify(),
Err(InstructionError::ModifiedProgramId),
"mallory should not be able to inject data into the alice program"
);
}
#[test]
fn test_verify_account_changes_executable() {
let owner = solana_sdk::pubkey::new_rand();
let mallory_program_id = solana_sdk::pubkey::new_rand();
let system_program_id = system_program::id();
assert_eq!(
Change::new(&owner, &system_program_id)
.executable(false, true)
.verify(),
Err(InstructionError::ExecutableModified),
"system program can't change executable if system doesn't own the account"
);
assert_eq!(
Change::new(&owner, &system_program_id)
.executable(true, true)
.data(vec![1], vec![2])
.verify(),
Err(InstructionError::ExecutableDataModified),
"system program can't change executable data if system doesn't own the account"
);
assert_eq!(
Change::new(&owner, &owner).executable(false, true).verify(),
Ok(()),
"owner should be able to change executable"
);
assert_eq!(
Change::new(&owner, &owner)
.executable(false, true)
.read_only()
.verify(),
Err(InstructionError::ExecutableModified),
"owner can't modify executable of read-only accounts"
);
assert_eq!(
Change::new(&owner, &owner).executable(true, false).verify(),
Err(InstructionError::ExecutableModified),
"owner program can't reverse executable"
);
assert_eq!(
Change::new(&owner, &mallory_program_id)
.executable(false, true)
.verify(),
Err(InstructionError::ExecutableModified),
"malicious Mallory should not be able to change the account executable"
);
assert_eq!(
Change::new(&owner, &owner)
.executable(false, true)
.data(vec![1], vec![2])
.verify(),
Ok(()),
"account data can change in the same instruction that sets the bit"
);
assert_eq!(
Change::new(&owner, &owner)
.executable(true, true)
.data(vec![1], vec![2])
.verify(),
Err(InstructionError::ExecutableDataModified),
"owner should not be able to change an account's data once its marked executable"
);
assert_eq!(
Change::new(&owner, &owner)
.executable(true, true)
.lamports(1, 2)
.verify(),
Err(InstructionError::ExecutableLamportChange),
"owner should not be able to add lamports once marked executable"
);
assert_eq!(
Change::new(&owner, &owner)
.executable(true, true)
.lamports(1, 2)
.verify(),
Err(InstructionError::ExecutableLamportChange),
"owner should not be able to add lamports once marked executable"
);
assert_eq!(
Change::new(&owner, &owner)
.executable(true, true)
.lamports(2, 1)
.verify(),
Err(InstructionError::ExecutableLamportChange),
"owner should not be able to subtract lamports once marked executable"
);
let data = vec![1; 100];
let min_lamports = Rent::default().minimum_balance(data.len());
assert_eq!(
Change::new(&owner, &owner)
.executable(false, true)
.lamports(0, min_lamports)
.data(data.clone(), data.clone())
.verify(),
Ok(()),
);
assert_eq!(
Change::new(&owner, &owner)
.executable(false, true)
.lamports(0, min_lamports - 1)
.data(data.clone(), data)
.verify(),
Err(InstructionError::ExecutableAccountNotRentExempt),
"owner should not be able to change an account's data once its marked executable"
);
}
#[test]
fn test_verify_account_changes_data_len() {
let alice_program_id = solana_sdk::pubkey::new_rand();
assert_eq!(
Change::new(&system_program::id(), &system_program::id())
.data(vec![0], vec![0, 0])
.verify(),
Ok(()),
"system program should be able to change the data len"
);
assert_eq!(
Change::new(&alice_program_id, &system_program::id())
.data(vec![0], vec![0,0])
.verify(),
Err(InstructionError::AccountDataSizeChanged),
"system program should not be able to change the data length of accounts it does not own"
);
}
#[test]
fn test_verify_account_changes_data() {
let alice_program_id = solana_sdk::pubkey::new_rand();
let mallory_program_id = solana_sdk::pubkey::new_rand();
assert_eq!(
Change::new(&alice_program_id, &alice_program_id)
.data(vec![0], vec![42])
.verify(),
Ok(()),
"alice program should be able to change the data"
);
assert_eq!(
Change::new(&mallory_program_id, &alice_program_id)
.data(vec![0], vec![42])
.verify(),
Err(InstructionError::ExternalAccountDataModified),
"non-owner mallory should not be able to change the account data"
);
assert_eq!(
Change::new(&alice_program_id, &alice_program_id)
.data(vec![0], vec![42])
.read_only()
.verify(),
Err(InstructionError::ReadonlyDataModified),
"alice isn't allowed to touch a CO account"
);
}
#[test]
fn test_verify_account_changes_rent_epoch() {
let alice_program_id = solana_sdk::pubkey::new_rand();
assert_eq!(
Change::new(&alice_program_id, &system_program::id()).verify(),
Ok(()),
"nothing changed!"
);
assert_eq!(
Change::new(&alice_program_id, &system_program::id())
.rent_epoch(0, 1)
.verify(),
Err(InstructionError::RentEpochModified),
"no one touches rent_epoch"
);
}
#[test]
fn test_verify_account_changes_deduct_lamports_and_reassign_account() {
let alice_program_id = solana_sdk::pubkey::new_rand();
let bob_program_id = solana_sdk::pubkey::new_rand();
// positive test of this capability
assert_eq!(
Change::new(&alice_program_id, &alice_program_id)
.owner(&bob_program_id)
.lamports(42, 1)
.data(vec![42], vec![0])
.verify(),
Ok(()),
"alice should be able to deduct lamports and give the account to bob if the data is zeroed",
);
}
#[test]
fn test_verify_account_changes_lamports() {
let alice_program_id = solana_sdk::pubkey::new_rand();
assert_eq!(
Change::new(&alice_program_id, &system_program::id())
.lamports(42, 0)
.read_only()
.verify(),
Err(InstructionError::ExternalAccountLamportSpend),
"debit should fail, even if system program"
);
assert_eq!(
Change::new(&alice_program_id, &alice_program_id)
.lamports(42, 0)
.read_only()
.verify(),
Err(InstructionError::ReadonlyLamportChange),
"debit should fail, even if owning program"
);
assert_eq!(
Change::new(&alice_program_id, &system_program::id())
.lamports(42, 0)
.owner(&system_program::id())
.verify(),
Err(InstructionError::ModifiedProgramId),
"system program can't debit the account unless it was the pre.owner"
);
assert_eq!(
Change::new(&system_program::id(), &system_program::id())
.lamports(42, 0)
.owner(&alice_program_id)
.verify(),
Ok(()),
"system can spend (and change owner)"
);
}
#[test]
fn test_verify_account_changes_data_size_changed() {
let alice_program_id = solana_sdk::pubkey::new_rand();
assert_eq!(
Change::new(&alice_program_id, &system_program::id())
.data(vec![0], vec![0, 0])
.verify(),
Err(InstructionError::AccountDataSizeChanged),
"system program should not be able to change another program's account data size"
);
assert_eq!(
Change::new(&alice_program_id, &alice_program_id)
.data(vec![0], vec![0, 0])
.verify(),
Err(InstructionError::AccountDataSizeChanged),
"non-system programs cannot change their data size"
);
assert_eq!(
Change::new(&system_program::id(), &system_program::id())
.data(vec![0], vec![0, 0])
.verify(),
Ok(()),
"system program should be able to change account data size"
);
}
#[test]
fn test_verify_account_changes_owner_executable() {
let alice_program_id = solana_sdk::pubkey::new_rand();
let bob_program_id = solana_sdk::pubkey::new_rand();
assert_eq!(
Change::new(&alice_program_id, &alice_program_id)
.owner(&bob_program_id)
.executable(false, true)
.verify(),
Err(InstructionError::ExecutableModified),
"Program should not be able to change owner and executable at the same time"
);
}
#[test]
fn test_process_message_readonly_handling() {
#[derive(Serialize, Deserialize)]
enum MockSystemInstruction {
Correct,
AttemptCredit { lamports: u64 },
AttemptDataChange { data: u8 },
}
fn mock_system_process_instruction(
_program_id: &Pubkey,
data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
let keyed_accounts = invoke_context.get_keyed_accounts()?;
if let Ok(instruction) = bincode::deserialize(data) {
match instruction {
MockSystemInstruction::Correct => Ok(()),
MockSystemInstruction::AttemptCredit { lamports } => {
keyed_accounts[0]
.account
.borrow_mut()
.checked_sub_lamports(lamports)?;
keyed_accounts[1]
.account
.borrow_mut()
.checked_add_lamports(lamports)?;
Ok(())
}
// Change data in a read-only account
MockSystemInstruction::AttemptDataChange { data } => {
keyed_accounts[1].account.borrow_mut().set_data(vec![data]);
Ok(())
}
}
} else {
Err(InstructionError::InvalidInstructionData)
}
}
let mock_system_program_id = Pubkey::new(&[2u8; 32]);
let rent_collector = RentCollector::default();
let mut message_processor = MessageProcessor::default();
message_processor.add_program(mock_system_program_id, mock_system_process_instruction);
let accounts = vec![
(
solana_sdk::pubkey::new_rand(),
AccountSharedData::new_ref(100, 1, &mock_system_program_id),
),
(
solana_sdk::pubkey::new_rand(),
AccountSharedData::new_ref(0, 1, &mock_system_program_id),
),
];
let account = Rc::new(RefCell::new(create_loadable_account_for_test(
"mock_system_program",
)));
let loaders = vec![vec![(mock_system_program_id, account)]];
let executors = Rc::new(RefCell::new(Executors::default()));
let ancestors = Ancestors::default();
let account_metas = vec![
AccountMeta::new(accounts[0].0, true),
AccountMeta::new_readonly(accounts[1].0, false),
];
let message = Message::new(
&[Instruction::new_with_bincode(
mock_system_program_id,
&MockSystemInstruction::Correct,
account_metas.clone(),
)],
Some(&accounts[0].0),
);
let result = message_processor.process_message(
&message,
&loaders,
&accounts,
&rent_collector,
None,
executors.clone(),
None,
Arc::new(FeatureSet::all_enabled()),
BpfComputeBudget::new(),
Rc::new(RefCell::new(MockComputeMeter::default())),
&mut ExecuteDetailsTimings::default(),
Arc::new(Accounts::default()),
&ancestors,
);
assert_eq!(result, Ok(()));
assert_eq!(accounts[0].1.borrow().lamports(), 100);
assert_eq!(accounts[1].1.borrow().lamports(), 0);
let message = Message::new(
&[Instruction::new_with_bincode(
mock_system_program_id,
&MockSystemInstruction::AttemptCredit { lamports: 50 },
account_metas.clone(),
)],
Some(&accounts[0].0),
);
let result = message_processor.process_message(
&message,
&loaders,
&accounts,
&rent_collector,
None,
executors.clone(),
None,
Arc::new(FeatureSet::all_enabled()),
BpfComputeBudget::new(),
Rc::new(RefCell::new(MockComputeMeter::default())),
&mut ExecuteDetailsTimings::default(),
Arc::new(Accounts::default()),
&ancestors,
);
assert_eq!(
result,
Err(TransactionError::InstructionError(
0,
InstructionError::ReadonlyLamportChange
))
);
let message = Message::new(
&[Instruction::new_with_bincode(
mock_system_program_id,
&MockSystemInstruction::AttemptDataChange { data: 50 },
account_metas,
)],
Some(&accounts[0].0),
);
let result = message_processor.process_message(
&message,
&loaders,
&accounts,
&rent_collector,
None,
executors,
None,
Arc::new(FeatureSet::all_enabled()),
BpfComputeBudget::new(),
Rc::new(RefCell::new(MockComputeMeter::default())),
&mut ExecuteDetailsTimings::default(),
Arc::new(Accounts::default()),
&ancestors,
);
assert_eq!(
result,
Err(TransactionError::InstructionError(
0,
InstructionError::ReadonlyDataModified
))
);
}
#[test]
fn test_process_message_duplicate_accounts() {
#[derive(Serialize, Deserialize)]
enum MockSystemInstruction {
BorrowFail,
MultiBorrowMut,
DoWork { lamports: u64, data: u8 },
}
fn mock_system_process_instruction(
_program_id: &Pubkey,
data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
let keyed_accounts = invoke_context.get_keyed_accounts()?;
if let Ok(instruction) = bincode::deserialize(data) {
match instruction {
MockSystemInstruction::BorrowFail => {
let from_account = keyed_accounts[0].try_account_ref_mut()?;
let dup_account = keyed_accounts[2].try_account_ref_mut()?;
if from_account.lamports() != dup_account.lamports() {
return Err(InstructionError::InvalidArgument);
}
Ok(())
}
MockSystemInstruction::MultiBorrowMut => {
let from_lamports = {
let from_account = keyed_accounts[0].try_account_ref_mut()?;
from_account.lamports()
};
let dup_lamports = {
let dup_account = keyed_accounts[2].try_account_ref_mut()?;
dup_account.lamports()
};
if from_lamports != dup_lamports {
return Err(InstructionError::InvalidArgument);
}
Ok(())
}
MockSystemInstruction::DoWork { lamports, data } => {
{
let mut to_account = keyed_accounts[1].try_account_ref_mut()?;
let mut dup_account = keyed_accounts[2].try_account_ref_mut()?;
dup_account.checked_sub_lamports(lamports)?;
to_account.checked_add_lamports(lamports)?;
dup_account.set_data(vec![data]);
}
keyed_accounts[0]
.try_account_ref_mut()?
.checked_sub_lamports(lamports)?;
keyed_accounts[1]
.try_account_ref_mut()?
.checked_add_lamports(lamports)?;
Ok(())
}
}
} else {
Err(InstructionError::InvalidInstructionData)
}
}
let mock_program_id = Pubkey::new(&[2u8; 32]);
let rent_collector = RentCollector::default();
let mut message_processor = MessageProcessor::default();
message_processor.add_program(mock_program_id, mock_system_process_instruction);
let accounts = vec![
(
solana_sdk::pubkey::new_rand(),
AccountSharedData::new_ref(100, 1, &mock_program_id),
),
(
solana_sdk::pubkey::new_rand(),
AccountSharedData::new_ref(0, 1, &mock_program_id),
),
];
let account = Rc::new(RefCell::new(create_loadable_account_for_test(
"mock_system_program",
)));
let loaders = vec![vec![(mock_program_id, account)]];
let executors = Rc::new(RefCell::new(Executors::default()));
let ancestors = Ancestors::default();
let account_metas = vec![
AccountMeta::new(accounts[0].0, true),
AccountMeta::new(accounts[1].0, false),
AccountMeta::new(accounts[0].0, false),
];
// Try to borrow mut the same account
let message = Message::new(
&[Instruction::new_with_bincode(
mock_program_id,
&MockSystemInstruction::BorrowFail,
account_metas.clone(),
)],
Some(&accounts[0].0),
);
let result = message_processor.process_message(
&message,
&loaders,
&accounts,
&rent_collector,
None,
executors.clone(),
None,
Arc::new(FeatureSet::all_enabled()),
BpfComputeBudget::new(),
Rc::new(RefCell::new(MockComputeMeter::default())),
&mut ExecuteDetailsTimings::default(),
Arc::new(Accounts::default()),
&ancestors,
);
assert_eq!(
result,
Err(TransactionError::InstructionError(
0,
InstructionError::AccountBorrowFailed
))
);
// Try to borrow mut the same account in a safe way
let message = Message::new(
&[Instruction::new_with_bincode(
mock_program_id,
&MockSystemInstruction::MultiBorrowMut,
account_metas.clone(),
)],
Some(&accounts[0].0),
);
let result = message_processor.process_message(
&message,
&loaders,
&accounts,
&rent_collector,
None,
executors.clone(),
None,
Arc::new(FeatureSet::all_enabled()),
BpfComputeBudget::new(),
Rc::new(RefCell::new(MockComputeMeter::default())),
&mut ExecuteDetailsTimings::default(),
Arc::new(Accounts::default()),
&ancestors,
);
assert_eq!(result, Ok(()));
// Do work on the same account but at different location in keyed_accounts[]
let message = Message::new(
&[Instruction::new_with_bincode(
mock_program_id,
&MockSystemInstruction::DoWork {
lamports: 10,
data: 42,
},
account_metas,
)],
Some(&accounts[0].0),
);
let ancestors = Ancestors::default();
let result = message_processor.process_message(
&message,
&loaders,
&accounts,
&rent_collector,
None,
executors,
None,
Arc::new(FeatureSet::all_enabled()),
BpfComputeBudget::new(),
Rc::new(RefCell::new(MockComputeMeter::default())),
&mut ExecuteDetailsTimings::default(),
Arc::new(Accounts::default()),
&ancestors,
);
assert_eq!(result, Ok(()));
assert_eq!(accounts[0].1.borrow().lamports(), 80);
assert_eq!(accounts[1].1.borrow().lamports(), 20);
assert_eq!(accounts[0].1.borrow().data(), &vec![42]);
}
#[test]
fn test_process_cross_program() {
#[derive(Debug, Serialize, Deserialize)]
enum MockInstruction {
NoopSuccess,
NoopFail,
ModifyOwned,
ModifyNotOwned,
}
fn mock_process_instruction(
program_id: &Pubkey,
data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
let keyed_accounts = invoke_context.get_keyed_accounts()?;
assert_eq!(*program_id, keyed_accounts[0].owner()?);
assert_ne!(
keyed_accounts[1].owner()?,
*keyed_accounts[0].unsigned_key()
);
if let Ok(instruction) = bincode::deserialize(data) {
match instruction {
MockInstruction::NoopSuccess => (),
MockInstruction::NoopFail => return Err(InstructionError::GenericError),
MockInstruction::ModifyOwned => {
keyed_accounts[0].try_account_ref_mut()?.data_as_mut_slice()[0] = 1
}
MockInstruction::ModifyNotOwned => {
keyed_accounts[1].try_account_ref_mut()?.data_as_mut_slice()[0] = 1
}
}
} else {
return Err(InstructionError::InvalidInstructionData);
}
Ok(())
}
let caller_program_id = solana_sdk::pubkey::new_rand();
let callee_program_id = solana_sdk::pubkey::new_rand();
let mut program_account = AccountSharedData::new(1, 0, &native_loader::id());
program_account.set_executable(true);
let executable_accounts = vec![(
callee_program_id,
Rc::new(RefCell::new(program_account.clone())),
)];
let owned_account = AccountSharedData::new(42, 1, &callee_program_id);
let not_owned_account = AccountSharedData::new(84, 1, &solana_sdk::pubkey::new_rand());
#[allow(unused_mut)]
let accounts = vec![
(
solana_sdk::pubkey::new_rand(),
Rc::new(RefCell::new(owned_account)),
),
(
solana_sdk::pubkey::new_rand(),
Rc::new(RefCell::new(not_owned_account)),
),
(callee_program_id, Rc::new(RefCell::new(program_account))),
];
let compiled_instruction = CompiledInstruction::new(2, &(), vec![0, 1, 2]);
let programs: Vec<(_, ProcessInstructionWithContext)> =
vec![(callee_program_id, mock_process_instruction)];
let metas = vec![
AccountMeta::new(accounts[0].0, false),
AccountMeta::new(accounts[1].0, false),
];
let instruction = Instruction::new_with_bincode(
callee_program_id,
&MockInstruction::NoopSuccess,
metas.clone(),
);
let message = Message::new(&[instruction], None);
let ancestors = Ancestors::default();
let mut invoke_context = ThisInvokeContext::new(
&caller_program_id,
Rent::default(),
&message,
&compiled_instruction,
&executable_accounts,
&accounts,
programs.as_slice(),
None,
BpfComputeBudget::default(),
Rc::new(RefCell::new(MockComputeMeter::default())),
Rc::new(RefCell::new(Executors::default())),
None,
Arc::new(FeatureSet::all_enabled()),
Arc::new(Accounts::default()),
&ancestors,
);
// not owned account modified by the caller (before the invoke)
let caller_write_privileges = message
.account_keys
.iter()
.enumerate()
.map(|(i, _)| message.is_writable(i))
.collect::<Vec<bool>>();
accounts[0].1.borrow_mut().data_as_mut_slice()[0] = 1;
assert_eq!(
MessageProcessor::process_cross_program_instruction(
&message,
&executable_accounts,
&accounts,
&caller_write_privileges,
&mut invoke_context,
),
Err(InstructionError::ExternalAccountDataModified)
);
accounts[0].1.borrow_mut().data_as_mut_slice()[0] = 0;
let cases = vec![
(MockInstruction::NoopSuccess, Ok(())),
(
MockInstruction::NoopFail,
Err(InstructionError::GenericError),
),
(MockInstruction::ModifyOwned, Ok(())),
(
MockInstruction::ModifyNotOwned,
Err(InstructionError::ExternalAccountDataModified),
),
];
for case in cases {
let instruction =
Instruction::new_with_bincode(callee_program_id, &case.0, metas.clone());
let message = Message::new(&[instruction], None);
let ancestors = Ancestors::default();
let mut invoke_context = ThisInvokeContext::new(
&caller_program_id,
Rent::default(),
&message,
&compiled_instruction,
&executable_accounts,
&accounts,
programs.as_slice(),
None,
BpfComputeBudget::default(),
Rc::new(RefCell::new(MockComputeMeter::default())),
Rc::new(RefCell::new(Executors::default())),
None,
Arc::new(FeatureSet::all_enabled()),
Arc::new(Accounts::default()),
&ancestors,
);
let caller_write_privileges = message
.account_keys
.iter()
.enumerate()
.map(|(i, _)| message.is_writable(i))
.collect::<Vec<bool>>();
assert_eq!(
MessageProcessor::process_cross_program_instruction(
&message,
&executable_accounts,
&accounts,
&caller_write_privileges,
&mut invoke_context,
),
case.1
);
}
}
#[test]
fn test_debug() {
let mut message_processor = MessageProcessor::default();
#[allow(clippy::unnecessary_wraps)]
fn mock_process_instruction(
_program_id: &Pubkey,
_data: &[u8],
_invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
fn mock_ix_processor(
_pubkey: &Pubkey,
_data: &[u8],
_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
Ok(())
}
let program_id = solana_sdk::pubkey::new_rand();
message_processor.add_program(program_id, mock_process_instruction);
message_processor.add_loader(program_id, mock_ix_processor);
assert!(!format!("{:?}", message_processor).is_empty());
}
}
| 37.069439 | 107 | 0.533291 |
f7a874bf93f107216ffb565e2ab077a4918a0754 | 7,992 | /*
* Client Portal Web API
*
* Client Poral Web API
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
#[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct AlertRequest {
/// The message you want to receive via email or text message
#[serde(rename = "alertMessage")]
alert_message: Option<String>,
/// name of alert
#[serde(rename = "alertName")]
alert_name: Option<String>,
/// whether alert is repeatable or not, so value can only be 0 or 1, this has to be 1 for MTA alert
#[serde(rename = "alertRepeatable")]
alert_repeatable: Option<i32>,
#[serde(rename = "conditions")]
conditions: Option<Vec<::models::AlertrequestConditions>>,
/// email address to receive alert
#[serde(rename = "email")]
email: Option<String>,
/// format, YYYYMMDD-HH:mm:ss, please NOTE this will only work when tif is GTD
#[serde(rename = "expireTime")]
expire_time: Option<String>,
/// value can only be 0 or 1, set to 1 to enable the alert only in IBKR mobile
#[serde(rename = "iTWSOrdersOnly")]
i_tws_orders_only: Option<i32>,
/// orderId is required when modifying alert. You can get it from /iserver/account/:accountId/alerts
#[serde(rename = "orderId")]
order_id: Option<i32>,
/// value can only be 0 or 1, set to 1 if the alert can be triggered outside regular trading hours.
#[serde(rename = "outsideRth")]
outside_rth: Option<i32>,
/// audio message to play when alert is triggered
#[serde(rename = "playAudio")]
play_audio: Option<String>,
/// whether allowing to send email or not, so value can only be 0 or 1,
#[serde(rename = "sendMessage")]
send_message: Option<i32>,
/// value can only be 0 or 1, set to 1 to allow to show alert in pop-ups
#[serde(rename = "showPopup")]
show_popup: Option<i32>,
/// time in force, can only be GTC or GTD
#[serde(rename = "tif")]
tif: Option<String>,
/// for MTA alert only, each user has a unique toolId and it will stay the same, do not send for normal alert
#[serde(rename = "toolId")]
tool_id: Option<i32>
}
impl AlertRequest {
pub fn new() -> AlertRequest {
AlertRequest {
alert_message: None,
alert_name: None,
alert_repeatable: None,
conditions: None,
email: None,
expire_time: None,
i_tws_orders_only: None,
order_id: None,
outside_rth: None,
play_audio: None,
send_message: None,
show_popup: None,
tif: None,
tool_id: None
}
}
pub fn set_alert_message(&mut self, alert_message: String) {
self.alert_message = Some(alert_message);
}
pub fn with_alert_message(mut self, alert_message: String) -> AlertRequest {
self.alert_message = Some(alert_message);
self
}
pub fn alert_message(&self) -> Option<&String> {
self.alert_message.as_ref()
}
pub fn reset_alert_message(&mut self) {
self.alert_message = None;
}
pub fn set_alert_name(&mut self, alert_name: String) {
self.alert_name = Some(alert_name);
}
pub fn with_alert_name(mut self, alert_name: String) -> AlertRequest {
self.alert_name = Some(alert_name);
self
}
pub fn alert_name(&self) -> Option<&String> {
self.alert_name.as_ref()
}
pub fn reset_alert_name(&mut self) {
self.alert_name = None;
}
pub fn set_alert_repeatable(&mut self, alert_repeatable: i32) {
self.alert_repeatable = Some(alert_repeatable);
}
pub fn with_alert_repeatable(mut self, alert_repeatable: i32) -> AlertRequest {
self.alert_repeatable = Some(alert_repeatable);
self
}
pub fn alert_repeatable(&self) -> Option<&i32> {
self.alert_repeatable.as_ref()
}
pub fn reset_alert_repeatable(&mut self) {
self.alert_repeatable = None;
}
pub fn set_conditions(&mut self, conditions: Vec<::models::AlertrequestConditions>) {
self.conditions = Some(conditions);
}
pub fn with_conditions(mut self, conditions: Vec<::models::AlertrequestConditions>) -> AlertRequest {
self.conditions = Some(conditions);
self
}
pub fn conditions(&self) -> Option<&Vec<::models::AlertrequestConditions>> {
self.conditions.as_ref()
}
pub fn reset_conditions(&mut self) {
self.conditions = None;
}
pub fn set_email(&mut self, email: String) {
self.email = Some(email);
}
pub fn with_email(mut self, email: String) -> AlertRequest {
self.email = Some(email);
self
}
pub fn email(&self) -> Option<&String> {
self.email.as_ref()
}
pub fn reset_email(&mut self) {
self.email = None;
}
pub fn set_expire_time(&mut self, expire_time: String) {
self.expire_time = Some(expire_time);
}
pub fn with_expire_time(mut self, expire_time: String) -> AlertRequest {
self.expire_time = Some(expire_time);
self
}
pub fn expire_time(&self) -> Option<&String> {
self.expire_time.as_ref()
}
pub fn reset_expire_time(&mut self) {
self.expire_time = None;
}
pub fn set_i_tws_orders_only(&mut self, i_tws_orders_only: i32) {
self.i_tws_orders_only = Some(i_tws_orders_only);
}
pub fn with_i_tws_orders_only(mut self, i_tws_orders_only: i32) -> AlertRequest {
self.i_tws_orders_only = Some(i_tws_orders_only);
self
}
pub fn i_tws_orders_only(&self) -> Option<&i32> {
self.i_tws_orders_only.as_ref()
}
pub fn reset_i_tws_orders_only(&mut self) {
self.i_tws_orders_only = None;
}
pub fn set_order_id(&mut self, order_id: i32) {
self.order_id = Some(order_id);
}
pub fn with_order_id(mut self, order_id: i32) -> AlertRequest {
self.order_id = Some(order_id);
self
}
pub fn order_id(&self) -> Option<&i32> {
self.order_id.as_ref()
}
pub fn reset_order_id(&mut self) {
self.order_id = None;
}
pub fn set_outside_rth(&mut self, outside_rth: i32) {
self.outside_rth = Some(outside_rth);
}
pub fn with_outside_rth(mut self, outside_rth: i32) -> AlertRequest {
self.outside_rth = Some(outside_rth);
self
}
pub fn outside_rth(&self) -> Option<&i32> {
self.outside_rth.as_ref()
}
pub fn reset_outside_rth(&mut self) {
self.outside_rth = None;
}
pub fn set_play_audio(&mut self, play_audio: String) {
self.play_audio = Some(play_audio);
}
pub fn with_play_audio(mut self, play_audio: String) -> AlertRequest {
self.play_audio = Some(play_audio);
self
}
pub fn play_audio(&self) -> Option<&String> {
self.play_audio.as_ref()
}
pub fn reset_play_audio(&mut self) {
self.play_audio = None;
}
pub fn set_send_message(&mut self, send_message: i32) {
self.send_message = Some(send_message);
}
pub fn with_send_message(mut self, send_message: i32) -> AlertRequest {
self.send_message = Some(send_message);
self
}
pub fn send_message(&self) -> Option<&i32> {
self.send_message.as_ref()
}
pub fn reset_send_message(&mut self) {
self.send_message = None;
}
pub fn set_show_popup(&mut self, show_popup: i32) {
self.show_popup = Some(show_popup);
}
pub fn with_show_popup(mut self, show_popup: i32) -> AlertRequest {
self.show_popup = Some(show_popup);
self
}
pub fn show_popup(&self) -> Option<&i32> {
self.show_popup.as_ref()
}
pub fn reset_show_popup(&mut self) {
self.show_popup = None;
}
pub fn set_tif(&mut self, tif: String) {
self.tif = Some(tif);
}
pub fn with_tif(mut self, tif: String) -> AlertRequest {
self.tif = Some(tif);
self
}
pub fn tif(&self) -> Option<&String> {
self.tif.as_ref()
}
pub fn reset_tif(&mut self) {
self.tif = None;
}
pub fn set_tool_id(&mut self, tool_id: i32) {
self.tool_id = Some(tool_id);
}
pub fn with_tool_id(mut self, tool_id: i32) -> AlertRequest {
self.tool_id = Some(tool_id);
self
}
pub fn tool_id(&self) -> Option<&i32> {
self.tool_id.as_ref()
}
pub fn reset_tool_id(&mut self) {
self.tool_id = None;
}
}
| 24.819876 | 112 | 0.665541 |
c1ed8de8ad8c3ed03a0635e7f65936597b5e07c8 | 8,485 | // run-rustfix
// The `try_into` suggestion doesn't include this, but we do suggest it after applying it
use std::convert::TryInto;
#[allow(unused_must_use)]
fn main() {
let x_usize: usize = 1;
let x_u128: u128 = 2;
let x_u64: u64 = 3;
let x_u32: u32 = 4;
let x_u16: u16 = 5;
let x_u8: u8 = 6;
let x_isize: isize = 7;
let x_i64: i64 = 8;
let x_i32: i32 = 9;
let x_i16: i16 = 10;
let x_i8: i8 = 11;
let x_i128: i128 = 12;
/* u<->u */
{
x_u8 > x_u16;
//~^ ERROR mismatched types
x_u8 > x_u32;
//~^ ERROR mismatched types
x_u8 > x_u64;
//~^ ERROR mismatched types
x_u8 > x_u128;
//~^ ERROR mismatched types
x_u8 > x_usize;
//~^ ERROR mismatched types
x_u16 > x_u8;
//~^ ERROR mismatched types
x_u16 > x_u32;
//~^ ERROR mismatched types
x_u16 > x_u64;
//~^ ERROR mismatched types
x_u16 > x_u128;
//~^ ERROR mismatched types
x_u16 > x_usize;
//~^ ERROR mismatched types
x_u32 > x_u8;
//~^ ERROR mismatched types
x_u32 > x_u16;
//~^ ERROR mismatched types
x_u32 > x_u64;
//~^ ERROR mismatched types
x_u32 > x_u128;
//~^ ERROR mismatched types
x_u32 > x_usize;
//~^ ERROR mismatched types
x_u64 > x_u8;
//~^ ERROR mismatched types
x_u64 > x_u16;
//~^ ERROR mismatched types
x_u64 > x_u32;
//~^ ERROR mismatched types
x_u64 > x_u128;
//~^ ERROR mismatched types
x_u64 > x_usize;
//~^ ERROR mismatched types
x_u128 > x_u8;
//~^ ERROR mismatched types
x_u128 > x_u16;
//~^ ERROR mismatched types
x_u128 > x_u32;
//~^ ERROR mismatched types
x_u128 > x_u64;
//~^ ERROR mismatched types
x_u128 > x_usize;
//~^ ERROR mismatched types
x_usize > x_u8;
//~^ ERROR mismatched types
x_usize > x_u16;
//~^ ERROR mismatched types
x_usize > x_u32;
//~^ ERROR mismatched types
x_usize > x_u64;
//~^ ERROR mismatched types
x_usize > x_u128;
//~^ ERROR mismatched types
}
/* i<->i */
{
x_i8 > x_i16;
//~^ ERROR mismatched types
x_i8 > x_i32;
//~^ ERROR mismatched types
x_i8 > x_i64;
//~^ ERROR mismatched types
x_i8 > x_i128;
//~^ ERROR mismatched types
x_i8 > x_isize;
//~^ ERROR mismatched types
x_i16 > x_i8;
//~^ ERROR mismatched types
x_i16 > x_i32;
//~^ ERROR mismatched types
x_i16 > x_i64;
//~^ ERROR mismatched types
x_i16 > x_i128;
//~^ ERROR mismatched types
x_i16 > x_isize;
//~^ ERROR mismatched types
x_i32 > x_i8;
//~^ ERROR mismatched types
x_i32 > x_i16;
//~^ ERROR mismatched types
x_i32 > x_i64;
//~^ ERROR mismatched types
x_i32 > x_i128;
//~^ ERROR mismatched types
x_i32 > x_isize;
//~^ ERROR mismatched types
x_i64 > x_i8;
//~^ ERROR mismatched types
x_i64 > x_i16;
//~^ ERROR mismatched types
x_i64 > x_i32;
//~^ ERROR mismatched types
x_i64 > x_i128;
//~^ ERROR mismatched types
x_i64 > x_isize;
//~^ ERROR mismatched types
x_i128 > x_i8;
//~^ ERROR mismatched types
x_i128 > x_i16;
//~^ ERROR mismatched types
x_i128 > x_i32;
//~^ ERROR mismatched types
x_i128 > x_i64;
//~^ ERROR mismatched types
x_i128 > x_isize;
//~^ ERROR mismatched types
x_isize > x_i8;
//~^ ERROR mismatched types
x_isize > x_i16;
//~^ ERROR mismatched types
x_isize > x_i32;
//~^ ERROR mismatched types
x_isize > x_i64;
//~^ ERROR mismatched types
x_isize > x_i128;
//~^ ERROR mismatched types
}
/* u<->i */
{
x_u8 > x_i8;
//~^ ERROR mismatched types
x_u8 > x_i16;
//~^ ERROR mismatched types
x_u8 > x_i32;
//~^ ERROR mismatched types
x_u8 > x_i64;
//~^ ERROR mismatched types
x_u8 > x_i128;
//~^ ERROR mismatched types
x_u8 > x_isize;
//~^ ERROR mismatched types
x_u16 > x_i8;
//~^ ERROR mismatched types
x_u16 > x_i16;
//~^ ERROR mismatched types
x_u16 > x_i32;
//~^ ERROR mismatched types
x_u16 > x_i64;
//~^ ERROR mismatched types
x_u16 > x_i128;
//~^ ERROR mismatched types
x_u16 > x_isize;
//~^ ERROR mismatched types
x_u32 > x_i8;
//~^ ERROR mismatched types
x_u32 > x_i16;
//~^ ERROR mismatched types
x_u32 > x_i32;
//~^ ERROR mismatched types
x_u32 > x_i64;
//~^ ERROR mismatched types
x_u32 > x_i128;
//~^ ERROR mismatched types
x_u32 > x_isize;
//~^ ERROR mismatched types
x_u64 > x_i8;
//~^ ERROR mismatched types
x_u64 > x_i16;
//~^ ERROR mismatched types
x_u64 > x_i32;
//~^ ERROR mismatched types
x_u64 > x_i64;
//~^ ERROR mismatched types
x_u64 > x_i128;
//~^ ERROR mismatched types
x_u64 > x_isize;
//~^ ERROR mismatched types
x_u128 > x_i8;
//~^ ERROR mismatched types
x_u128 > x_i16;
//~^ ERROR mismatched types
x_u128 > x_i32;
//~^ ERROR mismatched types
x_u128 > x_i64;
//~^ ERROR mismatched types
x_u128 > x_i128;
//~^ ERROR mismatched types
x_u128 > x_isize;
//~^ ERROR mismatched types
x_usize > x_i8;
//~^ ERROR mismatched types
x_usize > x_i16;
//~^ ERROR mismatched types
x_usize > x_i32;
//~^ ERROR mismatched types
x_usize > x_i64;
//~^ ERROR mismatched types
x_usize > x_i128;
//~^ ERROR mismatched types
x_usize > x_isize;
//~^ ERROR mismatched types
}
/* i<->u */
{
x_i8 > x_u8;
//~^ ERROR mismatched types
x_i8 > x_u16;
//~^ ERROR mismatched types
x_i8 > x_u32;
//~^ ERROR mismatched types
x_i8 > x_u64;
//~^ ERROR mismatched types
x_i8 > x_u128;
//~^ ERROR mismatched types
x_i8 > x_usize;
//~^ ERROR mismatched types
x_i16 > x_u8;
//~^ ERROR mismatched types
x_i16 > x_u16;
//~^ ERROR mismatched types
x_i16 > x_u32;
//~^ ERROR mismatched types
x_i16 > x_u64;
//~^ ERROR mismatched types
x_i16 > x_u128;
//~^ ERROR mismatched types
x_i16 > x_usize;
//~^ ERROR mismatched types
x_i32 > x_u8;
//~^ ERROR mismatched types
x_i32 > x_u16;
//~^ ERROR mismatched types
x_i32 > x_u32;
//~^ ERROR mismatched types
x_i32 > x_u64;
//~^ ERROR mismatched types
x_i32 > x_u128;
//~^ ERROR mismatched types
x_i32 > x_usize;
//~^ ERROR mismatched types
x_i64 > x_u8;
//~^ ERROR mismatched types
x_i64 > x_u16;
//~^ ERROR mismatched types
x_i64 > x_u32;
//~^ ERROR mismatched types
x_i64 > x_u64;
//~^ ERROR mismatched types
x_i64 > x_u128;
//~^ ERROR mismatched types
x_i64 > x_usize;
//~^ ERROR mismatched types
x_i128 > x_u8;
//~^ ERROR mismatched types
x_i128 > x_u16;
//~^ ERROR mismatched types
x_i128 > x_u32;
//~^ ERROR mismatched types
x_i128 > x_u64;
//~^ ERROR mismatched types
x_i128 > x_u128;
//~^ ERROR mismatched types
x_i128 > x_usize;
//~^ ERROR mismatched types
x_isize > x_u8;
//~^ ERROR mismatched types
x_isize > x_u16;
//~^ ERROR mismatched types
x_isize > x_u32;
//~^ ERROR mismatched types
x_isize > x_u64;
//~^ ERROR mismatched types
x_isize > x_u128;
//~^ ERROR mismatched types
x_isize > x_usize;
//~^ ERROR mismatched types
}
}
| 26.433022 | 89 | 0.511019 |
eb1eca220767544b679e234f7904100466de526a | 3,435 | #[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Debug Halting Control and Status Register"]
pub dhcsr: DHCSR,
#[doc = "0x04 - Debug Core Register Selector Register"]
pub dcrsr: DCRSR,
#[doc = "0x08 - Debug Core Register Data Register"]
pub dcrdr: DCRDR,
#[doc = "0x0c - Debug Exception and Monitor Control Register"]
pub demcr: DEMCR,
}
#[doc = "Debug Halting Control and Status Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dhcsr](dhcsr) module"]
pub type DHCSR = crate::Reg<u32, _DHCSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DHCSR;
#[doc = "`read()` method returns [dhcsr::R](dhcsr::R) reader structure"]
impl crate::Readable for DHCSR {}
#[doc = "`write(|w| ..)` method takes [dhcsr::W](dhcsr::W) writer structure"]
impl crate::Writable for DHCSR {}
#[doc = "Debug Halting Control and Status Register"]
pub mod dhcsr;
#[doc = "Debug Core Register Selector Register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcrsr](dcrsr) module"]
pub type DCRSR = crate::Reg<u32, _DCRSR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DCRSR;
#[doc = "`write(|w| ..)` method takes [dcrsr::W](dcrsr::W) writer structure"]
impl crate::Writable for DCRSR {}
#[doc = "Debug Core Register Selector Register"]
pub mod dcrsr;
#[doc = "Debug Core Register Data Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcrdr](dcrdr) module"]
pub type DCRDR = crate::Reg<u32, _DCRDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DCRDR;
#[doc = "`read()` method returns [dcrdr::R](dcrdr::R) reader structure"]
impl crate::Readable for DCRDR {}
#[doc = "`write(|w| ..)` method takes [dcrdr::W](dcrdr::W) writer structure"]
impl crate::Writable for DCRDR {}
#[doc = "Debug Core Register Data Register"]
pub mod dcrdr;
#[doc = "Debug Exception and Monitor Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [demcr](demcr) module"]
pub type DEMCR = crate::Reg<u32, _DEMCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DEMCR;
#[doc = "`read()` method returns [demcr::R](demcr::R) reader structure"]
impl crate::Readable for DEMCR {}
#[doc = "`write(|w| ..)` method takes [demcr::W](demcr::W) writer structure"]
impl crate::Writable for DEMCR {}
#[doc = "Debug Exception and Monitor Control Register"]
pub mod demcr;
| 62.454545 | 425 | 0.695488 |
ab37b8930bf074648b718b3e9b2bdd0977387af8 | 1,452 | use proc_macro2::{Ident, TokenStream};
use quote::{quote, quote_spanned};
use syn::{spanned::Spanned, Data, Field, Generics};
use crate::{
constants::EQUAL,
utils::{get_any_attribute_by_meta_prefix, meta_not_found_in_all_fields, resolve_all_fields},
};
pub fn impl_equal(ident: &Ident, data: &Data, generics: &Generics) -> TokenStream {
let ident_location = ident.to_string();
let fields = resolve_all_fields(
data,
true,
&is_equal_field,
&meta_not_found_in_all_fields(EQUAL, &ident_location),
);
let equal_fields_token = equal_fields_token(&fields);
let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
quote! {
impl #impl_generics PartialEq for #ident #type_generics #where_clause {
fn eq(&self, other: &Self) -> bool {
#equal_fields_token
}
}
}
}
fn is_equal_field(field: &Field) -> bool {
get_any_attribute_by_meta_prefix(EQUAL, &field.attrs, false, "").is_some()
}
fn equal_fields_token(fields: &[Field]) -> TokenStream {
let equal_fields = fields.iter().map(equal_field_token);
quote! {
#(#equal_fields)&&*
}
}
fn equal_field_token(field: &Field) -> TokenStream {
let field = field.to_owned();
let field_span = field.span();
let field_ident = field.ident.unwrap();
quote_spanned! { field_span =>
self.#field_ident == other.#field_ident
}
}
| 30.25 | 96 | 0.658402 |
bb4353c0ab018e814bc531cab2e24b19ead1ca04 | 395 | use lucet_runtime_tests::{guest_fault_common_defs, guest_fault_tests};
guest_fault_common_defs!();
cfg_if::cfg_if! {
if #[cfg(all(target_os = "linux", feature = "uffd"))] {
guest_fault_tests!(
mmap => lucet_runtime::MmapRegion,
uffd => lucet_runtime::UffdRegion
);
} else {
guest_fault_tests!(mmap => lucet_runtime::MmapRegion);
}
}
| 26.333333 | 70 | 0.63038 |
efb69b9f9576fa5461993753e713db897c451bcb | 583 | // 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.
// error-pattern:fail
fn fold_local() -> @~[int]{
fail2!();
}
fn main() {
let _lss = (fold_local(), 0);
}
| 29.15 | 68 | 0.699828 |
6965afb0c66a642f6647cc763a3a46b60c3cec94 | 2,272 | #![feature(dispatch_from_dyn)]
#![feature(unsize)]
#![feature(coerce_unsized)]
mod imp_impls;
mod tests;
use std::{cell::RefCell, rc::Rc};
#[doc = include_str!("../readme.md")]
pub struct Imp<T: ?Sized> {
v: Rc<RefCell<T>>,
}
#[allow(unused)]
impl<T> Imp<T> {
/// Returns a pointer to the data
///
/// # Arguments
///
/// * `t` - The value to be pointed to.
///
/// # Examples
///
/// ```
/// use interior_mutability_pointer::Imp;
/// let mut p = Imp::new(String::new());
/// let p2 = p.clone();
/// p.push_str("yoo"); // Modifies the inner value of both p and p2.
/// ```
pub fn new(t: T) -> Self {
Self {
v: Rc::new(RefCell::new(t)),
}
}
/// Returns true if two pointers are equal
///
/// # Arguments
/// * `this` - A pointer to compare
/// * `other` - The other pointer to compare to
///
/// # Examples
/// ```
/// use interior_mutability_pointer::Imp;
/// let p1 = Imp::new(String::new());
/// let p2 = p1.clone();
/// let p3 = Imp::new(String::new());
/// println!("{}", Imp::ptr_eq(&p1, &p2)); // Prints true
/// println!("{}", Imp::ptr_eq(&p1, &p3)); // Prints false
/// ```
pub fn ptr_eq(this: &Self, other: &Self) -> bool {
Rc::ptr_eq(&this.v, &other.v)
}
}
/*
Implements cloning the pointer.
*/
mod clone_impl {
use super::Imp;
use std::clone::Clone;
impl<T: ?Sized> Clone for Imp<T> {
fn clone(&self) -> Self {
Self { v: self.v.clone() }
}
}
}
/*
Allows access to the inner methods from T.
*/
mod deref_impl {
use std::{
marker::Unsize,
ops::{CoerceUnsized, Deref, DerefMut, DispatchFromDyn},
};
use super::Imp;
impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Imp<U>> for Imp<T> {}
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Imp<U>> for Imp<T> {}
impl<T: ?Sized> Deref for Imp<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
unsafe { &*self.v.as_ptr() }
}
}
impl<T: ?Sized> DerefMut for Imp<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.v.as_ptr() }
}
}
}
| 22.949495 | 80 | 0.510123 |
aba6b58dee53c816cc4054c28109603af5c6d4b0 | 4,754 | // Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
// Copyright 2019 Guillaume Becquin
// 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.
//! # Named Entity Recognition pipeline
//! Extracts entities (Person, Location, Organization, Miscellaneous) from text.
//! BERT cased large model finetuned on CoNNL03, contributed by the [MDZ Digital Library team at the Bavarian State Library](https://github.com/dbmdz)
//! All resources for this model can be downloaded using the Python utility script included in this repository.
//! 1. Set-up a Python virtual environment and install dependencies (in ./requirements.txt)
//! 2. Run the conversion script python /utils/download-dependencies_bert_ner.py.
//! The dependencies will be downloaded to the user's home directory, under ~/rustbert/bert-ner
//!
//! ```no_run
//! use rust_bert::pipelines::ner::NERModel;
//! # fn main() -> failure::Fallible<()> {
//! let ner_model = NERModel::new(Default::default())?;
//!
//! let input = [
//! "My name is Amy. I live in Paris.",
//! "Paris is a city in France.",
//! ];
//! let output = ner_model.predict(&input);
//! # Ok(())
//! # }
//! ```
//! Output: \
//! ```no_run
//! # use rust_bert::pipelines::question_answering::Answer;
//! # use rust_bert::pipelines::ner::Entity;
//! # let output =
//! [
//! Entity {
//! word: String::from("Amy"),
//! score: 0.9986,
//! label: String::from("I-PER"),
//! },
//! Entity {
//! word: String::from("Paris"),
//! score: 0.9985,
//! label: String::from("I-LOC"),
//! },
//! Entity {
//! word: String::from("Paris"),
//! score: 0.9988,
//! label: String::from("I-LOC"),
//! },
//! Entity {
//! word: String::from("France"),
//! score: 0.9993,
//! label: String::from("I-LOC"),
//! },
//! ]
//! # ;
//! ```
use crate::pipelines::token_classification::{TokenClassificationConfig, TokenClassificationModel};
#[derive(Debug)]
/// # Entity generated by a `NERModel`
pub struct Entity {
/// String representation of the Entity
pub word: String,
/// Confidence score
pub score: f64,
/// Entity label (e.g. ORG, LOC...)
pub label: String,
}
//type alias for some backward compatibility
type NERConfig = TokenClassificationConfig;
/// # NERModel to extract named entities
pub struct NERModel {
token_classification_model: TokenClassificationModel,
}
impl NERModel {
/// Build a new `NERModel`
///
/// # Arguments
///
/// * `ner_config` - `NERConfig` object containing the resource references (model, vocabulary, configuration) and device placement (CPU/GPU)
///
/// # Example
///
/// ```no_run
/// # fn main() -> failure::Fallible<()> {
/// use rust_bert::pipelines::ner::NERModel;
///
/// let ner_model = NERModel::new(Default::default())?;
/// # Ok(())
/// # }
/// ```
pub fn new(ner_config: NERConfig) -> failure::Fallible<NERModel> {
let model = TokenClassificationModel::new(ner_config)?;
Ok(NERModel {
token_classification_model: model,
})
}
/// Extract entities from a text
///
/// # Arguments
///
/// * `input` - `&[&str]` Array of texts to extract entities from.
///
/// # Returns
///
/// * `Vec<Entity>` containing extracted entities
///
/// # Example
///
/// ```no_run
/// # fn main() -> failure::Fallible<()> {
/// # use rust_bert::pipelines::ner::NERModel;
///
/// let ner_model = NERModel::new(Default::default())?;
/// let input = [
/// "My name is Amy. I live in Paris.",
/// "Paris is a city in France.",
/// ];
/// let output = ner_model.predict(&input);
/// # Ok(())
/// # }
/// ```
pub fn predict(&self, input: &[&str]) -> Vec<Entity> {
self.token_classification_model
.predict(input, true, false)
.into_iter()
.filter(|token| token.label != "O")
.map(|token| Entity {
word: token.text,
score: token.score,
label: token.label,
})
.collect()
}
}
| 32.340136 | 150 | 0.590029 |
ac6617247735a7a7b32f49e8613f07fb0fe21cf5 | 11,702 | // use std::println;
mod primitive_version_test {
use rvv_algo_demo::primitive_version::*;
fn test_n(n: u32) {
let mut mont = Mont::new(n);
mont.precompute();
let x: u32 = 10;
let x2 = mont.to_mont(x);
let x3 = mont.reduce(x2 as u64);
assert_eq!(x, x3);
let x: u32 = 10;
let y: u32 = 20;
// into montgomery form
let x2 = mont.to_mont(x);
let y2 = mont.to_mont(y);
// do multiplication operation
let xy2 = mont.multi(x2, y2);
// into normal form
let xy = mont.reduce(xy2 as u64);
// the result should be same
assert_eq!(xy, (x * y) % mont.n);
}
fn test_xy(x: u32, y: u32) {
let mut mont = Mont::new(1000001);
mont.precompute();
// into montgomery form
let x2 = mont.to_mont(x);
let y2 = mont.to_mont(y);
// do multiplication operation
let xy2 = mont.multi(x2, y2);
// into normal form
let xy = mont.reduce(xy2 as u64);
// the result should be same
assert_eq!(xy, (x * y) % mont.n);
}
pub fn test_xy_loops() {
for x in 10000..20000 {
test_xy(x, x + 20);
}
}
pub fn test_n_loops() {
for n in 19..10001 {
if n % 2 == 1 {
test_n(n);
}
}
}
pub fn test_multiple() {
let mut mont = Mont::new(17);
mont.precompute();
let x = 1;
let y = 2;
let z = 3;
let x2 = mont.to_mont(x);
let y2 = mont.to_mont(y);
let z2 = mont.to_mont(z);
let res = mont.multi(mont.multi(x2, y2), z2);
let res2 = mont.reduce(res as u64);
assert_eq!(x * y * z % mont.n, res2);
}
pub fn test_addsub() {
let mut mont = Mont::new(17);
mont.precompute();
let x = 15;
let y = 7;
let x2 = mont.to_mont(x);
let y2 = mont.to_mont(y);
let sum2 = x2 + y2;
let sum = mont.reduce(sum2 as u64);
assert_eq!(sum, (x + y) % mont.n);
let sub2 = x2 - y2;
let sub = mont.reduce(sub2 as u64);
assert_eq!(sub, (x - y) % mont.n);
}
pub fn test_pow() {
let mut mont = Mont::new(17);
mont.precompute();
for base in 2..5 {
for n in 5..10 {
let x = mont.to_mont(base);
let v = mont.pow(x, n);
let v = mont.reduce(v as u64);
let expected = base.pow(n) % mont.n;
assert_eq!(expected, v);
}
}
}
pub fn test_pow2() {
let mut mont = Mont::new(33);
mont.precompute();
let base: u32 = 2;
let x = mont.to_mont(base);
// println!("x = {}", x);
let v = mont.pow(x, 7);
let v = mont.reduce(v as u64);
assert_eq!(v, 29);
}
pub fn test_pow3() {
let mut mont = Mont::new(33);
mont.precompute();
let x: u32 = 2;
let y: u32 = 2;
let x2 = mont.to_mont(x);
let y2 = mont.to_mont(y);
let z2 = mont.multi(x2, y2);
let z = mont.reduce(z2 as u64);
assert_eq!(z, 4);
let p2 = mont.pow(x2, 2);
let p = mont.reduce(p2 as u64);
assert_eq!(p, 4);
}
}
mod rsa_test {
use rvv_algo_demo::rsa::*;
pub fn test_rsa() {
let rsa = Rsa::new();
let plain_text: u32 = 2;
let cipher_text = rsa.encrypt(plain_text);
// println!("cipher_text = {}", cipher_text);
let plain_text2 = rsa.decrypt(cipher_text);
assert_eq!(plain_text, plain_text2);
}
}
mod uint_version_test {
use rvv_algo_demo::uint_version::*;
use rvv_algo_demo::U;
pub fn test() {
let a = U512::from(100);
let b: U256 = a.into();
let b2: U512 = b.into();
assert_eq!(a, b2);
}
pub fn test_i512() {
let a = I512::from(2);
let b = I512::from(10);
let sum = a + b;
assert_eq!(sum, I512::from(12));
let sub = a - b;
assert_eq!(sub, I512::new(false, U512::from(8)));
let mul = a * b;
assert_eq!(mul, I512::from(20));
let div = b / a;
assert_eq!(div, I512::from(5));
let rem = b % a;
assert_eq!(rem, I512::from(0));
assert!(b > a);
assert!(a < b);
assert!(a != b);
let x = I512::new(false, 11.into());
let y = I512::from(7);
let rem = x % y;
assert_eq!(rem, I512::from(3));
}
pub fn test_egcd() {
let a = I512::from(11);
let b = I512::from(17);
let (gcd, x, y) = egcd(a, b);
assert_eq!(gcd, I512::from(1));
assert_eq!(a * x + b * y, I512::from(1));
}
fn test_n(n: U256) {
let mut mont = Mont::new(n);
mont.precompute();
let x = U!(10);
let x2 = mont.to_mont(x);
let x3 = mont.reduce(x2.into());
assert_eq!(x, x3);
let x = U!(10);
let y = U!(20);
// into montgomery form
let x2 = mont.to_mont(x);
let y2 = mont.to_mont(y);
// do multiplication operation
let xy2 = mont.multi(x2, y2);
// into normal form
let xy = mont.reduce(xy2.into());
// the result should be same
assert_eq!(xy, (x * y) % mont.n);
}
fn test_xy(x: U256, y: U256) {
let mut mont = Mont::new(U!(1000001));
mont.precompute();
// into montgomery form
let x2 = mont.to_mont(x);
let y2 = mont.to_mont(y);
// do multiplication operation
let xy2 = mont.multi(x2, y2);
// into normal form
let xy = mont.reduce(xy2.into());
// the result should be same
assert_eq!(xy, (x * y) % mont.n);
}
pub fn test_n_loops() {
for n in 19..10001 {
if n % 2 == 1 {
test_n(U!(n));
}
}
}
pub fn test_xy_loops() {
for x in 10000..20000 {
test_xy(U!(x), U!(x + 20));
}
}
pub fn test_multiple() {
let mut mont = Mont::new(U!(17));
mont.precompute();
let x = U!(1);
let y = U!(2);
let z = U!(3);
let x2 = mont.to_mont(x);
let y2 = mont.to_mont(y);
let z2 = mont.to_mont(z);
let res = mont.multi(mont.multi(x2, y2), z2);
let res2 = mont.reduce(res.into());
assert_eq!(x * y * z % mont.n, res2);
}
pub fn test_pow() {
let mut mont = Mont::new(U!(17));
mont.precompute();
for base in 2..5 {
for n in 5..10 {
let base = U!(base);
let n = U!(n);
let x = mont.to_mont(base);
let v = mont.pow(x, n);
let v = mont.reduce(v.into());
let expected = base.pow(n) % mont.n;
assert_eq!(expected, v);
}
}
}
pub fn test_pow2() {
let mut mont = Mont::new(U!(33));
mont.precompute();
let base = U!(2);
let x = mont.to_mont(base);
let v = mont.pow(x, U!(7));
let v = mont.reduce(v.into());
assert_eq!(v, U!(29));
}
pub fn test_pow3() {
let mut mont = Mont::new(U!(33));
mont.precompute();
let x = U!(2);
let y = U!(2);
let x2 = mont.to_mont(x);
let y2 = mont.to_mont(y);
let z2 = mont.multi(x2, y2);
let z = mont.reduce(z2.into());
assert_eq!(z, U!(4));
let p2 = mont.pow(x2, U!(2));
let p = mont.reduce(p2.into());
assert_eq!(p, U!(4));
}
pub fn test_ops() {
let mut mont = Mont::new(U!(33));
mont.precompute();
let x = &MontForm::from_u256(U!(2), mont);
let y = &x.derive_from_u256(U!(3));
let sum = x + y;
let res: U256 = sum.into();
assert_eq!(U!(5), res);
let sub = y - x;
assert_eq!(U!(1), sub.into());
let sub2 = x - y;
assert_eq!(U!(32), sub2.into());
let mul = x * y;
assert_eq!(U!(6), mul.into());
let pow = x.pow(U!(3));
assert_eq!(U!(8), pow.into());
}
/*
macro_rules! field_impl {
($name:ident, $modulus:expr, $rsquared:expr, $rcubed:expr, $one:expr, $inv:expr) => {
field_impl!(
Fr,
[
0x2833e84879b9709143e1f593f0000001,
0x30644e72e131a029b85045b68181585d
],
[
0x53fe3ab1e35c59e31bb8e645ae216da7,
0x0216d0b17f4e44a58c49833d53bb8085
],
[
0x2a489cbe1cfbb6b85e94d8e1b4bf0040,
0x0cf8594b7fcc657c893cc664a19fcfed
],
[
0x36fc76959f60cd29ac96341c4ffffffb,
0x0e0a77c19a07df2f666ea36f7879462e
],
0x6586864b4c6911b3c2e1f593efffffff
);
*/
fn from_u128pair(n: &[u128; 2]) -> U256 {
let mut buf = [0u8; 32];
buf[0..16].copy_from_slice(&n[0].to_le_bytes());
buf[16..32].copy_from_slice(&n[1].to_le_bytes());
U256::from_little_endian(&buf)
}
#[test]
pub fn test_number() {
let n = from_u128pair(&[
0x2833e84879b9709143e1f593f0000001u128,
0x30644e72e131a029b85045b68181585du128,
]);
let mut mont = Mont::new(n);
mont.precompute();
// println!("np1 = 0x{:x}", mont.np1);
let np1 = 0x6586864b4c6911b3c2e1f593efffffffu128;
assert_eq!(np1, mont.np1.low_u128());
let r: U512 = mont.r.into();
let r_square = (r % mont.n) * (r % mont.n);
let r_square2 = r_square % mont.n;
// println!("r_square = 0x{:x}", r_square2);
let original_r_square = from_u128pair(&[
0x53fe3ab1e35c59e31bb8e645ae216da7,
0x0216d0b17f4e44a58c49833d53bb8085,
]);
assert_eq!(original_r_square, r_square2.into());
let r_cubed = r_square2 * (r % mont.n) % mont.n;
let original_r_cubed = from_u128pair(&[
0x2a489cbe1cfbb6b85e94d8e1b4bf0040,
0x0cf8594b7fcc657c893cc664a19fcfed,
]);
assert_eq!(original_r_cubed, r_cubed.into());
}
#[test]
pub fn test_number2() {
// inv = 0x9ede7d651eca6ac987d20782e4866389
// modulo = 0x97816a916871ca8d3c208c16d87cfd47, 0x30644e72e131a029b85045b68181585d
let n = from_u128pair(&[
0x97816a916871ca8d3c208c16d87cfd47u128, 0x30644e72e131a029b85045b68181585du128
]);
let mut mont = Mont::new(n);
mont.precompute();
// println!("np1 = 0x{:x}", mont.np1);
let np1 = 0x9ede7d651eca6ac987d20782e4866389;
assert_eq!(np1, mont.np1.low_u128());
println!("mont.np1 = 0x{:x},0x{:x}", mont.np1.low_u128(), (mont.np1 >> 128).low_u128());
}
}
#[test]
pub fn test() {
main()
}
pub fn main() {
// #[test] is not supported in ckb-std
primitive_version_test::test_multiple();
primitive_version_test::test_addsub();
primitive_version_test::test_pow();
primitive_version_test::test_pow2();
primitive_version_test::test_pow3();
primitive_version_test::test_n_loops();
primitive_version_test::test_xy_loops();
rsa_test::test_rsa();
uint_version_test::test();
uint_version_test::test_i512();
uint_version_test::test_egcd();
uint_version_test::test_n_loops();
uint_version_test::test_xy_loops();
uint_version_test::test_multiple();
uint_version_test::test_pow();
uint_version_test::test_pow2();
uint_version_test::test_pow3();
uint_version_test::test_ops();
}
| 27.213953 | 96 | 0.507349 |
ed8a9f5f22c91d3b6274706cdd945f28a3cba50d | 9,931 | //! RustCrypto: `signature` crate.
//!
//! Traits which provide generic, object-safe APIs for generating and verifying
//! digital signatures, i.e. message authentication using public-key cryptography.
//!
//! ## Minimum Supported Rust Version
//!
//! Rust **1.41** or higher.
//!
//! Minimum supported Rust version may be changed in the future, but such
//! changes will be accompanied with a minor version bump.
//!
//! ## SemVer policy
//!
//! - MSRV is considered exempt from SemVer as noted above
//! - All on-by-default features of this library are covered by SemVer
//! - Off-by-default features ending in `*-preview` (e.g. `derive-preview`,
//! `digest-preview`) are unstable "preview" features which are also
//! considered exempt from SemVer (typically because they rely on pre-1.0
//! crates as dependencies). However, breaking changes to these features
//! will, like MSRV, also be accompanied by a minor version bump.
//!
//! # Design
//!
//! This crate provides a common set of traits for signing and verifying
//! digital signatures intended to be implemented by libraries which produce
//! or contain implementations of digital signature algorithms, and used by
//! libraries which want to produce or verify digital signatures while
//! generically supporting any compatible backend.
//!
//! ## Goals
//!
//! The traits provided by this crate were designed with the following goals
//! in mind:
//!
//! - Provide an easy-to-use, misuse resistant API optimized for consumers
//! (as opposed to implementers) of its traits.
//! - Support common type-safe wrappers around "bag-of-bytes" representations
//! which can be directly parsed from or written to the "wire".
//! - Expose a trait/object-safe API where signers/verifiers spanning multiple
//! homogeneous provider implementations can be seamlessly leveraged together
//! in the same logical "keyring" so long as they operate on the same
//! underlying signature type.
//! - Allow one provider type to potentially implement support (including
//! being generic over) several signature types.
//! - Keep signature algorithm customizations / "knobs" out-of-band from the
//! signing/verification APIs, ideally pushing such concerns into the type
//! system so that algorithm mismatches are caught as type errors.
//! - Opaque error type which minimizes information leaked from cryptographic
//! failures, as "rich" error types in these scenarios are often a source
//! of sidechannel information for attackers (e.g. [BB'06])
//!
//! [BB'06]: https://en.wikipedia.org/wiki/Daniel_Bleichenbacher
//!
//! ## Implementation
//!
//! To accomplish the above goals, the [`Signer`] and [`Verifier`] traits
//! provided by this are generic over a [`Signature`] return value, and use
//! generic parameters rather than associated types. Notably, they use such
//! a parameter for the return value, allowing it to be inferred by the type
//! checker based on the desired signature type.
//!
//! The [`Signature`] trait is bounded on `AsRef<[u8]>`, enforcing that
//! signature types are thin wrappers around a "bag-of-bytes"
//! serialization. Inspiration for this approach comes from the Ed25519
//! signature system, which was based on the observation that past
//! systems were not prescriptive about how signatures should be represented
//! on-the-wire, and that lead to a proliferation of different wire formats
//! and confusion about which ones should be used. This crate aims to provide
//! similar simplicity by minimizing the number of steps involved to obtain
//! a serializable signature.
//!
//! ## Alternatives considered
//!
//! This crate is based on over two years of exploration of how to encapsulate
//! digital signature systems in the most flexible, developer-friendly way.
//! During that time many design alternatives were explored, tradeoffs
//! compared, and ultimately the provided API was selected.
//!
//! The tradeoffs made in this API have all been to improve simplicity,
//! ergonomics, type safety, and flexibility for *consumers* of the traits.
//! At times, this has come at a cost to implementers. Below are some concerns
//! we are cognizant of which were considered in the design of the API:
//!
//! - "Bag-of-bytes" serialization precludes signature providers from using
//! their own internal representation of a signature, which can be helpful
//! for many reasons (e.g. advanced signature system features like batch
//! verification). Alternatively each provider could define its own signature
//! type, using a marker trait to identify the particular signature algorithm,
//! have `From` impls for converting to/from `[u8; N]`, and a marker trait
//! for identifying a specific signature algorithm.
//! - Associated types, rather than generic parameters of traits, could allow
//! more customization of the types used by a particular signature system,
//! e.g. using custom error types.
//!
//! It may still make sense to continue to explore the above tradeoffs, but
//! with a *new* set of traits which are intended to be implementor-friendly,
//! rather than consumer friendly. The existing [`Signer`] and [`Verifier`]
//! traits could have blanket impls for the "provider-friendly" traits.
//! However, as noted above this is a design space easily explored after
//! stabilizing the consumer-oriented traits, and thus we consider these
//! more important.
//!
//! That said, below are some caveats of trying to design such traits, and
//! why we haven't actively pursued them:
//!
//! - Generics in the return position are already used to select which trait
//! impl to use, i.e. for a particular signature algorithm/system. Avoiding
//! a unified, concrete signature type adds another dimension to complexity
//! and compiler errors, and in our experience makes them unsuitable for this
//! sort of API. We believe such an API is the natural one for signature
//! systems, reflecting the natural way they are written absent a trait.
//! - Associated types preclude multiple (or generic) implementations of the
//! same trait. These parameters are common in signature systems, notably
//! ones which support different digest algorithms.
//! - Digital signatures are almost always larger than the present 32-entry
//! trait impl limitation on array types, which complicates trait signatures
//! for these types (particularly things like `From` or `Borrow` bounds).
//! This may be more interesting to explore after const generics.
//!
//! ## Unstable features
//!
//! Despite being post-1.0, this crate includes a number of off-by-default
//! unstable features named `*-preview`, each of which depends on a pre-1.0
//! crate.
//!
//! These features are considered exempt from SemVer. See the
//! [SemVer policy](#semver-policy) above for more information.
//!
//! The following unstable features are presently supported:
//!
//! - `derive-preview`: for implementers of signature systems using
//! [`DigestSigner`] and [`DigestVerifier`], the `derive-preview` feature
//! can be used to derive [`Signer`] and [`Verifier`] traits which prehash
//! the input message using the [`PrehashSignature::Digest`] algorithm for
//! a given [`Signature`] type. When the `derive-preview` feature is enabled
//! import the proc macros with `use signature::{Signer, Verifier}` and then
//! add a `derive(Signer)` or `derive(Verifier)` attribute to the given
//! digest signer/verifier type. Enabling this feature also enables `digest`
//! support (see immediately below).
//! - `digest-preview`: enables the [`DigestSigner`] and [`DigestVerifier`]
//! traits which are based on the [`Digest`] trait from the [`digest`] crate.
//! These traits are used for representing signature systems based on the
//! [Fiat-Shamir heuristic] which compute a random challenge value to sign
//! by computing a cryptographically secure digest of the input message.
//! - `rand-preview`: enables the [`RandomizedSigner`] trait for signature
//! systems which rely on a cryptographically secure random number generator
//! for security.
//!
//! NOTE: the [`async-signature`] crate contains experimental `async` support
//! for [`Signer`] and [`DigestSigner`].
//!
//! [`async-signature`]: https://docs.rs/async-signature
//! [`digest`]: https://docs.rs/digest/
//! [`Digest`]: https://docs.rs/digest/latest/digest/trait.Digest.html
//! [Fiat-Shamir heuristic]: https://en.wikipedia.org/wiki/Fiat%E2%80%93Shamir_heuristic
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
html_root_url = "https://docs.rs/signature/1.4.0"
)]
#![forbid(unsafe_code)]
#![warn(missing_docs, rust_2018_idioms, unused_qualifications)]
#[cfg(feature = "std")]
extern crate std;
#[cfg(all(feature = "signature_derive", not(feature = "derive-preview")))]
compile_error!(
"The `signature_derive` feature should not be enabled directly. \
Use the `derive-preview` feature instead."
);
#[cfg(all(feature = "digest", not(feature = "digest-preview")))]
compile_error!(
"The `digest` feature should not be enabled directly. \
Use the `digest-preview` feature instead."
);
#[cfg(all(feature = "rand_core", not(feature = "rand-preview")))]
compile_error!(
"The `rand_core` feature should not be enabled directly. \
Use the `rand-preview` feature instead."
);
#[cfg(feature = "derive-preview")]
#[cfg_attr(docsrs, doc(cfg(feature = "derive-preview")))]
pub use signature_derive::{Signer, Verifier};
#[cfg(feature = "digest-preview")]
pub use digest;
#[cfg(feature = "rand-preview")]
#[cfg_attr(docsrs, doc(cfg(feature = "rand-preview")))]
pub use rand_core;
mod error;
mod signature;
mod signer;
mod verifier;
pub use crate::{error::*, signature::*, signer::*, verifier::*};
| 48.208738 | 94 | 0.728325 |
d5d328cabb06db7776ee4b32694800abb31d5521 | 766 | use crate::prelude::*;
#[system]
#[read_component(WantsToAttack)]
#[write_component(Health)]
pub fn combat(ecs: &mut SubWorld, commands: &mut CommandBuffer) {
let victims: Vec<(Entity, Entity)> = <(Entity, &WantsToAttack)>::query()
.iter(ecs)
.map(|(entity, attack)| (*entity, attack.victim))
.collect();
victims
.iter()
.for_each(|(msg, victim)| {
if let Ok(mut health) = ecs
.entry_mut(*victim)
.unwrap()
.get_component_mut::<Health>()
{
health.current -= 1;
if health.current < 1 {
commands.remove(*victim);
}
}
commands.remove(*msg);
});
}
| 27.357143 | 76 | 0.48564 |
ccb48cb8a760a307bc1c905bebb1e8381c9ee6c9 | 4,130 | //! API error and common error
use reqwest::{Error as ReqwestError, Response};
use std::error::Error as StdError;
use std::fmt;
use std::result::Result as StdResult;
use url::ParseError;
use crate::types::ErrorMessage;
pub type Result<T> = StdResult<T, Error>;
/// Error from Mojang API
///
/// The name of the enum means `error` from the message,
/// it's the short description of the error.
///
/// The `String` contained in the enum means `errorMessage` from the message,
/// it's the longer description which can be shown to the user.
#[derive(Debug)]
pub enum ApiError {
MethodNotAllowed(String),
NotFound(String),
ForbiddenOperationException(String),
IllegalArgumentException(String),
UnsupportedMediaType(String),
/// Unknown error
Unknown {
error: String,
message: String,
},
}
/// Common errors
#[derive(Debug)]
pub enum Error {
/// An error occurred from reqwest
Reqwest(ReqwestError),
/// Url parse error.
UrlParseError(ParseError),
/// Missing required fields to generate a request.
MissingField(&'static str),
/// API error, from Mojang server
API(ApiError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Reqwest(reqwest_error) => write!(f, "Reqwest error: {}", reqwest_error),
Error::UrlParseError(url_parse_error) => {
write!(f, "URL parse error: {}", url_parse_error)
}
Error::MissingField(field) => write!(f, "Missing field: {}", field),
Error::API(api_error) => match api_error {
ApiError::MethodNotAllowed(message) => {
write!(f, "API error: MethodNotAllowed ({})", message)
}
ApiError::NotFound(message) => write!(f, "API error: NotFound ({})", message),
ApiError::ForbiddenOperationException(message) => {
write!(f, "API error: ForbiddenOperationException ({})", message)
}
ApiError::IllegalArgumentException(message) => {
write!(f, "API error: IllegalArgumentException ({})", message)
}
ApiError::UnsupportedMediaType(message) => {
write!(f, "API error: UnsupportedMediaType ({})", message)
}
ApiError::Unknown { error, message } => {
write!(f, "API error: {} ({})", error, message)
}
},
}
}
}
impl StdError for Error {
fn cause(&self) -> Option<&dyn StdError> {
match self {
Error::Reqwest(reqwest_error) => Some(reqwest_error),
Error::UrlParseError(url_parse_error) => Some(url_parse_error),
_ => None,
}
}
}
impl From<ReqwestError> for Error {
fn from(error: ReqwestError) -> Self {
Error::Reqwest(error)
}
}
impl From<ParseError> for Error {
fn from(error: ParseError) -> Self {
Error::UrlParseError(error)
}
}
impl Error {
pub(crate) async fn from_response(error: Response) -> Self {
let msg = error.json::<ErrorMessage>().await;
if msg.is_err() {
return msg.unwrap_err().into();
}
let msg = msg.unwrap();
if msg.error == "ForbiddenOperationException" {
Error::API(ApiError::ForbiddenOperationException(msg.error_message))
} else if msg.error == "IllegalArgumentException" {
Error::API(ApiError::IllegalArgumentException(msg.error_message))
} else if msg.error == "Method Not Allowed" {
Error::API(ApiError::MethodNotAllowed(msg.error_message))
} else if msg.error == "Not Found" {
Error::API(ApiError::NotFound(msg.error_message))
} else if msg.error == "Unsupported Media Type" {
Error::API(ApiError::UnsupportedMediaType(msg.error_message))
} else {
Error::API(ApiError::Unknown {
error: msg.error,
message: msg.error_message,
})
}
}
}
| 32.015504 | 94 | 0.580387 |
5d1bb79586da7eb83b03d47ab6bc985a8994d0b2 | 1,838 | use bitcoin::blockdata::script::{Instruction::PushBytes, Script};
#[cfg(feature = "liquid")]
use elements::address as elements_address;
use crate::chain::Network;
use crate::chain::{TxIn, TxOut};
pub struct InnerScripts {
pub redeem_script: Option<Script>,
pub witness_script: Option<Script>,
}
pub fn script_to_address(script: &Script, network: Network) -> Option<String> {
match network {
#[cfg(feature = "liquid")]
Network::Liquid | Network::LiquidRegtest => {
elements_address::Address::from_script(script, None, network.address_params())
.map(|a| a.to_string())
}
_ => bitcoin::Address::from_script(script, network.into()).map(|s| s.to_string()),
}
}
pub fn get_script_asm(script: &Script) -> String {
let asm = format!("{:?}", script);
(&asm[7..asm.len() - 1]).to_string()
}
// Returns the witnessScript in the case of p2wsh, or the redeemScript in the case of p2sh.
pub fn get_innerscripts(txin: &TxIn, prevout: &TxOut) -> InnerScripts {
// Wrapped redeemScript for P2SH spends
let redeem_script = if prevout.script_pubkey.is_p2sh() {
if let Some(PushBytes(redeemscript)) = txin.script_sig.iter(true).last() {
Some(Script::from(redeemscript.to_vec()))
} else {
None
}
} else {
None
};
// Wrapped witnessScript for P2WSH or P2SH-P2WSH spends
let witness_script = if prevout.script_pubkey.is_v0_p2wsh()
|| redeem_script.as_ref().map_or(false, |s| s.is_v0_p2wsh())
{
let witness = &txin.witness;
#[cfg(feature = "liquid")]
let witness = &witness.script_witness;
witness.iter().last().cloned().map(Script::from)
} else {
None
};
InnerScripts {
redeem_script,
witness_script,
}
}
| 30.633333 | 91 | 0.624048 |
de3b237b7d9e7d706dfa5c9b7bed9c25eb64a67d | 10,568 | use crate::{err::Error, SafeHandle};
use winapi::{
ctypes::c_void,
shared::{minwindef::DWORD, winerror},
um::{
errhandlingapi as ehapi,
fileapi::ReadFile,
ioapiset::DeviceIoControl,
minwinbase::OVERLAPPED,
winioctl::{FSCTL_GET_RETRIEVAL_POINTERS, NTFS_VOLUME_DATA_BUFFER},
winnt::LONGLONG,
},
};
use std::{convert::TryInto as _, mem, ptr};
// Represents a continuous list of logical clusters in one file.
#[derive(Debug, Clone, Copy)]
struct Extent {
min_vcn: i64,
min_lcn: i64,
cluster_count: i64,
}
// Reads a file using a volume handle instead of a readable file handle.
// Although a file handle is needed to initialize this object, it's not
// persisted and does not need to be readable.
pub struct MftStream {
volume_handle: SafeHandle,
bytes_per_cluster: u64,
bytes_per_file_record_segment: u64,
len: u64,
extents: Vec<Extent>,
buffer: Vec<u8>,
buffer_offset: u64, // into the volume, in bytes
}
impl MftStream {
pub fn new(
volume_handle: SafeHandle,
volume_info: NTFS_VOLUME_DATA_BUFFER,
file_handle: &SafeHandle,
) -> Result<Self, Error> {
let extents = load_file_extents(&file_handle)?;
if extents.first().ok_or(Error::MftHasNoExtents)?.min_lcn
!= *unsafe { volume_info.MftStartLcn.QuadPart() }
{
return Err(Error::MftStartLcnNotFirstExtent);
}
let bytes_per_cluster = volume_info.BytesPerCluster.try_into().unwrap();
Ok(MftStream {
volume_handle,
bytes_per_cluster,
bytes_per_file_record_segment: volume_info
.BytesPerFileRecordSegment
.try_into()
.unwrap(),
len: unsafe { *volume_info.MftValidDataLength.QuadPart() }
.try_into()
.unwrap(),
extents,
// 16 MB is a reasonable tradeoff between perf and memory usage
buffer: vec![0; 16 * 1024 * 1024],
buffer_offset: 0,
})
}
pub fn get_file_record_segment_count(&self) -> u64 {
self.len / self.bytes_per_file_record_segment
}
pub fn read_clusters(
&mut self,
lcn: u64,
count: u64,
buf: &mut [u8],
use_cache: bool,
) -> Result<(), Error> {
debug_assert_eq!(buf.len() as u64, count * self.bytes_per_cluster);
self.read_volume(lcn * self.bytes_per_cluster, buf, use_cache)
}
pub fn read_file_record_segment(
&mut self,
segment: u64,
buf: &mut [u8],
use_cache: bool,
) -> Result<(), Error> {
debug_assert_eq!(0, self.len % self.bytes_per_file_record_segment);
debug_assert_eq!(buf.len() as u64, self.bytes_per_file_record_segment);
// Convert the segment to an LCN and offset. A file record segment can't be split
// across multiple extents (I think/hope).
let volume_offset: u64 = {
// Convert the segment number to a offset in the file.
let mut target_offset = segment * self.bytes_per_file_record_segment;
let mut extent_idx = 0;
loop {
let extent = &self.extents[extent_idx];
let extent_len = extent.cluster_count as u64 * self.bytes_per_cluster;
if target_offset < extent_len {
// We found the correct extent!
let extent_start_lcn = extent.min_lcn as u64;
break Some((extent_start_lcn * self.bytes_per_cluster) + target_offset);
} else {
extent_idx += 1;
target_offset -= extent_len;
}
if extent_idx >= self.extents.len() {
println!(
"WHOOPS: {:#?} {} {}",
self.extents, self.bytes_per_file_record_segment, segment,
);
break None;
}
}
}
.unwrap(); // TODO: proper error handling here
self.read_volume(volume_offset, buf, use_cache)
}
fn read_volume(&mut self, offset: u64, buf: &mut [u8], use_cache: bool) -> Result<(), Error> {
#[cfg(debug_assertions)]
{
println!("read_volume: {:X}", offset);
}
if use_cache {
let cur_buffer_end = self.buffer_offset + (self.buffer.len() as u64);
let request_end = offset + (buf.len() as u64);
if cur_buffer_end < request_end || offset < self.buffer_offset {
// The read will go out of the buffer, so read a new one.
#[cfg(debug_assertions)]
{
println!("reading new buffer");
}
self.buffer_offset = offset;
let mut overlapped = {
let offset: u64 = offset.try_into().unwrap();
let mut ov = OVERLAPPED::default();
unsafe { ov.u.s_mut() }.Offset =
(offset & 0x0000_0000_FFFF_FFFFu64).try_into().unwrap();
unsafe { ov.u.s_mut() }.OffsetHigh = ((offset & 0xFFFF_FFFF_0000_0000u64)
>> 32)
.try_into()
.unwrap();
ov
};
let mut num_bytes_read = 0;
let success = unsafe {
ReadFile(
*self.volume_handle,
self.buffer.as_mut_ptr() as *mut c_void,
self.buffer.len().try_into().unwrap(),
&mut num_bytes_read,
&mut overlapped,
)
};
if success == 0 {
let err = unsafe { ehapi::GetLastError() };
return Err(Error::ReadVolumeFailed(err));
}
let num_bytes_read: usize = num_bytes_read.try_into().unwrap();
if num_bytes_read != self.buffer.len() {
return Err(Error::ReadVolumeTooShort);
}
}
let buffer_start: usize = (offset - self.buffer_offset).try_into().unwrap();
let buffer_end = buffer_start + buf.len();
buf.copy_from_slice(&self.buffer[buffer_start..buffer_end]);
} else {
let mut overlapped = {
let offset: u64 = offset.try_into().unwrap();
let mut ov = OVERLAPPED::default();
unsafe { ov.u.s_mut() }.Offset =
(offset & 0x0000_0000_FFFF_FFFFu64).try_into().unwrap();
unsafe { ov.u.s_mut() }.OffsetHigh = ((offset & 0xFFFF_FFFF_0000_0000u64) >> 32)
.try_into()
.unwrap();
ov
};
let mut num_bytes_read = 0;
let success = unsafe {
ReadFile(
*self.volume_handle,
buf.as_mut_ptr() as *mut c_void,
buf.len().try_into().unwrap(),
&mut num_bytes_read,
&mut overlapped,
)
};
if success == 0 {
let err = unsafe { ehapi::GetLastError() };
return Err(Error::ReadVolumeFailed(err));
}
let num_bytes_read: usize = num_bytes_read.try_into().unwrap();
if num_bytes_read != buf.len() {
return Err(Error::ReadVolumeTooShort);
}
}
Ok(())
}
}
fn load_file_extents(handle: &SafeHandle) -> Result<Vec<Extent>, Error> {
let mut result = Vec::new();
let mut current_starting_vcn = 0;
// This should be big enough for all but the most fragmented files.
let mut retrieval_buffer = vec![0u8; 64 * 1024];
loop {
let mut result_size = 0;
let success = unsafe {
DeviceIoControl(
**handle,
FSCTL_GET_RETRIEVAL_POINTERS,
&mut current_starting_vcn as *mut LONGLONG as *mut c_void,
mem::size_of::<LONGLONG>().try_into().unwrap(),
retrieval_buffer.as_mut_ptr() as *mut c_void,
retrieval_buffer.len().try_into().unwrap(),
&mut result_size,
ptr::null_mut(),
)
};
let err = unsafe { ehapi::GetLastError() };
if success == 0 {
return Err(Error::GetRetrievalPointersFailed(err));
}
let mut returned_buffer = &retrieval_buffer[..result_size as usize];
// The first DWORD in the buffer is the number of Extents returned.
let extent_count = DWORD::from_le_bytes(
returned_buffer[0..mem::size_of::<DWORD>()]
.try_into()
.unwrap(),
);
// Note that we have now consumed sizeof(LONGLONG) bytes due to struct padding.
returned_buffer = &returned_buffer[mem::size_of::<LONGLONG>()..];
// That's followed by a LARGE_INTEGER representing the first VCN mapping returned.
let mut min_vcn = LONGLONG::from_le_bytes(
returned_buffer[..mem::size_of::<LONGLONG>()]
.try_into()
.unwrap(),
);
returned_buffer = &returned_buffer[mem::size_of::<LONGLONG>()..];
// Then, there's a list of tuples, each giving the starting LCN for the current
// extent and the VCN that starts the next extent.
let mut next_min_vcn = min_vcn;
for _ in 0..extent_count {
next_min_vcn = LONGLONG::from_le_bytes(
returned_buffer[..mem::size_of::<LONGLONG>()]
.try_into()
.unwrap(),
);
returned_buffer = &returned_buffer[mem::size_of::<LONGLONG>()..];
let min_lcn = LONGLONG::from_le_bytes(
returned_buffer[..mem::size_of::<LONGLONG>()]
.try_into()
.unwrap(),
);
returned_buffer = &returned_buffer[mem::size_of::<LONGLONG>()..];
result.push(Extent {
min_lcn,
min_vcn,
cluster_count: next_min_vcn - min_vcn,
});
min_vcn = next_min_vcn;
}
current_starting_vcn = next_min_vcn;
if err != winerror::ERROR_MORE_DATA {
break;
}
}
Ok(result)
}
| 35.344482 | 98 | 0.524413 |
381c752558d76f1203f57fc5d317e880d04fd0d6 | 242 | // variables2.rs
// Make me compile! Execute the command `rustlings hint variables2` if you want a hint :)
fn main() {
let x: u8;
x = 10;
if x == 10 {
println!("Ten!");
} else {
println!("Not ten!");
}
}
| 17.285714 | 89 | 0.520661 |
d7bc97d413e840ec5578fdc68cc68c233ad467e7 | 4,818 | // c:doughnutChart
use super::VaryColors;
use super::AreaChartSeries;
use super::DataLabels;
use super::FirstSliceAngle;
use super::HoleSize;
use writer::driver::*;
use quick_xml::Reader;
use quick_xml::events::{Event, BytesStart};
use quick_xml::Writer;
use std::io::Cursor;
#[derive(Default, Debug)]
pub struct DoughnutChart {
vary_colors: VaryColors,
area_chart_series: Vec<AreaChartSeries>,
data_labels: DataLabels,
first_slice_angle: FirstSliceAngle,
hole_size: HoleSize,
}
impl DoughnutChart {
pub fn get_vary_colors(&self)-> &VaryColors {
&self.vary_colors
}
pub fn get_vary_colors_mut(&mut self)-> &mut VaryColors {
&mut self.vary_colors
}
pub fn set_vary_colors(&mut self, value:VaryColors)-> &mut DoughnutChart {
self.vary_colors = value;
self
}
pub fn get_area_chart_series(&self)-> &Vec<AreaChartSeries> {
&self.area_chart_series
}
pub fn get_area_chart_series_mut(&mut self)-> &mut Vec<AreaChartSeries> {
&mut self.area_chart_series
}
pub fn set_area_chart_series(&mut self, value:Vec<AreaChartSeries>)-> &mut DoughnutChart {
self.area_chart_series = value;
self
}
pub fn add_area_chart_series(&mut self, value:AreaChartSeries)-> &mut DoughnutChart {
self.area_chart_series.push(value);
self
}
pub fn get_data_labels(&self)-> &DataLabels {
&self.data_labels
}
pub fn get_data_labels_mut(&mut self)-> &mut DataLabels {
&mut self.data_labels
}
pub fn set_data_labels(&mut self, value:DataLabels)-> &mut DoughnutChart {
self.data_labels = value;
self
}
pub fn get_first_slice_angle(&self)-> &FirstSliceAngle {
&self.first_slice_angle
}
pub fn get_first_slice_angle_mut(&mut self)-> &mut FirstSliceAngle {
&mut self.first_slice_angle
}
pub fn set_first_slice_angle(&mut self, value:FirstSliceAngle)-> &mut DoughnutChart {
self.first_slice_angle = value;
self
}
pub fn get_hole_size(&self)-> &HoleSize {
&self.hole_size
}
pub fn get_hole_size_mut(&mut self)-> &mut HoleSize {
&mut self.hole_size
}
pub fn set_hole_size(&mut self, value:HoleSize)-> &mut DoughnutChart {
self.hole_size = value;
self
}
pub(crate) fn set_attributes(
&mut self,
reader:&mut Reader<std::io::BufReader<std::fs::File>>,
_e:&BytesStart
) {
let mut buf = Vec::new();
loop {
match reader.read_event(&mut buf) {
Ok(Event::Start(ref e)) => {
match e.name() {
b"c:ser" => {
let mut obj = AreaChartSeries::default();
obj.set_attributes(reader, e);
self.add_area_chart_series(obj);
},
b"c:dLbls" => {
self.data_labels.set_attributes(reader, e);
},
_ => (),
}
},
Ok(Event::Empty(ref e)) => {
match e.name() {
b"c:varyColors" => {
self.vary_colors.set_attributes(reader, e);
},
b"c:firstSliceAng" => {
self.first_slice_angle.set_attributes(reader, e);
},
b"c:holeSize" => {
self.hole_size.set_attributes(reader, e);
},
_ => (),
}
},
Ok(Event::End(ref e)) => {
match e.name() {
b"c:doughnutChart" => return,
_ => (),
}
},
Ok(Event::Eof) => panic!("Error not find {} end element", "c:doughnutChart"),
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (),
}
buf.clear();
}
}
pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>) {
// c:doughnutChart
write_start_tag(writer, "c:doughnutChart", vec![], false);
// c:varyColors
&self.vary_colors.write_to(writer);
// c:ser
for v in &self.area_chart_series {
v.write_to(writer);
}
// c:dLbls
&self.data_labels.write_to(writer);
// c:firstSliceAng
&self.first_slice_angle.write_to(writer);
// c:holeSize
&self.hole_size.write_to(writer);
write_end_tag(writer, "c:doughnutChart");
}
}
| 29.2 | 94 | 0.521171 |
ff6df93366838f9faf558373b2113198f17909a1 | 5,730 | // Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::ErrorKind;
use std::io::Result;
use super::BufferRead;
pub trait BufferReadExt: BufferRead {
fn ignores(&mut self, f: impl Fn(u8) -> bool) -> Result<usize>;
fn ignore(&mut self, f: impl Fn(u8) -> bool) -> Result<bool>;
fn ignore_byte(&mut self, b: u8) -> Result<bool>;
fn ignore_bytes(&mut self, bs: &[u8]) -> Result<bool>;
fn ignore_insensitive_bytes(&mut self, bs: &[u8]) -> Result<bool>;
fn ignore_white_spaces(&mut self) -> Result<bool>;
fn until(&mut self, delim: u8, buf: &mut Vec<u8>) -> Result<usize>;
fn keep_read(&mut self, buf: &mut Vec<u8>, f: impl Fn(u8) -> bool) -> Result<usize>;
fn drain(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
let mut bytes = 0;
loop {
let available = self.fill_buf()?;
if available.is_empty() {
break;
}
let size = available.len();
buf.extend_from_slice(available);
bytes += size;
self.consume(size);
}
Ok(bytes)
}
fn read_quoted_text(&mut self, buf: &mut Vec<u8>, quota: u8) -> Result<()> {
self.must_ignore_byte(quota)?;
self.keep_read(buf, |b| b != quota)?;
self.must_ignore_byte(quota)
}
fn read_escaped_string_text(&mut self, buf: &mut Vec<u8>) -> Result<()> {
self.keep_read(buf, |f| f != b'\t' && f != b'\n' && f != b'\\')?;
// TODO judge escaped '\\'
Ok(())
}
fn must_eof(&mut self) -> Result<()> {
let buffer = self.fill_buf()?;
if !buffer.is_empty() {
return Err(std::io::Error::new(
ErrorKind::InvalidData,
"Must reach the buffer end",
));
}
Ok(())
}
fn must_ignore(&mut self, f: impl Fn(u8) -> bool) -> Result<()> {
if !self.ignore(f)? {
return Err(std::io::Error::new(
ErrorKind::InvalidData,
"Expected to ignore a byte",
));
}
Ok(())
}
fn must_ignore_byte(&mut self, b: u8) -> Result<()> {
if !self.ignore_byte(b)? {
return Err(std::io::Error::new(
ErrorKind::InvalidData,
format!("Expected to have char {}", b as char),
));
}
Ok(())
}
fn must_ignore_bytes(&mut self, bs: &[u8]) -> Result<()> {
if !self.ignore_bytes(bs)? {
return Err(std::io::Error::new(
ErrorKind::InvalidData,
format!("Expected to have bytes {:?}", bs),
));
}
Ok(())
}
fn must_ignore_insensitive_bytes(&mut self, bs: &[u8]) -> Result<()> {
if !self.ignore_insensitive_bytes(bs)? {
return Err(std::io::Error::new(
ErrorKind::InvalidData,
format!("Expected to have insensitive bytes {:?}", bs),
));
}
Ok(())
}
}
impl<R> BufferReadExt for R
where R: BufferRead
{
fn ignores(&mut self, f: impl Fn(u8) -> bool) -> Result<usize> {
let mut bytes = 0;
loop {
let available = self.fill_buf()?;
if available.is_empty() || !f(available[0]) {
break;
}
bytes += 1;
self.consume(1);
}
Ok(bytes)
}
fn ignore(&mut self, f: impl Fn(u8) -> bool) -> Result<bool> {
let available = self.fill_buf()?;
if available.is_empty() {
return Ok(false);
}
if f(available[0]) {
self.consume(1);
Ok(true)
} else {
Ok(false)
}
}
fn ignore_byte(&mut self, b: u8) -> Result<bool> {
let f = |c: u8| c == b;
self.ignore(f)
}
fn ignore_bytes(&mut self, bs: &[u8]) -> Result<bool> {
for b in bs {
let available = self.fill_buf()?;
if available.is_empty() || *b != available[0] {
return Ok(false);
}
self.consume(1);
}
Ok(true)
}
fn ignore_insensitive_bytes(&mut self, bs: &[u8]) -> Result<bool> {
for b in bs {
let available = self.fill_buf()?;
if available.is_empty() || !b.eq_ignore_ascii_case(&available[0]) {
return Ok(false);
}
self.consume(1);
}
Ok(true)
}
fn ignore_white_spaces(&mut self) -> Result<bool> {
let mut cnt = 0;
let f = |c: u8| c.is_ascii_whitespace();
while self.ignore(f)? {
cnt += 1;
}
Ok(cnt > 0)
}
fn until(&mut self, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
self.read_until(delim, buf)
}
fn keep_read(&mut self, buf: &mut Vec<u8>, f: impl Fn(u8) -> bool) -> Result<usize> {
let mut bytes = 0;
loop {
let available = self.fill_buf()?;
if available.is_empty() || !f(available[0]) {
break;
}
buf.push(available[0]);
bytes += 1;
self.consume(1);
}
Ok(bytes)
}
}
| 29.536082 | 89 | 0.504538 |
7a1e925a15dca71ca221244fb3234d3b96c393ae | 18,818 | // 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.
/*!
A library for iterating through the lines in a series of
files. Very similar to [the Python module of the same
name](http://docs.python.org/3.3/library/fileinput.html).
It allows the programmer to automatically take filenames from the
command line arguments (via `input` and `input_state`), as well as
specify them as a vector directly (`input_vec` and
`input_vec_state`). The files are opened as necessary, so any files
that can't be opened only cause an error when reached in the
iteration.
On the command line, `stdin` is represented by a filename of `-` (a
single hyphen) and in the functions that take a vector directly
(e.g. `input_vec`) it is represented by `None`. Note `stdin` is *not*
reset once it has been finished, so attempting to iterate on `[None,
None]` will only take input once unless `io::stdin().seek(0, SeekSet)`
is called between.
The `pathify` function handles converting a list of file paths as
strings to the appropriate format, including the (optional) conversion
of `"-"` to `stdin`.
# Basic
In many cases, one can use the `input_*` functions without having
to handle any `FileInput` structs. E.g. a simple `cat` program
for input |line| {
io::println(line)
}
or a program that numbers lines after concatenating two files
for input_vec_state(pathify([~"a.txt", ~"b.txt"])) |line, state| {
io::println(fmt!("%u: %s", state.line_num,
line));
}
The two `input_vec*` functions take a vec of file names (where empty
means read from `stdin`), the other two functions use the command line
arguments.
# Advanced
For more complicated uses (e.g. if one needs to pause iteration and
resume it later), a `FileInput` instance can be constructed via the
`from_vec`, `from_vec_raw` and `from_args` functions.
Once created, the `each_line` (from the `core::io::ReaderUtil` trait)
and `each_line_state` methods allow one to iterate on the lines; the
latter provides more information about the position within the
iteration to the caller.
It is possible (and safe) to skip lines and files using the
`read_line` and `next_file` methods. Also, `FileInput` implements
`core::io::Reader`, and the state will be updated correctly while
using any of those methods.
E.g. the following program reads until an empty line, pauses for user
input, skips the current file and then numbers the remaining lines
(where the numbers are from the start of each file, rather than the
total line count).
let in = FileInput::from_vec(pathify([~"a.txt", ~"b.txt", ~"c.txt"],
true));
for in.each_line |line| {
if line.is_empty() {
break
}
io::println(line);
}
io::println("Continue?");
if io::stdin().read_line() == ~"yes" {
in.next_file(); // skip!
for in.each_line_state |line, state| {
io::println(fmt!("%u: %s", state.line_num_file,
line))
}
}
*/
#[allow(missing_doc)];
use core::prelude::*;
use core::io::ReaderUtil;
use core::io;
use core::os;
use core::vec;
/**
A summary of the internal state of a `FileInput` object. `line_num`
and `line_num_file` represent the number of lines read in total and in
the current file respectively. `current_path` is `None` if the current
file is `stdin`.
*/
pub struct FileInputState {
current_path: Option<Path>,
line_num: uint,
line_num_file: uint
}
impl FileInputState {
fn is_stdin(&self) -> bool {
self.current_path.is_none()
}
fn is_first_line(&self) -> bool {
self.line_num_file == 1
}
}
struct FileInput_ {
/**
`Some(path)` is the file represented by `path`, `None` is
`stdin`. Consumed as the files are read.
*/
priv files: ~[Option<Path>],
/**
The current file: `Some(r)` for an open file, `None` before
starting and after reading everything.
*/
priv current_reader: Option<@io::Reader>,
priv state: FileInputState,
/**
Used to keep track of whether we need to insert the newline at the
end of a file that is missing it, which is needed to separate the
last and first lines.
*/
priv previous_was_newline: bool
}
// XXX: remove this when Reader has &mut self. Should be removable via
// "self.fi." -> "self." and renaming FileInput_. Documentation above
// will likely have to be updated to use `let mut in = ...`.
pub struct FileInput {
priv fi: @mut FileInput_
}
impl FileInput {
/**
Create a `FileInput` object from a vec of files. An empty
vec means lines are read from `stdin` (use `from_vec_raw` to stop
this behaviour). Any occurence of `None` represents `stdin`.
*/
pub fn from_vec(files: ~[Option<Path>]) -> FileInput {
FileInput::from_vec_raw(
if files.is_empty() {
~[None]
} else {
files
})
}
/**
Identical to `from_vec`, but an empty `files` vec stays
empty. (`None` is `stdin`.)
*/
pub fn from_vec_raw(files: ~[Option<Path>])
-> FileInput {
FileInput{
fi: @mut FileInput_ {
files: files,
current_reader: None,
state: FileInputState {
current_path: None,
line_num: 0,
line_num_file: 0
},
// there was no previous unended line
previous_was_newline: true
}
}
}
/**
Create a `FileInput` object from the command line
arguments. `"-"` represents `stdin`.
*/
pub fn from_args() -> FileInput {
let args = os::args();
let pathed = pathify(args.tail(), true);
FileInput::from_vec(pathed)
}
priv fn current_file_eof(&self) -> bool {
match self.fi.current_reader {
None => false,
Some(r) => r.eof()
}
}
/**
Skip to the next file in the queue. Can `fail` when opening
a file.
Returns `false` if there is no more files, and `true` when it
successfully opens the next file.
*/
pub fn next_file(&self) -> bool {
// No more files
if self.fi.files.is_empty() {
self.fi.current_reader = None;
return false;
}
let path_option = self.fi.files.shift();
let file = match path_option {
None => io::stdin(),
Some(ref path) => io::file_reader(path).get()
};
self.fi.current_reader = Some(file);
self.fi.state.current_path = path_option;
self.fi.state.line_num_file = 0;
true
}
/**
Attempt to open the next file if there is none currently open,
or if the current one is EOF'd.
Returns `true` if it had to move to the next file and did
so successfully.
*/
priv fn next_file_if_eof(&self) -> bool {
match self.fi.current_reader {
None => self.next_file(),
Some(r) => {
if r.eof() {
self.next_file()
} else {
false
}
}
}
}
/**
Apply `f` to each line successively, along with some state
(line numbers and file names, see documentation for
`FileInputState`). Otherwise identical to `lines_each`.
*/
pub fn each_line_state(&self,
f: &fn(&str, FileInputState) -> bool) -> bool {
self.each_line(|line| f(line, copy self.fi.state))
}
/**
Retrieve the current `FileInputState` information.
*/
pub fn state(&self) -> FileInputState {
copy self.fi.state
}
}
impl io::Reader for FileInput {
fn read_byte(&self) -> int {
loop {
let stepped = self.next_file_if_eof();
// if we moved to the next file, and the previous
// character wasn't \n, then there is an unfinished line
// from the previous file. This library models
// line-by-line processing and the trailing line of the
// previous file and the leading of the current file
// should be considered different, so we need to insert a
// fake line separator
if stepped && !self.fi.previous_was_newline {
self.fi.state.line_num += 1;
self.fi.state.line_num_file += 1;
self.fi.previous_was_newline = true;
return '\n' as int;
}
match self.fi.current_reader {
None => return -1,
Some(r) => {
let b = r.read_byte();
if b < 0 {
loop;
}
if b == '\n' as int {
self.fi.state.line_num += 1;
self.fi.state.line_num_file += 1;
self.fi.previous_was_newline = true;
} else {
self.fi.previous_was_newline = false;
}
return b;
}
}
}
}
fn read(&self, buf: &mut [u8], len: uint) -> uint {
let mut count = 0;
while count < len {
let b = self.read_byte();
if b < 0 { break }
buf[count] = b as u8;
count += 1;
}
count
}
fn eof(&self) -> bool {
// we've run out of files, and current_reader is either None or eof.
self.fi.files.is_empty() &&
match self.fi.current_reader { None => true, Some(r) => r.eof() }
}
fn seek(&self, offset: int, whence: io::SeekStyle) {
match self.fi.current_reader {
None => {},
Some(r) => r.seek(offset, whence)
}
}
fn tell(&self) -> uint {
match self.fi.current_reader {
None => 0,
Some(r) => r.tell()
}
}
}
/**
Convert a list of strings to an appropriate form for a `FileInput`
instance. `stdin_hyphen` controls whether `-` represents `stdin` or
a literal `-`.
*/
// XXX: stupid, unclear name
pub fn pathify(vec: &[~str], stdin_hyphen : bool) -> ~[Option<Path>] {
vec::map(vec, |&str : & ~str| {
if stdin_hyphen && str == ~"-" {
None
} else {
Some(Path(str))
}
})
}
/**
Iterate directly over the command line arguments (no arguments implies
reading from `stdin`).
Fails when attempting to read from a file that can't be opened.
*/
pub fn input(f: &fn(&str) -> bool) -> bool {
let i = FileInput::from_args();
i.each_line(f)
}
/**
Iterate directly over the command line arguments (no arguments
implies reading from `stdin`) with the current state of the iteration
provided at each call.
Fails when attempting to read from a file that can't be opened.
*/
pub fn input_state(f: &fn(&str, FileInputState) -> bool) -> bool {
let i = FileInput::from_args();
i.each_line_state(f)
}
/**
Iterate over a vector of files (an empty vector implies just `stdin`).
Fails when attempting to read from a file that can't be opened.
*/
pub fn input_vec(files: ~[Option<Path>], f: &fn(&str) -> bool) -> bool {
let i = FileInput::from_vec(files);
i.each_line(f)
}
/**
Iterate over a vector of files (an empty vector implies just `stdin`)
with the current state of the iteration provided at each call.
Fails when attempting to read from a file that can't be opened.
*/
pub fn input_vec_state(files: ~[Option<Path>],
f: &fn(&str, FileInputState) -> bool) -> bool {
let i = FileInput::from_vec(files);
i.each_line_state(f)
}
#[cfg(test)]
mod test {
use core::prelude::*;
use super::{FileInput, pathify, input_vec, input_vec_state};
use core::io;
use core::uint;
use core::vec;
fn make_file(path : &Path, contents: &[~str]) {
let file = io::file_writer(path, [io::Create, io::Truncate]).get();
for contents.iter().advance |&str| {
file.write_str(str);
file.write_char('\n');
}
}
#[test]
fn test_pathify() {
let strs = [~"some/path",
~"some/other/path"];
let paths = ~[Some(Path("some/path")),
Some(Path("some/other/path"))];
assert_eq!(pathify(strs, true), copy paths);
assert_eq!(pathify(strs, false), paths);
assert_eq!(pathify([~"-"], true), ~[None]);
assert_eq!(pathify([~"-"], false), ~[Some(Path("-"))]);
}
#[test]
fn test_fileinput_read_byte() {
let filenames = pathify(vec::from_fn(
3,
|i| fmt!("tmp/lib-fileinput-test-fileinput-read-byte-%u.tmp", i)), true);
// 3 files containing 0\n, 1\n, and 2\n respectively
for filenames.iter().enumerate().advance |(i, &filename)| {
make_file(filename.get_ref(), [fmt!("%u", i)]);
}
let fi = FileInput::from_vec(copy filenames);
for "012".iter().enumerate().advance |(line, c)| {
assert_eq!(fi.read_byte(), c as int);
assert_eq!(fi.state().line_num, line);
assert_eq!(fi.state().line_num_file, 0);
assert_eq!(fi.read_byte(), '\n' as int);
assert_eq!(fi.state().line_num, line + 1);
assert_eq!(fi.state().line_num_file, 1);
assert_eq!(copy fi.state().current_path, copy filenames[line]);
}
assert_eq!(fi.read_byte(), -1);
assert!(fi.eof());
assert_eq!(fi.state().line_num, 3)
}
#[test]
fn test_fileinput_read() {
let filenames = pathify(vec::from_fn(
3,
|i| fmt!("tmp/lib-fileinput-test-fileinput-read-%u.tmp", i)), true);
// 3 files containing 1\n, 2\n, and 3\n respectively
for filenames.iter().enumerate().advance |(i, &filename)| {
make_file(filename.get_ref(), [fmt!("%u", i)]);
}
let fi = FileInput::from_vec(filenames);
let mut buf : ~[u8] = vec::from_elem(6, 0u8);
let count = fi.read(buf, 10);
assert_eq!(count, 6);
assert_eq!(buf, "0\n1\n2\n".as_bytes().to_owned());
assert!(fi.eof())
assert_eq!(fi.state().line_num, 3);
}
#[test]
fn test_input_vec() {
let mut all_lines = ~[];
let filenames = pathify(vec::from_fn(
3,
|i| fmt!("tmp/lib-fileinput-test-input-vec-%u.tmp", i)), true);
for filenames.iter().enumerate().advance |(i, &filename)| {
let contents =
vec::from_fn(3, |j| fmt!("%u %u", i, j));
make_file(filename.get_ref(), contents);
all_lines.push_all(contents);
}
let mut read_lines = ~[];
for input_vec(filenames) |line| {
read_lines.push(line.to_owned());
}
assert_eq!(read_lines, all_lines);
}
#[test]
fn test_input_vec_state() {
let filenames = pathify(vec::from_fn(
3,
|i| fmt!("tmp/lib-fileinput-test-input-vec-state-%u.tmp", i)),true);
for filenames.iter().enumerate().advance |(i, &filename)| {
let contents =
vec::from_fn(3, |j| fmt!("%u %u", i, j + 1));
make_file(filename.get_ref(), contents);
}
for input_vec_state(filenames) |line, state| {
let nums: ~[&str] = line.split_iter(' ').collect();
let file_num = uint::from_str(nums[0]).get();
let line_num = uint::from_str(nums[1]).get();
assert_eq!(line_num, state.line_num_file);
assert_eq!(file_num * 3 + line_num, state.line_num);
}
}
#[test]
fn test_empty_files() {
let filenames = pathify(vec::from_fn(
3,
|i| fmt!("tmp/lib-fileinput-test-empty-files-%u.tmp", i)),true);
make_file(filenames[0].get_ref(), [~"1", ~"2"]);
make_file(filenames[1].get_ref(), []);
make_file(filenames[2].get_ref(), [~"3", ~"4"]);
let mut count = 0;
for input_vec_state(copy filenames) |line, state| {
let expected_path = match line {
"1" | "2" => copy filenames[0],
"3" | "4" => copy filenames[2],
_ => fail!("unexpected line")
};
assert_eq!(copy state.current_path, expected_path);
count += 1;
}
assert_eq!(count, 4);
}
#[test]
fn test_no_trailing_newline() {
let f1 =
Some(Path("tmp/lib-fileinput-test-no-trailing-newline-1.tmp"));
let f2 =
Some(Path("tmp/lib-fileinput-test-no-trailing-newline-2.tmp"));
let wr = io::file_writer(f1.get_ref(), [io::Create, io::Truncate]).get();
wr.write_str("1\n2");
let wr = io::file_writer(f2.get_ref(), [io::Create, io::Truncate]).get();
wr.write_str("3\n4");
let mut lines = ~[];
for input_vec(~[f1, f2]) |line| {
lines.push(line.to_owned());
}
assert_eq!(lines, ~[~"1", ~"2", ~"3", ~"4"]);
}
#[test]
fn test_next_file() {
let filenames = pathify(vec::from_fn(
3,
|i| fmt!("tmp/lib-fileinput-test-next-file-%u.tmp", i)),true);
for filenames.iter().enumerate().advance |(i, &filename)| {
let contents =
vec::from_fn(3, |j| fmt!("%u %u", i, j + 1));
make_file(&filename.get(), contents);
}
let in = FileInput::from_vec(filenames);
// read once from 0
assert_eq!(in.read_line(), ~"0 1");
in.next_file(); // skip the rest of 1
// read all lines from 1 (but don't read any from 2),
for uint::range(1, 4) |i| {
assert_eq!(in.read_line(), fmt!("1 %u", i));
}
// 1 is finished, but 2 hasn't been started yet, so this will
// just "skip" to the beginning of 2 (Python's fileinput does
// the same)
in.next_file();
assert_eq!(in.read_line(), ~"2 1");
}
#[test]
#[should_fail]
fn test_input_vec_missing_file() {
for input_vec(pathify([~"this/file/doesnt/exist"], true)) |line| {
io::println(line);
}
}
}
| 30.49919 | 85 | 0.561271 |
acdfb42aaf1cff4a55670b05fa2ec8d7e94141bc | 25,707 | use super::*;
use super::util::*;
use chrono::{DateTime, Utc};
use roblox::*;
use serenity;
use std::borrow::Cow;
use std::time::SystemTime;
use util;
// TODO: Check role existence.
// TODO: Take care of massive code redundancy here.
fn get_discord_username(discord_id: UserId) -> String {
match discord_id.to_user_cached() {
Some(x) => x.read().tag(),
None => match discord_id.to_user() {
Ok(x) => x.tag(),
Err(_) => format!("(discord uid #{})", discord_id.0),
}
}
}
fn verify_status_str(prefix: &str, result: SetRolesStatus) -> Cow<'static, str> {
match result {
SetRolesStatus::Success {
nickname_admin_error, determine_roles_error, set_roles_error, ..
} => {
if determine_roles_error || set_roles_error {
format!(
"An error occurred while {}, and some of your roles may not have been set. \
Please wait a while then use the '{}update' command.",
if determine_roles_error {
"looking up your Roblox account"
} else {
"setting your Discord roles"
},
prefix,
).into()
} else {
format!(
"Your roles have been updated.{}",
if nickname_admin_error {
" Your nickname was not set as this bot does not have the permissions \
needed to edit it."
} else { "" }
).into()
}
}
SetRolesStatus::NotVerified =>
"Your roles were not updated as you are not verified.".into(),
}
}
fn reverify_help(
ctx: &CommandContext, discord_id: UserId, roblox_id: RobloxUserID,
) -> Result<String> {
if ctx.core.verifier().get_verified_roblox_user(discord_id)? == Some(roblox_id) {
Ok(format!(" If you only want to update your roles, use the '{}update' command.",
ctx.prefix()))
} else {
Ok(String::new())
}
}
fn log_unverify(
ctx: &CommandContext, discord_id: UserId, roblox_id: RobloxUserID,
) -> Result<()> {
let log_channel = ctx.core.config().get(None, ConfigKeys::GlobalVerificationLogChannel)?;
if let Some(log_channel_id) = log_channel {
let log_channel_id = ChannelId(log_channel_id);
let discord_username = discord_id.to_user()?.tag();
let roblox_username = roblox_id.lookup_username()?;
log_channel_id.send_message(|m|
m.content(format_args!("`[{}]` ⚠ {} (`{}`) has been unverified.\n\
Old Roblox account: `{}` (https://www.roblox.com/users/{}/profile)",
Utc::now().format("%H:%M:%S"),
discord_username, discord_id.0, roblox_username, roblox_id.0))
)?;
}
Ok(())
}
fn do_verify(ctx: &CommandContext, _: &Context, msg: &Message) -> Result<()> {
cmd_ensure!(ctx.argc() >= 2, ctx.core.verify_channel().verify_instructions()?);
let roblox_username = ctx.arg(0)?;
let token = ctx.arg(1)?;
let roblox_id = RobloxUserID::for_username(roblox_username)?;
let discord_username = msg.author.tag();
let discord_id = msg.author.id;
let discord_display = format!("{} (`{}`)", discord_username, discord_id.0);
let roblox_display = format!("`{}` (https://www.roblox.com/users/{}/profile)",
roblox_username, roblox_id.0);
let guild_id = msg.guild_id?;
debug!("Beginning verification attempt: {} -> {}", discord_display, roblox_display);
let log_channel = ctx.core.config().get(None, ConfigKeys::GlobalVerificationLogChannel)?;
macro_rules! verify_status {
($prefix_log:expr, $($format:tt)*) => {
let buffer = format!($($format)*);
info!("{}", buffer);
if let Some(log_channel_id) = log_channel {
let log_channel_id = ChannelId(log_channel_id);
log_channel_id.send_message(|m|
m.content(format_args!(concat!("`[{}]` ", $prefix_log, "{}"),
Utc::now().format("%H:%M:%S"), buffer))
)?;
}
}
}
match ctx.core.verifier().try_verify(discord_id, roblox_id, token)? {
VerifyResult::VerificationOk => {
verify_status!("ℹ ", "{} successfully verified as {}",
discord_display, roblox_display);
}
VerifyResult::ReverifyOk { discord_link, roblox_link } => {
let discord_link_display = if let Some(discord_id) = discord_link {
let discord_username = discord_id.to_user()?.tag();
format!("Old Discord account: {} (`{}`)", discord_username, discord_id.0)
} else {
format!("No old Discord account")
};
let roblox_link_display = if let Some(roblox_id) = roblox_link {
let roblox_username = roblox_id.lookup_username()?;
format!("Old Roblox account: `{}` (https://www.roblox.com/users/{}/profile)",
roblox_username, roblox_id.0)
} else {
format!("No old Roblox account")
};
verify_status!("⚠ ", "{} successfully reverified as {}\n{}; {}",
discord_display, roblox_display,
discord_link_display, roblox_link_display);
}
VerifyResult::TokenAlreadyUsed => {
verify_status!("🛑 ", "{} failed to verify as {}: Token already used.",
discord_display, roblox_display);
cmd_error!("Someone has already used that verification code. Please wait for a \
new code to be generated, then try again.")
}
VerifyResult::VerificationPlaceOutdated => {
verify_status!("⚠⚠⚠⚠⚠ ", "{} failed to verify as {}: Outdated verification place.",
discord_display, roblox_display);
cmd_error!("The verification place is outdated, and has not been updated with the \
verification bot. Please contact the bot owner.")
}
VerifyResult::InvalidToken => {
verify_status!("🛑 ", "{} failed to verify as {}: Invalid token.",
discord_display, roblox_display);
cmd_error!("The verification code you used is not valid. Please check the code \
you entered and try again.")
}
VerifyResult::TooManyAttempts { max_attempts, cooldown, cooldown_ends } => {
verify_status!("🛑 ", "{} failed to verify as {}: Too many attempts.",
discord_display, roblox_display);
cmd_error!("You can only try to verify {} times every {}. \
Please try again in {}.{}",
max_attempts, util::to_english_time(cooldown),
util::english_time_diff(SystemTime::now(), cooldown_ends),
reverify_help(ctx, discord_id, roblox_id)?)
}
VerifyResult::SenderVerifiedAs { other_roblox_id } => {
let other_roblox_username = other_roblox_id.lookup_username()?;
verify_status!("🛑 ", "{} failed to verify as {}: Already verified as {}.",
discord_display, roblox_display, other_roblox_username);
cmd_error!("You are already verified as {}.{}",
other_roblox_username, reverify_help(ctx, discord_id, roblox_id)?)
}
VerifyResult::RobloxAccountVerifiedTo { other_discord_id } => {
let other_discord_username = get_discord_username(other_discord_id);
verify_status!("🛑 ", "{} failed to verify as {}: Roblox account already verified to {}.",
discord_display, roblox_display, other_discord_username);
cmd_error!("{} has already verified as {}.",
other_discord_username, roblox_username)
}
VerifyResult::ReverifyOnCooldown { cooldown, cooldown_ends } => {
verify_status!("🛑 ", "{} failed to verify as {}: Reverified too soon.",
discord_display, roblox_display);
cmd_error!("You can only reverify once every {}. Please try again in {}.{}",
util::to_english_time(cooldown),
util::english_time_diff(SystemTime::now(), cooldown_ends),
reverify_help(ctx, discord_id, roblox_id)?)
}
}
let status = ctx.core.roles().assign_roles(guild_id, msg.author.id, Some(roblox_id))?;
ctx.respond(verify_status_str(ctx.prefix(), status))?;
Ok(())
}
fn check_configuration(ctx: &CommandContext, guild_id: GuildId) -> Result<()> {
if let Some(err) = ctx.core.roles().check_error(guild_id)? {
ctx.respond(format!("The role configuration has been successfully updated. However, \
errors were found in the configuration: {}", err))
} else {
ctx.respond("The role configuration has been successfully updated.")
}
}
fn whois_msg(
ctx: &CommandContext, user: User, roblox_id: RobloxUserID, roblox_name: &str
) -> Result<()> {
ctx.respond(format!("{} (`{}`) is verified as {} (https://www.roblox.com/users/{}/profile)",
user.tag(), user.id.0, roblox_name, roblox_id.0))
}
fn whois_discord(ctx: &CommandContext, discord_user_id: UserId) -> Result<()> {
let user = discord_user_id.to_user().map_err(Error::from)
.status_to_cmd(StatusCode::NotFound, || "That Discord account does not exist.")?;
let roblox_user_id = ctx.core.verifier().get_verified_roblox_user(discord_user_id)?;
if let Some(roblox_user_id) = roblox_user_id {
let roblox_name = roblox_user_id.lookup_username_opt()?;
if let Some(roblox_name) = roblox_name {
whois_msg(ctx, user, roblox_user_id, &roblox_name)
} else {
cmd_error!("{} (`{}`) is verified as Roblox User ID #{}, which no longer exists. \
(https://www.roblox.com/users/{}/profile)",
user.tag(), user.id.0, roblox_user_id.0, roblox_user_id.0)
}
} else {
cmd_error!("{} (`{}`) isn't verified.", user.tag(), user.id.0)
}
}
fn whois_roblox(ctx: &CommandContext, roblox_name: &str) -> Result<()> {
let roblox_user_id = RobloxUserID::for_username(roblox_name)?;
let discord_user_id = ctx.core.verifier().get_verified_discord_user(roblox_user_id)?;
if let Some(discord_user_id) = discord_user_id {
let user = discord_user_id.to_user().map_err(Error::from)
.status_to_cmd(StatusCode::NotFound, ||
format!("The Discord account verified with '{}' no longer exists.", roblox_name)
)?;
whois_msg(ctx, user, roblox_user_id, roblox_name)
} else {
cmd_error!("No Discord user has verified as {} (https://www.roblox.com/users/{}/profile)",
roblox_name, roblox_user_id.0)
}
}
fn do_whois(ctx: &CommandContext) -> Result<()> {
let target_name = ctx.arg(0)?;
if let Some(user_id) = find_user(target_name)? {
whois_discord(ctx, user_id)
} else {
whois_roblox(ctx, target_name)
}
}
fn format_discord_id(id: UserId) -> String {
match id.to_user() {
Ok(user) => format!("{} (`{}`)", user.tag(), id.0),
Err(_) => format!("*(non-existent Discord id #{})*", id.0),
}
}
fn format_roblox_id(id: RobloxUserID) -> String {
match id.lookup_username() {
Ok(username) => username,
Err(_) => format!("*(non-existent Roblox id #{})*", id.0),
}
}
fn display_history<T>(
ctx: &CommandContext, entries: Vec<HistoryEntry<T>>,
header_name: &str, to_string: impl Fn(T) -> String,
) -> Result<()> {
let mut history = String::new();
writeln!(history, "History for {}:", header_name)?;
for entry in entries {
let date: DateTime<Utc> = entry.last_updated.into();
writeln!(history, "• Account was {} with {} on {} UTC",
if entry.is_unverify { "unverified" } else { "verified" },
to_string(entry.id), date.format("%Y-%m-%d %H:%M:%S"))?;
}
ctx.respond(history)
}
fn do_whowas(ctx: &CommandContext) -> Result<()> {
let target_name = ctx.arg(0)?;
if let Some(user_id) = find_user(target_name)? {
display_history(ctx, ctx.core.verifier().get_discord_user_history(user_id, 10)?,
&format!("Discord user {}", format_discord_id(user_id)), format_roblox_id)
} else {
let roblox_id = RobloxUserID::for_username(target_name)?;
display_history(ctx, ctx.core.verifier().get_roblox_user_history(roblox_id, 10)?,
&format!("Roblox user {}", format_roblox_id(roblox_id)), format_discord_id)
}
}
fn force_unverify(
ctx: &CommandContext, discord_id: UserId, roblox_id: RobloxUserID,
) -> Result<()> {
let user = discord_id.to_user().map_err(Error::from)
.status_to_cmd(StatusCode::NotFound, || "That Discord account does not exist.")?;
ctx.core.verifier().unverify(discord_id)?;
ctx.respond(format!("User {} has been unverified with {}.",
user.tag(), roblox_id.lookup_username()?))?;
log_unverify(ctx, discord_id, roblox_id)?;
Ok(())
}
fn do_force_unverify(ctx: &CommandContext) -> Result<()> {
let target_name = ctx.arg(0)?;
if let Some(discord_id) = find_user(target_name)? {
let roblox_id = ctx.core.verifier().get_verified_roblox_user(discord_id)?;
if let Some(roblox_id) = roblox_id {
force_unverify(ctx, discord_id, roblox_id)
} else {
cmd_error!("User isn't verified.");
}
} else {
let roblox_id = RobloxUserID::for_username(target_name)?;
let discord_id = ctx.core.verifier().get_verified_discord_user(roblox_id)?;
if let Some(discord_id) = discord_id {
force_unverify(ctx, discord_id, roblox_id)
} else {
cmd_error!("No Discord user has verified as {}.", target_name);
}
}
}
fn do_unverify(ctx: &CommandContext, _: &Context, msg: &Message) -> Result<()> {
let guild_id = msg.guild_id?;
let roblox_id = ctx.core.verifier().get_verified_roblox_user(msg.author.id)?;
if let Some(roblox_id) = roblox_id {
ctx.core.verifier().unverify(msg.author.id)?;
let status = ctx.core.roles().assign_roles(guild_id, msg.author.id, None)?;
ctx.respond(verify_status_str(ctx.prefix(), status))?;
log_unverify(ctx, msg.author.id, roblox_id)?;
Ok(())
} else {
cmd_error!("Your Discord account is not currently verified.");
}
}
fn maybe_sprunge(ctx: &CommandContext, text: &str) -> Result<()> {
if text.chars().count() < 1900 {
ctx.respond(format!("```\n{}\n```", text))
} else {
ctx.respond(format!("The response is too long and has been uploaded to a site: {}",
util::sprunge(text)?))
}
}
crate const COMMANDS: &[Command] = &[
Command::new("show_config")
.help(None, "Shows the role configuration for the current channel.")
.required_permissions(enum_set!(BotPermission::ManageRoles))
.allowed_contexts(enum_set!(CommandTarget::ServerMessage))
.exec_discord(|ctx, _, msg| {
let guild_id = msg.guild_id?;
let mut config = String::new();
let config_map = ctx.core.roles().get_configuration(guild_id)?;
let mut role_names: Vec<&str> = config_map.keys().map(|x| x.as_str()).collect();
role_names.sort();
for role in role_names {
let role_data = &config_map[role];
let definition = role_data.custom_rule.as_ref()
.map(|x| format!("`{}`", x))
.unwrap_or_else(|| if VerificationRule::has_builtin(role) {
"*(builtin)*".to_string()
} else {
"**(does not exist)**".to_string()
});
writeln!(config, "• {} = {}", role, definition)?;
if let Some(role_id) = role_data.role_id {
let guild = guild_id.to_guild_cached()?;
let guild = guild.read();
match guild.roles.get(&role_id) {
Some(role) =>
writeln!(config, " Users matching this rule will be assigned **{}**.",
role.name)?,
None =>
writeln!(config, " **A role with ID #{} was assigned to this rule, \
but it no longer exists!**", role_id)?,
};
}
let date: DateTime<Utc> = role_data.last_updated.into();
writeln!(config, " *Last updated at {} UTC*", date.format("%Y-%m-%d %H:%M:%S"))?;
}
if config.is_empty() {
ctx.respond("No roles are configured.")
} else {
ctx.respond(config.trim())
}
}),
Command::new("set_role")
.help(Some("<rule name> [discord role name]"),
"Sets the Discord role the bot will set when a rule is matched.")
.required_permissions(enum_set!(BotPermission::ManageRoles))
.allowed_contexts(enum_set!(CommandTarget::ServerMessage))
.exec_discord(|ctx, _, msg| {
let rule_name = ctx.arg(0)?;
let role_name = ctx.rest(1)?.trim();
let guild_id = msg.guild_id?;
let my_id = serenity::CACHE.read().user.id;
if !role_name.is_empty() {
let role_id = find_role(guild_id, role_name)?;
if !ctx.has_permissions(BotPermission::BypassHierarchy.into()) &&
!util::can_member_access_role(guild_id, msg.author.id, role_id)? {
cmd_error!("You do not have permission to modify that role.")
}
if !util::can_member_access_role(guild_id, my_id, role_id)? {
cmd_error!("This bot does not have permission to modify that role.")
}
ctx.core.roles().set_active_role(guild_id, rule_name, Some(role_id))?;
} else {
ctx.core.roles().set_active_role(guild_id, rule_name, None)?;
}
check_configuration(ctx, guild_id)
}),
Command::new("set_custom_rule")
.help(Some("<rule name> [rule definition]"),
"Defines a custom rule for setting roles.")
.required_permissions(enum_set!(BotPermission::ManageRoles))
.allowed_contexts(enum_set!(CommandTarget::ServerMessage))
.exec_discord(|ctx, _, msg| {
let rule_name = ctx.arg(0)?;
let definition = ctx.rest(1)?.trim();
let guild_id = msg.guild_id?;
if !definition.is_empty() {
ctx.core.roles().set_custom_rule(guild_id, rule_name, Some(definition))?;
} else {
ctx.core.roles().set_custom_rule(guild_id, rule_name, None)?;
}
check_configuration(ctx, guild_id)
}),
Command::new("test_verify")
.help(Some("<roblox username>"), "Tests the results of your role configuration.")
.required_permissions(enum_set!(BotPermission::ManageRoles))
.allowed_contexts(enum_set!(CommandTarget::ServerMessage))
.exec_discord(|ctx, _, msg| {
let roblox_username = ctx.arg(0)?;
let roblox_id = RobloxUserID::for_username(roblox_username)?;
let guild_id = msg.guild_id?;
let mut roles = String::new();
for role in ctx.core.roles().get_assigned_roles(guild_id, roblox_id)? {
writeln!(roles, "• {}{} {} **{}**",
if role.is_assigned == RuleResult::Error {
"An error occurred while determining if "
} else {
""
},
roblox_username,
match role.is_assigned {
RuleResult::True | RuleResult::Error => "matches the rule",
RuleResult::False => "does not match the rule",
},
role.rule)?
}
if roles.is_empty() {
ctx.respond("No roles are configured.")
} else {
ctx.respond(roles.trim())
}
}),
Command::new("update")
.help(None, "Updates your roles according to your Roblox account.")
.allowed_contexts(enum_set!(CommandTarget::ServerMessage))
.exec_discord(|ctx, _, msg| {
cmd_ensure!(ctx.core.verifier().get_verified_roblox_user(msg.author.id)?.is_some(),
"You are not verified with this bot. {}",
ctx.core.verify_channel().verify_instructions()?);
let guild_id = msg.guild_id?;
let cooldown =
ctx.core.config().get(Some(guild_id), ConfigKeys::UpdateCooldownSeconds)?;
let status = ctx.core.roles().update_user_with_cooldown(
guild_id, msg.author.id, cooldown, true, false,
)?;
ctx.respond(verify_status_str(ctx.prefix(), status))?;
Ok(())
}),
Command::new("whois")
.help(Some("<discord mention, user id, or roblox username>"),
"Retrieves the Roblox account a Discord account is verified with or vice versa.")
.required_permissions(enum_set!(BotPermission::Whois))
.exec(do_whois),
Command::new("whowas")
.help(Some("<discord mention, user id, or roblox username>"),
"Retrieves the verification history of a Roblox account or a Discord account.")
.required_permissions(enum_set!(BotPermission::Whowas))
.exec(do_whowas),
Command::new("verify")
.help(Some("<roblox username> <verification code>"),
"Verifies a Roblox account to your Discord account.")
.allowed_contexts(enum_set!(CommandTarget::ServerMessage))
.exec_discord(do_verify),
Command::new("unverify")
.help(None, "Unverifies your Roblox account from your Discord account.")
.allowed_contexts(enum_set!(CommandTarget::ServerMessage))
.required_permissions(enum_set!(BotPermission::Unverify))
.exec_discord(do_unverify),
Command::new("force_unverify")
.help(Some("<discord mention, user id, or roblox username>"),
"Forcefully unverifies a Roblox account from a Discord account.")
.allowed_contexts(enum_set!(CommandTarget::ServerMessage))
.required_permissions(enum_set!(BotPermission::UnverifyOther))
.exec(do_force_unverify),
Command::new("set_verification_channel")
.help(None, "Makes the current channel a verification channel.")
.allowed_contexts(enum_set!(CommandTarget::ServerMessage))
.required_permissions(enum_set!(BotPermission::ManageGuildSettings))
.exec_discord(|ctx, _, msg| {
let guild_id = msg.guild_id?;
if let Some("confirm") = ctx.arg_opt(0) {
ctx.core.verify_channel().setup(guild_id, msg.channel_id)?;
} else {
ctx.core.verify_channel().setup_check(guild_id, msg.channel_id)?;
ctx.respond(format!(
"You are setting this channel to be a verification channel. This will cause \
the bot to:\n\
• Delete all messages currently in in this channel.\n\
• Delete any messages sent by other users in this channel immediately \
after receiving them.\n\
• Automatically delete message sent by it in this channel after \
a certain period of time.\n\
\n\
Please use `{}set_verification_channel confirm` to verify that you wish to \
do this.", ctx.prefix(),
))?;
}
Ok(())
}),
Command::new("remove_verification_channel")
.help(None, "Unsets the server's current verification channel, if one exists.")
.allowed_contexts(enum_set!(CommandTarget::ServerMessage))
.required_permissions(enum_set!(BotPermission::ManageGuildSettings))
.exec_discord(|ctx, _, msg| {
let guild_id = msg.guild_id?;
ctx.core.verify_channel().remove(guild_id)?;
Ok(())
}),
Command::new("explain")
.help(Some("[rule to explain]"),
"Explains the compilation of your ruleset or a role. You probably don't need this.")
.required_permissions(enum_set!(BotPermission::ManageRoles))
.allowed_contexts(enum_set!(CommandTarget::ServerMessage))
.exec_discord(|ctx, _, msg| {
let rule = ctx.rest(0)?;
if rule == "" {
let guild_id = msg.guild_id?;
maybe_sprunge(ctx, &ctx.core.roles().explain_rule_set(guild_id)?)
} else {
let rule = format!("{}", VerificationRule::from_str(rule)?);
maybe_sprunge(ctx, &rule)
}
}),
];
| 47.255515 | 104 | 0.564632 |
691e76b306dced15c11b6a46314f907318116f3c | 1,561 | use crate::actions::*;
use crate::managers::*;
use js_sys::Function;
use wasm_bindgen::prelude::*;
#[derive(Clone)]
pub struct Sender {
f: Function,
}
impl Sender {
pub fn new(f: Function) -> Self {
Sender { f }
}
pub fn send(&self, msg: Message) -> anyhow::Result<()> {
let s = serde_json::to_string(&msg)?;
self.f.call1(&JsValue::NULL, &JsValue::from(s)).unwrap();
Ok(())
}
}
#[wasm_bindgen]
pub struct Resolution {
r: ResolutionManager,
}
#[wasm_bindgen]
impl Resolution {
pub fn new(f: Function) -> Self {
Self {
r: ResolutionManager::new(Sender::new(f)),
}
}
pub fn run(&mut self, m: String) {
let msg: Result<Message, serde_json::Error> = serde_json::from_str(&m);
if msg.is_err() {
println!("Unable to understand message:\n{}", m);
println!("Error: {:?}", msg);
}
let msg = msg.unwrap();
self.r.process_message(msg).unwrap();
}
}
#[wasm_bindgen]
pub struct Sseq {
s: SseqManager,
}
#[wasm_bindgen]
impl Sseq {
pub fn new(f: Function) -> Self {
Self {
s: SseqManager::new(Sender::new(f)),
}
}
pub fn run(&mut self, m: String) {
let msg: Result<Message, serde_json::Error> = serde_json::from_str(&m);
if msg.is_err() {
println!("Unable to understand message:\n{}", m);
println!("Error: {:?}", msg);
}
let msg = msg.unwrap();
self.s.process_message(msg).unwrap();
}
}
| 21.094595 | 79 | 0.538757 |
89cc492957af36d20af192d7665e6ca0f2477aab | 206,690 | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[derive(std::fmt::Debug)]
pub(crate) struct Handle {
client: aws_hyper::Client<aws_hyper::conn::Standard>,
conf: crate::Config,
}
#[derive(Clone, std::fmt::Debug)]
pub struct Client {
handle: std::sync::Arc<Handle>,
}
impl Client {
#[cfg(any(feature = "rustls", feature = "native-tls"))]
pub fn from_env() -> Self {
Self::from_conf_conn(
crate::Config::builder().build(),
aws_hyper::conn::Standard::https(),
)
}
#[cfg(any(feature = "rustls", feature = "native-tls"))]
pub fn from_conf(conf: crate::Config) -> Self {
Self::from_conf_conn(conf, aws_hyper::conn::Standard::https())
}
pub fn from_conf_conn(conf: crate::Config, conn: aws_hyper::conn::Standard) -> Self {
let client = aws_hyper::Client::new(conn);
Self {
handle: std::sync::Arc::new(Handle { client, conf }),
}
}
pub fn conf(&self) -> &crate::Config {
&self.handle.conf
}
pub fn add_layer_version_permission(&self) -> fluent_builders::AddLayerVersionPermission {
fluent_builders::AddLayerVersionPermission::new(self.handle.clone())
}
pub fn add_permission(&self) -> fluent_builders::AddPermission {
fluent_builders::AddPermission::new(self.handle.clone())
}
pub fn create_alias(&self) -> fluent_builders::CreateAlias {
fluent_builders::CreateAlias::new(self.handle.clone())
}
pub fn create_code_signing_config(&self) -> fluent_builders::CreateCodeSigningConfig {
fluent_builders::CreateCodeSigningConfig::new(self.handle.clone())
}
pub fn create_event_source_mapping(&self) -> fluent_builders::CreateEventSourceMapping {
fluent_builders::CreateEventSourceMapping::new(self.handle.clone())
}
pub fn create_function(&self) -> fluent_builders::CreateFunction {
fluent_builders::CreateFunction::new(self.handle.clone())
}
pub fn delete_alias(&self) -> fluent_builders::DeleteAlias {
fluent_builders::DeleteAlias::new(self.handle.clone())
}
pub fn delete_code_signing_config(&self) -> fluent_builders::DeleteCodeSigningConfig {
fluent_builders::DeleteCodeSigningConfig::new(self.handle.clone())
}
pub fn delete_event_source_mapping(&self) -> fluent_builders::DeleteEventSourceMapping {
fluent_builders::DeleteEventSourceMapping::new(self.handle.clone())
}
pub fn delete_function(&self) -> fluent_builders::DeleteFunction {
fluent_builders::DeleteFunction::new(self.handle.clone())
}
pub fn delete_function_code_signing_config(
&self,
) -> fluent_builders::DeleteFunctionCodeSigningConfig {
fluent_builders::DeleteFunctionCodeSigningConfig::new(self.handle.clone())
}
pub fn delete_function_concurrency(&self) -> fluent_builders::DeleteFunctionConcurrency {
fluent_builders::DeleteFunctionConcurrency::new(self.handle.clone())
}
pub fn delete_function_event_invoke_config(
&self,
) -> fluent_builders::DeleteFunctionEventInvokeConfig {
fluent_builders::DeleteFunctionEventInvokeConfig::new(self.handle.clone())
}
pub fn delete_layer_version(&self) -> fluent_builders::DeleteLayerVersion {
fluent_builders::DeleteLayerVersion::new(self.handle.clone())
}
pub fn delete_provisioned_concurrency_config(
&self,
) -> fluent_builders::DeleteProvisionedConcurrencyConfig {
fluent_builders::DeleteProvisionedConcurrencyConfig::new(self.handle.clone())
}
pub fn get_account_settings(&self) -> fluent_builders::GetAccountSettings {
fluent_builders::GetAccountSettings::new(self.handle.clone())
}
pub fn get_alias(&self) -> fluent_builders::GetAlias {
fluent_builders::GetAlias::new(self.handle.clone())
}
pub fn get_code_signing_config(&self) -> fluent_builders::GetCodeSigningConfig {
fluent_builders::GetCodeSigningConfig::new(self.handle.clone())
}
pub fn get_event_source_mapping(&self) -> fluent_builders::GetEventSourceMapping {
fluent_builders::GetEventSourceMapping::new(self.handle.clone())
}
pub fn get_function(&self) -> fluent_builders::GetFunction {
fluent_builders::GetFunction::new(self.handle.clone())
}
pub fn get_function_code_signing_config(
&self,
) -> fluent_builders::GetFunctionCodeSigningConfig {
fluent_builders::GetFunctionCodeSigningConfig::new(self.handle.clone())
}
pub fn get_function_concurrency(&self) -> fluent_builders::GetFunctionConcurrency {
fluent_builders::GetFunctionConcurrency::new(self.handle.clone())
}
pub fn get_function_configuration(&self) -> fluent_builders::GetFunctionConfiguration {
fluent_builders::GetFunctionConfiguration::new(self.handle.clone())
}
pub fn get_function_event_invoke_config(
&self,
) -> fluent_builders::GetFunctionEventInvokeConfig {
fluent_builders::GetFunctionEventInvokeConfig::new(self.handle.clone())
}
pub fn get_layer_version(&self) -> fluent_builders::GetLayerVersion {
fluent_builders::GetLayerVersion::new(self.handle.clone())
}
pub fn get_layer_version_by_arn(&self) -> fluent_builders::GetLayerVersionByArn {
fluent_builders::GetLayerVersionByArn::new(self.handle.clone())
}
pub fn get_layer_version_policy(&self) -> fluent_builders::GetLayerVersionPolicy {
fluent_builders::GetLayerVersionPolicy::new(self.handle.clone())
}
pub fn get_policy(&self) -> fluent_builders::GetPolicy {
fluent_builders::GetPolicy::new(self.handle.clone())
}
pub fn get_provisioned_concurrency_config(
&self,
) -> fluent_builders::GetProvisionedConcurrencyConfig {
fluent_builders::GetProvisionedConcurrencyConfig::new(self.handle.clone())
}
pub fn invoke(&self) -> fluent_builders::Invoke {
fluent_builders::Invoke::new(self.handle.clone())
}
pub fn invoke_async(&self) -> fluent_builders::InvokeAsync {
fluent_builders::InvokeAsync::new(self.handle.clone())
}
pub fn list_aliases(&self) -> fluent_builders::ListAliases {
fluent_builders::ListAliases::new(self.handle.clone())
}
pub fn list_code_signing_configs(&self) -> fluent_builders::ListCodeSigningConfigs {
fluent_builders::ListCodeSigningConfigs::new(self.handle.clone())
}
pub fn list_event_source_mappings(&self) -> fluent_builders::ListEventSourceMappings {
fluent_builders::ListEventSourceMappings::new(self.handle.clone())
}
pub fn list_function_event_invoke_configs(
&self,
) -> fluent_builders::ListFunctionEventInvokeConfigs {
fluent_builders::ListFunctionEventInvokeConfigs::new(self.handle.clone())
}
pub fn list_functions(&self) -> fluent_builders::ListFunctions {
fluent_builders::ListFunctions::new(self.handle.clone())
}
pub fn list_functions_by_code_signing_config(
&self,
) -> fluent_builders::ListFunctionsByCodeSigningConfig {
fluent_builders::ListFunctionsByCodeSigningConfig::new(self.handle.clone())
}
pub fn list_layers(&self) -> fluent_builders::ListLayers {
fluent_builders::ListLayers::new(self.handle.clone())
}
pub fn list_layer_versions(&self) -> fluent_builders::ListLayerVersions {
fluent_builders::ListLayerVersions::new(self.handle.clone())
}
pub fn list_provisioned_concurrency_configs(
&self,
) -> fluent_builders::ListProvisionedConcurrencyConfigs {
fluent_builders::ListProvisionedConcurrencyConfigs::new(self.handle.clone())
}
pub fn list_tags(&self) -> fluent_builders::ListTags {
fluent_builders::ListTags::new(self.handle.clone())
}
pub fn list_versions_by_function(&self) -> fluent_builders::ListVersionsByFunction {
fluent_builders::ListVersionsByFunction::new(self.handle.clone())
}
pub fn publish_layer_version(&self) -> fluent_builders::PublishLayerVersion {
fluent_builders::PublishLayerVersion::new(self.handle.clone())
}
pub fn publish_version(&self) -> fluent_builders::PublishVersion {
fluent_builders::PublishVersion::new(self.handle.clone())
}
pub fn put_function_code_signing_config(
&self,
) -> fluent_builders::PutFunctionCodeSigningConfig {
fluent_builders::PutFunctionCodeSigningConfig::new(self.handle.clone())
}
pub fn put_function_concurrency(&self) -> fluent_builders::PutFunctionConcurrency {
fluent_builders::PutFunctionConcurrency::new(self.handle.clone())
}
pub fn put_function_event_invoke_config(
&self,
) -> fluent_builders::PutFunctionEventInvokeConfig {
fluent_builders::PutFunctionEventInvokeConfig::new(self.handle.clone())
}
pub fn put_provisioned_concurrency_config(
&self,
) -> fluent_builders::PutProvisionedConcurrencyConfig {
fluent_builders::PutProvisionedConcurrencyConfig::new(self.handle.clone())
}
pub fn remove_layer_version_permission(&self) -> fluent_builders::RemoveLayerVersionPermission {
fluent_builders::RemoveLayerVersionPermission::new(self.handle.clone())
}
pub fn remove_permission(&self) -> fluent_builders::RemovePermission {
fluent_builders::RemovePermission::new(self.handle.clone())
}
pub fn tag_resource(&self) -> fluent_builders::TagResource {
fluent_builders::TagResource::new(self.handle.clone())
}
pub fn untag_resource(&self) -> fluent_builders::UntagResource {
fluent_builders::UntagResource::new(self.handle.clone())
}
pub fn update_alias(&self) -> fluent_builders::UpdateAlias {
fluent_builders::UpdateAlias::new(self.handle.clone())
}
pub fn update_code_signing_config(&self) -> fluent_builders::UpdateCodeSigningConfig {
fluent_builders::UpdateCodeSigningConfig::new(self.handle.clone())
}
pub fn update_event_source_mapping(&self) -> fluent_builders::UpdateEventSourceMapping {
fluent_builders::UpdateEventSourceMapping::new(self.handle.clone())
}
pub fn update_function_code(&self) -> fluent_builders::UpdateFunctionCode {
fluent_builders::UpdateFunctionCode::new(self.handle.clone())
}
pub fn update_function_configuration(&self) -> fluent_builders::UpdateFunctionConfiguration {
fluent_builders::UpdateFunctionConfiguration::new(self.handle.clone())
}
pub fn update_function_event_invoke_config(
&self,
) -> fluent_builders::UpdateFunctionEventInvokeConfig {
fluent_builders::UpdateFunctionEventInvokeConfig::new(self.handle.clone())
}
}
pub mod fluent_builders {
#[derive(std::fmt::Debug)]
pub struct AddLayerVersionPermission {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::add_layer_version_permission_input::Builder,
}
impl AddLayerVersionPermission {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::AddLayerVersionPermissionOutput,
smithy_http::result::SdkError<crate::error::AddLayerVersionPermissionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name or Amazon Resource Name (ARN) of the layer.</p>
pub fn layer_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.layer_name(inp);
self
}
pub fn set_layer_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_layer_name(inp);
self
}
/// <p>The version number.</p>
pub fn version_number(mut self, inp: i64) -> Self {
self.inner = self.inner.version_number(inp);
self
}
pub fn set_version_number(mut self, inp: i64) -> Self {
self.inner = self.inner.set_version_number(inp);
self
}
/// <p>An identifier that distinguishes the policy from others on the same layer version.</p>
pub fn statement_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.statement_id(inp);
self
}
pub fn set_statement_id(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_statement_id(inp);
self
}
/// <p>The API action that grants access to the layer. For example, <code>lambda:GetLayerVersion</code>.</p>
pub fn action(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.action(inp);
self
}
pub fn set_action(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_action(inp);
self
}
/// <p>An account ID, or <code>*</code> to grant permission to all AWS accounts.</p>
pub fn principal(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.principal(inp);
self
}
pub fn set_principal(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_principal(inp);
self
}
/// <p>With the principal set to <code>*</code>, grant permission to all accounts in the specified
/// organization.</p>
pub fn organization_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.organization_id(inp);
self
}
pub fn set_organization_id(
mut self,
inp: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_organization_id(inp);
self
}
/// <p>Only update the policy if the revision ID matches the ID specified. Use this option to avoid modifying a
/// policy that has changed since you last read it.</p>
pub fn revision_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.revision_id(inp);
self
}
pub fn set_revision_id(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_revision_id(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct AddPermission {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::add_permission_input::Builder,
}
impl AddPermission {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::AddPermissionOutput,
smithy_http::result::SdkError<crate::error::AddPermissionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function, version, or alias.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias).</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN.
/// If you specify only the function name, it is limited to 64 characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>A statement identifier that differentiates the statement from others in the same policy.</p>
pub fn statement_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.statement_id(inp);
self
}
pub fn set_statement_id(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_statement_id(inp);
self
}
/// <p>The action that the principal can use on the function. For example, <code>lambda:InvokeFunction</code> or
/// <code>lambda:GetFunction</code>.</p>
pub fn action(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.action(inp);
self
}
pub fn set_action(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_action(inp);
self
}
/// <p>The AWS service or account that invokes the function. If you specify a service, use <code>SourceArn</code> or
/// <code>SourceAccount</code> to limit who can invoke the function through that service.</p>
pub fn principal(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.principal(inp);
self
}
pub fn set_principal(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_principal(inp);
self
}
/// <p>For AWS services, the ARN of the AWS resource that invokes the function. For example, an Amazon S3 bucket or
/// Amazon SNS topic.</p>
pub fn source_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.source_arn(inp);
self
}
pub fn set_source_arn(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_source_arn(inp);
self
}
/// <p>For Amazon S3, the ID of the account that owns the resource. Use this together with <code>SourceArn</code> to
/// ensure that the resource is owned by the specified account. It is possible for an Amazon S3 bucket to be deleted
/// by its owner and recreated by another account.</p>
pub fn source_account(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.source_account(inp);
self
}
pub fn set_source_account(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_source_account(inp);
self
}
/// <p>For Alexa Smart Home functions, a token that must be supplied by the invoker.</p>
pub fn event_source_token(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.event_source_token(inp);
self
}
pub fn set_event_source_token(
mut self,
inp: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_event_source_token(inp);
self
}
/// <p>Specify a version or alias to add permissions to a published version of the function.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
/// <p>Only update the policy if the revision ID matches the ID that's specified. Use this option to avoid modifying a
/// policy that has changed since you last read it.</p>
pub fn revision_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.revision_id(inp);
self
}
pub fn set_revision_id(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_revision_id(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct CreateAlias {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::create_alias_input::Builder,
}
impl CreateAlias {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::CreateAliasOutput,
smithy_http::result::SdkError<crate::error::CreateAliasError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The name of the alias.</p>
pub fn name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.name(inp);
self
}
pub fn set_name(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_name(inp);
self
}
/// <p>The function version that the alias invokes.</p>
pub fn function_version(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_version(inp);
self
}
pub fn set_function_version(
mut self,
inp: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_function_version(inp);
self
}
/// <p>A description of the alias.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
pub fn set_description(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(inp);
self
}
/// <p>The <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html#configuring-alias-routing">routing
/// configuration</a> of the alias.</p>
pub fn routing_config(mut self, inp: crate::model::AliasRoutingConfiguration) -> Self {
self.inner = self.inner.routing_config(inp);
self
}
pub fn set_routing_config(
mut self,
inp: std::option::Option<crate::model::AliasRoutingConfiguration>,
) -> Self {
self.inner = self.inner.set_routing_config(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct CreateCodeSigningConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::create_code_signing_config_input::Builder,
}
impl CreateCodeSigningConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::CreateCodeSigningConfigOutput,
smithy_http::result::SdkError<crate::error::CreateCodeSigningConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>Descriptive name for this code signing configuration.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
pub fn set_description(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(inp);
self
}
/// <p>Signing profiles for this code signing configuration.</p>
pub fn allowed_publishers(mut self, inp: crate::model::AllowedPublishers) -> Self {
self.inner = self.inner.allowed_publishers(inp);
self
}
pub fn set_allowed_publishers(
mut self,
inp: std::option::Option<crate::model::AllowedPublishers>,
) -> Self {
self.inner = self.inner.set_allowed_publishers(inp);
self
}
/// <p>The code signing policies define the actions to take if the validation checks fail. </p>
pub fn code_signing_policies(mut self, inp: crate::model::CodeSigningPolicies) -> Self {
self.inner = self.inner.code_signing_policies(inp);
self
}
pub fn set_code_signing_policies(
mut self,
inp: std::option::Option<crate::model::CodeSigningPolicies>,
) -> Self {
self.inner = self.inner.set_code_signing_policies(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct CreateEventSourceMapping {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::create_event_source_mapping_input::Builder,
}
impl CreateEventSourceMapping {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::CreateEventSourceMappingOutput,
smithy_http::result::SdkError<crate::error::CreateEventSourceMappingError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the event source.</p>
/// <ul>
/// <li>
/// <p>
/// <b>Amazon Kinesis</b> - The ARN of the data stream or a stream consumer.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon DynamoDB Streams</b> - The ARN of the stream.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon Simple Queue Service</b> - The ARN of the queue.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon Managed Streaming for Apache Kafka</b> - The ARN of the cluster.</p>
/// </li>
/// </ul>
pub fn event_source_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.event_source_arn(inp);
self
}
pub fn set_event_source_arn(
mut self,
inp: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_event_source_arn(inp);
self
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Version or Alias ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction:PROD</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it's limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>If true, the event source mapping is active. Set to false to pause polling and invocation.</p>
pub fn enabled(mut self, inp: bool) -> Self {
self.inner = self.inner.enabled(inp);
self
}
pub fn set_enabled(mut self, inp: std::option::Option<bool>) -> Self {
self.inner = self.inner.set_enabled(inp);
self
}
/// <p>The maximum number of items to retrieve in a single batch.</p>
/// <ul>
/// <li>
/// <p>
/// <b>Amazon Kinesis</b> - Default 100. Max 10,000.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon DynamoDB Streams</b> - Default 100. Max 1,000.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon Simple Queue Service</b> - Default 10. For standard queues the max is 10,000. For FIFO queues the max is 10.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon Managed Streaming for Apache Kafka</b> - Default 100. Max 10,000.</p>
/// </li>
/// <li>
/// <p>
/// <b>Self-Managed Apache Kafka</b> - Default 100. Max 10,000.</p>
/// </li>
/// </ul>
pub fn batch_size(mut self, inp: i32) -> Self {
self.inner = self.inner.batch_size(inp);
self
}
pub fn set_batch_size(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_batch_size(inp);
self
}
/// <p>(Streams and SQS standard queues) The maximum amount of time to gather records before invoking the function, in seconds.</p>
pub fn maximum_batching_window_in_seconds(mut self, inp: i32) -> Self {
self.inner = self.inner.maximum_batching_window_in_seconds(inp);
self
}
pub fn set_maximum_batching_window_in_seconds(
mut self,
inp: std::option::Option<i32>,
) -> Self {
self.inner = self.inner.set_maximum_batching_window_in_seconds(inp);
self
}
/// <p>(Streams) The number of batches to process from each shard concurrently.</p>
pub fn parallelization_factor(mut self, inp: i32) -> Self {
self.inner = self.inner.parallelization_factor(inp);
self
}
pub fn set_parallelization_factor(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_parallelization_factor(inp);
self
}
/// <p>The position in a stream from which to start reading. Required for Amazon Kinesis, Amazon DynamoDB, and Amazon MSK Streams
/// sources. <code>AT_TIMESTAMP</code> is only supported for Amazon Kinesis streams.</p>
pub fn starting_position(mut self, inp: crate::model::EventSourcePosition) -> Self {
self.inner = self.inner.starting_position(inp);
self
}
pub fn set_starting_position(
mut self,
inp: std::option::Option<crate::model::EventSourcePosition>,
) -> Self {
self.inner = self.inner.set_starting_position(inp);
self
}
/// <p>With <code>StartingPosition</code> set to <code>AT_TIMESTAMP</code>, the time from which to start
/// reading.</p>
pub fn starting_position_timestamp(mut self, inp: smithy_types::Instant) -> Self {
self.inner = self.inner.starting_position_timestamp(inp);
self
}
pub fn set_starting_position_timestamp(
mut self,
inp: std::option::Option<smithy_types::Instant>,
) -> Self {
self.inner = self.inner.set_starting_position_timestamp(inp);
self
}
/// <p>(Streams) An Amazon SQS queue or Amazon SNS topic destination for discarded records.</p>
pub fn destination_config(mut self, inp: crate::model::DestinationConfig) -> Self {
self.inner = self.inner.destination_config(inp);
self
}
pub fn set_destination_config(
mut self,
inp: std::option::Option<crate::model::DestinationConfig>,
) -> Self {
self.inner = self.inner.set_destination_config(inp);
self
}
/// <p>(Streams) Discard records older than the specified age. The default value is infinite (-1).</p>
pub fn maximum_record_age_in_seconds(mut self, inp: i32) -> Self {
self.inner = self.inner.maximum_record_age_in_seconds(inp);
self
}
pub fn set_maximum_record_age_in_seconds(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_maximum_record_age_in_seconds(inp);
self
}
/// <p>(Streams) If the function returns an error, split the batch in two and retry.</p>
pub fn bisect_batch_on_function_error(mut self, inp: bool) -> Self {
self.inner = self.inner.bisect_batch_on_function_error(inp);
self
}
pub fn set_bisect_batch_on_function_error(
mut self,
inp: std::option::Option<bool>,
) -> Self {
self.inner = self.inner.set_bisect_batch_on_function_error(inp);
self
}
/// <p>(Streams) Discard records after the specified number of retries. The default value is infinite (-1). When set to infinite (-1), failed records will be retried until the record expires.</p>
pub fn maximum_retry_attempts(mut self, inp: i32) -> Self {
self.inner = self.inner.maximum_retry_attempts(inp);
self
}
pub fn set_maximum_retry_attempts(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_maximum_retry_attempts(inp);
self
}
/// <p>(Streams) The duration in seconds of a processing window. The range is between 1 second up to 900 seconds.</p>
pub fn tumbling_window_in_seconds(mut self, inp: i32) -> Self {
self.inner = self.inner.tumbling_window_in_seconds(inp);
self
}
pub fn set_tumbling_window_in_seconds(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_tumbling_window_in_seconds(inp);
self
}
/// <p>The name of the Kafka topic.</p>
pub fn topics(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.topics(inp);
self
}
pub fn set_topics(
mut self,
inp: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_topics(inp);
self
}
/// <p>
/// (MQ) The name of the Amazon MQ broker destination queue to consume.
/// </p>
pub fn queues(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.queues(inp);
self
}
pub fn set_queues(
mut self,
inp: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_queues(inp);
self
}
/// <p>An array of the authentication protocol, or the VPC components to secure your event source.</p>
pub fn source_access_configurations(
mut self,
inp: impl Into<crate::model::SourceAccessConfiguration>,
) -> Self {
self.inner = self.inner.source_access_configurations(inp);
self
}
pub fn set_source_access_configurations(
mut self,
inp: std::option::Option<std::vec::Vec<crate::model::SourceAccessConfiguration>>,
) -> Self {
self.inner = self.inner.set_source_access_configurations(inp);
self
}
/// <p>The Self-Managed Apache Kafka cluster to send records.</p>
pub fn self_managed_event_source(
mut self,
inp: crate::model::SelfManagedEventSource,
) -> Self {
self.inner = self.inner.self_managed_event_source(inp);
self
}
pub fn set_self_managed_event_source(
mut self,
inp: std::option::Option<crate::model::SelfManagedEventSource>,
) -> Self {
self.inner = self.inner.set_self_managed_event_source(inp);
self
}
/// <p>(Streams) A list of current response type enums applied to the event source mapping.</p>
pub fn function_response_types(
mut self,
inp: impl Into<crate::model::FunctionResponseType>,
) -> Self {
self.inner = self.inner.function_response_types(inp);
self
}
pub fn set_function_response_types(
mut self,
inp: std::option::Option<std::vec::Vec<crate::model::FunctionResponseType>>,
) -> Self {
self.inner = self.inner.set_function_response_types(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct CreateFunction {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::create_function_input::Builder,
}
impl CreateFunction {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::CreateFunctionOutput,
smithy_http::result::SdkError<crate::error::CreateFunctionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The identifier of the function's <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html">runtime</a>.</p>
pub fn runtime(mut self, inp: crate::model::Runtime) -> Self {
self.inner = self.inner.runtime(inp);
self
}
pub fn set_runtime(mut self, inp: std::option::Option<crate::model::Runtime>) -> Self {
self.inner = self.inner.set_runtime(inp);
self
}
/// <p>The Amazon Resource Name (ARN) of the function's execution role.</p>
pub fn role(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.role(inp);
self
}
pub fn set_role(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_role(inp);
self
}
/// <p>The name of the method within your code that Lambda calls to execute your function. The format includes the
/// file name. It can also include namespaces and other qualifiers, depending on the runtime. For more information,
/// see <a href="https://docs.aws.amazon.com/lambda/latest/dg/programming-model-v2.html">Programming Model</a>.</p>
pub fn handler(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.handler(inp);
self
}
pub fn set_handler(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_handler(inp);
self
}
/// <p>The code for the function.</p>
pub fn code(mut self, inp: crate::model::FunctionCode) -> Self {
self.inner = self.inner.code(inp);
self
}
pub fn set_code(mut self, inp: std::option::Option<crate::model::FunctionCode>) -> Self {
self.inner = self.inner.set_code(inp);
self
}
/// <p>A description of the function.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
pub fn set_description(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(inp);
self
}
/// <p>The amount of time that Lambda allows a function to run before stopping it. The default is 3 seconds. The
/// maximum allowed value is 900 seconds.</p>
pub fn timeout(mut self, inp: i32) -> Self {
self.inner = self.inner.timeout(inp);
self
}
pub fn set_timeout(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_timeout(inp);
self
}
/// <p>The amount of memory available to the function at runtime. Increasing the function's memory also increases its CPU
/// allocation. The default value is 128 MB. The value can be any multiple of 1 MB.</p>
pub fn memory_size(mut self, inp: i32) -> Self {
self.inner = self.inner.memory_size(inp);
self
}
pub fn set_memory_size(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_memory_size(inp);
self
}
/// <p>Set to true to publish the first version of the function during creation.</p>
pub fn publish(mut self, inp: bool) -> Self {
self.inner = self.inner.publish(inp);
self
}
pub fn set_publish(mut self, inp: bool) -> Self {
self.inner = self.inner.set_publish(inp);
self
}
/// <p>For network connectivity to AWS resources in a VPC, specify a list of security groups and subnets in the VPC.
/// When you connect a function to a VPC, it can only access resources and the internet through that VPC. For more
/// information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html">VPC Settings</a>.</p>
pub fn vpc_config(mut self, inp: crate::model::VpcConfig) -> Self {
self.inner = self.inner.vpc_config(inp);
self
}
pub fn set_vpc_config(mut self, inp: std::option::Option<crate::model::VpcConfig>) -> Self {
self.inner = self.inner.set_vpc_config(inp);
self
}
/// <p>The type of deployment package. Set to <code>Image</code> for container image and set <code>Zip</code> for ZIP archive.</p>
pub fn package_type(mut self, inp: crate::model::PackageType) -> Self {
self.inner = self.inner.package_type(inp);
self
}
pub fn set_package_type(
mut self,
inp: std::option::Option<crate::model::PackageType>,
) -> Self {
self.inner = self.inner.set_package_type(inp);
self
}
/// <p>A dead letter queue configuration that specifies the queue or topic where Lambda sends asynchronous events
/// when they fail processing. For more information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#dlq">Dead Letter Queues</a>.</p>
pub fn dead_letter_config(mut self, inp: crate::model::DeadLetterConfig) -> Self {
self.inner = self.inner.dead_letter_config(inp);
self
}
pub fn set_dead_letter_config(
mut self,
inp: std::option::Option<crate::model::DeadLetterConfig>,
) -> Self {
self.inner = self.inner.set_dead_letter_config(inp);
self
}
/// <p>Environment variables that are accessible from function code during execution.</p>
pub fn environment(mut self, inp: crate::model::Environment) -> Self {
self.inner = self.inner.environment(inp);
self
}
pub fn set_environment(
mut self,
inp: std::option::Option<crate::model::Environment>,
) -> Self {
self.inner = self.inner.set_environment(inp);
self
}
/// <p>The ARN of the AWS Key Management Service (AWS KMS) key that's used to encrypt your function's environment
/// variables. If it's not provided, AWS Lambda uses a default service key.</p>
pub fn kms_key_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.kms_key_arn(inp);
self
}
pub fn set_kms_key_arn(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_kms_key_arn(inp);
self
}
/// <p>Set <code>Mode</code> to <code>Active</code> to sample and trace a subset of incoming requests with AWS
/// X-Ray.</p>
pub fn tracing_config(mut self, inp: crate::model::TracingConfig) -> Self {
self.inner = self.inner.tracing_config(inp);
self
}
pub fn set_tracing_config(
mut self,
inp: std::option::Option<crate::model::TracingConfig>,
) -> Self {
self.inner = self.inner.set_tracing_config(inp);
self
}
/// <p>A list of <a href="https://docs.aws.amazon.com/lambda/latest/dg/tagging.html">tags</a> to apply to the
/// function.</p>
pub fn tags(
mut self,
k: impl Into<std::string::String>,
v: impl Into<std::string::String>,
) -> Self {
self.inner = self.inner.tags(k, v);
self
}
pub fn set_tags(
mut self,
inp: std::option::Option<
std::collections::HashMap<std::string::String, std::string::String>,
>,
) -> Self {
self.inner = self.inner.set_tags(inp);
self
}
/// <p>A list of <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">function layers</a>
/// to add to the function's execution environment. Specify each layer by its ARN, including the version.</p>
pub fn layers(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.layers(inp);
self
}
pub fn set_layers(
mut self,
inp: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_layers(inp);
self
}
/// <p>Connection settings for an Amazon EFS file system.</p>
pub fn file_system_configs(
mut self,
inp: impl Into<crate::model::FileSystemConfig>,
) -> Self {
self.inner = self.inner.file_system_configs(inp);
self
}
pub fn set_file_system_configs(
mut self,
inp: std::option::Option<std::vec::Vec<crate::model::FileSystemConfig>>,
) -> Self {
self.inner = self.inner.set_file_system_configs(inp);
self
}
/// <p>
/// <a href="https://docs.aws.amazon.com/lambda/latest/dg/images-parms.html">Container image configuration
/// values</a> that override the values in the container image Dockerfile.</p>
pub fn image_config(mut self, inp: crate::model::ImageConfig) -> Self {
self.inner = self.inner.image_config(inp);
self
}
pub fn set_image_config(
mut self,
inp: std::option::Option<crate::model::ImageConfig>,
) -> Self {
self.inner = self.inner.set_image_config(inp);
self
}
/// <p>To enable code signing for this function, specify the ARN of a code-signing configuration. A code-signing configuration
/// includes a set of signing profiles, which define the trusted publishers for this function.</p>
pub fn code_signing_config_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.code_signing_config_arn(inp);
self
}
pub fn set_code_signing_config_arn(
mut self,
inp: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_code_signing_config_arn(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteAlias {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::delete_alias_input::Builder,
}
impl DeleteAlias {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::DeleteAliasOutput,
smithy_http::result::SdkError<crate::error::DeleteAliasError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The name of the alias.</p>
pub fn name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.name(inp);
self
}
pub fn set_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_name(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteCodeSigningConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::delete_code_signing_config_input::Builder,
}
impl DeleteCodeSigningConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::DeleteCodeSigningConfigOutput,
smithy_http::result::SdkError<crate::error::DeleteCodeSigningConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The The Amazon Resource Name (ARN) of the code signing configuration.</p>
pub fn code_signing_config_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.code_signing_config_arn(inp);
self
}
pub fn set_code_signing_config_arn(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_code_signing_config_arn(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteEventSourceMapping {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::delete_event_source_mapping_input::Builder,
}
impl DeleteEventSourceMapping {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::DeleteEventSourceMappingOutput,
smithy_http::result::SdkError<crate::error::DeleteEventSourceMappingError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The identifier of the event source mapping.</p>
pub fn uuid(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.uuid(inp);
self
}
pub fn set_uuid(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_uuid(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteFunction {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::delete_function_input::Builder,
}
impl DeleteFunction {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::DeleteFunctionOutput,
smithy_http::result::SdkError<crate::error::DeleteFunctionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function or version.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:1</code> (with version).</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN.
/// If you specify only the function name, it is limited to 64 characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>Specify a version to delete. You can't delete a version that's referenced by an alias.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteFunctionCodeSigningConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::delete_function_code_signing_config_input::Builder,
}
impl DeleteFunctionCodeSigningConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::DeleteFunctionCodeSigningConfigOutput,
smithy_http::result::SdkError<crate::error::DeleteFunctionCodeSigningConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteFunctionConcurrency {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::delete_function_concurrency_input::Builder,
}
impl DeleteFunctionConcurrency {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::DeleteFunctionConcurrencyOutput,
smithy_http::result::SdkError<crate::error::DeleteFunctionConcurrencyError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteFunctionEventInvokeConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::delete_function_event_invoke_config_input::Builder,
}
impl DeleteFunctionEventInvokeConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::DeleteFunctionEventInvokeConfigOutput,
smithy_http::result::SdkError<crate::error::DeleteFunctionEventInvokeConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function, version, or alias.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias).</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN.
/// If you specify only the function name, it is limited to 64 characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>A version number or alias name.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteLayerVersion {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::delete_layer_version_input::Builder,
}
impl DeleteLayerVersion {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::DeleteLayerVersionOutput,
smithy_http::result::SdkError<crate::error::DeleteLayerVersionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name or Amazon Resource Name (ARN) of the layer.</p>
pub fn layer_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.layer_name(inp);
self
}
pub fn set_layer_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_layer_name(inp);
self
}
/// <p>The version number.</p>
pub fn version_number(mut self, inp: i64) -> Self {
self.inner = self.inner.version_number(inp);
self
}
pub fn set_version_number(mut self, inp: i64) -> Self {
self.inner = self.inner.set_version_number(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct DeleteProvisionedConcurrencyConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::delete_provisioned_concurrency_config_input::Builder,
}
impl DeleteProvisionedConcurrencyConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::DeleteProvisionedConcurrencyConfigOutput,
smithy_http::result::SdkError<crate::error::DeleteProvisionedConcurrencyConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The version number or alias name.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetAccountSettings {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_account_settings_input::Builder,
}
impl GetAccountSettings {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetAccountSettingsOutput,
smithy_http::result::SdkError<crate::error::GetAccountSettingsError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
}
#[derive(std::fmt::Debug)]
pub struct GetAlias {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_alias_input::Builder,
}
impl GetAlias {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetAliasOutput,
smithy_http::result::SdkError<crate::error::GetAliasError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The name of the alias.</p>
pub fn name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.name(inp);
self
}
pub fn set_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_name(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetCodeSigningConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_code_signing_config_input::Builder,
}
impl GetCodeSigningConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetCodeSigningConfigOutput,
smithy_http::result::SdkError<crate::error::GetCodeSigningConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The The Amazon Resource Name (ARN) of the code signing configuration. </p>
pub fn code_signing_config_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.code_signing_config_arn(inp);
self
}
pub fn set_code_signing_config_arn(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_code_signing_config_arn(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetEventSourceMapping {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_event_source_mapping_input::Builder,
}
impl GetEventSourceMapping {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetEventSourceMappingOutput,
smithy_http::result::SdkError<crate::error::GetEventSourceMappingError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The identifier of the event source mapping.</p>
pub fn uuid(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.uuid(inp);
self
}
pub fn set_uuid(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_uuid(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetFunction {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_function_input::Builder,
}
impl GetFunction {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetFunctionOutput,
smithy_http::result::SdkError<crate::error::GetFunctionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function, version, or alias.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias).</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN.
/// If you specify only the function name, it is limited to 64 characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>Specify a version or alias to get details about a published version of the function.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetFunctionCodeSigningConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_function_code_signing_config_input::Builder,
}
impl GetFunctionCodeSigningConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetFunctionCodeSigningConfigOutput,
smithy_http::result::SdkError<crate::error::GetFunctionCodeSigningConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetFunctionConcurrency {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_function_concurrency_input::Builder,
}
impl GetFunctionConcurrency {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetFunctionConcurrencyOutput,
smithy_http::result::SdkError<crate::error::GetFunctionConcurrencyError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetFunctionConfiguration {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_function_configuration_input::Builder,
}
impl GetFunctionConfiguration {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetFunctionConfigurationOutput,
smithy_http::result::SdkError<crate::error::GetFunctionConfigurationError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function, version, or alias.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias).</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN.
/// If you specify only the function name, it is limited to 64 characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>Specify a version or alias to get details about a published version of the function.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetFunctionEventInvokeConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_function_event_invoke_config_input::Builder,
}
impl GetFunctionEventInvokeConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetFunctionEventInvokeConfigOutput,
smithy_http::result::SdkError<crate::error::GetFunctionEventInvokeConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function, version, or alias.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias).</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN.
/// If you specify only the function name, it is limited to 64 characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>A version number or alias name.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetLayerVersion {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_layer_version_input::Builder,
}
impl GetLayerVersion {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetLayerVersionOutput,
smithy_http::result::SdkError<crate::error::GetLayerVersionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name or Amazon Resource Name (ARN) of the layer.</p>
pub fn layer_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.layer_name(inp);
self
}
pub fn set_layer_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_layer_name(inp);
self
}
/// <p>The version number.</p>
pub fn version_number(mut self, inp: i64) -> Self {
self.inner = self.inner.version_number(inp);
self
}
pub fn set_version_number(mut self, inp: i64) -> Self {
self.inner = self.inner.set_version_number(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetLayerVersionByArn {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_layer_version_by_arn_input::Builder,
}
impl GetLayerVersionByArn {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetLayerVersionByArnOutput,
smithy_http::result::SdkError<crate::error::GetLayerVersionByArnError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The ARN of the layer version.</p>
pub fn arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.arn(inp);
self
}
pub fn set_arn(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_arn(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetLayerVersionPolicy {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_layer_version_policy_input::Builder,
}
impl GetLayerVersionPolicy {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetLayerVersionPolicyOutput,
smithy_http::result::SdkError<crate::error::GetLayerVersionPolicyError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name or Amazon Resource Name (ARN) of the layer.</p>
pub fn layer_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.layer_name(inp);
self
}
pub fn set_layer_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_layer_name(inp);
self
}
/// <p>The version number.</p>
pub fn version_number(mut self, inp: i64) -> Self {
self.inner = self.inner.version_number(inp);
self
}
pub fn set_version_number(mut self, inp: i64) -> Self {
self.inner = self.inner.set_version_number(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetPolicy {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_policy_input::Builder,
}
impl GetPolicy {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetPolicyOutput,
smithy_http::result::SdkError<crate::error::GetPolicyError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function, version, or alias.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias).</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN.
/// If you specify only the function name, it is limited to 64 characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>Specify a version or alias to get the policy for that resource.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct GetProvisionedConcurrencyConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::get_provisioned_concurrency_config_input::Builder,
}
impl GetProvisionedConcurrencyConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::GetProvisionedConcurrencyConfigOutput,
smithy_http::result::SdkError<crate::error::GetProvisionedConcurrencyConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The version number or alias name.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct Invoke {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::invoke_input::Builder,
}
impl Invoke {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::InvokeOutput,
smithy_http::result::SdkError<crate::error::InvokeError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function, version, or alias.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias).</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN.
/// If you specify only the function name, it is limited to 64 characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>Choose from the following options.</p>
/// <ul>
/// <li>
/// <p>
/// <code>RequestResponse</code> (default) - Invoke the function synchronously. Keep the connection open until
/// the function returns a response or times out. The API response includes the function response and additional
/// data.</p>
/// </li>
/// <li>
/// <p>
/// <code>Event</code> - Invoke the function asynchronously. Send events that fail multiple times to the
/// function's dead-letter queue (if it's configured). The API response only includes a status code.</p>
/// </li>
/// <li>
/// <p>
/// <code>DryRun</code> - Validate parameter values and verify that the user or role has permission to invoke
/// the function.</p>
/// </li>
/// </ul>
pub fn invocation_type(mut self, inp: crate::model::InvocationType) -> Self {
self.inner = self.inner.invocation_type(inp);
self
}
pub fn set_invocation_type(
mut self,
inp: std::option::Option<crate::model::InvocationType>,
) -> Self {
self.inner = self.inner.set_invocation_type(inp);
self
}
/// <p>Set to <code>Tail</code> to include the execution log in the response.</p>
pub fn log_type(mut self, inp: crate::model::LogType) -> Self {
self.inner = self.inner.log_type(inp);
self
}
pub fn set_log_type(mut self, inp: std::option::Option<crate::model::LogType>) -> Self {
self.inner = self.inner.set_log_type(inp);
self
}
/// <p>Up to 3583 bytes of base64-encoded data about the invoking client to pass to the function in the context
/// object.</p>
pub fn client_context(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.client_context(inp);
self
}
pub fn set_client_context(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_client_context(inp);
self
}
/// <p>The JSON that you want to provide to your Lambda function as input.</p>
pub fn payload(mut self, inp: smithy_types::Blob) -> Self {
self.inner = self.inner.payload(inp);
self
}
pub fn set_payload(mut self, inp: std::option::Option<smithy_types::Blob>) -> Self {
self.inner = self.inner.set_payload(inp);
self
}
/// <p>Specify a version or alias to invoke a published version of the function.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct InvokeAsync {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::invoke_async_input::Builder,
}
impl InvokeAsync {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::InvokeAsyncOutput,
smithy_http::result::SdkError<crate::error::InvokeAsyncError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The JSON that you want to provide to your Lambda function as input.</p>
pub fn invoke_args(mut self, inp: smithy_http::byte_stream::ByteStream) -> Self {
self.inner = self.inner.invoke_args(inp);
self
}
pub fn set_invoke_args(mut self, inp: smithy_http::byte_stream::ByteStream) -> Self {
self.inner = self.inner.set_invoke_args(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListAliases {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::list_aliases_input::Builder,
}
impl ListAliases {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::ListAliasesOutput,
smithy_http::result::SdkError<crate::error::ListAliasesError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>Specify a function version to only list aliases that invoke that version.</p>
pub fn function_version(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_version(inp);
self
}
pub fn set_function_version(
mut self,
inp: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_function_version(inp);
self
}
/// <p>Specify the pagination token that's returned by a previous request to retrieve the next page of results.</p>
pub fn marker(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.marker(inp);
self
}
pub fn set_marker(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_marker(inp);
self
}
/// <p>Limit the number of aliases returned.</p>
pub fn max_items(mut self, inp: i32) -> Self {
self.inner = self.inner.max_items(inp);
self
}
pub fn set_max_items(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_items(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListCodeSigningConfigs {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::list_code_signing_configs_input::Builder,
}
impl ListCodeSigningConfigs {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::ListCodeSigningConfigsOutput,
smithy_http::result::SdkError<crate::error::ListCodeSigningConfigsError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>Specify the pagination token that's returned by a previous request to retrieve the next page of results.</p>
pub fn marker(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.marker(inp);
self
}
pub fn set_marker(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_marker(inp);
self
}
/// <p>Maximum number of items to return.</p>
pub fn max_items(mut self, inp: i32) -> Self {
self.inner = self.inner.max_items(inp);
self
}
pub fn set_max_items(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_items(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListEventSourceMappings {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::list_event_source_mappings_input::Builder,
}
impl ListEventSourceMappings {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::ListEventSourceMappingsOutput,
smithy_http::result::SdkError<crate::error::ListEventSourceMappingsError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The Amazon Resource Name (ARN) of the event source.</p>
/// <ul>
/// <li>
/// <p>
/// <b>Amazon Kinesis</b> - The ARN of the data stream or a stream consumer.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon DynamoDB Streams</b> - The ARN of the stream.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon Simple Queue Service</b> - The ARN of the queue.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon Managed Streaming for Apache Kafka</b> - The ARN of the cluster.</p>
/// </li>
/// </ul>
pub fn event_source_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.event_source_arn(inp);
self
}
pub fn set_event_source_arn(
mut self,
inp: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_event_source_arn(inp);
self
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Version or Alias ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction:PROD</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it's limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>A pagination token returned by a previous call.</p>
pub fn marker(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.marker(inp);
self
}
pub fn set_marker(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_marker(inp);
self
}
/// <p>The maximum number of event source mappings to return.</p>
pub fn max_items(mut self, inp: i32) -> Self {
self.inner = self.inner.max_items(inp);
self
}
pub fn set_max_items(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_items(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListFunctionEventInvokeConfigs {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::list_function_event_invoke_configs_input::Builder,
}
impl ListFunctionEventInvokeConfigs {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::ListFunctionEventInvokeConfigsOutput,
smithy_http::result::SdkError<crate::error::ListFunctionEventInvokeConfigsError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>Specify the pagination token that's returned by a previous request to retrieve the next page of results.</p>
pub fn marker(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.marker(inp);
self
}
pub fn set_marker(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_marker(inp);
self
}
/// <p>The maximum number of configurations to return.</p>
pub fn max_items(mut self, inp: i32) -> Self {
self.inner = self.inner.max_items(inp);
self
}
pub fn set_max_items(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_items(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListFunctions {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::list_functions_input::Builder,
}
impl ListFunctions {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::ListFunctionsOutput,
smithy_http::result::SdkError<crate::error::ListFunctionsError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>For Lambda@Edge functions, the AWS Region of the master function. For example, <code>us-east-1</code> filters
/// the list of functions to only include Lambda@Edge functions replicated from a master function in US East (N.
/// Virginia). If specified, you must set <code>FunctionVersion</code> to <code>ALL</code>.</p>
pub fn master_region(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.master_region(inp);
self
}
pub fn set_master_region(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_master_region(inp);
self
}
/// <p>Set to <code>ALL</code> to include entries for all published versions of each function.</p>
pub fn function_version(mut self, inp: crate::model::FunctionVersion) -> Self {
self.inner = self.inner.function_version(inp);
self
}
pub fn set_function_version(
mut self,
inp: std::option::Option<crate::model::FunctionVersion>,
) -> Self {
self.inner = self.inner.set_function_version(inp);
self
}
/// <p>Specify the pagination token that's returned by a previous request to retrieve the next page of results.</p>
pub fn marker(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.marker(inp);
self
}
pub fn set_marker(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_marker(inp);
self
}
/// <p>The maximum number of functions to return in the response. Note that <code>ListFunctions</code> returns a maximum of 50 items in each response,
/// even if you set the number higher.</p>
pub fn max_items(mut self, inp: i32) -> Self {
self.inner = self.inner.max_items(inp);
self
}
pub fn set_max_items(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_items(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListFunctionsByCodeSigningConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::list_functions_by_code_signing_config_input::Builder,
}
impl ListFunctionsByCodeSigningConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::ListFunctionsByCodeSigningConfigOutput,
smithy_http::result::SdkError<crate::error::ListFunctionsByCodeSigningConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The The Amazon Resource Name (ARN) of the code signing configuration.</p>
pub fn code_signing_config_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.code_signing_config_arn(inp);
self
}
pub fn set_code_signing_config_arn(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_code_signing_config_arn(inp);
self
}
/// <p>Specify the pagination token that's returned by a previous request to retrieve the next page of results.</p>
pub fn marker(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.marker(inp);
self
}
pub fn set_marker(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_marker(inp);
self
}
/// <p>Maximum number of items to return.</p>
pub fn max_items(mut self, inp: i32) -> Self {
self.inner = self.inner.max_items(inp);
self
}
pub fn set_max_items(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_items(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListLayers {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::list_layers_input::Builder,
}
impl ListLayers {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::ListLayersOutput,
smithy_http::result::SdkError<crate::error::ListLayersError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>A runtime identifier. For example, <code>go1.x</code>.</p>
pub fn compatible_runtime(mut self, inp: crate::model::Runtime) -> Self {
self.inner = self.inner.compatible_runtime(inp);
self
}
pub fn set_compatible_runtime(
mut self,
inp: std::option::Option<crate::model::Runtime>,
) -> Self {
self.inner = self.inner.set_compatible_runtime(inp);
self
}
/// <p>A pagination token returned by a previous call.</p>
pub fn marker(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.marker(inp);
self
}
pub fn set_marker(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_marker(inp);
self
}
/// <p>The maximum number of layers to return.</p>
pub fn max_items(mut self, inp: i32) -> Self {
self.inner = self.inner.max_items(inp);
self
}
pub fn set_max_items(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_items(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListLayerVersions {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::list_layer_versions_input::Builder,
}
impl ListLayerVersions {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::ListLayerVersionsOutput,
smithy_http::result::SdkError<crate::error::ListLayerVersionsError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>A runtime identifier. For example, <code>go1.x</code>.</p>
pub fn compatible_runtime(mut self, inp: crate::model::Runtime) -> Self {
self.inner = self.inner.compatible_runtime(inp);
self
}
pub fn set_compatible_runtime(
mut self,
inp: std::option::Option<crate::model::Runtime>,
) -> Self {
self.inner = self.inner.set_compatible_runtime(inp);
self
}
/// <p>The name or Amazon Resource Name (ARN) of the layer.</p>
pub fn layer_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.layer_name(inp);
self
}
pub fn set_layer_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_layer_name(inp);
self
}
/// <p>A pagination token returned by a previous call.</p>
pub fn marker(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.marker(inp);
self
}
pub fn set_marker(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_marker(inp);
self
}
/// <p>The maximum number of versions to return.</p>
pub fn max_items(mut self, inp: i32) -> Self {
self.inner = self.inner.max_items(inp);
self
}
pub fn set_max_items(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_items(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListProvisionedConcurrencyConfigs {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::list_provisioned_concurrency_configs_input::Builder,
}
impl ListProvisionedConcurrencyConfigs {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::ListProvisionedConcurrencyConfigsOutput,
smithy_http::result::SdkError<crate::error::ListProvisionedConcurrencyConfigsError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>Specify the pagination token that's returned by a previous request to retrieve the next page of results.</p>
pub fn marker(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.marker(inp);
self
}
pub fn set_marker(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_marker(inp);
self
}
/// <p>Specify a number to limit the number of configurations returned.</p>
pub fn max_items(mut self, inp: i32) -> Self {
self.inner = self.inner.max_items(inp);
self
}
pub fn set_max_items(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_items(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListTags {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::list_tags_input::Builder,
}
impl ListTags {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::ListTagsOutput,
smithy_http::result::SdkError<crate::error::ListTagsError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The function's Amazon Resource Name (ARN).</p>
pub fn resource(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.resource(inp);
self
}
pub fn set_resource(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_resource(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct ListVersionsByFunction {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::list_versions_by_function_input::Builder,
}
impl ListVersionsByFunction {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::ListVersionsByFunctionOutput,
smithy_http::result::SdkError<crate::error::ListVersionsByFunctionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>Specify the pagination token that's returned by a previous request to retrieve the next page of results.</p>
pub fn marker(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.marker(inp);
self
}
pub fn set_marker(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_marker(inp);
self
}
/// <p>The maximum number of versions to return.</p>
pub fn max_items(mut self, inp: i32) -> Self {
self.inner = self.inner.max_items(inp);
self
}
pub fn set_max_items(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_max_items(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct PublishLayerVersion {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::publish_layer_version_input::Builder,
}
impl PublishLayerVersion {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::PublishLayerVersionOutput,
smithy_http::result::SdkError<crate::error::PublishLayerVersionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name or Amazon Resource Name (ARN) of the layer.</p>
pub fn layer_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.layer_name(inp);
self
}
pub fn set_layer_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_layer_name(inp);
self
}
/// <p>The description of the version.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
pub fn set_description(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(inp);
self
}
/// <p>The function layer archive.</p>
pub fn content(mut self, inp: crate::model::LayerVersionContentInput) -> Self {
self.inner = self.inner.content(inp);
self
}
pub fn set_content(
mut self,
inp: std::option::Option<crate::model::LayerVersionContentInput>,
) -> Self {
self.inner = self.inner.set_content(inp);
self
}
/// <p>A list of compatible <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html">function
/// runtimes</a>. Used for filtering with <a>ListLayers</a> and <a>ListLayerVersions</a>.</p>
pub fn compatible_runtimes(mut self, inp: impl Into<crate::model::Runtime>) -> Self {
self.inner = self.inner.compatible_runtimes(inp);
self
}
pub fn set_compatible_runtimes(
mut self,
inp: std::option::Option<std::vec::Vec<crate::model::Runtime>>,
) -> Self {
self.inner = self.inner.set_compatible_runtimes(inp);
self
}
/// <p>The layer's software license. It can be any of the following:</p>
/// <ul>
/// <li>
/// <p>An <a href="https://spdx.org/licenses/">SPDX license identifier</a>. For example,
/// <code>MIT</code>.</p>
/// </li>
/// <li>
/// <p>The URL of a license hosted on the internet. For example,
/// <code>https://opensource.org/licenses/MIT</code>.</p>
/// </li>
/// <li>
/// <p>The full text of the license.</p>
/// </li>
/// </ul>
pub fn license_info(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.license_info(inp);
self
}
pub fn set_license_info(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_license_info(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct PublishVersion {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::publish_version_input::Builder,
}
impl PublishVersion {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::PublishVersionOutput,
smithy_http::result::SdkError<crate::error::PublishVersionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>Only publish a version if the hash value matches the value that's specified. Use this option to avoid
/// publishing a version if the function code has changed since you last updated it. You can get the hash for the
/// version that you uploaded from the output of <a>UpdateFunctionCode</a>.</p>
pub fn code_sha256(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.code_sha256(inp);
self
}
pub fn set_code_sha256(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_code_sha256(inp);
self
}
/// <p>A description for the version to override the description in the function configuration.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
pub fn set_description(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(inp);
self
}
/// <p>Only update the function if the revision ID matches the ID that's specified. Use this option to avoid
/// publishing a version if the function configuration has changed since you last updated it.</p>
pub fn revision_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.revision_id(inp);
self
}
pub fn set_revision_id(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_revision_id(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct PutFunctionCodeSigningConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::put_function_code_signing_config_input::Builder,
}
impl PutFunctionCodeSigningConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::PutFunctionCodeSigningConfigOutput,
smithy_http::result::SdkError<crate::error::PutFunctionCodeSigningConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The The Amazon Resource Name (ARN) of the code signing configuration.</p>
pub fn code_signing_config_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.code_signing_config_arn(inp);
self
}
pub fn set_code_signing_config_arn(
mut self,
inp: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_code_signing_config_arn(inp);
self
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct PutFunctionConcurrency {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::put_function_concurrency_input::Builder,
}
impl PutFunctionConcurrency {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::PutFunctionConcurrencyOutput,
smithy_http::result::SdkError<crate::error::PutFunctionConcurrencyError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The number of simultaneous executions to reserve for the function.</p>
pub fn reserved_concurrent_executions(mut self, inp: i32) -> Self {
self.inner = self.inner.reserved_concurrent_executions(inp);
self
}
pub fn set_reserved_concurrent_executions(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_reserved_concurrent_executions(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct PutFunctionEventInvokeConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::put_function_event_invoke_config_input::Builder,
}
impl PutFunctionEventInvokeConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::PutFunctionEventInvokeConfigOutput,
smithy_http::result::SdkError<crate::error::PutFunctionEventInvokeConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function, version, or alias.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias).</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN.
/// If you specify only the function name, it is limited to 64 characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>A version number or alias name.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
/// <p>The maximum number of times to retry when the function returns an error.</p>
pub fn maximum_retry_attempts(mut self, inp: i32) -> Self {
self.inner = self.inner.maximum_retry_attempts(inp);
self
}
pub fn set_maximum_retry_attempts(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_maximum_retry_attempts(inp);
self
}
/// <p>The maximum age of a request that Lambda sends to a function for processing.</p>
pub fn maximum_event_age_in_seconds(mut self, inp: i32) -> Self {
self.inner = self.inner.maximum_event_age_in_seconds(inp);
self
}
pub fn set_maximum_event_age_in_seconds(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_maximum_event_age_in_seconds(inp);
self
}
/// <p>A destination for events after they have been sent to a function for processing.</p>
/// <p class="title">
/// <b>Destinations</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function</b> - The Amazon Resource Name (ARN) of a Lambda function.</p>
/// </li>
/// <li>
/// <p>
/// <b>Queue</b> - The ARN of an SQS queue.</p>
/// </li>
/// <li>
/// <p>
/// <b>Topic</b> - The ARN of an SNS topic.</p>
/// </li>
/// <li>
/// <p>
/// <b>Event Bus</b> - The ARN of an Amazon EventBridge event bus.</p>
/// </li>
/// </ul>
pub fn destination_config(mut self, inp: crate::model::DestinationConfig) -> Self {
self.inner = self.inner.destination_config(inp);
self
}
pub fn set_destination_config(
mut self,
inp: std::option::Option<crate::model::DestinationConfig>,
) -> Self {
self.inner = self.inner.set_destination_config(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct PutProvisionedConcurrencyConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::put_provisioned_concurrency_config_input::Builder,
}
impl PutProvisionedConcurrencyConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::PutProvisionedConcurrencyConfigOutput,
smithy_http::result::SdkError<crate::error::PutProvisionedConcurrencyConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The version number or alias name.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
/// <p>The amount of provisioned concurrency to allocate for the version or alias.</p>
pub fn provisioned_concurrent_executions(mut self, inp: i32) -> Self {
self.inner = self.inner.provisioned_concurrent_executions(inp);
self
}
pub fn set_provisioned_concurrent_executions(
mut self,
inp: std::option::Option<i32>,
) -> Self {
self.inner = self.inner.set_provisioned_concurrent_executions(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct RemoveLayerVersionPermission {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::remove_layer_version_permission_input::Builder,
}
impl RemoveLayerVersionPermission {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::RemoveLayerVersionPermissionOutput,
smithy_http::result::SdkError<crate::error::RemoveLayerVersionPermissionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name or Amazon Resource Name (ARN) of the layer.</p>
pub fn layer_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.layer_name(inp);
self
}
pub fn set_layer_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_layer_name(inp);
self
}
/// <p>The version number.</p>
pub fn version_number(mut self, inp: i64) -> Self {
self.inner = self.inner.version_number(inp);
self
}
pub fn set_version_number(mut self, inp: i64) -> Self {
self.inner = self.inner.set_version_number(inp);
self
}
/// <p>The identifier that was specified when the statement was added.</p>
pub fn statement_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.statement_id(inp);
self
}
pub fn set_statement_id(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_statement_id(inp);
self
}
/// <p>Only update the policy if the revision ID matches the ID specified. Use this option to avoid modifying a
/// policy that has changed since you last read it.</p>
pub fn revision_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.revision_id(inp);
self
}
pub fn set_revision_id(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_revision_id(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct RemovePermission {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::remove_permission_input::Builder,
}
impl RemovePermission {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::RemovePermissionOutput,
smithy_http::result::SdkError<crate::error::RemovePermissionError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function, version, or alias.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias).</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN.
/// If you specify only the function name, it is limited to 64 characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>Statement ID of the permission to remove.</p>
pub fn statement_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.statement_id(inp);
self
}
pub fn set_statement_id(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_statement_id(inp);
self
}
/// <p>Specify a version or alias to remove permissions from a published version of the function.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
/// <p>Only update the policy if the revision ID matches the ID that's specified. Use this option to avoid modifying a
/// policy that has changed since you last read it.</p>
pub fn revision_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.revision_id(inp);
self
}
pub fn set_revision_id(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_revision_id(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct TagResource {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::tag_resource_input::Builder,
}
impl TagResource {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::TagResourceOutput,
smithy_http::result::SdkError<crate::error::TagResourceError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The function's Amazon Resource Name (ARN).</p>
pub fn resource(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.resource(inp);
self
}
pub fn set_resource(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_resource(inp);
self
}
/// <p>A list of tags to apply to the function.</p>
pub fn tags(
mut self,
k: impl Into<std::string::String>,
v: impl Into<std::string::String>,
) -> Self {
self.inner = self.inner.tags(k, v);
self
}
pub fn set_tags(
mut self,
inp: std::option::Option<
std::collections::HashMap<std::string::String, std::string::String>,
>,
) -> Self {
self.inner = self.inner.set_tags(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UntagResource {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::untag_resource_input::Builder,
}
impl UntagResource {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::UntagResourceOutput,
smithy_http::result::SdkError<crate::error::UntagResourceError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The function's Amazon Resource Name (ARN).</p>
pub fn resource(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.resource(inp);
self
}
pub fn set_resource(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_resource(inp);
self
}
/// <p>A list of tag keys to remove from the function.</p>
pub fn tag_keys(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.tag_keys(inp);
self
}
pub fn set_tag_keys(
mut self,
inp: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_tag_keys(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UpdateAlias {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::update_alias_input::Builder,
}
impl UpdateAlias {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::UpdateAliasOutput,
smithy_http::result::SdkError<crate::error::UpdateAliasError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The name of the alias.</p>
pub fn name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.name(inp);
self
}
pub fn set_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_name(inp);
self
}
/// <p>The function version that the alias invokes.</p>
pub fn function_version(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_version(inp);
self
}
pub fn set_function_version(
mut self,
inp: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_function_version(inp);
self
}
/// <p>A description of the alias.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
pub fn set_description(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(inp);
self
}
/// <p>The <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html#configuring-alias-routing">routing
/// configuration</a> of the alias.</p>
pub fn routing_config(mut self, inp: crate::model::AliasRoutingConfiguration) -> Self {
self.inner = self.inner.routing_config(inp);
self
}
pub fn set_routing_config(
mut self,
inp: std::option::Option<crate::model::AliasRoutingConfiguration>,
) -> Self {
self.inner = self.inner.set_routing_config(inp);
self
}
/// <p>Only update the alias if the revision ID matches the ID that's specified. Use this option to avoid modifying
/// an alias that has changed since you last read it.</p>
pub fn revision_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.revision_id(inp);
self
}
pub fn set_revision_id(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_revision_id(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UpdateCodeSigningConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::update_code_signing_config_input::Builder,
}
impl UpdateCodeSigningConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::UpdateCodeSigningConfigOutput,
smithy_http::result::SdkError<crate::error::UpdateCodeSigningConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The The Amazon Resource Name (ARN) of the code signing configuration.</p>
pub fn code_signing_config_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.code_signing_config_arn(inp);
self
}
pub fn set_code_signing_config_arn(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_code_signing_config_arn(inp);
self
}
/// <p>Descriptive name for this code signing configuration.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
pub fn set_description(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(inp);
self
}
/// <p>Signing profiles for this code signing configuration.</p>
pub fn allowed_publishers(mut self, inp: crate::model::AllowedPublishers) -> Self {
self.inner = self.inner.allowed_publishers(inp);
self
}
pub fn set_allowed_publishers(
mut self,
inp: std::option::Option<crate::model::AllowedPublishers>,
) -> Self {
self.inner = self.inner.set_allowed_publishers(inp);
self
}
/// <p>The code signing policy.</p>
pub fn code_signing_policies(mut self, inp: crate::model::CodeSigningPolicies) -> Self {
self.inner = self.inner.code_signing_policies(inp);
self
}
pub fn set_code_signing_policies(
mut self,
inp: std::option::Option<crate::model::CodeSigningPolicies>,
) -> Self {
self.inner = self.inner.set_code_signing_policies(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UpdateEventSourceMapping {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::update_event_source_mapping_input::Builder,
}
impl UpdateEventSourceMapping {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::UpdateEventSourceMappingOutput,
smithy_http::result::SdkError<crate::error::UpdateEventSourceMappingError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The identifier of the event source mapping.</p>
pub fn uuid(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.uuid(inp);
self
}
pub fn set_uuid(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_uuid(inp);
self
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Version or Alias ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:MyFunction:PROD</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:MyFunction</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it's limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>If true, the event source mapping is active. Set to false to pause polling and invocation.</p>
pub fn enabled(mut self, inp: bool) -> Self {
self.inner = self.inner.enabled(inp);
self
}
pub fn set_enabled(mut self, inp: std::option::Option<bool>) -> Self {
self.inner = self.inner.set_enabled(inp);
self
}
/// <p>The maximum number of items to retrieve in a single batch.</p>
/// <ul>
/// <li>
/// <p>
/// <b>Amazon Kinesis</b> - Default 100. Max 10,000.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon DynamoDB Streams</b> - Default 100. Max 1,000.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon Simple Queue Service</b> - Default 10. For standard queues the max is 10,000. For FIFO queues the max is 10.</p>
/// </li>
/// <li>
/// <p>
/// <b>Amazon Managed Streaming for Apache Kafka</b> - Default 100. Max 10,000.</p>
/// </li>
/// <li>
/// <p>
/// <b>Self-Managed Apache Kafka</b> - Default 100. Max 10,000.</p>
/// </li>
/// </ul>
pub fn batch_size(mut self, inp: i32) -> Self {
self.inner = self.inner.batch_size(inp);
self
}
pub fn set_batch_size(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_batch_size(inp);
self
}
/// <p>(Streams and SQS standard queues) The maximum amount of time to gather records before invoking the function, in seconds.</p>
pub fn maximum_batching_window_in_seconds(mut self, inp: i32) -> Self {
self.inner = self.inner.maximum_batching_window_in_seconds(inp);
self
}
pub fn set_maximum_batching_window_in_seconds(
mut self,
inp: std::option::Option<i32>,
) -> Self {
self.inner = self.inner.set_maximum_batching_window_in_seconds(inp);
self
}
/// <p>(Streams) An Amazon SQS queue or Amazon SNS topic destination for discarded records.</p>
pub fn destination_config(mut self, inp: crate::model::DestinationConfig) -> Self {
self.inner = self.inner.destination_config(inp);
self
}
pub fn set_destination_config(
mut self,
inp: std::option::Option<crate::model::DestinationConfig>,
) -> Self {
self.inner = self.inner.set_destination_config(inp);
self
}
/// <p>(Streams) Discard records older than the specified age. The default value is infinite (-1).</p>
pub fn maximum_record_age_in_seconds(mut self, inp: i32) -> Self {
self.inner = self.inner.maximum_record_age_in_seconds(inp);
self
}
pub fn set_maximum_record_age_in_seconds(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_maximum_record_age_in_seconds(inp);
self
}
/// <p>(Streams) If the function returns an error, split the batch in two and retry.</p>
pub fn bisect_batch_on_function_error(mut self, inp: bool) -> Self {
self.inner = self.inner.bisect_batch_on_function_error(inp);
self
}
pub fn set_bisect_batch_on_function_error(
mut self,
inp: std::option::Option<bool>,
) -> Self {
self.inner = self.inner.set_bisect_batch_on_function_error(inp);
self
}
/// <p>(Streams) Discard records after the specified number of retries. The default value is infinite (-1). When set to infinite (-1), failed records will be retried until the record expires.</p>
pub fn maximum_retry_attempts(mut self, inp: i32) -> Self {
self.inner = self.inner.maximum_retry_attempts(inp);
self
}
pub fn set_maximum_retry_attempts(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_maximum_retry_attempts(inp);
self
}
/// <p>(Streams) The number of batches to process from each shard concurrently.</p>
pub fn parallelization_factor(mut self, inp: i32) -> Self {
self.inner = self.inner.parallelization_factor(inp);
self
}
pub fn set_parallelization_factor(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_parallelization_factor(inp);
self
}
/// <p>An array of the authentication protocol, or the VPC components to secure your event source.</p>
pub fn source_access_configurations(
mut self,
inp: impl Into<crate::model::SourceAccessConfiguration>,
) -> Self {
self.inner = self.inner.source_access_configurations(inp);
self
}
pub fn set_source_access_configurations(
mut self,
inp: std::option::Option<std::vec::Vec<crate::model::SourceAccessConfiguration>>,
) -> Self {
self.inner = self.inner.set_source_access_configurations(inp);
self
}
/// <p>(Streams) The duration in seconds of a processing window. The range is between 1 second up to 900 seconds.</p>
pub fn tumbling_window_in_seconds(mut self, inp: i32) -> Self {
self.inner = self.inner.tumbling_window_in_seconds(inp);
self
}
pub fn set_tumbling_window_in_seconds(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_tumbling_window_in_seconds(inp);
self
}
/// <p>(Streams) A list of current response type enums applied to the event source mapping.</p>
pub fn function_response_types(
mut self,
inp: impl Into<crate::model::FunctionResponseType>,
) -> Self {
self.inner = self.inner.function_response_types(inp);
self
}
pub fn set_function_response_types(
mut self,
inp: std::option::Option<std::vec::Vec<crate::model::FunctionResponseType>>,
) -> Self {
self.inner = self.inner.set_function_response_types(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UpdateFunctionCode {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::update_function_code_input::Builder,
}
impl UpdateFunctionCode {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::UpdateFunctionCodeOutput,
smithy_http::result::SdkError<crate::error::UpdateFunctionCodeError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The base64-encoded contents of the deployment package. AWS SDK and AWS CLI clients handle the encoding for
/// you.</p>
pub fn zip_file(mut self, inp: smithy_types::Blob) -> Self {
self.inner = self.inner.zip_file(inp);
self
}
pub fn set_zip_file(mut self, inp: std::option::Option<smithy_types::Blob>) -> Self {
self.inner = self.inner.set_zip_file(inp);
self
}
/// <p>An Amazon S3 bucket in the same AWS Region as your function. The bucket can be in a different AWS account.</p>
pub fn s3_bucket(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.s3_bucket(inp);
self
}
pub fn set_s3_bucket(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_s3_bucket(inp);
self
}
/// <p>The Amazon S3 key of the deployment package.</p>
pub fn s3_key(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.s3_key(inp);
self
}
pub fn set_s3_key(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_s3_key(inp);
self
}
/// <p>For versioned objects, the version of the deployment package object to use.</p>
pub fn s3_object_version(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.s3_object_version(inp);
self
}
pub fn set_s3_object_version(
mut self,
inp: std::option::Option<std::string::String>,
) -> Self {
self.inner = self.inner.set_s3_object_version(inp);
self
}
/// <p>URI of a container image in the Amazon ECR registry.</p>
pub fn image_uri(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.image_uri(inp);
self
}
pub fn set_image_uri(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_image_uri(inp);
self
}
/// <p>Set to true to publish a new version of the function after updating the code. This has the same effect as
/// calling <a>PublishVersion</a> separately.</p>
pub fn publish(mut self, inp: bool) -> Self {
self.inner = self.inner.publish(inp);
self
}
pub fn set_publish(mut self, inp: bool) -> Self {
self.inner = self.inner.set_publish(inp);
self
}
/// <p>Set to true to validate the request parameters and access permissions without modifying the function
/// code.</p>
pub fn dry_run(mut self, inp: bool) -> Self {
self.inner = self.inner.dry_run(inp);
self
}
pub fn set_dry_run(mut self, inp: bool) -> Self {
self.inner = self.inner.set_dry_run(inp);
self
}
/// <p>Only update the function if the revision ID matches the ID that's specified. Use this option to avoid modifying a
/// function that has changed since you last read it.</p>
pub fn revision_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.revision_id(inp);
self
}
pub fn set_revision_id(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_revision_id(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UpdateFunctionConfiguration {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::update_function_configuration_input::Builder,
}
impl UpdateFunctionConfiguration {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::UpdateFunctionConfigurationOutput,
smithy_http::result::SdkError<crate::error::UpdateFunctionConfigurationError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64
/// characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>The Amazon Resource Name (ARN) of the function's execution role.</p>
pub fn role(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.role(inp);
self
}
pub fn set_role(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_role(inp);
self
}
/// <p>The name of the method within your code that Lambda calls to execute your function. The format includes the
/// file name. It can also include namespaces and other qualifiers, depending on the runtime. For more information,
/// see <a href="https://docs.aws.amazon.com/lambda/latest/dg/programming-model-v2.html">Programming Model</a>.</p>
pub fn handler(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.handler(inp);
self
}
pub fn set_handler(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_handler(inp);
self
}
/// <p>A description of the function.</p>
pub fn description(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.description(inp);
self
}
pub fn set_description(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_description(inp);
self
}
/// <p>The amount of time that Lambda allows a function to run before stopping it. The default is 3 seconds. The
/// maximum allowed value is 900 seconds.</p>
pub fn timeout(mut self, inp: i32) -> Self {
self.inner = self.inner.timeout(inp);
self
}
pub fn set_timeout(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_timeout(inp);
self
}
/// <p>The amount of memory available to the function at runtime. Increasing the function's memory also increases its CPU
/// allocation. The default value is 128 MB. The value can be any multiple of 1 MB.</p>
pub fn memory_size(mut self, inp: i32) -> Self {
self.inner = self.inner.memory_size(inp);
self
}
pub fn set_memory_size(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_memory_size(inp);
self
}
/// <p>For network connectivity to AWS resources in a VPC, specify a list of security groups and subnets in the VPC.
/// When you connect a function to a VPC, it can only access resources and the internet through that VPC. For more
/// information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html">VPC Settings</a>.</p>
pub fn vpc_config(mut self, inp: crate::model::VpcConfig) -> Self {
self.inner = self.inner.vpc_config(inp);
self
}
pub fn set_vpc_config(mut self, inp: std::option::Option<crate::model::VpcConfig>) -> Self {
self.inner = self.inner.set_vpc_config(inp);
self
}
/// <p>Environment variables that are accessible from function code during execution.</p>
pub fn environment(mut self, inp: crate::model::Environment) -> Self {
self.inner = self.inner.environment(inp);
self
}
pub fn set_environment(
mut self,
inp: std::option::Option<crate::model::Environment>,
) -> Self {
self.inner = self.inner.set_environment(inp);
self
}
/// <p>The identifier of the function's <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html">runtime</a>.</p>
pub fn runtime(mut self, inp: crate::model::Runtime) -> Self {
self.inner = self.inner.runtime(inp);
self
}
pub fn set_runtime(mut self, inp: std::option::Option<crate::model::Runtime>) -> Self {
self.inner = self.inner.set_runtime(inp);
self
}
/// <p>A dead letter queue configuration that specifies the queue or topic where Lambda sends asynchronous events
/// when they fail processing. For more information, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#dlq">Dead Letter Queues</a>.</p>
pub fn dead_letter_config(mut self, inp: crate::model::DeadLetterConfig) -> Self {
self.inner = self.inner.dead_letter_config(inp);
self
}
pub fn set_dead_letter_config(
mut self,
inp: std::option::Option<crate::model::DeadLetterConfig>,
) -> Self {
self.inner = self.inner.set_dead_letter_config(inp);
self
}
/// <p>The ARN of the AWS Key Management Service (AWS KMS) key that's used to encrypt your function's environment
/// variables. If it's not provided, AWS Lambda uses a default service key.</p>
pub fn kms_key_arn(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.kms_key_arn(inp);
self
}
pub fn set_kms_key_arn(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_kms_key_arn(inp);
self
}
/// <p>Set <code>Mode</code> to <code>Active</code> to sample and trace a subset of incoming requests with AWS
/// X-Ray.</p>
pub fn tracing_config(mut self, inp: crate::model::TracingConfig) -> Self {
self.inner = self.inner.tracing_config(inp);
self
}
pub fn set_tracing_config(
mut self,
inp: std::option::Option<crate::model::TracingConfig>,
) -> Self {
self.inner = self.inner.set_tracing_config(inp);
self
}
/// <p>Only update the function if the revision ID matches the ID that's specified. Use this option to avoid modifying a
/// function that has changed since you last read it.</p>
pub fn revision_id(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.revision_id(inp);
self
}
pub fn set_revision_id(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_revision_id(inp);
self
}
/// <p>A list of <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">function layers</a>
/// to add to the function's execution environment. Specify each layer by its ARN, including the version.</p>
pub fn layers(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.layers(inp);
self
}
pub fn set_layers(
mut self,
inp: std::option::Option<std::vec::Vec<std::string::String>>,
) -> Self {
self.inner = self.inner.set_layers(inp);
self
}
/// <p>Connection settings for an Amazon EFS file system.</p>
pub fn file_system_configs(
mut self,
inp: impl Into<crate::model::FileSystemConfig>,
) -> Self {
self.inner = self.inner.file_system_configs(inp);
self
}
pub fn set_file_system_configs(
mut self,
inp: std::option::Option<std::vec::Vec<crate::model::FileSystemConfig>>,
) -> Self {
self.inner = self.inner.set_file_system_configs(inp);
self
}
/// <p>
/// <a href="https://docs.aws.amazon.com/lambda/latest/dg/images-parms.html">Container image configuration
/// values</a> that override the values in the container image Dockerfile.</p>
pub fn image_config(mut self, inp: crate::model::ImageConfig) -> Self {
self.inner = self.inner.image_config(inp);
self
}
pub fn set_image_config(
mut self,
inp: std::option::Option<crate::model::ImageConfig>,
) -> Self {
self.inner = self.inner.set_image_config(inp);
self
}
}
#[derive(std::fmt::Debug)]
pub struct UpdateFunctionEventInvokeConfig {
handle: std::sync::Arc<super::Handle>,
inner: crate::input::update_function_event_invoke_config_input::Builder,
}
impl UpdateFunctionEventInvokeConfig {
pub(crate) fn new(handle: std::sync::Arc<super::Handle>) -> Self {
Self {
handle,
inner: Default::default(),
}
}
pub async fn send(
self,
) -> Result<
crate::output::UpdateFunctionEventInvokeConfigOutput,
smithy_http::result::SdkError<crate::error::UpdateFunctionEventInvokeConfigError>,
> {
let input = self
.inner
.build()
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
let op = input
.make_operation(&self.handle.conf)
.map_err(|err| smithy_http::result::SdkError::ConstructionFailure(err.into()))?;
self.handle.client.call(op).await
}
/// <p>The name of the Lambda function, version, or alias.</p>
/// <p class="title">
/// <b>Name formats</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function name</b> - <code>my-function</code> (name-only), <code>my-function:v1</code> (with alias).</p>
/// </li>
/// <li>
/// <p>
/// <b>Function ARN</b> - <code>arn:aws:lambda:us-west-2:123456789012:function:my-function</code>.</p>
/// </li>
/// <li>
/// <p>
/// <b>Partial ARN</b> - <code>123456789012:function:my-function</code>.</p>
/// </li>
/// </ul>
/// <p>You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN.
/// If you specify only the function name, it is limited to 64 characters in length.</p>
pub fn function_name(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.function_name(inp);
self
}
pub fn set_function_name(mut self, inp: std::string::String) -> Self {
self.inner = self.inner.set_function_name(inp);
self
}
/// <p>A version number or alias name.</p>
pub fn qualifier(mut self, inp: impl Into<std::string::String>) -> Self {
self.inner = self.inner.qualifier(inp);
self
}
pub fn set_qualifier(mut self, inp: std::option::Option<std::string::String>) -> Self {
self.inner = self.inner.set_qualifier(inp);
self
}
/// <p>The maximum number of times to retry when the function returns an error.</p>
pub fn maximum_retry_attempts(mut self, inp: i32) -> Self {
self.inner = self.inner.maximum_retry_attempts(inp);
self
}
pub fn set_maximum_retry_attempts(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_maximum_retry_attempts(inp);
self
}
/// <p>The maximum age of a request that Lambda sends to a function for processing.</p>
pub fn maximum_event_age_in_seconds(mut self, inp: i32) -> Self {
self.inner = self.inner.maximum_event_age_in_seconds(inp);
self
}
pub fn set_maximum_event_age_in_seconds(mut self, inp: std::option::Option<i32>) -> Self {
self.inner = self.inner.set_maximum_event_age_in_seconds(inp);
self
}
/// <p>A destination for events after they have been sent to a function for processing.</p>
/// <p class="title">
/// <b>Destinations</b>
/// </p>
/// <ul>
/// <li>
/// <p>
/// <b>Function</b> - The Amazon Resource Name (ARN) of a Lambda function.</p>
/// </li>
/// <li>
/// <p>
/// <b>Queue</b> - The ARN of an SQS queue.</p>
/// </li>
/// <li>
/// <p>
/// <b>Topic</b> - The ARN of an SNS topic.</p>
/// </li>
/// <li>
/// <p>
/// <b>Event Bus</b> - The ARN of an Amazon EventBridge event bus.</p>
/// </li>
/// </ul>
pub fn destination_config(mut self, inp: crate::model::DestinationConfig) -> Self {
self.inner = self.inner.destination_config(inp);
self
}
pub fn set_destination_config(
mut self,
inp: std::option::Option<crate::model::DestinationConfig>,
) -> Self {
self.inner = self.inner.set_destination_config(inp);
self
}
}
}
| 40.91251 | 203 | 0.547501 |
6a1bb49117ddd4ec02ab4c1007b9f056a52729a0 | 7,878 | use std::collections::BTreeMap;
use event::{tags, Metric};
use snafu::ResultExt;
use sqlx::MySqlPool;
use super::{valid_name, QueryFailed};
const GLOBAL_STATUS_QUERY: &str = r#"SHOW GLOBAL STATUS"#;
#[derive(Debug, sqlx::FromRow)]
struct GlobalStatus {
#[sqlx(rename = "Variable_name")]
name: String,
#[sqlx(rename = "Value")]
value: String,
}
pub async fn gather(pool: &MySqlPool) -> Result<Vec<Metric>, super::Error> {
let stats = sqlx::query_as::<_, GlobalStatus>(GLOBAL_STATUS_QUERY)
.fetch_all(pool)
.await
.context(QueryFailed {
query: GLOBAL_STATUS_QUERY,
})?;
let mut metrics = vec![];
let mut text_items = BTreeMap::new();
text_items.insert("wsrep_local_state_uuid".to_string(), "".to_string());
text_items.insert("wsrep_cluster_state_uuid".to_string(), "".to_string());
text_items.insert("wsrep_provider_version".to_string(), "".to_string());
text_items.insert("wsrep_evs_repl_latency".to_string(), "".to_string());
for stat in stats.iter() {
let key = valid_name(&stat.name);
let fv = match stat.value.parse::<f64>() {
Ok(v) => v,
_ => {
if text_items.contains_key(&key) {
text_items.insert(key.clone(), stat.value.clone());
}
continue;
}
};
let (split_key, name) = match key.split_once("_") {
Some((key, name)) => (key, name),
None => {
// TODO: handle those metrics
// GlobalStatus { name: "Connections", value: "20" }
// GlobalStatus { name: "Queries", value: "248" }
// GlobalStatus { name: "Questions", value: "116" }
// GlobalStatus { name: "Uptime", value: "1321" }
continue;
}
};
match split_key {
"com" => metrics.push(Metric::sum_with_tags(
"mysql_global_status_commands_total",
"Total number of executed MySQL commands",
fv,
tags!(
"command" => name
),
)),
"handler" => metrics.push(Metric::sum_with_tags(
"mysql_global_status_handlers_total",
"Total number of executed MySQL handlers",
fv,
tags!(
"handler" => name
),
)),
"connection_errors" => metrics.push(Metric::sum_with_tags(
"mysql_global_status_connection_errors_total",
"Total number of MySQL connection errors",
fv,
tags!(
"error" => name
),
)),
"innodb_buffer_pool_pages" => {
match name {
"data" | "free" | "misc" | "old" => {
metrics.push(Metric::gauge_with_tags(
"mysql_global_status_buffer_pool_pages",
"Innodb buffer pool pages by state",
fv,
tags!(
"state" => name
),
));
}
"dirty" => {
metrics.push(Metric::gauge(
"mysql_global_status_buffer_pool_dirty_pages",
"Innodb buffer pool dirty pages",
fv,
));
}
"total" => continue,
_ => {
metrics.push(Metric::gauge_with_tags(
"mysql_global_status_buffer_pool_page_changes_total",
"Innodb buffer pool page state changes",
fv,
tags!(
"operation" => name
),
));
}
}
}
"innodb_rows" => metrics.push(Metric::sum_with_tags(
"mysql_global_status_innodb_row_ops_total",
"Total number of MySQL InnoDB row operations",
fv,
tags!(
"operation" => name
),
)),
"performance_schema" => metrics.push(Metric::sum_with_tags(
"mysql_global_status_performance_schema_lost_total",
"Total number of MySQL instrumentations that could not be loaded or created due to memory constraints.",
fv,
tags!(
"instrumentation" => name
),
)),
_ => {
metrics.push(Metric::gauge(
"mysql_global_status_".to_owned() + &key,
"Generic metric from SHOW GLOBAL STATUS",
fv,
));
}
}
}
// mysql_galera_variables_info metric
if text_items.get("wsrep_local_state_uuid").unwrap() != "" {
metrics.push(Metric::gauge_with_tags(
"mysql_galera_status_info",
"PXC/Galera status information.",
1,
tags!(
"wsrep_local_state_uuid" => text_items.get("wsrep_local_state_uuid").unwrap(),
"wsrep_cluster_state_uuid" => text_items.get("wsrep_cluster_state_uuid").unwrap(),
"wsrep_provider_version" => text_items.get("wsrep_provider_version").unwrap()
),
));
}
// mysql_galera_evs_repl_latency
if text_items.get("wsrep_evs_repl_latency").unwrap() != "" {
let mut evs = [
(
"min_seconds",
0f64,
0usize,
"PXC/Galera group communication latency. Min value.",
),
(
"avg_seconds",
0f64,
1usize,
"PXC/Galera group communication latency. Avg value.",
),
(
"max_seconds",
0f64,
2usize,
"PXC/Galera group communication latency. Max value.",
),
(
"stdev",
0f64,
3usize,
"PXC/Galera group communication latency. Standard Deviation.",
),
(
"sample_size",
0f64,
4usize,
"PXC/Galera group communication latency. Sample Size.",
),
];
let mut parsing_success = true;
let values = text_items
.get("wsrep_evs_repl_latency")
.unwrap()
.split('/')
.collect::<Vec<_>>();
if evs.len() == values.len() {
for (_, value, index, _) in evs.iter_mut() {
let index = *index;
match values[index].parse::<f64>() {
Ok(v) => *value = v,
Err(_) => parsing_success = false,
}
}
if parsing_success {
for (name, value, _, desc) in evs {
metrics.push(Metric::gauge(
"mysql_galera_evs_repl_latency_".to_owned() + name,
desc,
value,
));
}
}
}
}
Ok(metrics)
}
fn is_global_status(name: &str) -> bool {
const GLOBAL_STATUS_PREFIXES: [&str; 6] = [
"com_",
"handler_",
"connection_errors_",
"innodb_buffer_pool_pages_",
"innodb_rows_",
"performance_schema_",
];
GLOBAL_STATUS_PREFIXES.contains(&name)
}
| 33.811159 | 120 | 0.44948 |
28cd97d1ed12adca1c7def3af8ee52e3030fb861 | 1,742 | use std::fs;
#[derive(Eq, Debug)]
struct Coordinates {
x: usize,
y: usize,
}
impl PartialEq for Coordinates {
fn eq(&self, other: &Self) -> bool {
self.x == other.x && self.y == other.y
}
}
fn main() {
let contents = fs::read_to_string("input.txt").expect("Couldn't read input file :(");
let lines = contents.lines();
let mut state = vec![vec![0isize; 1000]; 1000];
for line in lines {
let tokens: Vec<&str> = line.split(' ').collect();
let start_coord_token: Vec<&str> = tokens[1].split(',').collect();
let start_coord = Coordinates {
x: start_coord_token[0].parse::<usize>().unwrap(),
y: start_coord_token[1].parse::<usize>().unwrap(),
};
let end_coord_token: Vec<&str> = tokens[2].split(',').collect();
let end_coord = Coordinates {
x: end_coord_token[0].parse::<usize>().unwrap(),
y: end_coord_token[1].parse::<usize>().unwrap(),
};
for x in start_coord.x..(end_coord.x + 1) {
for y in start_coord.y..(end_coord.y + 1) {
state[x][y] += match tokens[0] {
"on" => 1,
"off" => {
-1
},
"toggle" => {
2
}
_ => panic!("Invalid operation found in input file!"),
};
if state[x][y] < 0 {
state[x][y] = 0;
}
}
}
}
let mut count = 0;
for x in 0..999 {
for y in 0..999 {
count += state[x][y];
}
}
print!("Total on in the end {}", count);
}
| 28.557377 | 89 | 0.443169 |
fc4400a061483eed8709c784d236bf7acde8bfd7 | 9,764 | // Copyright 2019 The Druid Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! GTK code handling.
use gdk::keys::constants::*;
pub use super::super::shared::hardware_keycode_to_code;
use crate::keyboard_types::{Key, Location};
pub type RawKey = gdk::keys::Key;
#[allow(clippy::just_underscores_and_digits, non_upper_case_globals)]
pub fn raw_key_to_key(raw: RawKey) -> Option<Key> {
// changes from x11 backend keycodes:
// * XKB_KEY_ prefix removed
// * 3270 is replaced with _3270
// * XF86 prefix is removed
// * Sun* Keys are gone
Some(match raw {
BackSpace => Key::Backspace,
Tab | KP_Tab | ISO_Left_Tab => Key::Tab,
Clear | KP_Begin => Key::Clear,
Return | KP_Enter => Key::Enter,
Linefeed => Key::Enter,
Pause => Key::Pause,
Scroll_Lock => Key::ScrollLock,
Escape => Key::Escape,
Multi_key => Key::Compose,
Kanji => Key::KanjiMode,
Muhenkan => Key::NonConvert,
Henkan_Mode => Key::Convert,
Romaji => Key::Romaji,
Hiragana => Key::Hiragana,
Katakana => Key::Katakana,
Hiragana_Katakana => Key::HiraganaKatakana,
Zenkaku => Key::Zenkaku,
Hankaku => Key::Hankaku,
Zenkaku_Hankaku => Key::ZenkakuHankaku,
Kana_Lock => Key::KanaMode,
Eisu_Shift | Eisu_toggle => Key::Alphanumeric,
Hangul => Key::HangulMode,
Hangul_Hanja => Key::HanjaMode,
Codeinput => Key::CodeInput,
SingleCandidate => Key::SingleCandidate,
MultipleCandidate => Key::AllCandidates,
PreviousCandidate => Key::PreviousCandidate,
Home | KP_Home => Key::Home,
Left | KP_Left => Key::ArrowLeft,
Up | KP_Up => Key::ArrowUp,
Right | KP_Right => Key::ArrowRight,
Down | KP_Down => Key::ArrowDown,
Prior | KP_Prior => Key::PageUp,
Next | KP_Next => Key::PageDown,
End | KP_End => Key::End,
Select => Key::Select,
// Treat Print/PrintScreen as PrintScreen https://crbug.com/683097.
Print | _3270_PrintScreen => Key::PrintScreen,
Execute => Key::Execute,
Insert | KP_Insert => Key::Insert,
Undo => Key::Undo,
Redo => Key::Redo,
Menu => Key::ContextMenu,
Find => Key::Find,
Cancel => Key::Cancel,
Help => Key::Help,
Break | _3270_Attn => Key::Attn,
Mode_switch => Key::ModeChange,
Num_Lock => Key::NumLock,
F1 | KP_F1 => Key::F1,
F2 | KP_F2 => Key::F2,
F3 | KP_F3 => Key::F3,
F4 | KP_F4 => Key::F4,
F5 => Key::F5,
F6 => Key::F6,
F7 => Key::F7,
F8 => Key::F8,
F9 => Key::F9,
F10 => Key::F10,
F11 => Key::F11,
F12 => Key::F12,
// not available in keyboard-types
// Tools | F13 => Key::F13,
// F14 | Launch5 => Key::F14,
// F15 | Launch6 => Key::F15,
// F16 | Launch7 => Key::F16,
// F17 | Launch8 => Key::F17,
// F18 | Launch9 => Key::F18,
// F19 => Key::F19,
// F20 => Key::F20,
// F21 => Key::F21,
// F22 => Key::F22,
// F23 => Key::F23,
// F24 => Key::F24,
// Calculator => Key::LaunchCalculator,
// MyComputer | Explorer => Key::LaunchMyComputer,
// ISO_Level3_Latch => Key::AltGraphLatch,
// ISO_Level5_Shift => Key::ShiftLevel5,
Shift_L | Shift_R => Key::Shift,
Control_L | Control_R => Key::Control,
Caps_Lock => Key::CapsLock,
Meta_L | Meta_R => Key::Meta,
Alt_L | Alt_R => Key::Alt,
Super_L | Super_R => Key::Meta,
Hyper_L | Hyper_R => Key::Hyper,
Delete => Key::Delete,
Next_VMode => Key::VideoModeNext,
MonBrightnessUp => Key::BrightnessUp,
MonBrightnessDown => Key::BrightnessDown,
Standby | Sleep | Suspend => Key::Standby,
AudioLowerVolume => Key::AudioVolumeDown,
AudioMute => Key::AudioVolumeMute,
AudioRaiseVolume => Key::AudioVolumeUp,
AudioPlay => Key::MediaPlayPause,
AudioStop => Key::MediaStop,
AudioPrev => Key::MediaTrackPrevious,
AudioNext => Key::MediaTrackNext,
HomePage => Key::BrowserHome,
Mail => Key::LaunchMail,
Search => Key::BrowserSearch,
AudioRecord => Key::MediaRecord,
Calendar => Key::LaunchCalendar,
Back => Key::BrowserBack,
Forward => Key::BrowserForward,
Stop => Key::BrowserStop,
Refresh | Reload => Key::BrowserRefresh,
PowerOff => Key::PowerOff,
WakeUp => Key::WakeUp,
Eject => Key::Eject,
ScreenSaver => Key::LaunchScreenSaver,
WWW => Key::LaunchWebBrowser,
Favorites => Key::BrowserFavorites,
AudioPause => Key::MediaPause,
AudioMedia | Music => Key::LaunchMusicPlayer,
AudioRewind => Key::MediaRewind,
CD | Video => Key::LaunchMediaPlayer,
Close => Key::Close,
Copy => Key::Copy,
Cut => Key::Cut,
Display => Key::DisplaySwap,
Excel => Key::LaunchSpreadsheet,
LogOff => Key::LogOff,
New => Key::New,
Open => Key::Open,
Paste => Key::Paste,
Reply => Key::MailReply,
Save => Key::Save,
Send => Key::MailSend,
Spell => Key::SpellCheck,
SplitScreen => Key::SplitScreenToggle,
Word | OfficeHome => Key::LaunchWordProcessor,
ZoomIn => Key::ZoomIn,
ZoomOut => Key::ZoomOut,
WebCam => Key::LaunchWebCam,
MailForward => Key::MailForward,
AudioForward => Key::MediaFastForward,
AudioRandomPlay => Key::RandomToggle,
Subtitle => Key::Subtitle,
Hibernate => Key::Hibernate,
_3270_EraseEOF => Key::EraseEof,
_3270_Play => Key::Play,
_3270_ExSelect => Key::ExSel,
_3270_CursorSelect => Key::CrSel,
ISO_Level3_Shift => Key::AltGraph,
ISO_Next_Group => Key::GroupNext,
ISO_Prev_Group => Key::GroupPrevious,
ISO_First_Group => Key::GroupFirst,
ISO_Last_Group => Key::GroupLast,
dead_grave
| dead_acute
| dead_circumflex
| dead_tilde
| dead_macron
| dead_breve
| dead_abovedot
| dead_diaeresis
| dead_abovering
| dead_doubleacute
| dead_caron
| dead_cedilla
| dead_ogonek
| dead_iota
| dead_voiced_sound
| dead_semivoiced_sound
| dead_belowdot
| dead_hook
| dead_horn
| dead_stroke
| dead_abovecomma
| dead_abovereversedcomma
| dead_doublegrave
| dead_belowring
| dead_belowmacron
| dead_belowcircumflex
| dead_belowtilde
| dead_belowbreve
| dead_belowdiaeresis
| dead_invertedbreve
| dead_belowcomma
| dead_currency
| dead_greek => Key::Dead,
_ => return None,
})
}
#[allow(clippy::just_underscores_and_digits, non_upper_case_globals)]
pub fn raw_key_to_location(raw: RawKey) -> Location {
match raw {
Control_L | Shift_L | Alt_L | Super_L | Meta_L => Location::Left,
Control_R | Shift_R | Alt_R | Super_R | Meta_R => Location::Right,
KP_0 | KP_1 | KP_2 | KP_3 | KP_4 | KP_5 | KP_6 | KP_7 | KP_8 | KP_9 | KP_Add | KP_Begin
| KP_Decimal | KP_Delete | KP_Divide | KP_Down | KP_End | KP_Enter | KP_Equal | KP_F1
| KP_F2 | KP_F3 | KP_F4 | KP_Home | KP_Insert | KP_Left | KP_Multiply | KP_Page_Down
| KP_Page_Up | KP_Right | KP_Separator | KP_Space | KP_Subtract | KP_Tab | KP_Up => {
Location::Numpad
}
_ => Location::Standard,
}
}
#[allow(non_upper_case_globals)]
pub fn key_to_raw_key(src: &Key) -> Option<RawKey> {
Some(match src {
Key::Escape => Escape,
Key::Backspace => BackSpace,
Key::Tab => Tab,
Key::Enter => Return,
// Give "left" variants
Key::Control => Control_L,
Key::Alt => Alt_L,
Key::Shift => Shift_L,
Key::Meta => Super_L,
Key::CapsLock => Caps_Lock,
Key::F1 => F1,
Key::F2 => F2,
Key::F3 => F3,
Key::F4 => F4,
Key::F5 => F5,
Key::F6 => F6,
Key::F7 => F7,
Key::F8 => F8,
Key::F9 => F9,
Key::F10 => F10,
Key::F11 => F11,
Key::F12 => F12,
Key::PrintScreen => Print,
Key::ScrollLock => Scroll_Lock,
// Pause/Break not audio.
Key::Pause => Pause,
Key::Insert => Insert,
Key::Delete => Delete,
Key::Home => Home,
Key::End => End,
Key::PageUp => Page_Up,
Key::PageDown => Page_Down,
Key::NumLock => Num_Lock,
Key::ArrowUp => Up,
Key::ArrowDown => Down,
Key::ArrowLeft => Left,
Key::ArrowRight => Right,
Key::ContextMenu => Menu,
Key::WakeUp => WakeUp,
Key::LaunchApplication1 => Launch0,
Key::LaunchApplication2 => Launch1,
Key::AltGraph => ISO_Level3_Shift,
// TODO: probably more
_ => return None,
})
}
| 33.785467 | 95 | 0.563089 |
219ae683d1cb19433505bc7db3431531e2ad9d41 | 164 | extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
use uuid::Uuid;
#[wasm_bindgen]
pub fn get_uuid() -> String {
Uuid::new_v4().to_simple().to_string()
}
| 16.4 | 40 | 0.70122 |
142886a0fe5f23b9c27e3b84869cdb23c4670fee | 28,021 | use super::crypto::{decrypt, encrypt};
use byteorder::ReadBytesExt;
use bytes::{BufMut, BytesMut};
use interledger_packet::{
oer::{BufOerExt, MutBufOerExt},
PacketType as IlpPacketType, ParseError,
};
use std::{fmt, str};
const STREAM_VERSION: u8 = 1;
pub struct StreamPacketBuilder<'a> {
pub sequence: u64,
pub ilp_packet_type: IlpPacketType,
pub prepare_amount: u64,
pub frames: &'a [Frame<'a>],
}
impl<'a> StreamPacketBuilder<'a> {
pub fn build(&self) -> StreamPacket {
// TODO predict length first
let mut buffer_unencrypted = Vec::new();
buffer_unencrypted.put_u8(STREAM_VERSION);
buffer_unencrypted.put_u8(self.ilp_packet_type as u8);
buffer_unencrypted.put_var_uint(self.sequence);
buffer_unencrypted.put_var_uint(self.prepare_amount);
buffer_unencrypted.put_var_uint(self.frames.len() as u64);
let frames_offset = buffer_unencrypted.len();
for frame in self.frames {
let mut contents = Vec::new();
match frame {
Frame::ConnectionClose(ref frame) => {
buffer_unencrypted.put_u8(FrameType::ConnectionClose as u8);
frame.put_contents(&mut contents);
}
Frame::ConnectionNewAddress(ref frame) => {
buffer_unencrypted.put_u8(FrameType::ConnectionNewAddress as u8);
frame.put_contents(&mut contents);
}
Frame::ConnectionAssetDetails(ref frame) => {
buffer_unencrypted.put_u8(FrameType::ConnectionAssetDetails as u8);
frame.put_contents(&mut contents);
}
Frame::ConnectionMaxData(ref frame) => {
buffer_unencrypted.put_u8(FrameType::ConnectionMaxData as u8);
frame.put_contents(&mut contents);
}
Frame::ConnectionDataBlocked(ref frame) => {
buffer_unencrypted.put_u8(FrameType::ConnectionDataBlocked as u8);
frame.put_contents(&mut contents);
}
Frame::ConnectionMaxStreamId(ref frame) => {
buffer_unencrypted.put_u8(FrameType::ConnectionMaxStreamId as u8);
frame.put_contents(&mut contents);
}
Frame::ConnectionStreamIdBlocked(ref frame) => {
buffer_unencrypted.put_u8(FrameType::ConnectionStreamIdBlocked as u8);
frame.put_contents(&mut contents);
}
Frame::StreamClose(ref frame) => {
buffer_unencrypted.put_u8(FrameType::StreamClose as u8);
frame.put_contents(&mut contents);
}
Frame::StreamMoney(ref frame) => {
buffer_unencrypted.put_u8(FrameType::StreamMoney as u8);
frame.put_contents(&mut contents);
}
Frame::StreamMaxMoney(ref frame) => {
buffer_unencrypted.put_u8(FrameType::StreamMaxMoney as u8);
frame.put_contents(&mut contents);
}
Frame::StreamMoneyBlocked(ref frame) => {
buffer_unencrypted.put_u8(FrameType::StreamMoneyBlocked as u8);
frame.put_contents(&mut contents);
}
Frame::StreamData(ref frame) => {
buffer_unencrypted.put_u8(FrameType::StreamData as u8);
frame.put_contents(&mut contents);
}
Frame::StreamMaxData(ref frame) => {
buffer_unencrypted.put_u8(FrameType::StreamMaxData as u8);
frame.put_contents(&mut contents);
}
Frame::StreamDataBlocked(ref frame) => {
buffer_unencrypted.put_u8(FrameType::StreamDataBlocked as u8);
frame.put_contents(&mut contents);
}
Frame::Unknown => continue,
}
buffer_unencrypted.put_var_octet_string(contents);
}
StreamPacket {
buffer_unencrypted: BytesMut::from(buffer_unencrypted),
sequence: self.sequence,
ilp_packet_type: self.ilp_packet_type,
prepare_amount: self.prepare_amount,
frames_offset,
}
}
}
#[derive(PartialEq, Clone)]
pub struct StreamPacket {
pub(crate) buffer_unencrypted: BytesMut,
sequence: u64,
ilp_packet_type: IlpPacketType,
prepare_amount: u64,
frames_offset: usize,
}
impl StreamPacket {
pub fn from_encrypted(shared_secret: &[u8], ciphertext: BytesMut) -> Result<Self, ParseError> {
// TODO handle decryption failure
let decrypted = decrypt(shared_secret, ciphertext)
.map_err(|_err| ParseError::InvalidPacket(String::from("Unable to decrypt packet")))?;
StreamPacket::from_bytes_unencrypted(decrypted)
}
fn from_bytes_unencrypted(buffer_unencrypted: BytesMut) -> Result<Self, ParseError> {
// TODO don't copy the whole packet again
let mut reader = &buffer_unencrypted[..];
let version = reader.read_u8()?;
if version != STREAM_VERSION {
return Err(ParseError::InvalidPacket(format!(
"Unsupported STREAM version: {}",
version
)));
}
let ilp_packet_type = IlpPacketType::try_from(reader.read_u8()?)?;
let sequence = reader.read_var_uint()?;
let prepare_amount = reader.read_var_uint()?;
// TODO save num_frames?
let num_frames = reader.read_var_uint()?;
let frames_offset = buffer_unencrypted.len() - reader.len();
// Try reading through all the frames to make sure they can be parsed correctly
if num_frames
== (FrameIterator {
buffer: &buffer_unencrypted[frames_offset..],
})
.count() as u64
{
Ok(StreamPacket {
buffer_unencrypted,
sequence,
ilp_packet_type,
prepare_amount,
frames_offset,
})
} else {
Err(ParseError::InvalidPacket(
"Incorrect number of frames or unable to parse all frames".to_string(),
))
}
}
pub fn into_encrypted(self, shared_secret: &[u8]) -> BytesMut {
encrypt(shared_secret, self.buffer_unencrypted)
}
pub fn sequence(&self) -> u64 {
self.sequence
}
pub fn ilp_packet_type(&self) -> IlpPacketType {
self.ilp_packet_type
}
pub fn prepare_amount(&self) -> u64 {
self.prepare_amount
}
pub fn frames(&self) -> FrameIterator {
FrameIterator {
buffer: &self.buffer_unencrypted[self.frames_offset..],
}
}
}
impl fmt::Debug for StreamPacket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"StreamPacket {{ sequence: {}, ilp_packet_type: {:?}, prepare_amount: {}, frames: {:?} }}",
self.sequence,
self.ilp_packet_type,
self.prepare_amount,
self.frames()
)
}
}
pub struct FrameIterator<'a> {
buffer: &'a [u8],
}
impl<'a> FrameIterator<'a> {
fn try_read_next_frame(&mut self) -> Result<Frame<'a>, ParseError> {
let frame_type = self.buffer.read_u8()?;
let contents: &'a [u8] = self.buffer.read_var_octet_string()?;
let frame: Frame<'a> = match FrameType::from(frame_type) {
FrameType::ConnectionClose => {
Frame::ConnectionClose(ConnectionCloseFrame::read_contents(&contents)?)
}
FrameType::ConnectionNewAddress => {
Frame::ConnectionNewAddress(ConnectionNewAddressFrame::read_contents(&contents)?)
}
FrameType::ConnectionAssetDetails => Frame::ConnectionAssetDetails(
ConnectionAssetDetailsFrame::read_contents(&contents)?,
),
FrameType::ConnectionMaxData => {
Frame::ConnectionMaxData(ConnectionMaxDataFrame::read_contents(&contents)?)
}
FrameType::ConnectionDataBlocked => {
Frame::ConnectionDataBlocked(ConnectionDataBlockedFrame::read_contents(&contents)?)
}
FrameType::ConnectionMaxStreamId => {
Frame::ConnectionMaxStreamId(ConnectionMaxStreamIdFrame::read_contents(&contents)?)
}
FrameType::ConnectionStreamIdBlocked => Frame::ConnectionStreamIdBlocked(
ConnectionStreamIdBlockedFrame::read_contents(&contents)?,
),
FrameType::StreamClose => {
Frame::StreamClose(StreamCloseFrame::read_contents(&contents)?)
}
FrameType::StreamMoney => {
Frame::StreamMoney(StreamMoneyFrame::read_contents(&contents)?)
}
FrameType::StreamMaxMoney => {
Frame::StreamMaxMoney(StreamMaxMoneyFrame::read_contents(&contents)?)
}
FrameType::StreamMoneyBlocked => {
Frame::StreamMoneyBlocked(StreamMoneyBlockedFrame::read_contents(&contents)?)
}
FrameType::StreamData => Frame::StreamData(StreamDataFrame::read_contents(&contents)?),
FrameType::StreamMaxData => {
Frame::StreamMaxData(StreamMaxDataFrame::read_contents(&contents)?)
}
FrameType::StreamDataBlocked => {
Frame::StreamDataBlocked(StreamDataBlockedFrame::read_contents(&contents)?)
}
FrameType::Unknown => {
warn!(
"Ignoring unknown frame of type {}: {:x?}",
frame_type, contents,
);
Frame::Unknown
}
};
Ok(frame)
}
}
impl<'a> Iterator for FrameIterator<'a> {
type Item = Frame<'a>;
fn next(&mut self) -> Option<Self::Item> {
while !self.buffer.is_empty() {
// TODO don't ignore errors if the packet is just invalid
match self.try_read_next_frame() {
Ok(frame) => return Some(frame),
Err(err) => warn!("Error reading STREAM frame: {:?}", err),
}
}
None
}
}
impl<'a> fmt::Debug for FrameIterator<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[ ")?;
let mut iter = FrameIterator {
buffer: &self.buffer[..],
};
if let Some(next) = iter.next() {
write!(f, "{:?}", next)?;
}
for frame in iter {
write!(f, ", {:?}", frame)?;
}
write!(f, " ]")
}
}
#[derive(PartialEq, Clone)]
pub enum Frame<'a> {
ConnectionClose(ConnectionCloseFrame<'a>),
ConnectionNewAddress(ConnectionNewAddressFrame<'a>),
ConnectionAssetDetails(ConnectionAssetDetailsFrame<'a>),
ConnectionMaxData(ConnectionMaxDataFrame),
ConnectionDataBlocked(ConnectionDataBlockedFrame),
ConnectionMaxStreamId(ConnectionMaxStreamIdFrame),
ConnectionStreamIdBlocked(ConnectionStreamIdBlockedFrame),
StreamClose(StreamCloseFrame<'a>),
StreamMoney(StreamMoneyFrame),
StreamMaxMoney(StreamMaxMoneyFrame),
StreamMoneyBlocked(StreamMoneyBlockedFrame),
StreamData(StreamDataFrame<'a>),
StreamMaxData(StreamMaxDataFrame),
StreamDataBlocked(StreamDataBlockedFrame),
Unknown,
}
impl<'a> fmt::Debug for Frame<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Frame::ConnectionClose(frame) => write!(f, "{:?}", frame),
Frame::ConnectionNewAddress(frame) => write!(f, "{:?}", frame),
Frame::ConnectionAssetDetails(frame) => write!(f, "{:?}", frame),
Frame::ConnectionMaxData(frame) => write!(f, "{:?}", frame),
Frame::ConnectionDataBlocked(frame) => write!(f, "{:?}", frame),
Frame::ConnectionMaxStreamId(frame) => write!(f, "{:?}", frame),
Frame::ConnectionStreamIdBlocked(frame) => write!(f, "{:?}", frame),
Frame::StreamClose(frame) => write!(f, "{:?}", frame),
Frame::StreamMoney(frame) => write!(f, "{:?}", frame),
Frame::StreamMaxMoney(frame) => write!(f, "{:?}", frame),
Frame::StreamMoneyBlocked(frame) => write!(f, "{:?}", frame),
Frame::StreamData(frame) => write!(f, "{:?}", frame),
Frame::StreamMaxData(frame) => write!(f, "{:?}", frame),
Frame::StreamDataBlocked(frame) => write!(f, "{:?}", frame),
Frame::Unknown => write!(f, "UnknownFrame"),
}
}
}
#[derive(Debug, PartialEq, Clone)]
#[repr(u8)]
pub enum FrameType {
ConnectionClose = 0x01,
ConnectionNewAddress = 0x02,
ConnectionMaxData = 0x03,
ConnectionDataBlocked = 0x04,
ConnectionMaxStreamId = 0x05,
ConnectionStreamIdBlocked = 0x06,
ConnectionAssetDetails = 0x07,
StreamClose = 0x10,
StreamMoney = 0x11,
StreamMaxMoney = 0x12,
StreamMoneyBlocked = 0x13,
StreamData = 0x14,
StreamMaxData = 0x15,
StreamDataBlocked = 0x16,
Unknown,
}
impl From<u8> for FrameType {
fn from(num: u8) -> Self {
match num {
0x01 => FrameType::ConnectionClose,
0x02 => FrameType::ConnectionNewAddress,
0x03 => FrameType::ConnectionMaxData,
0x04 => FrameType::ConnectionDataBlocked,
0x05 => FrameType::ConnectionMaxStreamId,
0x06 => FrameType::ConnectionStreamIdBlocked,
0x07 => FrameType::ConnectionAssetDetails,
0x10 => FrameType::StreamClose,
0x11 => FrameType::StreamMoney,
0x12 => FrameType::StreamMaxMoney,
0x13 => FrameType::StreamMoneyBlocked,
0x14 => FrameType::StreamData,
0x15 => FrameType::StreamMaxData,
0x16 => FrameType::StreamDataBlocked,
_ => FrameType::Unknown,
}
}
}
#[derive(Debug, PartialEq, Clone)]
#[repr(u8)]
pub enum ErrorCode {
NoError = 0x01,
InternalError = 0x02,
EndpointBusy = 0x03,
FlowControlError = 0x04,
StreamIdError = 0x05,
StreamStateError = 0x06,
FrameFormatError = 0x07,
ProtocolViolation = 0x08,
ApplicationError = 0x09,
Unknown,
}
impl From<u8> for ErrorCode {
fn from(num: u8) -> Self {
match num {
0x01 => ErrorCode::NoError,
0x02 => ErrorCode::InternalError,
0x03 => ErrorCode::EndpointBusy,
0x04 => ErrorCode::FlowControlError,
0x05 => ErrorCode::StreamIdError,
0x06 => ErrorCode::StreamStateError,
0x07 => ErrorCode::FrameFormatError,
0x08 => ErrorCode::ProtocolViolation,
0x09 => ErrorCode::ApplicationError,
_ => ErrorCode::Unknown,
}
}
}
pub trait SerializableFrame<'a>: Sized {
fn put_contents(&self, buf: &mut impl MutBufOerExt) -> ();
fn read_contents(reader: &'a [u8]) -> Result<Self, ParseError>;
}
#[derive(Debug, PartialEq, Clone)]
pub struct ConnectionCloseFrame<'a> {
pub code: ErrorCode,
pub message: &'a str,
}
impl<'a> SerializableFrame<'a> for ConnectionCloseFrame<'a> {
fn read_contents(mut reader: &'a [u8]) -> Result<Self, ParseError> {
let code = ErrorCode::from(reader.read_u8()?);
let message_bytes = reader.read_var_octet_string()?;
let message = str::from_utf8(message_bytes)?;
Ok(ConnectionCloseFrame { code, message })
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_u8(self.code.clone() as u8);
buf.put_var_octet_string(self.message.as_bytes());
}
}
#[derive(PartialEq, Clone)]
pub struct ConnectionNewAddressFrame<'a> {
pub source_account: &'a [u8],
}
impl<'a> SerializableFrame<'a> for ConnectionNewAddressFrame<'a> {
fn read_contents(mut reader: &'a [u8]) -> Result<Self, ParseError> {
let source_account = reader.read_var_octet_string()?;
Ok(ConnectionNewAddressFrame { source_account })
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_octet_string(self.source_account);
}
}
impl<'a> fmt::Debug for ConnectionNewAddressFrame<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"ConnectionNewAddressFrame {{ source_account: {} }}",
str::from_utf8(self.source_account).map_err(|_| fmt::Error)?
)
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct ConnectionAssetDetailsFrame<'a> {
pub source_asset_code: &'a str,
pub source_asset_scale: u8,
}
impl<'a> SerializableFrame<'a> for ConnectionAssetDetailsFrame<'a> {
fn read_contents(mut reader: &'a [u8]) -> Result<Self, ParseError> {
let source_asset_code = str::from_utf8(reader.read_var_octet_string()?)?;
let source_asset_scale = reader.read_u8()?;
Ok(ConnectionAssetDetailsFrame {
source_asset_scale,
source_asset_code,
})
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_octet_string(self.source_asset_code.as_bytes());
buf.put_u8(self.source_asset_scale);
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct ConnectionMaxDataFrame {
pub max_offset: u64,
}
impl<'a> SerializableFrame<'a> for ConnectionMaxDataFrame {
fn read_contents(mut reader: &[u8]) -> Result<Self, ParseError> {
let max_offset = reader.read_var_uint()?;
Ok(ConnectionMaxDataFrame { max_offset })
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.max_offset);
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct ConnectionDataBlockedFrame {
pub max_offset: u64,
}
impl<'a> SerializableFrame<'a> for ConnectionDataBlockedFrame {
fn read_contents(mut reader: &[u8]) -> Result<Self, ParseError> {
let max_offset = reader.read_var_uint()?;
Ok(ConnectionDataBlockedFrame { max_offset })
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.max_offset);
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct ConnectionMaxStreamIdFrame {
pub max_stream_id: u64,
}
impl<'a> SerializableFrame<'a> for ConnectionMaxStreamIdFrame {
fn read_contents(mut reader: &[u8]) -> Result<Self, ParseError> {
let max_stream_id = reader.read_var_uint()?;
Ok(ConnectionMaxStreamIdFrame { max_stream_id })
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.max_stream_id);
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct ConnectionStreamIdBlockedFrame {
pub max_stream_id: u64,
}
impl<'a> SerializableFrame<'a> for ConnectionStreamIdBlockedFrame {
fn read_contents(mut reader: &[u8]) -> Result<Self, ParseError> {
let max_stream_id = reader.read_var_uint()?;
Ok(ConnectionStreamIdBlockedFrame { max_stream_id })
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.max_stream_id);
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct StreamCloseFrame<'a> {
pub stream_id: u64,
pub code: ErrorCode,
pub message: &'a str,
}
impl<'a> SerializableFrame<'a> for StreamCloseFrame<'a> {
fn read_contents(mut reader: &'a [u8]) -> Result<Self, ParseError> {
let stream_id = reader.read_var_uint()?;
let code = ErrorCode::from(reader.read_u8()?);
let message_bytes = reader.read_var_octet_string()?;
let message = str::from_utf8(message_bytes)?;
Ok(StreamCloseFrame {
stream_id,
code,
message,
})
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.stream_id);
buf.put_u8(self.code.clone() as u8);
buf.put_var_octet_string(self.message.as_bytes());
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct StreamMoneyFrame {
pub stream_id: u64,
pub shares: u64,
}
impl<'a> SerializableFrame<'a> for StreamMoneyFrame {
fn read_contents(mut reader: &[u8]) -> Result<Self, ParseError> {
let stream_id = reader.read_var_uint()?;
let shares = reader.read_var_uint()?;
Ok(StreamMoneyFrame { stream_id, shares })
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.stream_id);
buf.put_var_uint(self.shares);
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct StreamMaxMoneyFrame {
pub stream_id: u64,
pub receive_max: u64,
pub total_received: u64,
}
impl<'a> SerializableFrame<'a> for StreamMaxMoneyFrame {
fn read_contents(mut reader: &[u8]) -> Result<Self, ParseError> {
let stream_id = reader.read_var_uint()?;
let receive_max = reader.read_var_uint()?;
let total_received = reader.read_var_uint()?;
Ok(StreamMaxMoneyFrame {
stream_id,
receive_max,
total_received,
})
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.stream_id);
buf.put_var_uint(self.receive_max);
buf.put_var_uint(self.total_received);
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct StreamMoneyBlockedFrame {
pub stream_id: u64,
pub send_max: u64,
pub total_sent: u64,
}
impl<'a> SerializableFrame<'a> for StreamMoneyBlockedFrame {
fn read_contents(mut reader: &[u8]) -> Result<Self, ParseError> {
let stream_id = reader.read_var_uint()?;
let send_max = reader.read_var_uint()?;
let total_sent = reader.read_var_uint()?;
Ok(StreamMoneyBlockedFrame {
stream_id,
send_max,
total_sent,
})
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.stream_id);
buf.put_var_uint(self.send_max);
buf.put_var_uint(self.total_sent);
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct StreamDataFrame<'a> {
pub stream_id: u64,
pub offset: u64,
pub data: &'a [u8],
}
impl<'a> SerializableFrame<'a> for StreamDataFrame<'a> {
fn read_contents(mut reader: &'a [u8]) -> Result<Self, ParseError> {
let stream_id = reader.read_var_uint()?;
let offset = reader.read_var_uint()?;
let data = reader.read_var_octet_string()?;
Ok(StreamDataFrame {
stream_id,
offset,
data,
})
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.stream_id);
buf.put_var_uint(self.offset);
buf.put_var_octet_string(self.data);
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct StreamMaxDataFrame {
pub stream_id: u64,
pub max_offset: u64,
}
impl<'a> SerializableFrame<'a> for StreamMaxDataFrame {
fn read_contents(mut reader: &[u8]) -> Result<Self, ParseError> {
let stream_id = reader.read_var_uint()?;
let max_offset = reader.read_var_uint()?;
Ok(StreamMaxDataFrame {
stream_id,
max_offset,
})
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.stream_id);
buf.put_var_uint(self.max_offset);
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct StreamDataBlockedFrame {
pub stream_id: u64,
pub max_offset: u64,
}
impl<'a> SerializableFrame<'a> for StreamDataBlockedFrame {
fn read_contents(mut reader: &[u8]) -> Result<Self, ParseError> {
let stream_id = reader.read_var_uint()?;
let max_offset = reader.read_var_uint()?;
Ok(StreamDataBlockedFrame {
stream_id,
max_offset,
})
}
fn put_contents(&self, buf: &mut impl MutBufOerExt) {
buf.put_var_uint(self.stream_id);
buf.put_var_uint(self.max_offset);
}
}
#[cfg(test)]
mod serialization {
use super::*;
lazy_static! {
static ref PACKET: StreamPacket = StreamPacketBuilder {
sequence: 1,
ilp_packet_type: IlpPacketType::try_from(12).unwrap(),
prepare_amount: 99,
frames: &[
Frame::ConnectionClose(ConnectionCloseFrame {
code: ErrorCode::NoError,
message: "oop"
}),
Frame::ConnectionNewAddress(ConnectionNewAddressFrame {
source_account: b"example.blah"
}),
Frame::ConnectionMaxData(ConnectionMaxDataFrame { max_offset: 1000 }),
Frame::ConnectionDataBlocked(ConnectionDataBlockedFrame { max_offset: 2000 }),
Frame::ConnectionMaxStreamId(ConnectionMaxStreamIdFrame {
max_stream_id: 3000,
}),
Frame::ConnectionStreamIdBlocked(ConnectionStreamIdBlockedFrame {
max_stream_id: 4000,
}),
Frame::ConnectionAssetDetails(ConnectionAssetDetailsFrame {
source_asset_code: "XYZ",
source_asset_scale: 9
}),
Frame::StreamClose(StreamCloseFrame {
stream_id: 76,
code: ErrorCode::InternalError,
message: "blah",
}),
Frame::StreamMoney(StreamMoneyFrame {
stream_id: 88,
shares: 99,
}),
Frame::StreamMaxMoney(StreamMaxMoneyFrame {
stream_id: 11,
receive_max: 987,
total_received: 500,
}),
Frame::StreamMoneyBlocked(StreamMoneyBlockedFrame {
stream_id: 66,
send_max: 20000,
total_sent: 6000,
}),
Frame::StreamData(StreamDataFrame {
stream_id: 34,
offset: 9000,
data: b"hello",
}),
Frame::StreamMaxData(StreamMaxDataFrame {
stream_id: 35,
max_offset: 8766
}),
Frame::StreamDataBlocked(StreamDataBlockedFrame {
stream_id: 888,
max_offset: 44444
}),
]
}
.build();
static ref SERIALIZED: BytesMut = BytesMut::from(vec![
1, 12, 1, 1, 1, 99, 1, 14, 1, 5, 1, 3, 111, 111, 112, 2, 13, 12, 101, 120, 97, 109,
112, 108, 101, 46, 98, 108, 97, 104, 3, 3, 2, 3, 232, 4, 3, 2, 7, 208, 5, 3, 2, 11,
184, 6, 3, 2, 15, 160, 7, 5, 3, 88, 89, 90, 9, 16, 8, 1, 76, 2, 4, 98, 108, 97, 104,
17, 4, 1, 88, 1, 99, 18, 8, 1, 11, 2, 3, 219, 2, 1, 244, 19, 8, 1, 66, 2, 78, 32, 2,
23, 112, 20, 11, 1, 34, 2, 35, 40, 5, 104, 101, 108, 108, 111, 21, 5, 1, 35, 2, 34, 62,
22, 6, 2, 3, 120, 2, 173, 156
]);
}
#[test]
fn it_serializes_to_same_as_javascript() {
assert_eq!(PACKET.buffer_unencrypted, *SERIALIZED);
}
#[test]
fn it_deserializes_from_javascript() {
assert_eq!(
StreamPacket::from_bytes_unencrypted(SERIALIZED.clone()).unwrap(),
*PACKET
);
}
#[test]
fn it_iterates_through_the_frames() {
let mut iter = PACKET.frames();
assert_eq!(
iter.next().unwrap(),
Frame::ConnectionClose(ConnectionCloseFrame {
code: ErrorCode::NoError,
message: "oop"
})
);
assert_eq!(
iter.next().unwrap(),
Frame::ConnectionNewAddress(ConnectionNewAddressFrame {
source_account: b"example.blah"
})
);
assert_eq!(iter.count(), 12);
}
}
| 33.719615 | 103 | 0.584169 |
1c85413a8d8eb7a02f401790aa209e8620210036 | 15,779 | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Name resolution for lifetimes.
*
* Name resolution for lifetimes follows MUCH simpler rules than the
* full resolve. For example, lifetime names are never exported or
* used between functions, and they operate in a purely top-down
* way. Therefore we break lifetime name resolution into a separate pass.
*/
use driver::session::Session;
use middle::subst;
use syntax::ast;
use syntax::codemap::Span;
use syntax::owned_slice::OwnedSlice;
use syntax::parse::token::special_idents;
use syntax::parse::token;
use syntax::print::pprust::{lifetime_to_string};
use syntax::visit;
use syntax::visit::Visitor;
use util::nodemap::NodeMap;
#[deriving(Clone, PartialEq, Eq, Hash, Encodable, Decodable, Show)]
pub enum DefRegion {
DefStaticRegion,
DefEarlyBoundRegion(/* space */ subst::ParamSpace,
/* index */ uint,
/* lifetime decl */ ast::NodeId),
DefLateBoundRegion(/* binder_id */ ast::NodeId,
/* depth */ uint,
/* lifetime decl */ ast::NodeId),
DefFreeRegion(/* block scope */ ast::NodeId,
/* lifetime decl */ ast::NodeId),
}
// maps the id of each lifetime reference to the lifetime decl
// that it corresponds to
pub type NamedRegionMap = NodeMap<DefRegion>;
// Returns an instance of some type that implements std::fmt::Show
fn lifetime_show(lt_name: &ast::Name) -> token::InternedString {
token::get_name(*lt_name)
}
struct LifetimeContext<'a> {
sess: &'a Session,
named_region_map: NamedRegionMap,
}
enum ScopeChain<'a> {
/// EarlyScope(i, ['a, 'b, ...], s) extends s with early-bound
/// lifetimes, assigning indexes 'a => i, 'b => i+1, ... etc.
EarlyScope(subst::ParamSpace, &'a Vec<ast::Lifetime>, Scope<'a>),
/// LateScope(binder_id, ['a, 'b, ...], s) extends s with late-bound
/// lifetimes introduced by the declaration binder_id.
LateScope(ast::NodeId, &'a Vec<ast::Lifetime>, Scope<'a>),
/// lifetimes introduced by items within a code block are scoped
/// to that block.
BlockScope(ast::NodeId, Scope<'a>),
RootScope
}
type Scope<'a> = &'a ScopeChain<'a>;
pub fn krate(sess: &Session, krate: &ast::Crate) -> NamedRegionMap {
let mut ctxt = LifetimeContext {
sess: sess,
named_region_map: NodeMap::new()
};
visit::walk_crate(&mut ctxt, krate, &RootScope);
sess.abort_if_errors();
ctxt.named_region_map
}
impl<'a, 'b> Visitor<Scope<'a>> for LifetimeContext<'b> {
fn visit_item(&mut self,
item: &ast::Item,
_: Scope<'a>) {
let root = RootScope;
let scope = match item.node {
ast::ItemFn(..) | // fn lifetimes get added in visit_fn below
ast::ItemMod(..) |
ast::ItemMac(..) |
ast::ItemForeignMod(..) |
ast::ItemStatic(..) => {
RootScope
}
ast::ItemTy(_, ref generics) |
ast::ItemEnum(_, ref generics) |
ast::ItemStruct(_, ref generics) |
ast::ItemImpl(ref generics, _, _, _) |
ast::ItemTrait(ref generics, _, _, _) => {
self.check_lifetime_names(&generics.lifetimes);
EarlyScope(subst::TypeSpace, &generics.lifetimes, &root)
}
};
debug!("entering scope {:?}", scope);
visit::walk_item(self, item, &scope);
debug!("exiting scope {:?}", scope);
}
fn visit_fn(&mut self, fk: &visit::FnKind, fd: &ast::FnDecl,
b: &ast::Block, s: Span, n: ast::NodeId,
scope: Scope<'a>) {
match *fk {
visit::FkItemFn(_, generics, _, _) |
visit::FkMethod(_, generics, _) => {
self.visit_fn_decl(
n, generics, scope,
|this, scope1| visit::walk_fn(this, fk, fd, b, s, scope1))
}
visit::FkFnBlock(..) => {
visit::walk_fn(self, fk, fd, b, s, scope)
}
}
}
fn visit_ty(&mut self, ty: &ast::Ty, scope: Scope<'a>) {
match ty.node {
ast::TyClosure(c, _) | ast::TyProc(c) => {
push_fn_scope(self, ty, scope, &c.lifetimes);
}
ast::TyBareFn(c) => push_fn_scope(self, ty, scope, &c.lifetimes),
_ => visit::walk_ty(self, ty, scope),
}
fn push_fn_scope(this: &mut LifetimeContext,
ty: &ast::Ty,
scope: Scope,
lifetimes: &Vec<ast::Lifetime>) {
let scope1 = LateScope(ty.id, lifetimes, scope);
this.check_lifetime_names(lifetimes);
debug!("pushing fn scope id={} due to type", ty.id);
visit::walk_ty(this, ty, &scope1);
debug!("popping fn scope id={} due to type", ty.id);
}
}
fn visit_ty_method(&mut self,
m: &ast::TypeMethod,
scope: Scope<'a>) {
self.visit_fn_decl(
m.id, &m.generics, scope,
|this, scope1| visit::walk_ty_method(this, m, scope1))
}
fn visit_block(&mut self,
b: &ast::Block,
scope: Scope<'a>) {
let scope1 = BlockScope(b.id, scope);
debug!("pushing block scope {}", b.id);
visit::walk_block(self, b, &scope1);
debug!("popping block scope {}", b.id);
}
fn visit_lifetime_ref(&mut self,
lifetime_ref: &ast::Lifetime,
scope: Scope<'a>) {
if lifetime_ref.name == special_idents::static_lifetime.name {
self.insert_lifetime(lifetime_ref, DefStaticRegion);
return;
}
self.resolve_lifetime_ref(lifetime_ref, scope);
}
}
impl<'a> LifetimeContext<'a> {
/// Visits self by adding a scope and handling recursive walk over the contents with `walk`.
fn visit_fn_decl(&mut self,
n: ast::NodeId,
generics: &ast::Generics,
scope: Scope,
walk: |&mut LifetimeContext, Scope|) {
/*!
* Handles visiting fns and methods. These are a bit
* complicated because we must distinguish early- vs late-bound
* lifetime parameters. We do this by checking which lifetimes
* appear within type bounds; those are early bound lifetimes,
* and the rest are late bound.
*
* For example:
*
* fn foo<'a,'b,'c,T:Trait<'b>>(...)
*
* Here `'a` and `'c` are late bound but `'b` is early
* bound. Note that early- and late-bound lifetimes may be
* interspersed together.
*
* If early bound lifetimes are present, we separate them into
* their own list (and likewise for late bound). They will be
* numbered sequentially, starting from the lowest index that
* is already in scope (for a fn item, that will be 0, but for
* a method it might not be). Late bound lifetimes are
* resolved by name and associated with a binder id (`n`), so
* the ordering is not important there.
*/
self.check_lifetime_names(&generics.lifetimes);
let referenced_idents = free_lifetimes(&generics.ty_params);
debug!("pushing fn scope id={} due to fn item/method\
referenced_idents={:?}",
n,
referenced_idents.iter().map(lifetime_show).collect::<Vec<token::InternedString>>());
if referenced_idents.is_empty() {
let scope1 = LateScope(n, &generics.lifetimes, scope);
walk(self, &scope1)
} else {
let (early, late) = generics.lifetimes.clone().partition(
|l| referenced_idents.iter().any(|&i| i == l.name));
let scope1 = EarlyScope(subst::FnSpace, &early, scope);
let scope2 = LateScope(n, &late, &scope1);
walk(self, &scope2);
}
debug!("popping fn scope id={} due to fn item/method", n);
}
fn resolve_lifetime_ref(&mut self,
lifetime_ref: &ast::Lifetime,
scope: Scope) {
// Walk up the scope chain, tracking the number of fn scopes
// that we pass through, until we find a lifetime with the
// given name or we run out of scopes. If we encounter a code
// block, then the lifetime is not bound but free, so switch
// over to `resolve_free_lifetime_ref()` to complete the
// search.
let mut depth = 0;
let mut scope = scope;
loop {
match *scope {
BlockScope(id, s) => {
return self.resolve_free_lifetime_ref(id, lifetime_ref, s);
}
RootScope => {
break;
}
EarlyScope(space, lifetimes, s) => {
match search_lifetimes(lifetimes, lifetime_ref) {
Some((index, decl_id)) => {
let def = DefEarlyBoundRegion(space, index, decl_id);
self.insert_lifetime(lifetime_ref, def);
return;
}
None => {
depth += 1;
scope = s;
}
}
}
LateScope(binder_id, lifetimes, s) => {
match search_lifetimes(lifetimes, lifetime_ref) {
Some((_index, decl_id)) => {
let def = DefLateBoundRegion(binder_id, depth, decl_id);
self.insert_lifetime(lifetime_ref, def);
return;
}
None => {
depth += 1;
scope = s;
}
}
}
}
}
self.unresolved_lifetime_ref(lifetime_ref);
}
fn resolve_free_lifetime_ref(&mut self,
scope_id: ast::NodeId,
lifetime_ref: &ast::Lifetime,
scope: Scope) {
// Walk up the scope chain, tracking the outermost free scope,
// until we encounter a scope that contains the named lifetime
// or we run out of scopes.
let mut scope_id = scope_id;
let mut scope = scope;
let mut search_result = None;
loop {
match *scope {
BlockScope(id, s) => {
scope_id = id;
scope = s;
}
RootScope => {
break;
}
EarlyScope(_, lifetimes, s) |
LateScope(_, lifetimes, s) => {
search_result = search_lifetimes(lifetimes, lifetime_ref);
if search_result.is_some() {
break;
}
scope = s;
}
}
}
match search_result {
Some((_depth, decl_id)) => {
let def = DefFreeRegion(scope_id, decl_id);
self.insert_lifetime(lifetime_ref, def);
}
None => {
self.unresolved_lifetime_ref(lifetime_ref);
}
}
}
fn unresolved_lifetime_ref(&self,
lifetime_ref: &ast::Lifetime) {
self.sess.span_err(
lifetime_ref.span,
format!("use of undeclared lifetime name `{}`",
token::get_name(lifetime_ref.name)).as_slice());
}
fn check_lifetime_names(&self, lifetimes: &Vec<ast::Lifetime>) {
for i in range(0, lifetimes.len()) {
let lifetime_i = lifetimes.get(i);
let special_idents = [special_idents::static_lifetime];
for lifetime in lifetimes.iter() {
if special_idents.iter().any(|&i| i.name == lifetime.name) {
self.sess.span_err(
lifetime.span,
format!("illegal lifetime parameter name: `{}`",
token::get_name(lifetime.name)).as_slice());
}
}
for j in range(i + 1, lifetimes.len()) {
let lifetime_j = lifetimes.get(j);
if lifetime_i.name == lifetime_j.name {
self.sess.span_err(
lifetime_j.span,
format!("lifetime name `{}` declared twice in \
the same scope",
token::get_name(lifetime_j.name)).as_slice());
}
}
}
}
fn insert_lifetime(&mut self,
lifetime_ref: &ast::Lifetime,
def: DefRegion) {
if lifetime_ref.id == ast::DUMMY_NODE_ID {
self.sess.span_bug(lifetime_ref.span,
"lifetime reference not renumbered, \
probably a bug in syntax::fold");
}
debug!("lifetime_ref={} id={} resolved to {:?}",
lifetime_to_string(lifetime_ref),
lifetime_ref.id,
def);
self.named_region_map.insert(lifetime_ref.id, def);
}
}
fn search_lifetimes(lifetimes: &Vec<ast::Lifetime>,
lifetime_ref: &ast::Lifetime)
-> Option<(uint, ast::NodeId)> {
for (i, lifetime_decl) in lifetimes.iter().enumerate() {
if lifetime_decl.name == lifetime_ref.name {
return Some((i, lifetime_decl.id));
}
}
return None;
}
///////////////////////////////////////////////////////////////////////////
pub fn early_bound_lifetimes<'a>(generics: &'a ast::Generics) -> Vec<ast::Lifetime> {
let referenced_idents = free_lifetimes(&generics.ty_params);
if referenced_idents.is_empty() {
return Vec::new();
}
generics.lifetimes.iter()
.filter(|l| referenced_idents.iter().any(|&i| i == l.name))
.map(|l| *l)
.collect()
}
pub fn free_lifetimes(ty_params: &OwnedSlice<ast::TyParam>) -> Vec<ast::Name> {
/*!
* Gathers up and returns the names of any lifetimes that appear
* free in `ty_params`. Of course, right now, all lifetimes appear
* free, since we don't currently have any binders in type parameter
* declarations; just being forwards compatible with future extensions.
*/
let mut collector = FreeLifetimeCollector { names: vec!() };
for ty_param in ty_params.iter() {
visit::walk_ty_param_bounds(&mut collector, &ty_param.bounds, ());
}
return collector.names;
struct FreeLifetimeCollector {
names: Vec<ast::Name>,
}
impl Visitor<()> for FreeLifetimeCollector {
fn visit_lifetime_ref(&mut self,
lifetime_ref: &ast::Lifetime,
_: ()) {
self.names.push(lifetime_ref.name);
}
}
}
| 36.441109 | 100 | 0.520755 |
084b7a166cdd36c4f9a24d18ec61996c5051216e | 1,358 | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:issue13507.rs
#![feature(core)]
extern crate issue13507;
use issue13507::testtypes;
use std::any::TypeId;
pub fn type_ids() -> Vec<TypeId> {
use issue13507::testtypes::*;
vec![
TypeId::of::<FooBool>(),
TypeId::of::<FooInt>(),
TypeId::of::<FooUint>(),
TypeId::of::<FooFloat>(),
TypeId::of::<FooStr>(),
TypeId::of::<FooArray>(),
TypeId::of::<FooSlice>(),
TypeId::of::<FooBox>(),
TypeId::of::<FooPtr>(),
TypeId::of::<FooRef>(),
TypeId::of::<FooFnPtr>(),
TypeId::of::<FooNil>(),
TypeId::of::<FooTuple>(),
TypeId::of::<FooTrait>(),
TypeId::of::<FooStruct>(),
TypeId::of::<FooEnum>()
]
}
pub fn main() {
let othercrate = issue13507::testtypes::type_ids();
let thiscrate = type_ids();
assert_eq!(thiscrate, othercrate);
}
| 28.291667 | 69 | 0.608984 |
dba82e8f1d89a9f0899f612cd76864ad154767a6 | 9,662 | //! Console Capsule
//!
//! Console provides userspace with the ability to print text via a serial
//! interface.
use core::cell::Cell;
use kernel::{AppId, AppSlice, Container, Callback, Shared, Driver, ReturnCode};
use kernel::common::take_cell::TakeCell;
use kernel::hil::uart::{self, UART, Client};
use kernel::process::Error;
pub struct App {
write_callback: Option<Callback>,
read_buffer: Option<AppSlice<Shared, u8>>,
write_buffer: Option<AppSlice<Shared, u8>>,
write_len: usize,
write_remaining: usize, // How many bytes didn't fit in the buffer and still need to be printed.
pending_write: bool,
read_idx: usize,
}
impl Default for App {
fn default() -> App {
App {
write_callback: None,
read_buffer: None,
write_buffer: None,
write_len: 0,
write_remaining: 0,
pending_write: false,
read_idx: 0,
}
}
}
pub static mut WRITE_BUF: [u8; 64] = [0; 64];
pub struct Console<'a, U: UART + 'a> {
uart: &'a U,
apps: Container<App>,
in_progress: Cell<Option<AppId>>,
tx_buffer: TakeCell<'static, [u8]>,
baud_rate: u32,
}
impl<'a, U: UART> Console<'a, U> {
pub fn new(uart: &'a U,
baud_rate: u32,
tx_buffer: &'static mut [u8],
container: Container<App>)
-> Console<'a, U> {
Console {
uart: uart,
apps: container,
in_progress: Cell::new(None),
tx_buffer: TakeCell::new(tx_buffer),
baud_rate: baud_rate,
}
}
pub fn initialize(&self) {
self.uart.init(uart::UARTParams {
baud_rate: self.baud_rate,
stop_bits: uart::StopBits::One,
parity: uart::Parity::None,
hw_flow_control: false,
});
}
/// Internal helper function for setting up a new send transaction
fn send_new(&self, app_id: AppId, app: &mut App, callback: Callback) -> ReturnCode {
match app.write_buffer.take() {
Some(slice) => {
app.write_len = slice.len();
app.write_remaining = app.write_len;
app.write_callback = Some(callback);
self.send(app_id, app, slice);
ReturnCode::SUCCESS
}
None => ReturnCode::EBUSY,
}
}
/// Internal helper function for continuing a previously set up transaction
/// Returns true if this send is still active, or false if it has completed
fn send_continue(&self, app_id: AppId, app: &mut App) -> Result<bool, ReturnCode> {
if app.write_remaining > 0 {
app.write_buffer.take().map_or(Err(ReturnCode::ERESERVE), |slice| {
self.send(app_id, app, slice);
Ok(true)
})
} else {
Ok(false)
}
}
/// Internal helper function for sending data for an existing transaction.
/// Cannot fail. If can't send now, it will schedule for sending later.
fn send(&self, app_id: AppId, app: &mut App, slice: AppSlice<Shared, u8>) {
if self.in_progress.get().is_none() {
self.in_progress.set(Some(app_id));
self.tx_buffer.take().map(|buffer| {
let mut transaction_len = app.write_remaining;
for (i, c) in slice.as_ref()[slice.len() - app.write_remaining..slice.len()]
.iter()
.enumerate() {
if buffer.len() <= i {
break;
}
buffer[i] = *c;
}
// Check if everything we wanted to print
// fit in the buffer.
if app.write_remaining > buffer.len() {
transaction_len = buffer.len();
app.write_remaining -= buffer.len();
app.write_buffer = Some(slice);
} else {
app.write_remaining = 0;
}
self.uart.transmit(buffer, transaction_len);
});
} else {
app.pending_write = true;
app.write_buffer = Some(slice);
}
}
}
impl<'a, U: UART> Driver for Console<'a, U> {
fn allow(&self, appid: AppId, allow_num: usize, slice: AppSlice<Shared, u8>) -> ReturnCode {
match allow_num {
0 => {
self.apps
.enter(appid, |app, _| {
app.read_buffer = Some(slice);
app.read_idx = 0;
ReturnCode::SUCCESS
})
.unwrap_or_else(|err| match err {
Error::OutOfMemory => ReturnCode::ENOMEM,
Error::AddressOutOfBounds => ReturnCode::EINVAL,
Error::NoSuchApp => ReturnCode::EINVAL,
})
}
1 => {
self.apps
.enter(appid, |app, _| {
app.write_buffer = Some(slice);
ReturnCode::SUCCESS
})
.unwrap_or_else(|err| match err {
Error::OutOfMemory => ReturnCode::ENOMEM,
Error::AddressOutOfBounds => ReturnCode::EINVAL,
Error::NoSuchApp => ReturnCode::EINVAL,
})
}
_ => ReturnCode::ENOSUPPORT,
}
}
fn subscribe(&self, subscribe_num: usize, callback: Callback) -> ReturnCode {
match subscribe_num {
0 /* read line */ => {
// read line is not implemented for console at this time
ReturnCode::ENOSUPPORT
},
1 /* putstr/write_done */ => {
self.apps.enter(callback.app_id(), |app, _| {
self.send_new(callback.app_id(), app, callback)
}).unwrap_or_else(|err| {
match err {
Error::OutOfMemory => ReturnCode::ENOMEM,
Error::AddressOutOfBounds => ReturnCode::EINVAL,
Error::NoSuchApp => ReturnCode::EINVAL,
}
})
},
_ => ReturnCode::ENOSUPPORT
}
}
fn command(&self, cmd_num: usize, arg1: usize, _: AppId) -> ReturnCode {
match cmd_num {
0 /* check if present */ => ReturnCode::SUCCESS,
1 /* putc */ => {
self.tx_buffer.take().map(|buffer| {
buffer[0] = arg1 as u8;
self.uart.transmit(buffer, 1);
});
ReturnCode::SuccessWithValue { value: 1 }
},
_ => ReturnCode::ENOSUPPORT
}
}
}
impl<'a, U: UART> Client for Console<'a, U> {
fn transmit_complete(&self, buffer: &'static mut [u8], _error: uart::Error) {
// Either print more from the AppSlice or send a callback to the
// application.
self.tx_buffer.replace(buffer);
self.in_progress.get().map(|appid| {
self.in_progress.set(None);
self.apps.enter(appid, |app, _| {
match self.send_continue(appid, app) {
Ok(more_to_send) => {
if !more_to_send {
// Go ahead and signal the application
let written = app.write_len;
app.write_len = 0;
app.write_callback.map(|mut cb| { cb.schedule(written, 0, 0); });
}
}
Err(return_code) => {
// XXX This shouldn't ever happen?
app.write_len = 0;
app.write_remaining = 0;
app.pending_write = false;
let r0 = isize::from(return_code) as usize;
app.write_callback.map(|mut cb| { cb.schedule(r0, 0, 0); });
}
}
})
});
// If we are not printing more from the current AppSlice,
// see if any other applications have pending messages.
if self.in_progress.get().is_none() {
for cntr in self.apps.iter() {
let started_tx = cntr.enter(|app, _| {
if app.pending_write {
app.pending_write = false;
match self.send_continue(app.appid(), app) {
Ok(more_to_send) => more_to_send,
Err(return_code) => {
// XXX This shouldn't ever happen?
app.write_len = 0;
app.write_remaining = 0;
app.pending_write = false;
let r0 = isize::from(return_code) as usize;
app.write_callback.map(|mut cb| { cb.schedule(r0, 0, 0); });
false
}
}
} else {
false
}
});
if started_tx {
break;
}
}
}
}
fn receive_complete(&self,
_rx_buffer: &'static mut [u8],
_rx_len: usize,
_error: uart::Error) {
// this is currently unimplemented for console
}
}
| 36.323308 | 100 | 0.466984 |
67e16f261f47fdf6b6946feff14e901ac104a91e | 3,178 | use crate::{hlt_loop, memory::gdt, print, println};
use lazy_static::lazy_static;
use pc_keyboard::{layouts, HandleControl, Keyboard, ScancodeSet1};
use pic8259_simple::ChainedPics;
use spin::Mutex;
use x86_64::instructions::port::Port;
use x86_64::structures::idt::PageFaultErrorCode;
use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame};
pub const PIC_1_OFFSET: u8 = 32;
pub const PIC_2_OFFSET: u8 = PIC_1_OFFSET + 8;
pub static PICS: spin::Mutex<ChainedPics> =
spin::Mutex::new(unsafe { ChainedPics::new(PIC_1_OFFSET, PIC_2_OFFSET) });
#[derive(Debug, Clone, Copy)]
#[repr(u8)]
pub enum InterruptIndex {
Timer = PIC_1_OFFSET,
Keyboard,
}
impl InterruptIndex {
fn as_u8(self) -> u8 {
self as u8
}
fn as_usize(self) -> usize {
usize::from(self.as_u8())
}
}
lazy_static! {
static ref IDT: InterruptDescriptorTable = {
let mut idt = InterruptDescriptorTable::new();
idt.breakpoint.set_handler_fn(breakpoint_handler);
unsafe {
idt.double_fault
.set_handler_fn(double_fault_handler)
.set_stack_index(gdt::DOUBLE_FAULT_IST_INDEX);
}
idt[InterruptIndex::Timer.as_usize()].set_handler_fn(timer_interrupt_handler);
idt[InterruptIndex::Keyboard.as_usize()].set_handler_fn(keyboard_interrupt_handler);
idt.page_fault.set_handler_fn(page_fault_handler);
idt
};
static ref KEYBOARD: Mutex<Keyboard<layouts::Us104Key, ScancodeSet1>> = Mutex::new(
Keyboard::new(layouts::Us104Key, ScancodeSet1, HandleControl::Ignore)
);
}
pub fn init_idt() {
IDT.load();
}
// Breakpoint handler
extern "x86-interrupt" fn breakpoint_handler(stack_frame: &mut InterruptStackFrame) {
println!("EXCEPTION: BREAKPOINT\n{:#?}", stack_frame);
}
#[test_case]
fn test_breakpoint_exception() {
x86_64::instructions::interrupts::int3();
}
// Double fault handler
extern "x86-interrupt" fn double_fault_handler(
stack_frame: &mut InterruptStackFrame,
_error_code: u64,
) -> ! {
panic!("EXCEPTION: DOUBLE FAULT\n{:#?}", stack_frame);
}
// Timer interrupt handler
extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: &mut InterruptStackFrame) {
print!(".");
unsafe {
PICS.lock()
.notify_end_of_interrupt(InterruptIndex::Timer.as_u8());
}
}
// Keyboard interrupt handler (PS/2)
extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: &mut InterruptStackFrame) {
let _keyboard = KEYBOARD.lock();
let mut port = Port::new(0x60);
let scancode: u8 = unsafe { port.read() };
crate::io::keyboard::add_scancode(scancode);
unsafe {
PICS.lock()
.notify_end_of_interrupt(InterruptIndex::Keyboard.as_u8());
}
}
// Page fault handler
extern "x86-interrupt" fn page_fault_handler(
stack_frame: &mut InterruptStackFrame,
error_code: PageFaultErrorCode,
) {
use x86_64::registers::control::Cr2;
println!("EXCEPTION: PAGE FAULT");
println!("Accessed Address: {:?}", Cr2::read());
println!("Error Code: {:?}", error_code);
println!("{:#?}", stack_frame);
hlt_loop();
}
| 28.890909 | 94 | 0.681561 |
62357bd30e5e6117f1f0d016f2c7f92508949e6e | 6,074 | use bellperson::{ConstraintSystem, SynthesisError};
use ff::Field;
use fil_sapling_crypto::circuit::num;
use paired::Engine;
use crate::circuit::constraint;
/// Circuit version of sloth decoding.
pub fn decode<E, CS>(
mut cs: CS,
key: &num::AllocatedNum<E>,
ciphertext: Option<E::Fr>,
rounds: usize,
) -> Result<num::AllocatedNum<E>, SynthesisError>
where
E: Engine,
CS: ConstraintSystem<E>,
{
let mut plaintext = num::AllocatedNum::alloc(cs.namespace(|| "decoded"), || {
Ok(ciphertext.ok_or_else(|| SynthesisError::AssignmentMissing)?)
})?;
for i in 0..rounds {
let cs = &mut cs.namespace(|| format!("round {}", i));
let c = plaintext;
let c2 = c.square(cs.namespace(|| "c^2"))?;
let c4 = c2.square(cs.namespace(|| "c^4"))?;
let c5 = c4.mul(cs.namespace(|| "c^5"), &c)?;
plaintext = sub(cs.namespace(|| "c^5 - k"), &c5, key)?;
}
if rounds == 0 {
plaintext = sub(cs.namespace(|| "plaintext - k"), &plaintext, key)?;
}
Ok(plaintext)
}
fn sub<E: Engine, CS: ConstraintSystem<E>>(
mut cs: CS,
a: &num::AllocatedNum<E>,
b: &num::AllocatedNum<E>,
) -> Result<num::AllocatedNum<E>, SynthesisError> {
let res = num::AllocatedNum::alloc(cs.namespace(|| "sub num"), || {
let mut tmp = a
.get_value()
.ok_or_else(|| SynthesisError::AssignmentMissing)?;
tmp.sub_assign(
&b.get_value()
.ok_or_else(|| SynthesisError::AssignmentMissing)?,
);
Ok(tmp)
})?;
// a - b = res
constraint::difference(&mut cs, || "subtraction constraint", &a, &b, &res);
Ok(res)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::circuit::test::TestConstraintSystem;
use crate::crypto::sloth;
use paired::bls12_381::{Bls12, Fr};
use rand::{Rng, SeedableRng, XorShiftRng};
#[test]
fn sloth_snark_decode() {
let rng = &mut XorShiftRng::from_seed([0x3dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]);
for _ in 0..10 {
let key: Fr = rng.gen();
let plaintext: Fr = rng.gen();
let ciphertext = sloth::encode::<Bls12>(&key, &plaintext, 10);
// Vanilla
let decrypted = sloth::decode::<Bls12>(&key, &ciphertext, 10);
assert_eq!(plaintext, decrypted, "vanilla failed");
let mut cs = TestConstraintSystem::<Bls12>::new();
let key_num = num::AllocatedNum::alloc(cs.namespace(|| "key"), || Ok(key)).unwrap();
let out = decode(cs.namespace(|| "sloth"), &key_num, Some(ciphertext), 10).unwrap();
assert!(cs.is_satisfied());
assert_eq!(out.get_value().unwrap(), decrypted, "no interop");
}
}
#[test]
fn sloth_snark_decode_bad() {
let rng = &mut XorShiftRng::from_seed([0x3dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]);
for _ in 0..10 {
let key: Fr = rng.gen();
let key_bad: Fr = rng.gen();
let plaintext: Fr = rng.gen();
let ciphertext = sloth::encode::<Bls12>(&key, &plaintext, 10);
let decrypted = sloth::decode::<Bls12>(&key, &ciphertext, 10);
let mut cs = TestConstraintSystem::<Bls12>::new();
let key_bad_num =
num::AllocatedNum::alloc(cs.namespace(|| "key bad"), || Ok(key_bad)).unwrap();
let out = decode(cs.namespace(|| "sloth"), &key_bad_num, Some(ciphertext), 10).unwrap();
assert!(cs.is_satisfied());
assert_ne!(out.get_value().unwrap(), decrypted);
}
}
#[test]
fn sloth_snark_decode_different_iterations() {
let rng = &mut XorShiftRng::from_seed([0x3dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]);
for _ in 0..10 {
let key: Fr = rng.gen();
let plaintext: Fr = rng.gen();
let ciphertext = sloth::encode::<Bls12>(&key, &plaintext, 10);
let decrypted = sloth::decode::<Bls12>(&key, &ciphertext, 10);
{
let mut cs = TestConstraintSystem::<Bls12>::new();
let key_num = num::AllocatedNum::alloc(cs.namespace(|| "key"), || Ok(key)).unwrap();
let out9 =
decode(cs.namespace(|| "sloth 9"), &key_num, Some(ciphertext), 9).unwrap();
assert!(cs.is_satisfied());
assert_ne!(out9.get_value().unwrap(), decrypted);
}
{
let mut cs = TestConstraintSystem::<Bls12>::new();
let key_num = num::AllocatedNum::alloc(cs.namespace(|| "key"), || Ok(key)).unwrap();
let out10 =
decode(cs.namespace(|| "sloth 10"), &key_num, Some(ciphertext), 10).unwrap();
assert!(cs.is_satisfied());
assert_eq!(out10.get_value().unwrap(), decrypted);
}
{
let mut cs = TestConstraintSystem::<Bls12>::new();
let key_num = num::AllocatedNum::alloc(cs.namespace(|| "key"), || Ok(key)).unwrap();
let out11 =
decode(cs.namespace(|| "sloth 11"), &key_num, Some(ciphertext), 11).unwrap();
assert!(cs.is_satisfied());
assert_ne!(out11.get_value().unwrap(), decrypted);
}
}
}
#[test]
fn sub_constraint() {
let rng = &mut XorShiftRng::from_seed([0x3dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]);
for _ in 0..100 {
let mut cs = TestConstraintSystem::<Bls12>::new();
let a = num::AllocatedNum::alloc(cs.namespace(|| "a"), || Ok(rng.gen())).unwrap();
let b = num::AllocatedNum::alloc(cs.namespace(|| "b"), || Ok(rng.gen())).unwrap();
let res = sub(cs.namespace(|| "a-b"), &a, &b).unwrap();
let mut tmp = a.get_value().unwrap().clone();
tmp.sub_assign(&b.get_value().unwrap());
assert_eq!(res.get_value().unwrap(), tmp);
assert!(cs.is_satisfied());
}
}
}
| 33.191257 | 100 | 0.541818 |
defba345b2883c39b14a1a66a567199fffc70da4 | 1,569 | #[derive(Debug)]
enum Gender {
#[allow(dead_code)]
Unspecified = 0,
Female = 1,
Male = 2,
}
#[derive(Debug, Copy, Clone)]
struct UserId(u64);
#[derive(Debug, Copy, Clone)]
struct TopicId(u64);
#[derive(Debug)]
struct User {
id: UserId,
name: String,
gender: Gender,
}
#[derive(Debug)]
struct Topic {
id: TopicId,
name: String,
owner: UserId,
}
#[derive(Debug)]
#[allow(dead_code)]
enum Event {
Join((UserId, TopicId)),
Leave((UserId, TopicId)),
Message((UserId, TopicId, String)),
}
fn main() {
let alice = User {
id: UserId(1),
name: "Alice".into(),
gender: Gender::Female,
};
let bob = User {
id: UserId(2),
name: "Bob".into(),
gender: Gender::Male,
};
let topic = Topic {
id: TopicId(1),
name: "rust".into(),
owner: UserId(1),
};
let event1 = Event::Join((alice.id, topic.id));
let event2 = Event::Join((bob.id, topic.id));
let event3 = Event::Message((alice.id, topic.id, "Hello world!".into()));
println!(
"event1: {:?}, event2: {:?}, event3: {:?}",
event1, event2, event3
);
// pattern match event
process_event(&event1);
process_event(&event2);
process_event(&event3);
}
fn process_event(event: &Event) {
match event {
Event::Join((uid, _tid)) => println!("user {:?} joined", uid),
Event::Leave((uid, tid)) => println!("user {:?} left {:?}", uid, tid),
Event::Message((_, _, msg)) => println!("broadcast: {}", msg),
}
}
| 20.644737 | 78 | 0.542384 |
2265d445db88a2186a63ed2a153cf358f35588d9 | 13,717 | use std::collections::HashMap;
use conduit::{Request, Response};
use conduit_router::RequestParams;
use pg::GenericConnection;
use pg::rows::Row;
use rustc_serialize::json;
use semver;
use time::Duration;
use time::Timespec;
use url;
use {Model, Crate, User};
use app::RequestApp;
use db::RequestTransaction;
use dependency::{Dependency, EncodableDependency, Kind};
use download::{VersionDownload, EncodableVersionDownload};
use git;
use upload;
use user::RequestUser;
use owner::{rights, Rights};
use util::{RequestUtils, CargoResult, ChainError, internal, human};
#[derive(Clone)]
pub struct Version {
pub id: i32,
pub crate_id: i32,
pub num: semver::Version,
pub updated_at: Timespec,
pub created_at: Timespec,
pub downloads: i32,
pub features: HashMap<String, Vec<String>>,
pub yanked: bool,
}
pub enum Author {
User(User),
Name(String),
}
#[derive(RustcEncodable, RustcDecodable)]
pub struct EncodableVersion {
pub id: i32,
pub krate: String,
pub num: String,
pub dl_path: String,
pub updated_at: String,
pub created_at: String,
pub downloads: i32,
pub features: HashMap<String, Vec<String>>,
pub yanked: bool,
pub links: VersionLinks,
}
#[derive(RustcEncodable, RustcDecodable)]
pub struct VersionLinks {
pub dependencies: String,
pub version_downloads: String,
pub authors: String,
}
impl Version {
pub fn find_by_num(conn: &GenericConnection,
crate_id: i32,
num: &semver::Version)
-> CargoResult<Option<Version>> {
let num = num.to_string();
let stmt = try!(conn.prepare("SELECT * FROM versions \
WHERE crate_id = $1 AND num = $2"));
let rows = try!(stmt.query(&[&crate_id, &num]));
Ok(rows.iter().next().map(|r| Model::from_row(&r)))
}
pub fn insert(conn: &GenericConnection,
crate_id: i32,
num: &semver::Version,
features: &HashMap<String, Vec<String>>,
authors: &[String])
-> CargoResult<Version> {
let num = num.to_string();
let features = json::encode(features).unwrap();
let stmt = try!(conn.prepare("INSERT INTO versions \
(crate_id, num, features) \
VALUES ($1, $2, $3) \
RETURNING *"));
let rows = try!(stmt.query(&[&crate_id, &num, &features]));
let ret: Version = Model::from_row(&try!(rows.iter().next().chain_error(|| {
internal("no version returned")
})));
for author in authors.iter() {
try!(ret.add_author(conn, &author));
}
Ok(ret)
}
pub fn valid(version: &str) -> bool {
semver::Version::parse(version).is_ok()
}
pub fn encodable(self, crate_name: &str) -> EncodableVersion {
let Version { id, crate_id: _, num, updated_at, created_at,
downloads, features, yanked } = self;
let num = num.to_string();
EncodableVersion {
dl_path: format!("/api/v1/crates/{}/{}/download", crate_name, num),
num: num.clone(),
id: id,
krate: crate_name.to_string(),
updated_at: ::encode_time(updated_at),
created_at: ::encode_time(created_at),
downloads: downloads,
features: features,
yanked: yanked,
links: VersionLinks {
dependencies: format!("/api/v1/crates/{}/{}/dependencies",
crate_name, num),
version_downloads: format!("/api/v1/crates/{}/{}/downloads",
crate_name, num),
authors: format!("/api/v1/crates/{}/{}/authors", crate_name, num),
},
}
}
/// Add a dependency to this version, returning both the dependency and the
/// crate that the dependency points to
pub fn add_dependency(&mut self,
conn: &GenericConnection,
dep: &upload::CrateDependency)
-> CargoResult<(Dependency, Crate)> {
let name = &dep.name;
let krate = try!(Crate::find_by_name(conn, name).map_err(|_| {
human(format!("no known crate named `{}`", &**name))
}));
if dep.version_req.0 == semver::VersionReq::parse("*").unwrap() {
return Err(human(format!("wildcard (`*`) dependency constraints are not allowed \
on crates.io. See http://doc.crates.io/faq.html#can-\
libraries-use--as-a-version-for-their-dependencies for more \
information")));
}
let features: Vec<String> = dep.features.iter().map(|s| {
s[..].to_string()
}).collect();
let dep = try!(Dependency::insert(conn, self.id, krate.id,
&*dep.version_req,
dep.kind.unwrap_or(Kind::Normal),
dep.optional,
dep.default_features,
&features,
&dep.target));
Ok((dep, krate))
}
/// Returns (dependency, crate dependency name)
pub fn dependencies(&self, conn: &GenericConnection)
-> CargoResult<Vec<(Dependency, String)>> {
let stmt = try!(conn.prepare("SELECT dependencies.*,
crates.name AS crate_name
FROM dependencies
LEFT JOIN crates
ON crates.id = dependencies.crate_id
WHERE dependencies.version_id = $1"));
let rows = try!(stmt.query(&[&self.id]));
Ok(rows.iter().map(|r| {
(Model::from_row(&r), r.get("crate_name"))
}).collect())
}
pub fn authors(&self, conn: &GenericConnection) -> CargoResult<Vec<Author>> {
let stmt = try!(conn.prepare("SELECT * FROM version_authors
WHERE version_id = $1"));
let rows = try!(stmt.query(&[&self.id]));
rows.into_iter().map(|row| {
let user_id: Option<i32> = row.get("user_id");
let name: String = row.get("name");
Ok(match user_id {
Some(id) => Author::User(try!(User::find(conn, id))),
None => Author::Name(name),
})
}).collect()
}
pub fn add_author(&self,
conn: &GenericConnection,
name: &str) -> CargoResult<()> {
println!("add author: {}", name);
// TODO: at least try to link `name` to a pre-existing user
try!(conn.execute("INSERT INTO version_authors (version_id, name)
VALUES ($1, $2)", &[&self.id, &name]));
Ok(())
}
pub fn yank(&self, conn: &GenericConnection, yanked: bool) -> CargoResult<()> {
try!(conn.execute("UPDATE versions SET yanked = $1 WHERE id = $2",
&[&yanked, &self.id]));
Ok(())
}
}
impl Model for Version {
fn from_row(row: &Row) -> Version {
let num: String = row.get("num");
let features: Option<String> = row.get("features");
let features = features.map(|s| {
json::decode(&s).unwrap()
}).unwrap_or_else(|| HashMap::new());
Version {
id: row.get("id"),
crate_id: row.get("crate_id"),
num: semver::Version::parse(&num).unwrap(),
updated_at: row.get("updated_at"),
created_at: row.get("created_at"),
downloads: row.get("downloads"),
features: features,
yanked: row.get("yanked"),
}
}
fn table_name(_: Option<Version>) -> &'static str { "versions" }
}
/// Handles the `GET /versions` route.
pub fn index(req: &mut Request) -> CargoResult<Response> {
let conn = try!(req.tx());
// Extract all ids requested.
let query = url::form_urlencoded::parse(req.query_string().unwrap_or("")
.as_bytes());
let ids = query.filter_map(|(ref a, ref b)| {
if *a == "ids[]" {
b.parse().ok()
} else {
None
}
}).collect::<Vec<i32>>();
// Load all versions
//
// TODO: can rust-postgres do this for us?
let mut versions = Vec::new();
if ids.len() > 0 {
let stmt = try!(conn.prepare("\
SELECT versions.*, crates.name AS crate_name
FROM versions
LEFT JOIN crates ON crates.id = versions.crate_id
WHERE versions.id = ANY($1)
"));
for row in try!(stmt.query(&[&ids])).iter() {
let v: Version = Model::from_row(&row);
let crate_name: String = row.get("crate_name");
versions.push(v.encodable(&crate_name));
}
}
#[derive(RustcEncodable)]
struct R { versions: Vec<EncodableVersion> }
Ok(req.json(&R { versions: versions }))
}
/// Handles the `GET /versions/:version_id` route.
pub fn show(req: &mut Request) -> CargoResult<Response> {
let (version, krate) = match req.params().find("crate_id") {
Some(..) => try!(version_and_crate(req)),
None => {
let id = &req.params()["version_id"];
let id = id.parse().unwrap_or(0);
let conn = try!(req.tx());
let version = try!(Version::find(&*conn, id));
let krate = try!(Crate::find(&*conn, version.crate_id));
(version, krate)
}
};
#[derive(RustcEncodable)]
struct R { version: EncodableVersion }
Ok(req.json(&R { version: version.encodable(&krate.name) }))
}
fn version_and_crate(req: &mut Request) -> CargoResult<(Version, Crate)> {
let crate_name = &req.params()["crate_id"];
let semver = &req.params()["version"];
let semver = try!(semver::Version::parse(semver).map_err(|_| {
human(format!("invalid semver: {}", semver))
}));
let tx = try!(req.tx());
let krate = try!(Crate::find_by_name(tx, crate_name));
let version = try!(Version::find_by_num(tx, krate.id, &semver));
let version = try!(version.chain_error(|| {
human(format!("crate `{}` does not have a version `{}`",
crate_name, semver))
}));
Ok((version, krate))
}
/// Handles the `GET /crates/:crate_id/:version/dependencies` route.
pub fn dependencies(req: &mut Request) -> CargoResult<Response> {
let (version, _) = try!(version_and_crate(req));
let tx = try!(req.tx());
let deps = try!(version.dependencies(tx));
let deps = deps.into_iter().map(|(dep, crate_name)| {
dep.encodable(&crate_name)
}).collect();
#[derive(RustcEncodable)]
struct R { dependencies: Vec<EncodableDependency> }
Ok(req.json(&R{ dependencies: deps }))
}
/// Handles the `GET /crates/:crate_id/:version/downloads` route.
pub fn downloads(req: &mut Request) -> CargoResult<Response> {
let (version, _) = try!(version_and_crate(req));
let tx = try!(req.tx());
let cutoff_date = ::now() + Duration::days(-90);
let stmt = try!(tx.prepare("SELECT * FROM version_downloads
WHERE date > $1 AND version_id = $2
ORDER BY date ASC"));
let mut downloads = Vec::new();
for row in try!(stmt.query(&[&cutoff_date, &version.id])).iter() {
let download: VersionDownload = Model::from_row(&row);
downloads.push(download.encodable());
}
#[derive(RustcEncodable)]
struct R { version_downloads: Vec<EncodableVersionDownload> }
Ok(req.json(&R{ version_downloads: downloads }))
}
/// Handles the `GET /crates/:crate_id/:version/authors` route.
pub fn authors(req: &mut Request) -> CargoResult<Response> {
let (version, _) = try!(version_and_crate(req));
let tx = try!(req.tx());
let (mut users, mut names) = (Vec::new(), Vec::new());
for author in try!(version.authors(tx)).into_iter() {
match author {
Author::User(u) => users.push(u.encodable()),
Author::Name(n) => names.push(n),
}
}
#[derive(RustcEncodable)]
struct R { users: Vec<::user::EncodableUser>, meta: Meta }
#[derive(RustcEncodable)]
struct Meta { names: Vec<String> }
Ok(req.json(&R{ users: users, meta: Meta { names: names } }))
}
/// Handles the `DELETE /crates/:crate_id/:version/yank` route.
pub fn yank(req: &mut Request) -> CargoResult<Response> {
modify_yank(req, true)
}
/// Handles the `PUT /crates/:crate_id/:version/unyank` route.
pub fn unyank(req: &mut Request) -> CargoResult<Response> {
modify_yank(req, false)
}
fn modify_yank(req: &mut Request, yanked: bool) -> CargoResult<Response> {
let (version, krate) = try!(version_and_crate(req));
let user = try!(req.user());
let tx = try!(req.tx());
let owners = try!(krate.owners(tx));
if try!(rights(req.app(), &owners, &user)) < Rights::Publish {
return Err(human("must already be an owner to yank or unyank"))
}
if version.yanked != yanked {
try!(version.yank(tx, yanked));
try!(git::yank(&**req.app(), &krate.name, &version.num, yanked));
}
#[derive(RustcEncodable)]
struct R { ok: bool }
Ok(req.json(&R{ ok: true }))
}
| 36.676471 | 99 | 0.540935 |
f83d02b9268a9d273b1d2edb1c368049eb062907 | 1,044 | /*
* Copyright 2019 Boyd Johnson
*
* 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.
*/
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum NdJsonSpatialError {
Error(String),
}
#[cfg(feature = "spatial")]
impl From<geos::Error> for NdJsonSpatialError {
fn from(other: geos::Error) -> Self {
NdJsonSpatialError::Error(format!("Geos Error: {}", other))
}
}
impl From<std::convert::Infallible> for NdJsonSpatialError {
fn from(_: std::convert::Infallible) -> Self {
panic!("Error is Infallible")
}
}
| 30.705882 | 74 | 0.708812 |
f49afbf228ad1d56336c5a1b3a286148c91a7b92 | 3,495 | #[doc = "Register `USHFRCOCAL0` reader"]
pub struct R(crate::R<USHFRCOCAL0_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<USHFRCOCAL0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<USHFRCOCAL0_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<USHFRCOCAL0_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Field `BAND24_TUNING` reader - 24 MHz TUNING value for USFRCO"]
pub struct BAND24_TUNING_R(crate::FieldReader<u8, u8>);
impl BAND24_TUNING_R {
pub(crate) fn new(bits: u8) -> Self {
BAND24_TUNING_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for BAND24_TUNING_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `BAND24_FINETUNING` reader - 24 MHz FINETUNING value for USFRCO"]
pub struct BAND24_FINETUNING_R(crate::FieldReader<u8, u8>);
impl BAND24_FINETUNING_R {
pub(crate) fn new(bits: u8) -> Self {
BAND24_FINETUNING_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for BAND24_FINETUNING_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `BAND48_TUNING` reader - 24 MHz TUNING value for USFRCO"]
pub struct BAND48_TUNING_R(crate::FieldReader<u8, u8>);
impl BAND48_TUNING_R {
pub(crate) fn new(bits: u8) -> Self {
BAND48_TUNING_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for BAND48_TUNING_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `BAND48_FINETUNING` reader - 24 MHz FINETUNING value for USFRCO"]
pub struct BAND48_FINETUNING_R(crate::FieldReader<u8, u8>);
impl BAND48_FINETUNING_R {
pub(crate) fn new(bits: u8) -> Self {
BAND48_FINETUNING_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for BAND48_FINETUNING_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:6 - 24 MHz TUNING value for USFRCO"]
#[inline(always)]
pub fn band24_tuning(&self) -> BAND24_TUNING_R {
BAND24_TUNING_R::new((self.bits & 0x7f) as u8)
}
#[doc = "Bits 8:13 - 24 MHz FINETUNING value for USFRCO"]
#[inline(always)]
pub fn band24_finetuning(&self) -> BAND24_FINETUNING_R {
BAND24_FINETUNING_R::new(((self.bits >> 8) & 0x3f) as u8)
}
#[doc = "Bits 16:22 - 24 MHz TUNING value for USFRCO"]
#[inline(always)]
pub fn band48_tuning(&self) -> BAND48_TUNING_R {
BAND48_TUNING_R::new(((self.bits >> 16) & 0x7f) as u8)
}
#[doc = "Bits 24:29 - 24 MHz FINETUNING value for USFRCO"]
#[inline(always)]
pub fn band48_finetuning(&self) -> BAND48_FINETUNING_R {
BAND48_FINETUNING_R::new(((self.bits >> 24) & 0x3f) as u8)
}
}
#[doc = "USHFRCO calibration register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ushfrcocal0](index.html) module"]
pub struct USHFRCOCAL0_SPEC;
impl crate::RegisterSpec for USHFRCOCAL0_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [ushfrcocal0::R](R) reader structure"]
impl crate::Readable for USHFRCOCAL0_SPEC {
type Reader = R;
}
| 33.932039 | 242 | 0.648069 |
cc852084d82296390a029bcf288be35b99b80496 | 5,798 | use super::*;
use crate::models::commons::{DataDecoded, Operation};
use crate::providers::info::{SafeAppInfo, TokenInfo};
use serde::Serialize;
use std::collections::HashMap;
/// Top level object returned by the `/v1/transactions/<details_id>` endpoint
///
/// <details>
/// <summary>Sample 1: Multisig Transaction awaiting confirmation</summary>
///
/// ```json
/// {
/// "executedAt": null,
/// "txStatus": "AWAITING_CONFIRMATIONS",
/// "txInfo": {
/// "type": "SettingsChange",
/// "dataDecoded": {
/// "method": "changeThreshold",
/// "parameters": [
/// {
/// "name": "_threshold",
/// "type": "uint256",
/// "value": "2"
/// }
/// ]
/// }
/// },
/// "txData": {
/// "hexData": "0x694e80c30000000000000000000000000000000000000000000000000000000000000002",
/// "dataDecoded": {
/// "method": "changeThreshold",
/// "parameters": [
/// {
/// "name": "_threshold",
/// "type": "uint256",
/// "value": "2"
/// }
/// ]
/// },
/// "to": "0x1230B3d59858296A31053C1b8562Ecf89A2f888b",
/// "value": "0",
/// "operation": 0
/// },
/// "detailedExecutionInfo": {
/// "type": "MULTISIG",
/// "submittedAt": 1596792600322,
/// "nonce": 180,
/// "safeTxHash": "0x0ef685fb7984d7314c1368497e1b0c73016066bec41f966d32f18354b88fbd46",
/// "signers": [
/// "0xBEA2F9227230976d2813a2f8b922c22bE1DE1B23",
/// "0x37e9F140A9Df5DCBc783C6c220660a4E15CBFe72",
/// "0xA3DAa0d9Ae02dAA17a664c232aDa1B739eF5ae8D",
/// "0xF2CeA96575d6b10f51d9aF3b10e3e4E5738aa6bd",
/// "0x65F8236309e5A99Ff0d129d04E486EBCE20DC7B0"
/// ],
/// "confirmationsRequired": 3,
/// "confirmations": [
/// {
/// "signer": "0xBEA2F9227230976d2813a2f8b922c22bE1DE1B23",
/// "signature": "0x1b01f3d79a50576e82d1da31810c0313bed9b76b016e1d9c6216512b2c7e53bb70df8163e568ca8ec1b8c7e7ef0a8db52d6ab2b7f47dc51c31729dd064ce375b1c"
/// }
/// ]
/// },
/// "txHash": null
/// }
/// ```
/// </details>
///
///
/// <details>
/// <summary>Sample 2: Ethereum transaction</summary>
///
/// ```json
/// {
/// "executedAt": 1596719563000,
/// "txStatus": "SUCCESS",
/// "txInfo": {
/// "type": "Transfer",
/// "sender": "0x938bae50a210b80EA233112800Cd5Bc2e7644300",
/// "recipient": "0x1230B3d59858296A31053C1b8562Ecf89A2f888b",
/// "direction": "INCOMING",
/// "transferInfo": {
/// "type": "ETHER",
/// "value": "50000000000000"
/// }
/// },
/// "txData": null,
/// "detailedExecutionInfo": null,
/// "txHash": "0x70b3c7f81a49f270fe86673f6c08beecfee384a89ef8b0869e46584905d4ecc2"
/// }
/// ```
/// </details>
///
///
/// <details>
/// <summary>Sample 3: Settings change</summary>
///
/// ```json
/// {
/// "id": "multisig_0x57d94fe21bbee8f6646c420ee23126cd1ba1b9a53a6c9b10099a043da8f32eea",
/// "timestamp": 1595429831000,
/// "txStatus": "SUCCESS",
/// "txInfo": {
/// "type": "SettingsChange",
/// "dataDecoded": {
/// "method": "addOwnerWithThreshold",
/// "parameters": [
/// {
/// "name": "owner",
/// "type": "address",
/// "value": "0xA3DAa0d9Ae02dAA17a664c232aDa1B739eF5ae8D"
/// },
/// {
/// "name": "_threshold",
/// "type": "uint256",
/// "value": "2"
/// }
/// ]
/// }
/// },
/// "executionInfo": {
/// "nonce": 135,
/// "confirmationsRequired": 2,
/// "confirmationsSubmitted": 2
/// }
/// }
/// ```
/// </details>
#[derive(Serialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TransactionDetails {
pub executed_at: Option<i64>,
pub tx_status: TransactionStatus,
pub tx_info: TransactionInfo,
pub tx_data: Option<TransactionData>,
pub detailed_execution_info: Option<DetailedExecutionInfo>,
pub tx_hash: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub safe_app_info: Option<SafeAppInfo>,
}
#[derive(Serialize, Debug, PartialEq)]
#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DetailedExecutionInfo {
Multisig(MultisigExecutionDetails),
Module(ModuleExecutionDetails),
}
#[derive(Serialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MultisigExecutionDetails {
pub submitted_at: i64,
pub nonce: u64,
pub safe_tx_gas: usize,
pub base_gas: usize,
pub gas_price: String,
pub gas_token: String,
pub refund_receiver: String,
pub safe_tx_hash: String,
pub executor: Option<String>,
pub signers: Vec<String>,
pub confirmations_required: u64,
pub confirmations: Vec<MultisigConfirmation>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rejectors: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub gas_token_info: Option<TokenInfo>,
}
#[derive(Serialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MultisigConfirmation {
pub signer: String,
pub signature: Option<String>,
pub submitted_at: i64,
}
#[derive(Serialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ModuleExecutionDetails {
pub address: String,
}
#[derive(Serialize, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TransactionData {
pub hex_data: Option<String>,
pub data_decoded: Option<DataDecoded>,
pub to: String,
pub value: Option<String>,
pub operation: Operation,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_info_index: Option<HashMap<String, AddressInfo>>,
}
| 29.581633 | 159 | 0.59969 |
79e9ebe2df74f13192c429cbc978a96e899b3190 | 7,883 | use crate::commands::WholeStreamCommand;
use crate::context::CommandRegistry;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{ColumnPath, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::Tagged;
use nu_value_ext::ValueExt;
enum IsEmptyFor {
Value,
RowWithFieldsAndFallback(Vec<Tagged<ColumnPath>>, Value),
RowWithField(Tagged<ColumnPath>),
RowWithFieldAndFallback(Box<Tagged<ColumnPath>>, Value),
}
pub struct IsEmpty;
#[derive(Deserialize)]
pub struct IsEmptyArgs {
rest: Vec<Value>,
}
#[async_trait]
impl WholeStreamCommand for IsEmpty {
fn name(&self) -> &str {
"empty?"
}
fn signature(&self) -> Signature {
Signature::build("empty?").rest(
SyntaxShape::Any,
"the names of the columns to check emptiness followed by the replacement value.",
)
}
fn usage(&self) -> &str {
"Checks emptiness. The last value is the replacement value for any empty column(s) given to check against the table."
}
async fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
is_empty(args, registry).await
}
}
async fn is_empty(
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let (IsEmptyArgs { rest }, input) = args.process(®istry).await?;
Ok(input
.map(move |value| {
let value_tag = value.tag();
let action = if rest.len() <= 2 {
let field = rest.get(0);
let replacement_if_true = rest.get(1);
match (field, replacement_if_true) {
(Some(field), Some(replacement_if_true)) => {
IsEmptyFor::RowWithFieldAndFallback(
Box::new(field.as_column_path()?),
replacement_if_true.clone(),
)
}
(Some(field), None) => IsEmptyFor::RowWithField(field.as_column_path()?),
(_, _) => IsEmptyFor::Value,
}
} else {
// let no_args = vec![];
let mut arguments = rest.iter().rev();
let replacement_if_true = match arguments.next() {
Some(arg) => arg.clone(),
None => UntaggedValue::boolean(value.is_empty()).into_value(&value_tag),
};
IsEmptyFor::RowWithFieldsAndFallback(
arguments
.map(|a| a.as_column_path())
.filter_map(Result::ok)
.collect(),
replacement_if_true,
)
};
match action {
IsEmptyFor::Value => Ok(ReturnSuccess::Value(
UntaggedValue::boolean(value.is_empty()).into_value(value_tag),
)),
IsEmptyFor::RowWithFieldsAndFallback(fields, default) => {
let mut out = value;
for field in fields.iter() {
let val = crate::commands::get::get_column_path(&field, &out)?;
let emptiness_value = match out {
obj
@
Value {
value: UntaggedValue::Row(_),
..
} => {
if val.is_empty() {
match obj.replace_data_at_column_path(&field, default.clone()) {
Some(v) => Ok(v),
None => Err(ShellError::labeled_error(
"empty? could not find place to check emptiness",
"column name",
&field.tag,
)),
}
} else {
Ok(obj)
}
}
_ => Err(ShellError::labeled_error(
"Unrecognized type in stream",
"original value",
&value_tag,
)),
};
out = emptiness_value?;
}
Ok(ReturnSuccess::Value(out))
}
IsEmptyFor::RowWithField(field) => {
let val = crate::commands::get::get_column_path(&field, &value)?;
match &value {
obj
@
Value {
value: UntaggedValue::Row(_),
..
} => {
if val.is_empty() {
match obj.replace_data_at_column_path(
&field,
UntaggedValue::boolean(true).into_value(&value_tag),
) {
Some(v) => Ok(ReturnSuccess::Value(v)),
None => Err(ShellError::labeled_error(
"empty? could not find place to check emptiness",
"column name",
&field.tag,
)),
}
} else {
Ok(ReturnSuccess::Value(value))
}
}
_ => Err(ShellError::labeled_error(
"Unrecognized type in stream",
"original value",
&value_tag,
)),
}
}
IsEmptyFor::RowWithFieldAndFallback(field, default) => {
let val = crate::commands::get::get_column_path(&field, &value)?;
match &value {
obj
@
Value {
value: UntaggedValue::Row(_),
..
} => {
if val.is_empty() {
match obj.replace_data_at_column_path(&field, default) {
Some(v) => Ok(ReturnSuccess::Value(v)),
None => Err(ShellError::labeled_error(
"empty? could not find place to check emptiness",
"column name",
&field.tag,
)),
}
} else {
Ok(ReturnSuccess::Value(value))
}
}
_ => Err(ShellError::labeled_error(
"Unrecognized type in stream",
"original value",
&value_tag,
)),
}
}
}
})
.to_output_stream())
}
#[cfg(test)]
mod tests {
use super::IsEmpty;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(IsEmpty {})
}
}
| 37.183962 | 125 | 0.390334 |
8a86337e2672249b2e45588e13cc89a37c99e094 | 1,407 | use crate::controller::base::{OperationOutcome, ResourceOperations};
use async_trait::async_trait;
use drogue_client::{core, error::ClientError, registry, Translator};
use std::ops::Deref;
#[async_trait]
impl<S> ResourceOperations<String, registry::v1::Application, registry::v1::Application> for S
where
S: Deref<Target = registry::v1::Client> + Send + Sync,
{
async fn get(
&self,
key: &String,
) -> Result<Option<registry::v1::Application>, ClientError<reqwest::Error>> {
self.get_app(&key, Default::default()).await
}
async fn update_if(
&self,
original: ®istry::v1::Application,
mut current: registry::v1::Application,
) -> Result<OperationOutcome, ()> {
current
.update_section(core::v1::Conditions::aggregate_ready)
.map_err(|_| ())?;
if original != ¤t {
match self.update_app(¤t, Default::default()).await {
Ok(_) => Ok(OperationOutcome::Complete),
Err(err) => match err {
ClientError::Syntax(_) => Ok(OperationOutcome::Complete),
_ => Ok(OperationOutcome::RetryNow),
},
}
} else {
Ok(OperationOutcome::Complete)
}
}
fn ref_output(input: ®istry::v1::Application) -> ®istry::v1::Application {
input
}
}
| 31.977273 | 94 | 0.5828 |
ed788ef5088998d3ce39e8056dfffd9250c7504e | 8,211 | // Take a look at the license at the top of the repository in the LICENSE file.
use crate::{PageSetup, PrintContext, PrintOperationPreview};
use glib::subclass::prelude::*;
use glib::translate::*;
use glib::Cast;
pub trait PrintOperationPreviewImpl: ObjectImpl {
fn ready(&self, print_operation_preview: &Self::Type, context: &PrintContext) {
self.parent_ready(print_operation_preview, context)
}
fn got_page_size(
&self,
print_operation_preview: &Self::Type,
context: &PrintContext,
page_setup: &PageSetup,
) {
self.parent_got_page_size(print_operation_preview, context, page_setup)
}
fn render_page(&self, print_operation_preview: &Self::Type, page_nr: i32);
fn is_selected(&self, print_operation_preview: &Self::Type, page_nr: i32) -> bool;
fn end_preview(&self, print_operation_preview: &Self::Type);
}
pub trait PrintOperationPreviewImplExt: ObjectSubclass {
fn parent_ready(&self, print_operation_preview: &Self::Type, context: &PrintContext);
fn parent_got_page_size(
&self,
print_operation_preview: &Self::Type,
context: &PrintContext,
page_setup: &PageSetup,
);
fn parent_render_page(&self, print_operation_preview: &Self::Type, page_nr: i32);
fn parent_is_selected(&self, print_operation_preview: &Self::Type, page_nr: i32) -> bool;
fn parent_end_preview(&self, print_operation_preview: &Self::Type);
}
impl<T: PrintOperationPreviewImpl> PrintOperationPreviewImplExt for T {
fn parent_ready(&self, print_operation_preview: &Self::Type, context: &PrintContext) {
unsafe {
let type_data = Self::type_data();
let parent_iface = type_data
.as_ref()
.get_parent_interface::<PrintOperationPreview>()
as *const ffi::GtkPrintOperationPreviewIface;
if let Some(func) = (*parent_iface).ready {
func(
print_operation_preview
.unsafe_cast_ref::<PrintOperationPreview>()
.to_glib_none()
.0,
context.to_glib_none().0,
);
}
}
}
fn parent_got_page_size(
&self,
print_operation_preview: &Self::Type,
context: &PrintContext,
page_setup: &PageSetup,
) {
unsafe {
let type_data = Self::type_data();
let parent_iface = type_data
.as_ref()
.get_parent_interface::<PrintOperationPreview>()
as *const ffi::GtkPrintOperationPreviewIface;
if let Some(func) = (*parent_iface).got_page_size {
func(
print_operation_preview
.unsafe_cast_ref::<PrintOperationPreview>()
.to_glib_none()
.0,
context.to_glib_none().0,
page_setup.to_glib_none().0,
);
}
}
}
fn parent_render_page(&self, print_operation_preview: &Self::Type, page_nr: i32) {
unsafe {
let type_data = Self::type_data();
let parent_iface = type_data
.as_ref()
.get_parent_interface::<PrintOperationPreview>()
as *const ffi::GtkPrintOperationPreviewIface;
if let Some(func) = (*parent_iface).render_page {
func(
print_operation_preview
.unsafe_cast_ref::<PrintOperationPreview>()
.to_glib_none()
.0,
page_nr,
);
}
}
}
fn parent_is_selected(&self, print_operation_preview: &Self::Type, page_nr: i32) -> bool {
unsafe {
let type_data = Self::type_data();
let parent_iface = type_data
.as_ref()
.get_parent_interface::<PrintOperationPreview>()
as *const ffi::GtkPrintOperationPreviewIface;
let func = (*parent_iface)
.is_selected
.expect("no parent \"is_selected\" implementation");
from_glib(func(
print_operation_preview
.unsafe_cast_ref::<PrintOperationPreview>()
.to_glib_none()
.0,
page_nr,
))
}
}
fn parent_end_preview(&self, print_operation_preview: &Self::Type) {
unsafe {
let type_data = Self::type_data();
let parent_iface = type_data
.as_ref()
.get_parent_interface::<PrintOperationPreview>()
as *const ffi::GtkPrintOperationPreviewIface;
if let Some(func) = (*parent_iface).end_preview {
func(
print_operation_preview
.unsafe_cast_ref::<PrintOperationPreview>()
.to_glib_none()
.0,
);
}
}
}
}
unsafe impl<T: PrintOperationPreviewImpl> IsImplementable<T> for PrintOperationPreview {
fn interface_init(iface: &mut glib::Interface<Self>) {
let iface = iface.as_mut();
iface.ready = Some(print_operation_preview_ready::<T>);
iface.got_page_size = Some(print_operation_preview_got_page_size::<T>);
iface.render_page = Some(print_operation_preview_render_page::<T>);
iface.is_selected = Some(print_operation_preview_is_selected::<T>);
iface.end_preview = Some(print_operation_preview_end_preview::<T>);
}
fn instance_init(_instance: &mut glib::subclass::InitializingObject<T>) {}
}
unsafe extern "C" fn print_operation_preview_ready<T: PrintOperationPreviewImpl>(
print_operation_preview: *mut ffi::GtkPrintOperationPreview,
contextptr: *mut ffi::GtkPrintContext,
) {
let instance = &*(print_operation_preview as *mut T::Instance);
let imp = instance.get_impl();
let context: Borrowed<PrintContext> = from_glib_borrow(contextptr);
imp.ready(
from_glib_borrow::<_, PrintOperationPreview>(print_operation_preview).unsafe_cast_ref(),
&context,
)
}
unsafe extern "C" fn print_operation_preview_got_page_size<T: PrintOperationPreviewImpl>(
print_operation_preview: *mut ffi::GtkPrintOperationPreview,
contextptr: *mut ffi::GtkPrintContext,
setupptr: *mut ffi::GtkPageSetup,
) {
let instance = &*(print_operation_preview as *mut T::Instance);
let imp = instance.get_impl();
let context: Borrowed<PrintContext> = from_glib_borrow(contextptr);
let setup: Borrowed<PageSetup> = from_glib_borrow(setupptr);
imp.got_page_size(
from_glib_borrow::<_, PrintOperationPreview>(print_operation_preview).unsafe_cast_ref(),
&context,
&setup,
)
}
unsafe extern "C" fn print_operation_preview_render_page<T: PrintOperationPreviewImpl>(
print_operation_preview: *mut ffi::GtkPrintOperationPreview,
page_nr: i32,
) {
let instance = &*(print_operation_preview as *mut T::Instance);
let imp = instance.get_impl();
imp.render_page(
from_glib_borrow::<_, PrintOperationPreview>(print_operation_preview).unsafe_cast_ref(),
page_nr,
)
}
unsafe extern "C" fn print_operation_preview_is_selected<T: PrintOperationPreviewImpl>(
print_operation_preview: *mut ffi::GtkPrintOperationPreview,
page_nr: i32,
) -> glib::ffi::gboolean {
let instance = &*(print_operation_preview as *mut T::Instance);
let imp = instance.get_impl();
imp.is_selected(
from_glib_borrow::<_, PrintOperationPreview>(print_operation_preview).unsafe_cast_ref(),
page_nr,
)
.to_glib()
}
unsafe extern "C" fn print_operation_preview_end_preview<T: PrintOperationPreviewImpl>(
print_operation_preview: *mut ffi::GtkPrintOperationPreview,
) {
let instance = &*(print_operation_preview as *mut T::Instance);
let imp = instance.get_impl();
imp.end_preview(
from_glib_borrow::<_, PrintOperationPreview>(print_operation_preview).unsafe_cast_ref(),
)
}
| 35.545455 | 96 | 0.615272 |
3ad18156eaa5bb9ace6502fedd650daf406220a2 | 6,024 | use std::sync::atomic::{AtomicUsize, Ordering};
use rand::prelude::*;
use sycamore::prelude::*;
static ADJECTIVES: &[&str] = &[
"pretty",
"large",
"big",
"small",
"tall",
"short",
"long",
"handsome",
"plain",
"quaint",
"clean",
"elegant",
"easy",
"angry",
"crazy",
"helpful",
"mushy",
"odd",
"unsightly",
"adorable",
"important",
"inexpensive",
"cheap",
"expensive",
"fancy",
];
static COLOURS: &[&str] = &[
"red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black",
"orange",
];
static NOUNS: &[&str] = &[
"table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger",
"pizza", "mouse", "keyboard",
];
#[derive(Prop)]
struct ButtonProps<'a> {
id: &'static str,
text: &'static str,
callback: Box<dyn Fn() + 'a>,
}
#[component]
fn Button<'a, G: Html>(ctx: ScopeRef<'a>, props: ButtonProps<'a>) -> View<G> {
let ButtonProps { id, text, callback } = props;
view! { ctx,
div(class="col-sm-6 smallpad") {
button(id=id, class="btn btn-primary btn-block", type="button", on:click=move |_| callback()) {
(text)
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct RowData {
id: usize,
label: RcSignal<String>,
}
static ID_COUNTER: AtomicUsize = AtomicUsize::new(1);
fn build_data(count: usize) -> Vec<RowData> {
let mut thread_rng = thread_rng();
let mut data = Vec::new();
data.reserve_exact(count);
for _i in 0..count {
let adjective = ADJECTIVES.choose(&mut thread_rng).unwrap();
let colour = COLOURS.choose(&mut thread_rng).unwrap();
let noun = NOUNS.choose(&mut thread_rng).unwrap();
let capacity = adjective.len() + colour.len() + noun.len() + 2;
let mut label = String::with_capacity(capacity);
label.push_str(adjective);
label.push(' ');
label.push_str(colour);
label.push(' ');
label.push_str(noun);
data.push(RowData {
id: ID_COUNTER.load(Ordering::Relaxed),
label: create_rc_signal(label),
});
ID_COUNTER.store(ID_COUNTER.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
}
data
}
#[component]
fn App<G: Html>(ctx: ScopeRef) -> View<G> {
let data = ctx.create_signal(Vec::<RowData>::new());
let selected = ctx.create_signal(None::<usize>);
let remove = |id| {
data.set(
data.get()
.iter()
.filter(|row| row.id != id)
.cloned()
.collect(),
);
};
let run = || {
data.set(build_data(1000));
selected.set(None);
};
let runlots = || {
data.set(build_data(10000));
selected.set(None);
};
let add = || {
data.set(data.get().iter().cloned().chain(build_data(1000)).collect());
};
let update = || {
let mut tmp = (*data.get()).clone();
for row in tmp.iter_mut().step_by(10) {
row.label.set(format!("{} !!!", row.label.get()));
}
data.set(tmp);
};
let clear = || {
data.set(Vec::new());
selected.set(None);
};
let swaprows = || {
let mut d = (*data.get()).clone();
if d.len() > 998 {
d.swap(1, 998);
}
data.set(d);
};
view! { ctx,
div(class="container") {
div(class="jumbotron") {
div(class="row") {
div(class="col-md-6") { h1 { "Sycamore Keyed" } }
div(class="col-md-6") {
div(class="row") {
Button { id: "run", text: "Create 1,000 rows", callback: Box::new(run) }
Button { id: "runlots", text: "Create 10,000 rows", callback: Box::new(runlots) }
Button { id: "add", text: "Append 1,000 rows", callback: Box::new(add) }
Button { id: "update", text: "Update every 10th row", callback: Box::new(update) }
Button { id: "clear", text: "Clear", callback: Box::new(clear) }
Button { id: "swaprows", text: "Swap Rows", callback: Box::new(swaprows) }
}
}
}
}
table(class="table table-hover table-striped test-data") {
tbody {
Keyed {
iterable: data,
view: move |ctx, row| {
let is_selected = ctx.create_selector(move || *selected.get() == Some(row.id));
let handle_click = move |_| selected.set(Some(row.id));
view! { ctx,
tr(class=is_selected.get().then(|| "danger").unwrap_or("")) {
td(class="col-md-1") { (row.id) }
td(class="col-md-4") {
a(on:click=handle_click) { (row.label.get()) }
}
td(class="col-md-1") {
a(on:click=move |_| remove(row.id)) {
span(class="glyphicon glyphicon-remove", aria-hidden="true")
}
}
td(class="col-md-6")
}
}
},
key: |row| row.id
}
}
}
}
}
}
fn main() {
let document = web_sys::window().unwrap().document().unwrap();
let mount_el = document.query_selector("#main").unwrap().unwrap();
sycamore::render_to(|ctx| view! { ctx, App {} }, &mount_el);
}
| 29.674877 | 110 | 0.449535 |
8aaadbac97f84c7a72b8b9354e77d89b490ef48c | 3,567 | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::char;
use super::UnicodeNormalization;
use super::char::is_combining_mark;
#[test]
fn test_nfd() {
macro_rules! t {
($input: expr, $expected: expr) => {
assert_eq!($input.nfd().to_string(), $expected);
// A dummy iterator that is not std::str::Chars directly;
// note that `id_func` is used to ensure `Clone` implementation
assert_eq!($input.chars().map(|c| c).nfd().collect::<String>(), $expected);
}
}
t!("abc", "abc");
t!("\u{1e0b}\u{1c4}", "d\u{307}\u{1c4}");
t!("\u{2026}", "\u{2026}");
t!("\u{2126}", "\u{3a9}");
t!("\u{1e0b}\u{323}", "d\u{323}\u{307}");
t!("\u{1e0d}\u{307}", "d\u{323}\u{307}");
t!("a\u{301}", "a\u{301}");
t!("\u{301}a", "\u{301}a");
t!("\u{d4db}", "\u{1111}\u{1171}\u{11b6}");
t!("\u{ac1c}", "\u{1100}\u{1162}");
}
#[test]
fn test_nfkd() {
macro_rules! t {
($input: expr, $expected: expr) => {
assert_eq!($input.nfkd().to_string(), $expected);
}
}
t!("abc", "abc");
t!("\u{1e0b}\u{1c4}", "d\u{307}DZ\u{30c}");
t!("\u{2026}", "...");
t!("\u{2126}", "\u{3a9}");
t!("\u{1e0b}\u{323}", "d\u{323}\u{307}");
t!("\u{1e0d}\u{307}", "d\u{323}\u{307}");
t!("a\u{301}", "a\u{301}");
t!("\u{301}a", "\u{301}a");
t!("\u{d4db}", "\u{1111}\u{1171}\u{11b6}");
t!("\u{ac1c}", "\u{1100}\u{1162}");
}
#[test]
fn test_nfc() {
macro_rules! t {
($input: expr, $expected: expr) => {
assert_eq!($input.nfc().to_string(), $expected);
}
}
t!("abc", "abc");
t!("\u{1e0b}\u{1c4}", "\u{1e0b}\u{1c4}");
t!("\u{2026}", "\u{2026}");
t!("\u{2126}", "\u{3a9}");
t!("\u{1e0b}\u{323}", "\u{1e0d}\u{307}");
t!("\u{1e0d}\u{307}", "\u{1e0d}\u{307}");
t!("a\u{301}", "\u{e1}");
t!("\u{301}a", "\u{301}a");
t!("\u{d4db}", "\u{d4db}");
t!("\u{ac1c}", "\u{ac1c}");
t!("a\u{300}\u{305}\u{315}\u{5ae}b", "\u{e0}\u{5ae}\u{305}\u{315}b");
}
#[test]
fn test_nfkc() {
macro_rules! t {
($input: expr, $expected: expr) => {
assert_eq!($input.nfkc().to_string(), $expected);
}
}
t!("abc", "abc");
t!("\u{1e0b}\u{1c4}", "\u{1e0b}D\u{17d}");
t!("\u{2026}", "...");
t!("\u{2126}", "\u{3a9}");
t!("\u{1e0b}\u{323}", "\u{1e0d}\u{307}");
t!("\u{1e0d}\u{307}", "\u{1e0d}\u{307}");
t!("a\u{301}", "\u{e1}");
t!("\u{301}a", "\u{301}a");
t!("\u{d4db}", "\u{d4db}");
t!("\u{ac1c}", "\u{ac1c}");
t!("a\u{300}\u{305}\u{315}\u{5ae}b", "\u{e0}\u{5ae}\u{305}\u{315}b");
}
#[test]
fn test_is_combining_mark_ascii() {
for cp in 0..0x7f {
assert!(!is_combining_mark(char::from_u32(cp).unwrap()));
}
}
#[test]
fn test_is_combining_mark_misc() {
// https://github.com/unicode-rs/unicode-normalization/issues/16
// U+11C3A BHAIKSUKI VOWEL SIGN O
// Category: Mark, Nonspacing [Mn]
assert!(is_combining_mark('\u{11C3A}'));
// U+11C3F BHAIKSUKI SIGN VIRAMA
// Category: Mark, Nonspacing [Mn]
assert!(is_combining_mark('\u{11C3F}'));
}
| 30.75 | 87 | 0.509952 |
2993e7a89df67ff255c3647288f172df7ab7519f | 11,927 | //! Simple library to listen and send events to keyboard and mouse on MacOS, Windows and Linux
//! (x11).
//!
//! You can also check out [Enigo](https://github.com/Enigo-rs/Enigo) which is another
//! crate which helped me write this one.
//!
//! This crate is so far a pet project for me to understand the rust ecosystem.
//!
//! # Listening to global events
//!
//! ```no_run
//! use rdev::{listen, Event};
//!
//! // This will block.
//! if let Err(error) = listen(callback) {
//! println!("Error: {:?}", error)
//! }
//!
//! fn callback(event: Event) {
//! println!("My callback {:?}", event);
//! match event.name {
//! Some(string) => println!("User wrote {:?}", string),
//! None => (),
//! }
//! }
//! ```
//!
//! # Sending some events
//!
//! ```no_run
//! use rdev::{simulate, Button, EventType, Key, SimulateError};
//! use std::{thread, time};
//!
//! fn send(event_type: &EventType) {
//! let delay = time::Duration::from_millis(20);
//! match simulate(event_type) {
//! Ok(()) => (),
//! Err(SimulateError) => {
//! println!("We could not send {:?}", event_type);
//! }
//! }
//! // Let ths OS catchup (at least MacOS)
//! thread::sleep(delay);
//! }
//!
//! send(&EventType::KeyPress(Key::KeyS));
//! send(&EventType::KeyRelease(Key::KeyS));
//!
//! send(&EventType::MouseMove { x: 0.0, y: 0.0 });
//! send(&EventType::MouseMove { x: 400.0, y: 400.0 });
//! send(&EventType::ButtonPress(Button::Left));
//! send(&EventType::ButtonRelease(Button::Right));
//! send(&EventType::Wheel {
//! delta_x: 0,
//! delta_y: 1,
//! });
//! ```
//! # Main structs
//! ## Event
//!
//! In order to detect what a user types, we need to plug to the OS level management
//! of keyboard state (modifiers like shift, ctrl, but also dead keys if they exist).
//!
//! `EventType` corresponds to a *physical* event, corresponding to QWERTY layout
//! `Event` corresponds to an actual event that was received and `Event.name` reflects
//! what key was interpreted by the OS at that time, it will respect the layout.
//!
//! ```no_run
//! # use crate::rdev::EventType;
//! # use std::time::SystemTime;
//! /// When events arrive from the system we can add some information
//! /// time is when the event was received.
//! #[derive(Debug)]
//! pub struct Event {
//! pub time: SystemTime,
//! pub name: Option<String>,
//! pub event_type: EventType,
//! }
//! ```
//!
//! Be careful, Event::name, might be None, but also String::from(""), and might contain
//! not displayable unicode characters. We send exactly what the OS sends us so do some sanity checking
//! before using it.
//! Caveat: Dead keys don't function yet on Linux
//!
//! ## EventType
//!
//! In order to manage different OS, the current EventType choices is a mix&match
//! to account for all possible events.
//! There is a safe mechanism to detect events no matter what, which are the
//! Unknown() variant of the enum which will contain some OS specific value.
//! Also not that not all keys are mapped to an OS code, so simulate might fail if you
//! try to send an unmapped key. Sending Unknown() variants will always work (the OS might
//! still reject it).
//!
//! ```no_run
//! # use crate::rdev::{Key, Button};
//! /// In order to manage different OS, the current EventType choices is a mix&match
//! /// to account for all possible events.
//! #[derive(Debug)]
//! pub enum EventType {
//! /// The keys correspond to a standard qwerty layout, they don't correspond
//! /// To the actual letter a user would use, that requires some layout logic to be added.
//! KeyPress(Key),
//! KeyRelease(Key),
//! /// Some mouse will have more than 3 buttons, these are not defined, and different OS will
//! /// give different Unknown code.
//! ButtonPress(Button),
//! ButtonRelease(Button),
//! /// Values in pixels
//! MouseMove {
//! x: f64,
//! y: f64,
//! deltaX: f64,
//! deltaY: f64
//! },
//! /// Note: On Linux, there is no actual delta the actual values are ignored for delta_x
//! /// and we only look at the sign of delta_y to simulate wheelup or wheeldown.
//! Wheel {
//! delta_x: i64,
//! delta_y: i64,
//! },
//! }
//! ```
//!
//! ## OS Specificities
//!
//! For now the code only works for Linux (X11), MacOS and Windows. On MacOS, the listen
//! loop needs to be the primary app (no fork before) and needs to have accessibility
//! settings enabled (Terminal added in System Preferences > Security & Privacy > Privacy > Accessibility).
//!
//! # Getting the main screen size
//!
//! ```no_run
//! use rdev::{display_size};
//!
//! let (w, h) = display_size().unwrap();
//! assert!(w > 0);
//! assert!(h > 0);
//! ```
//!
//! # Keyboard state
//!
//! We can define a dummy Keyboard, that we will use to detect
//! what kind of EventType trigger some String. We get the currently used
//! layout for now !
//! Caveat : This is layout dependent. If your app needs to support
//! layout switching don't use this !
//! Caveat: On Linux, the dead keys mechanism is not implemented.
//! Caveat: Only shift and dead keys are implemented, Alt+unicode code on windows
//! won't work.
//!
//! ```no_run
//! use rdev::{Keyboard, EventType, Key, KeyboardState};
//!
//! let mut keyboard = Keyboard::new().unwrap();
//! let string = keyboard.add(&EventType::KeyPress(Key::KeyS));
//! // string == Some("s")
//! ```
//!
//! # Grabbing global events. (Requires `unstable_grab` feature)
//!
//! In the callback, returning None ignores the event
//! and returning the event let's it pass. There is no modification of the event
//! possible here.
//! Caveat: On MacOS, you require the grab
//! loop needs to be the primary app (no fork before) and need to have accessibility
//! settings enabled.
//! **Not implemented on Linux, you will always receive an error.**
//!
//! # Serialization
//!
//! Serialization and deserialization. (Requires `serialize` feature).
mod rdev;
pub use crate::rdev::{
Button, Callback, DisplayError, Event, EventType, GrabCallback, GrabError, Key, KeyboardState,
ListenError, SimulateError,
};
#[cfg(target_os = "macos")]
pub mod macos;
#[cfg(target_os = "macos")]
pub use crate::macos::Keyboard;
#[cfg(target_os = "macos")]
use crate::macos::{display_size as _display_size, listen as _listen, simulate as _simulate};
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
pub use crate::linux::Keyboard;
#[cfg(target_os = "linux")]
use crate::linux::{display_size as _display_size, listen as _listen, simulate as _simulate};
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
pub use crate::windows::Keyboard;
#[cfg(target_os = "windows")]
use crate::windows::{display_size as _display_size, listen as _listen, simulate as _simulate};
/// Listening to global events. Caveat: On MacOS, you require the listen
/// loop needs to be the primary app (no fork before) and need to have accessibility
/// settings enabled.
///
/// ```no_run
/// use rdev::{listen, Event};
///
/// fn callback(event: Event) {
/// println!("My callback {:?}", event);
/// match event.name{
/// Some(string) => println!("User wrote {:?}", string),
/// None => ()
/// }
/// }
/// fn main(){
/// // This will block.
/// if let Err(error) = listen(callback) {
/// println!("Error: {:?}", error)
/// }
/// }
/// ```
pub fn listen(callback: Callback) -> Result<(), ListenError> {
_listen(callback)
}
/// Sending some events
///
/// ```no_run
/// use rdev::{simulate, Button, EventType, Key, SimulateError};
/// use std::{thread, time};
///
/// fn send(event_type: &EventType) {
/// let delay = time::Duration::from_millis(20);
/// match simulate(event_type) {
/// Ok(()) => (),
/// Err(SimulateError) => {
/// println!("We could not send {:?}", event_type);
/// }
/// }
/// // Let ths OS catchup (at least MacOS)
/// thread::sleep(delay);
/// }
///
/// fn my_shortcut() {
/// send(&EventType::KeyPress(Key::KeyS));
/// send(&EventType::KeyRelease(Key::KeyS));
///
/// send(&EventType::MouseMove { x: 0.0, y: 0.0 });
/// send(&EventType::MouseMove { x: 400.0, y: 400.0 });
/// send(&EventType::ButtonPress(Button::Left));
/// send(&EventType::ButtonRelease(Button::Right));
/// send(&EventType::Wheel {
/// delta_x: 0,
/// delta_y: 1,
/// });
/// }
/// ```
pub fn simulate(event_type: &EventType) -> Result<(), SimulateError> {
_simulate(event_type)
}
/// Returns the size in pixels of the main screen.
/// This is useful to use with x, y from MouseMove Event.
///
/// ```no_run
/// use rdev::{display_size};
///
/// let (w, h) = display_size().unwrap();
/// println!("My screen size : {:?}x{:?}", w, h);
/// ```
pub fn display_size() -> Result<(u64, u64), DisplayError> {
_display_size()
}
#[cfg(feature = "unstable_grab")]
#[cfg(target_os = "linux")]
pub use crate::linux::grab as _grab;
#[cfg(feature = "unstable_grab")]
#[cfg(target_os = "macos")]
pub use crate::macos::grab as _grab;
#[cfg(feature = "unstable_grab")]
#[cfg(target_os = "windows")]
pub use crate::windows::grab as _grab;
#[cfg(any(feature = "unstable_grab"))]
/// Grabbing global events. In the callback, returning None ignores the event
/// and returning the event let's it pass. There is no modification of the event
/// possible here.
/// Caveat: On MacOS, you require the grab
/// loop needs to be the primary app (no fork before) and need to have accessibility
/// settings enabled.
/// On Linux, this is not implemented, you will always receive an error.
///
/// ```no_run
/// use rdev::{grab, Event, EventType, Key};
///
/// fn callback(event: Event) -> Option<Event> {
/// println!("My callback {:?}", event);
/// match event.event_type{
/// EventType::KeyPress(Key::Tab) => None,
/// _ => Some(event),
/// }
/// }
/// fn main(){
/// // This will block.
/// if let Err(error) = grab(callback) {
/// println!("Error: {:?}", error)
/// }
/// }
/// ```
#[cfg(any(feature = "unstable_grab"))]
pub fn grab(callback: GrabCallback) -> Result<(), GrabError> {
_grab(callback)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_keyboard_state() {
// S
let mut keyboard = Keyboard::new().unwrap();
let char_s = keyboard.add(&EventType::KeyPress(Key::KeyS)).unwrap();
assert_eq!(
char_s,
"s".to_string(),
"This test should pass only on Qwerty layout !"
);
let n = keyboard.add(&EventType::KeyRelease(Key::KeyS));
assert_eq!(n, None);
// Shift + S
keyboard.add(&EventType::KeyPress(Key::ShiftLeft));
let char_s = keyboard.add(&EventType::KeyPress(Key::KeyS)).unwrap();
assert_eq!(char_s, "S".to_string());
let n = keyboard.add(&EventType::KeyRelease(Key::KeyS));
assert_eq!(n, None);
keyboard.add(&EventType::KeyRelease(Key::ShiftLeft));
// Reset
keyboard.add(&EventType::KeyPress(Key::ShiftLeft));
keyboard.reset();
let char_s = keyboard.add(&EventType::KeyPress(Key::KeyS)).unwrap();
assert_eq!(char_s, "s".to_string());
let n = keyboard.add(&EventType::KeyRelease(Key::KeyS));
assert_eq!(n, None);
keyboard.add(&EventType::KeyRelease(Key::ShiftLeft));
// UsIntl layout required
// let n = keyboard.add(&EventType::KeyPress(Key::Quote));
// assert_eq!(n, Some("".to_string()));
// let m = keyboard.add(&EventType::KeyRelease(Key::Quote));
// assert_eq!(m, None);
// let e = keyboard.add(&EventType::KeyPress(Key::KeyE)).unwrap();
// assert_eq!(e, "é".to_string());
// keyboard.add(&EventType::KeyRelease(Key::KeyE));
}
}
| 33.222841 | 107 | 0.61038 |
9b42c02519528d9a2b9c2530d47434b17e816d2a | 3,594 | use super::{DayLimiter, Queue};
use futures_channel::{
mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
oneshot::{self, Sender},
};
use futures_util::{sink::SinkExt, stream::StreamExt};
use std::{fmt::Debug, future::Future, pin::Pin, time::Duration};
use tokio::time::delay_for;
/// Queue built for single-process clusters that require identifying via
/// [Sharding for Very Large Bots].
///
/// Usage with other processes will cause inconsistencies between each process
/// cluster's ratelimit buckets. If you use multiple processes for clusters,
/// then refer to the [module-level] documentation.
///
/// [Sharding for Very Large Bots]: https://discord.com/developers/docs/topics/gateway#sharding-for-very-large-bots
/// [module-level]: ./index.html
#[derive(Debug)]
pub struct LargeBotQueue {
buckets: Vec<UnboundedSender<Sender<()>>>,
limiter: DayLimiter,
}
impl LargeBotQueue {
/// Create a new large bot queue.
///
/// You must provide the number of buckets Discord requires your bot to
/// connect with.
pub async fn new(buckets: usize, http: &twilight_http::Client) -> Self {
let mut queues = Vec::with_capacity(buckets);
for _ in 0..buckets {
let (tx, rx) = unbounded();
tokio::spawn(waiter(rx));
queues.push(tx)
}
let limiter = DayLimiter::new(http).await.expect(
"Getting the first session limits failed, \
Is network connection available?",
);
// The level_enabled macro does not turn off with the dynamic
// tracing levels. It is made for the static_max_level_xxx features
// And will return false if you do not use those features of if
// You use the feature but then dynamically set a lower feature.
if tracing::level_enabled!(tracing::Level::INFO) {
let lock = limiter.0.lock().await;
tracing::info!(
"{}/{} identifies used before next reset in {:.2?}",
lock.current,
lock.total,
lock.next_reset
);
}
Self {
buckets: queues,
limiter,
}
}
}
async fn waiter(mut rx: UnboundedReceiver<Sender<()>>) {
const DUR: Duration = Duration::from_secs(6);
while let Some(req) = rx.next().await {
if let Err(err) = req.send(()) {
tracing::warn!("skipping, send failed with: {:?}", err);
}
delay_for(DUR).await;
}
}
impl Queue for LargeBotQueue {
/// Request to be able to identify with the gateway. This will place this
/// request behind all other requests, and the returned future will resolve
/// once the request has been completed.
fn request(&'_ self, shard_id: [u64; 2]) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
#[allow(clippy::cast_possible_truncation)]
let bucket = (shard_id[0] % (self.buckets.len() as u64)) as usize;
let (tx, rx) = oneshot::channel();
Box::pin(async move {
self.limiter.get().await;
if let Err(err) = self.buckets[bucket].clone().send(tx).await {
tracing::warn!("skipping, send failed with: {:?}", err);
return;
}
tracing::info!("waiting for allowance on shard {}", shard_id[0]);
let _ = rx.await;
})
}
}
#[cfg(test)]
mod tests {
use super::{LargeBotQueue, Queue};
use static_assertions::assert_impl_all;
use std::fmt::Debug;
assert_impl_all!(LargeBotQueue: Debug, Queue, Send, Sync);
}
| 33.588785 | 115 | 0.604619 |
4b6516a0b6d566e17272e68e419a69976e124669 | 13,386 | use crate::hal::blocking::i2c;
use crate::{
ic, marker, AlsGain, AlsIntTime, AlsMeasRate, AlsPersist, Error, InterruptMode,
InterruptPinPolarity, LedCurrent, LedDutyCycle, LedPulse, Ltr559, PhantomData, PsMeasRate,
PsPersist, SlaveAddr, Status,
};
struct Register;
impl Register {
const ALS_CONTR: u8 = 0x80;
const PS_CONTR: u8 = 0x81;
const PS_LED: u8 = 0x82;
const PS_N_PULSES: u8 = 0x83;
const PS_MEAS_RATE: u8 = 0x84;
const ALS_MEAS_RATE: u8 = 0x85;
const PART_ID: u8 = 0x86;
const MANUFAC_ID: u8 = 0x87;
const ALS_DATA_CH1_0: u8 = 0x88;
const ALS_DATA_CH1_1: u8 = 0x89;
const ALS_DATA_CH0_0: u8 = 0x8A;
const ALS_DATA_CH0_1: u8 = 0x8B;
const ALS_PS_STATUS: u8 = 0x8C;
const PS_DATA_0: u8 = 0x8D;
const PS_DATA_1: u8 = 0x8E;
const INTERRUPT: u8 = 0x8F;
const PS_THRES_UP_0: u8 = 0x90;
const PS_THRES_UP_1: u8 = 0x91;
const PS_THRES_LOW_0: u8 = 0x92;
const PS_THRES_LOW_1: u8 = 0x93;
const PS_OFFSET_0: u8 = 0x94;
const PS_OFFSET_1: u8 = 0x95;
const ALS_THRES_UP_0: u8 = 0x97;
const ALS_THRES_UP_1: u8 = 0x98;
const ALS_THRES_LOW_0: u8 = 0x99;
const ALS_THRES_LOW_1: u8 = 0x9A;
const INTERRUPT_PERSIST: u8 = 0x9E;
}
struct BitFlags;
impl BitFlags {
const R8C_PS_DATA_STATUS: u8 = 1 << 0;
const R8C_PS_INTERRUPT_STATUS: u8 = 1 << 1;
const R8C_ALS_DATA_STATUS: u8 = 1 << 2;
const R8C_ALS_INTERRUPT_STATUS: u8 = 1 << 3;
const R8C_ALS_DATA_VALID: u8 = 1 << 7;
const R8C_ALS_GAIN: u8 = 7 << 4;
const R8E_PS_SATURATION: u8 = 1 << 7;
}
impl marker::WithDeviceId for ic::Ltr559 {}
macro_rules! create {
($ic:ident, $method:ident) => {
impl<I2C> Ltr559<I2C, ic::$ic> {
/// Create new instance of the device
pub fn $method(i2c: I2C, address: SlaveAddr) -> Self {
Ltr559 {
i2c,
address: address.addr(),
als_gain: AlsGain::default(),
als_int: AlsIntTime::default(),
_ic: PhantomData,
}
}
}
};
}
create!(Ltr559, new_device);
impl<I2C, IC> Ltr559<I2C, IC> {
/// Destroy driver instance, return I²C bus instance.
pub fn destroy(self) -> I2C {
self.i2c
}
}
impl<I2C, E, IC> Ltr559<I2C, IC>
where
I2C: i2c::WriteRead<Error = E>,
{
/// Read the status of the conversion.
///
/// Note that the conversion ready flag is cleared automatically
/// after calling this method.
pub fn get_status(&mut self) -> Result<Status, Error<E>> {
let config = self.read_register(Register::ALS_PS_STATUS)?;
Ok(Status {
ps_data_status: (config & BitFlags::R8C_PS_DATA_STATUS) != 0,
ps_interrupt_status: (config & BitFlags::R8C_PS_INTERRUPT_STATUS) != 0,
als_data_status: (config & BitFlags::R8C_ALS_DATA_STATUS) != 0,
als_interrupt_status: (config & BitFlags::R8C_ALS_INTERRUPT_STATUS) != 0,
als_gain: (config & BitFlags::R8C_ALS_GAIN) >> 4,
als_data_valid: (config & BitFlags::R8C_ALS_DATA_VALID) != BitFlags::R8C_ALS_DATA_VALID,
})
}
}
impl<I2C, E, IC> Ltr559<I2C, IC>
where
I2C: i2c::Write<Error = E>,
{
/// Set ALS_CONTR Register
///
pub fn set_als_contr(
&mut self,
als_gain: AlsGain,
sw_reset: bool,
als_active: bool,
) -> Result<(), Error<E>> {
let mut value: u8 = als_gain.value();
if sw_reset {
value += 2;
}
if als_active {
value += 1;
}
self.write_register(Register::ALS_CONTR, value)?;
self.als_gain = als_gain;
Ok(())
}
/// Set PS_CONTR Register
///
pub fn set_ps_contr(
&mut self,
ps_saturation_indicator_enable: bool,
ps_active: bool,
) -> Result<(), Error<E>> {
let mut value: u8 = 0;
if ps_saturation_indicator_enable {
value += 1 << 5;
}
if ps_active {
value += 1 << 2;
}
self.write_register(Register::PS_CONTR, value)
}
/// Set PS LED controls
///
pub fn set_ps_led(
&mut self,
led_pulse_freq: LedPulse,
led_duty_cycle: LedDutyCycle,
led_peak_current: LedCurrent,
) -> Result<(), Error<E>> {
let mut value: u8;
value = led_pulse_freq.value();
value |= led_duty_cycle.value();
value |= led_peak_current.value();
self.write_register(Register::PS_LED, value)
}
/// Set the fault count for both ALS and PS
///
pub fn set_interrupt_persist(
&mut self,
als_count: AlsPersist,
ps_count: PsPersist,
) -> Result<(), Error<E>> {
let value = ps_count.value() | als_count.value();
self.write_register(Register::INTERRUPT_PERSIST, value)
}
/// Set the integration (conversion) time and measurement repeat timer
pub fn set_als_meas_rate(
&mut self,
als_int: AlsIntTime,
als_meas_rate: AlsMeasRate,
) -> Result<(), Error<E>> {
let value = (als_int.value() << 3) | als_meas_rate.value();
self.write_register(Register::ALS_MEAS_RATE, value)?;
self.als_int = als_int;
Ok(())
}
/// Set the lux low limit in raw format
pub fn set_als_low_limit_raw(&mut self, value: u16) -> Result<(), Error<E>> {
let low = (value & 0xff) as u8;
let high = ((value >> 8) & 0xff) as u8;
self.write_register(Register::ALS_THRES_LOW_0, low)?;
self.write_register(Register::ALS_THRES_LOW_1, high)?;
Ok(())
}
/// Set the lux low limit in raw format
pub fn set_als_high_limit_raw(&mut self, value: u16) -> Result<(), Error<E>> {
let low = (value & 0xff) as u8;
let high = ((value >> 8) & 0xff) as u8;
self.write_register(Register::ALS_THRES_UP_0, low)?;
self.write_register(Register::ALS_THRES_UP_1, high)?;
Ok(())
}
/// Set the ps low limit in raw format
pub fn set_ps_low_limit_raw(&mut self, value: u16) -> Result<(), Error<E>> {
let low = (value & 0xff) as u8;
let high = ((value >> 8) & 0xff) as u8;
self.write_register(Register::PS_THRES_LOW_0, low)?;
self.write_register(Register::PS_THRES_LOW_1, high)?;
Ok(())
}
/// Set the ps low limit in raw format
pub fn set_ps_high_limit_raw(&mut self, value: u16) -> Result<(), Error<E>> {
let low = (value & 0xff) as u8;
let high = ((value >> 8) & 0xff) as u8;
self.write_register(Register::PS_THRES_UP_0, low)?;
self.write_register(Register::PS_THRES_UP_1, high)?;
Ok(())
}
/// Set PS Meas Rate
pub fn set_ps_meas_rate(&mut self, ps_meas_rate: PsMeasRate) -> Result<(), Error<E>> {
self.write_register(Register::PS_MEAS_RATE, ps_meas_rate.value())
}
/// Set PS OFFSET.
///
/// Values that exceed 1023 will cause an Err to be returned
pub fn set_ps_offset(&mut self, value: u16) -> Result<(), Error<E>> {
if value > 1023 {
return Err(Error::InvalidInputData);
}
let ps_offset_0 = (value & 0xff) as u8;
let ps_offset_1 = ((value >> 8) & 0xff) as u8;
self.write_register(Register::PS_OFFSET_0, ps_offset_0)?;
self.write_register(Register::PS_OFFSET_1, ps_offset_1)
}
/// Set PS N Pulses
///
/// Accepted values are 1..16
pub fn set_ps_n_pulses(&mut self, value: u8) -> Result<(), Error<E>> {
if value > 0 && value < 16 {
self.write_register(Register::PS_N_PULSES, value)
} else {
Err(Error::InvalidInputData)
}
}
/// Set Interrupt Polarity and Enable
pub fn set_interrupt(
&mut self,
polarity: InterruptPinPolarity,
mode: InterruptMode,
) -> Result<(), Error<E>> {
let value = mode.value() | polarity.value();
self.write_register(Register::INTERRUPT, value)
}
}
impl<I2C, E, IC> Ltr559<I2C, IC>
where
I2C: i2c::WriteRead<Error = E>,
IC: marker::WithDeviceId,
{
/// Read the manufacturer ID
pub fn get_manufacturer_id(&mut self) -> Result<u8, Error<E>> {
self.read_register(Register::MANUFAC_ID)
}
/// Read the device part number and revision id
pub fn get_part_id(&mut self) -> Result<u8, Error<E>> {
self.read_register(Register::PART_ID)
}
/// Get ALS Data in (als_ch0, als_ch1) format
pub fn get_als_raw_data(&mut self) -> Result<(u16, u16), Error<E>> {
let mut measurements = [0; 4];
let regs = [
Register::ALS_DATA_CH1_0,
Register::ALS_DATA_CH1_1,
Register::ALS_DATA_CH0_0,
Register::ALS_DATA_CH0_1,
];
for i in 0..4 {
let value = self.read_register(regs[i])?;
measurements[i] = value;
}
let ch1 = ((measurements[1] as u16) << 8) + (measurements[0] as u16);
let ch0 = ((measurements[3] as u16) << 8) + (measurements[2] as u16);
Ok((ch0, ch1))
}
/// Return calculated lux
pub fn get_lux(&mut self) -> Result<f32, Error<E>> {
let (als_data_ch0, als_data_ch1) = self.get_als_raw_data()?;
let mut ret;
let ratio;
if als_data_ch1 + als_data_ch0 == 0 {
ratio = 1000.0;
} else {
ratio = (als_data_ch1 as f32 * 1000.0) as f32 / (als_data_ch1 + als_data_ch0) as f32;
}
let ch0_c: [f32; 4] = [17743.0, 42785.0, 5926.0, 0.0];
let ch1_c: [f32; 4] = [-11059.0, 19548.0, -1185.0, 0.0];
let index_co;
if ratio < 450.0 {
index_co = 0;
} else if ratio < 640.0 {
index_co = 1;
} else if ratio < 850.0 {
index_co = 2;
} else {
index_co = 3;
}
ret = ((als_data_ch0 as f32) * ch0_c[index_co] - (als_data_ch1 as f32) * ch1_c[index_co])
/ 10000.0;
ret /= self.als_int.lux_compute_value();
ret /= self.als_gain.lux_compute_value();
Ok(ret)
}
/// Return PS Data in format (value, saturated)
pub fn get_ps_data(&mut self) -> Result<(u16, bool), Error<E>> {
let ps0 = self.read_register(Register::PS_DATA_0)?;
let ps1 = self.read_register(Register::PS_DATA_1)?;
let value = (((ps1 & 7) as u16) << 8) + (ps0 as u16);
let saturated = ps1 & BitFlags::R8E_PS_SATURATION;
Ok((value, saturated != 0))
}
}
impl<I2C, IC> Ltr559<I2C, IC> {
/// Reset the internal state of this driver to the default values.
///
/// *Note:* This does not alter the state or configuration of the device.
///
/// This resets the cached configuration register value in this driver to
/// the power-up (reset) configuration of the device.
///
/// This needs to be called after performing a reset on the device, for
/// example through an I2C general-call Reset command, which was not done
/// through this driver to ensure that the configurations in the device
/// and in the driver match.
pub fn reset_internal_driver_state(&mut self) {
self.als_gain = AlsGain::default();
self.als_int = AlsIntTime::default();
}
}
impl<I2C, E, IC> Ltr559<I2C, IC>
where
I2C: i2c::WriteRead<Error = E>,
{
fn read_register(&mut self, register: u8) -> Result<u8, Error<E>> {
let mut data = [0];
self.i2c
.write_read(self.address, &[register], &mut data)
.map_err(Error::I2C)
.and(Ok(data[0]))
}
}
impl<I2C, E, IC> Ltr559<I2C, IC>
where
I2C: i2c::Write<Error = E>,
{
fn write_register(&mut self, register: u8, value: u8) -> Result<(), Error<E>> {
let data = [register, value];
self.i2c.write(self.address, &data).map_err(Error::I2C)
}
}
#[cfg(test)]
mod tests {
use super::*;
struct I2cMock;
impl i2c::Write for I2cMock {
type Error = ();
fn write(&mut self, _addr: u8, _bytes: &[u8]) -> Result<(), Self::Error> {
Ok(())
}
}
#[test]
fn can_reset_driver_state() {
let mut device = Ltr559::new_device(I2cMock {}, SlaveAddr::default());
device
.set_interrupt_persist(AlsPersist::_3v, PsPersist::_2v)
.unwrap();
device
.set_als_contr(AlsGain::Gain96x, false, false)
.unwrap();
assert_eq!(device.als_gain, AlsGain::Gain96x);
device.reset_internal_driver_state();
assert_eq!(device.als_gain, AlsGain::default());
}
#[test]
fn ps_offset_outside() {
let mut device = Ltr559::new_device(I2cMock {}, SlaveAddr::default());
assert!(device.set_ps_offset(1024).is_err());
}
#[test]
fn ps_offset_ok() {
let mut device = Ltr559::new_device(I2cMock {}, SlaveAddr::default());
assert!(device.set_ps_offset(1023).is_ok());
}
#[test]
fn ps_n_pulses_outside() {
let mut device = Ltr559::new_device(I2cMock {}, SlaveAddr::default());
assert!(device.set_ps_n_pulses(0).is_err());
}
#[test]
fn ps_n_pulses_ok() {
let mut device = Ltr559::new_device(I2cMock {}, SlaveAddr::default());
assert!(device.set_ps_n_pulses(15).is_ok());
}
}
| 31.720379 | 100 | 0.580308 |
1e19e7f6a132ae1b7b38c39d738f341ffd634db4 | 2,894 | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(conservative_impl_trait)]
#![allow(warnings)]
use std::fmt::Debug;
fn any_lifetime<'a>() -> &'a u32 { &5 }
fn static_lifetime() -> &'static u32 { &5 }
fn any_lifetime_as_static_impl_trait() -> impl Debug {
any_lifetime()
}
fn lifetimes_as_static_impl_trait() -> impl Debug {
static_lifetime()
}
fn no_params_or_lifetimes_is_static() -> impl Debug + 'static {
lifetimes_as_static_impl_trait()
}
fn static_input_type_is_static<T: Debug + 'static>(x: T) -> impl Debug + 'static { x }
fn type_outlives_reference_lifetime<'a, T: Debug>(x: &'a T) -> impl Debug + 'a { x }
trait SingleRegionTrait<'a> {}
impl<'a> SingleRegionTrait<'a> for u32 {}
fn simple_type_hrtb<'b>() -> impl for<'a> SingleRegionTrait<'a> { 5 }
fn closure_hrtb() -> impl for<'a> Fn(&'a u32) { |_| () }
fn mixed_lifetimes<'a>() -> impl for<'b: 'a> Fn(&'b u32) { |_| () }
fn mixed_as_static() -> impl Fn(&'static u32) { mixed_lifetimes() }
trait MultiRegionTrait<'a, 'b>: Debug {}
#[derive(Debug)]
struct MultiRegionStruct<'a, 'b>(&'a u32, &'b u32);
impl<'a, 'b> MultiRegionTrait<'a, 'b> for MultiRegionStruct<'a, 'b> {}
#[derive(Debug)]
struct NoRegionStruct;
impl<'a, 'b> MultiRegionTrait<'a, 'b> for NoRegionStruct {}
fn finds_least_region<'a: 'b, 'b>(x: &'a u32, y: &'b u32) -> impl MultiRegionTrait<'a, 'b> {
MultiRegionStruct(x, y)
}
fn finds_explicit_bound<'a: 'b, 'b>
(x: &'a u32, y: &'b u32) -> impl MultiRegionTrait<'a, 'b> + 'b
{
MultiRegionStruct(x, y)
}
fn finds_explicit_bound_even_without_least_region<'a, 'b>
(x: &'a u32, y: &'b u32) -> impl MultiRegionTrait<'a, 'b> + 'b
{
NoRegionStruct
}
/* FIXME: `impl Trait<'a> + 'b` should live as long as 'b, even if 'b outlives 'a
fn outlives_bounds_even_with_contained_regions<'a, 'b>
(x: &'a u32, y: &'b u32) -> impl Debug + 'b
{
finds_explicit_bound_even_without_least_region(x, y)
}
*/
fn unnamed_lifetimes_arent_contained_in_impl_trait_and_will_unify<'a, 'b>
(x: &'a u32, y: &'b u32) -> impl Debug
{
fn deref<'lt>(x: &'lt u32) -> impl Debug { *x }
if true { deref(x) } else { deref(y) }
}
fn can_add_region_bound_to_static_type<'a, 'b>(_: &'a u32) -> impl Debug + 'a { 5 }
struct MyVec(Vec<Vec<u8>>);
impl<'unnecessary_lifetime> MyVec {
fn iter_doesnt_capture_unnecessary_lifetime<'s>(&'s self) -> impl Iterator<Item = &'s u8> {
self.0.iter().flat_map(|inner_vec| inner_vec.iter())
}
}
fn main() {}
| 29.530612 | 95 | 0.662059 |
b98a29ecb9f348bae2f87927aede0dfe691b8711 | 12,141 | //! Big vector type, used with vectors that can't be serde'd
use {
arrayref::array_ref,
borsh::{BorshDeserialize, BorshSerialize},
solana_program::{
program_error::ProgramError, program_memory::sol_memmove, program_pack::Pack,
},
std::marker::PhantomData,
};
/// Contains easy to use utilities for a big vector of Borsh-compatible types,
/// to avoid managing the entire struct on-chain and blow through stack limits.
pub struct BigVec<'data> {
/// Underlying data buffer, pieces of which are serialized
pub data: &'data mut [u8],
}
const VEC_SIZE_BYTES: usize = 4;
impl<'data> BigVec<'data> {
/// Get the length of the vector
pub fn len(&self) -> u32 {
let vec_len = array_ref![self.data, 0, VEC_SIZE_BYTES];
u32::from_le_bytes(*vec_len)
}
/// Find out if the vector has no contents (as demanded by clippy)
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Retain all elements that match the provided function, discard all others
pub fn retain<T: Pack>(&mut self, predicate: fn(&[u8]) -> bool) -> Result<(), ProgramError> {
let mut vec_len = self.len();
let mut removals_found = 0;
let mut dst_start_index = 0;
let data_start_index = VEC_SIZE_BYTES;
let data_end_index =
data_start_index.saturating_add((vec_len as usize).saturating_mul(T::LEN));
for start_index in (data_start_index..data_end_index).step_by(T::LEN) {
let end_index = start_index + T::LEN;
let slice = &self.data[start_index..end_index];
if !predicate(slice) {
let gap = removals_found * T::LEN;
if removals_found > 0 {
// In case the compute budget is ever bumped up, allowing us
// to use this safe code instead:
// self.data.copy_within(dst_start_index + gap..start_index, dst_start_index);
unsafe {
sol_memmove(
self.data[dst_start_index..start_index - gap].as_mut_ptr(),
self.data[dst_start_index + gap..start_index].as_mut_ptr(),
start_index - gap - dst_start_index,
);
}
}
dst_start_index = start_index - gap;
removals_found += 1;
vec_len -= 1;
}
}
// final memmove
if removals_found > 0 {
let gap = removals_found * T::LEN;
// In case the compute budget is ever bumped up, allowing us
// to use this safe code instead:
//self.data.copy_within(dst_start_index + gap..data_end_index, dst_start_index);
unsafe {
sol_memmove(
self.data[dst_start_index..data_end_index - gap].as_mut_ptr(),
self.data[dst_start_index + gap..data_end_index].as_mut_ptr(),
data_end_index - gap - dst_start_index,
);
}
}
let mut vec_len_ref = &mut self.data[0..VEC_SIZE_BYTES];
vec_len.serialize(&mut vec_len_ref)?;
Ok(())
}
/// Extracts a slice of the data types
pub fn deserialize_mut_slice<T: Pack>(
&mut self,
skip: usize,
len: usize,
) -> Result<Vec<&'data mut T>, ProgramError> {
let vec_len = self.len();
let last_item_index = skip
.checked_add(len)
.ok_or(ProgramError::AccountDataTooSmall)?;
if last_item_index > vec_len as usize {
return Err(ProgramError::AccountDataTooSmall);
}
let start_index = VEC_SIZE_BYTES.saturating_add(skip.saturating_mul(T::LEN));
let end_index = start_index.saturating_add(len.saturating_mul(T::LEN));
let mut deserialized = vec![];
for slice in self.data[start_index..end_index].chunks_exact_mut(T::LEN) {
deserialized.push(unsafe { &mut *(slice.as_ptr() as *mut T) });
}
Ok(deserialized)
}
/// Add new element to the end
pub fn push<T: Pack>(&mut self, element: T) -> Result<(), ProgramError> {
let mut vec_len_ref = &mut self.data[0..VEC_SIZE_BYTES];
let mut vec_len = u32::try_from_slice(vec_len_ref)?;
let start_index = VEC_SIZE_BYTES + vec_len as usize * T::LEN;
let end_index = start_index + T::LEN;
vec_len += 1;
vec_len.serialize(&mut vec_len_ref)?;
if self.data.len() < end_index {
return Err(ProgramError::AccountDataTooSmall);
}
let element_ref = &mut self.data[start_index..start_index + T::LEN];
element.pack_into_slice(element_ref);
Ok(())
}
/// Get an iterator for the type provided
pub fn iter<'vec, T: Pack>(&'vec self) -> Iter<'data, 'vec, T> {
Iter {
len: self.len() as usize,
current: 0,
current_index: VEC_SIZE_BYTES,
inner: self,
phantom: PhantomData,
}
}
/// Get a mutable iterator for the type provided
pub fn iter_mut<'vec, T: Pack>(&'vec mut self) -> IterMut<'data, 'vec, T> {
IterMut {
len: self.len() as usize,
current: 0,
current_index: VEC_SIZE_BYTES,
inner: self,
phantom: PhantomData,
}
}
/// Find matching data in the array
pub fn find<T: Pack>(&self, data: &[u8], predicate: fn(&[u8], &[u8]) -> bool) -> Option<&T> {
let len = self.len() as usize;
let mut current = 0;
let mut current_index = VEC_SIZE_BYTES;
while current != len {
let end_index = current_index + T::LEN;
let current_slice = &self.data[current_index..end_index];
if predicate(current_slice, data) {
return Some(unsafe { &*(current_slice.as_ptr() as *const T) });
}
current_index = end_index;
current += 1;
}
None
}
/// Find matching data in the array
pub fn find_mut<T: Pack>(
&mut self,
data: &[u8],
predicate: fn(&[u8], &[u8]) -> bool,
) -> Option<&mut T> {
let len = self.len() as usize;
let mut current = 0;
let mut current_index = VEC_SIZE_BYTES;
while current != len {
let end_index = current_index + T::LEN;
let current_slice = &self.data[current_index..end_index];
if predicate(current_slice, data) {
return Some(unsafe { &mut *(current_slice.as_ptr() as *mut T) });
}
current_index = end_index;
current += 1;
}
None
}
}
/// Iterator wrapper over a BigVec
pub struct Iter<'data, 'vec, T> {
len: usize,
current: usize,
current_index: usize,
inner: &'vec BigVec<'data>,
phantom: PhantomData<T>,
}
impl<'data, 'vec, T: Pack + 'data> Iterator for Iter<'data, 'vec, T> {
type Item = &'data T;
fn next(&mut self) -> Option<Self::Item> {
if self.current == self.len {
None
} else {
let end_index = self.current_index + T::LEN;
let value = Some(unsafe {
&*(self.inner.data[self.current_index..end_index].as_ptr() as *const T)
});
self.current += 1;
self.current_index = end_index;
value
}
}
}
/// Iterator wrapper over a BigVec
pub struct IterMut<'data, 'vec, T> {
len: usize,
current: usize,
current_index: usize,
inner: &'vec mut BigVec<'data>,
phantom: PhantomData<T>,
}
impl<'data, 'vec, T: Pack + 'data> Iterator for IterMut<'data, 'vec, T> {
type Item = &'data mut T;
fn next(&mut self) -> Option<Self::Item> {
if self.current == self.len {
None
} else {
let end_index = self.current_index + T::LEN;
let value = Some(unsafe {
&mut *(self.inner.data[self.current_index..end_index].as_ptr() as *mut T)
});
self.current += 1;
self.current_index = end_index;
value
}
}
}
#[cfg(test)]
mod tests {
use {
super::*,
solana_program::{program_memory::sol_memcmp, program_pack::Sealed},
};
#[derive(Debug, PartialEq)]
struct TestStruct {
value: u64,
}
impl Sealed for TestStruct {}
impl Pack for TestStruct {
const LEN: usize = 8;
fn pack_into_slice(&self, data: &mut [u8]) {
let mut data = data;
self.value.serialize(&mut data).unwrap();
}
fn unpack_from_slice(src: &[u8]) -> Result<Self, ProgramError> {
Ok(TestStruct {
value: u64::try_from_slice(src).unwrap(),
})
}
}
impl TestStruct {
fn new(value: u64) -> Self {
Self { value }
}
}
fn from_slice<'data, 'other>(data: &'data mut [u8], vec: &'other [u64]) -> BigVec<'data> {
let mut big_vec = BigVec { data };
for element in vec {
big_vec.push(TestStruct::new(*element)).unwrap();
}
big_vec
}
fn check_big_vec_eq(big_vec: &BigVec, slice: &[u64]) {
assert!(big_vec
.iter::<TestStruct>()
.map(|x| &x.value)
.zip(slice.iter())
.all(|(a, b)| a == b));
}
#[test]
fn push() {
let mut data = [0u8; 4 + 8 * 3];
let mut v = BigVec { data: &mut data };
v.push(TestStruct::new(1)).unwrap();
check_big_vec_eq(&v, &[1]);
v.push(TestStruct::new(2)).unwrap();
check_big_vec_eq(&v, &[1, 2]);
v.push(TestStruct::new(3)).unwrap();
check_big_vec_eq(&v, &[1, 2, 3]);
assert_eq!(
v.push(TestStruct::new(4)).unwrap_err(),
ProgramError::AccountDataTooSmall
);
}
#[test]
fn retain() {
fn mod_2_predicate(data: &[u8]) -> bool {
u64::try_from_slice(data).unwrap() % 2 == 0
}
let mut data = [0u8; 4 + 8 * 4];
let mut v = from_slice(&mut data, &[1, 2, 3, 4]);
v.retain::<TestStruct>(mod_2_predicate).unwrap();
check_big_vec_eq(&v, &[2, 4]);
}
fn find_predicate(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
false
} else {
sol_memcmp(a, b, a.len()) == 0
}
}
#[test]
fn find() {
let mut data = [0u8; 4 + 8 * 4];
let v = from_slice(&mut data, &[1, 2, 3, 4]);
assert_eq!(
v.find::<TestStruct>(&1u64.to_le_bytes(), find_predicate),
Some(&TestStruct::new(1))
);
assert_eq!(
v.find::<TestStruct>(&4u64.to_le_bytes(), find_predicate),
Some(&TestStruct::new(4))
);
assert_eq!(
v.find::<TestStruct>(&5u64.to_le_bytes(), find_predicate),
None
);
}
#[test]
fn find_mut() {
let mut data = [0u8; 4 + 8 * 4];
let mut v = from_slice(&mut data, &[1, 2, 3, 4]);
let mut test_struct = v
.find_mut::<TestStruct>(&1u64.to_le_bytes(), find_predicate)
.unwrap();
test_struct.value = 0;
check_big_vec_eq(&v, &[0, 2, 3, 4]);
assert_eq!(
v.find_mut::<TestStruct>(&5u64.to_le_bytes(), find_predicate),
None
);
}
#[test]
fn deserialize_mut_slice() {
let mut data = [0u8; 4 + 8 * 4];
let mut v = from_slice(&mut data, &[1, 2, 3, 4]);
let mut slice = v.deserialize_mut_slice::<TestStruct>(1, 2).unwrap();
slice[0].value = 10;
slice[1].value = 11;
check_big_vec_eq(&v, &[1, 10, 11, 4]);
assert_eq!(
v.deserialize_mut_slice::<TestStruct>(1, 4).unwrap_err(),
ProgramError::AccountDataTooSmall
);
assert_eq!(
v.deserialize_mut_slice::<TestStruct>(4, 1).unwrap_err(),
ProgramError::AccountDataTooSmall
);
}
}
| 32.034301 | 98 | 0.532987 |
1afa09ae21c3e74f304343e4be4fc63f82696e6a | 106,943 | #![allow(non_snake_case, non_upper_case_globals)]
#![allow(non_camel_case_types)]
//! High Resolution Timer: TIMD
//!
//! Used by: stm32h743, stm32h743v, stm32h747cm4, stm32h747cm7, stm32h753, stm32h753v, stm32h7b3
use crate::{RORegister, RWRegister, WORegister};
#[cfg(not(feature = "nosync"))]
use core::marker::PhantomData;
/// Timerx Control Register
pub mod TIMDCR {
/// Update Gating
pub mod UPDGAT {
/// Offset (28 bits)
pub const offset: u32 = 28;
/// Mask (4 bits: 0b1111 << 28)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Preload enable
pub mod PREEN {
/// Offset (27 bits)
pub const offset: u32 = 27;
/// Mask (1 bit: 1 << 27)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// AC Synchronization
pub mod DACSYNC {
/// Offset (25 bits)
pub const offset: u32 = 25;
/// Mask (2 bits: 0b11 << 25)
pub const mask: u32 = 0b11 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Master Timer update
pub mod MSTU {
/// Offset (24 bits)
pub const offset: u32 = 24;
/// Mask (1 bit: 1 << 24)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TEU
pub mod TEU {
/// Offset (23 bits)
pub const offset: u32 = 23;
/// Mask (1 bit: 1 << 23)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TDU
pub mod TDU {
/// Offset (22 bits)
pub const offset: u32 = 22;
/// Mask (1 bit: 1 << 22)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TCU
pub mod TCU {
/// Offset (21 bits)
pub const offset: u32 = 21;
/// Mask (1 bit: 1 << 21)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TBU
pub mod TBU {
/// Offset (20 bits)
pub const offset: u32 = 20;
/// Mask (1 bit: 1 << 20)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timerx reset update
pub mod TxRSTU {
/// Offset (18 bits)
pub const offset: u32 = 18;
/// Mask (1 bit: 1 << 18)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer x Repetition update
pub mod TxREPU {
/// Offset (17 bits)
pub const offset: u32 = 17;
/// Mask (1 bit: 1 << 17)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Delayed CMP4 mode
pub mod DELCMP4 {
/// Offset (14 bits)
pub const offset: u32 = 14;
/// Mask (2 bits: 0b11 << 14)
pub const mask: u32 = 0b11 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Delayed CMP2 mode
pub mod DELCMP2 {
/// Offset (12 bits)
pub const offset: u32 = 12;
/// Mask (2 bits: 0b11 << 12)
pub const mask: u32 = 0b11 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Synchronization Starts Timer x
pub mod SYNCSTRTx {
/// Offset (11 bits)
pub const offset: u32 = 11;
/// Mask (1 bit: 1 << 11)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Synchronization Resets Timer x
pub mod SYNCRSTx {
/// Offset (10 bits)
pub const offset: u32 = 10;
/// Mask (1 bit: 1 << 10)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Push-Pull mode enable
pub mod PSHPLL {
/// Offset (6 bits)
pub const offset: u32 = 6;
/// Mask (1 bit: 1 << 6)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Half mode enable
pub mod HALF {
/// Offset (5 bits)
pub const offset: u32 = 5;
/// Mask (1 bit: 1 << 5)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Re-triggerable mode
pub mod RETRIG {
/// Offset (4 bits)
pub const offset: u32 = 4;
/// Mask (1 bit: 1 << 4)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Continuous mode
pub mod CONT {
/// Offset (3 bits)
pub const offset: u32 = 3;
/// Mask (1 bit: 1 << 3)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// HRTIM Timer x Clock prescaler
pub mod CK_PSCx {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (3 bits: 0b111 << 0)
pub const mask: u32 = 0b111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Interrupt Status Register
pub mod TIMDISR {
/// Output 2 State
pub mod O2STAT {
/// Offset (19 bits)
pub const offset: u32 = 19;
/// Mask (1 bit: 1 << 19)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 1 State
pub mod O1STAT {
/// Offset (18 bits)
pub const offset: u32 = 18;
/// Mask (1 bit: 1 << 18)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Idle Push Pull Status
pub mod IPPSTAT {
/// Offset (17 bits)
pub const offset: u32 = 17;
/// Mask (1 bit: 1 << 17)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Current Push Pull Status
pub mod CPPSTAT {
/// Offset (16 bits)
pub const offset: u32 = 16;
/// Mask (1 bit: 1 << 16)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Delayed Protection Flag
pub mod DLYPRT {
/// Offset (14 bits)
pub const offset: u32 = 14;
/// Mask (1 bit: 1 << 14)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Reset Interrupt Flag
pub mod RST {
/// Offset (13 bits)
pub const offset: u32 = 13;
/// Mask (1 bit: 1 << 13)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 2 Reset Interrupt Flag
pub mod RSTx2 {
/// Offset (12 bits)
pub const offset: u32 = 12;
/// Mask (1 bit: 1 << 12)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 2 Set Interrupt Flag
pub mod SETx2 {
/// Offset (11 bits)
pub const offset: u32 = 11;
/// Mask (1 bit: 1 << 11)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 1 Reset Interrupt Flag
pub mod RSTx1 {
/// Offset (10 bits)
pub const offset: u32 = 10;
/// Mask (1 bit: 1 << 10)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 1 Set Interrupt Flag
pub mod SETx1 {
/// Offset (9 bits)
pub const offset: u32 = 9;
/// Mask (1 bit: 1 << 9)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Capture2 Interrupt Flag
pub mod CPT2 {
/// Offset (8 bits)
pub const offset: u32 = 8;
/// Mask (1 bit: 1 << 8)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Capture1 Interrupt Flag
pub mod CPT1 {
/// Offset (7 bits)
pub const offset: u32 = 7;
/// Mask (1 bit: 1 << 7)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Update Interrupt Flag
pub mod UPD {
/// Offset (6 bits)
pub const offset: u32 = 6;
/// Mask (1 bit: 1 << 6)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Repetition Interrupt Flag
pub mod REP {
/// Offset (4 bits)
pub const offset: u32 = 4;
/// Mask (1 bit: 1 << 4)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Compare 4 Interrupt Flag
pub mod CMP4 {
/// Offset (3 bits)
pub const offset: u32 = 3;
/// Mask (1 bit: 1 << 3)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Compare 3 Interrupt Flag
pub mod CMP3 {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Compare 2 Interrupt Flag
pub mod CMP2 {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Compare 1 Interrupt Flag
pub mod CMP1 {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Interrupt Clear Register
pub mod TIMDICR {
/// Delayed Protection Flag Clear
pub mod DLYPRTC {
/// Offset (14 bits)
pub const offset: u32 = 14;
/// Mask (1 bit: 1 << 14)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Reset Interrupt flag Clear
pub mod RSTC {
/// Offset (13 bits)
pub const offset: u32 = 13;
/// Mask (1 bit: 1 << 13)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 2 Reset flag Clear
pub mod RSTx2C {
/// Offset (12 bits)
pub const offset: u32 = 12;
/// Mask (1 bit: 1 << 12)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 2 Set flag Clear
pub mod SET2xC {
/// Offset (11 bits)
pub const offset: u32 = 11;
/// Mask (1 bit: 1 << 11)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 1 Reset flag Clear
pub mod RSTx1C {
/// Offset (10 bits)
pub const offset: u32 = 10;
/// Mask (1 bit: 1 << 10)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 1 Set flag Clear
pub mod SET1xC {
/// Offset (9 bits)
pub const offset: u32 = 9;
/// Mask (1 bit: 1 << 9)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Capture2 Interrupt flag Clear
pub mod CPT2C {
/// Offset (8 bits)
pub const offset: u32 = 8;
/// Mask (1 bit: 1 << 8)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Capture1 Interrupt flag Clear
pub mod CPT1C {
/// Offset (7 bits)
pub const offset: u32 = 7;
/// Mask (1 bit: 1 << 7)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Update Interrupt flag Clear
pub mod UPDC {
/// Offset (6 bits)
pub const offset: u32 = 6;
/// Mask (1 bit: 1 << 6)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Repetition Interrupt flag Clear
pub mod REPC {
/// Offset (4 bits)
pub const offset: u32 = 4;
/// Mask (1 bit: 1 << 4)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Compare 4 Interrupt flag Clear
pub mod CMP4C {
/// Offset (3 bits)
pub const offset: u32 = 3;
/// Mask (1 bit: 1 << 3)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Compare 3 Interrupt flag Clear
pub mod CMP3C {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Compare 2 Interrupt flag Clear
pub mod CMP2C {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Compare 1 Interrupt flag Clear
pub mod CMP1C {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// TIMxDIER5
pub mod TIMDDIER5 {
/// DLYPRTDE
pub mod DLYPRTDE {
/// Offset (30 bits)
pub const offset: u32 = 30;
/// Mask (1 bit: 1 << 30)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// RSTDE
pub mod RSTDE {
/// Offset (29 bits)
pub const offset: u32 = 29;
/// Mask (1 bit: 1 << 29)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// RSTx2DE
pub mod RSTx2DE {
/// Offset (28 bits)
pub const offset: u32 = 28;
/// Mask (1 bit: 1 << 28)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// SETx2DE
pub mod SETx2DE {
/// Offset (27 bits)
pub const offset: u32 = 27;
/// Mask (1 bit: 1 << 27)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// RSTx1DE
pub mod RSTx1DE {
/// Offset (26 bits)
pub const offset: u32 = 26;
/// Mask (1 bit: 1 << 26)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// SET1xDE
pub mod SET1xDE {
/// Offset (25 bits)
pub const offset: u32 = 25;
/// Mask (1 bit: 1 << 25)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CPT2DE
pub mod CPT2DE {
/// Offset (24 bits)
pub const offset: u32 = 24;
/// Mask (1 bit: 1 << 24)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CPT1DE
pub mod CPT1DE {
/// Offset (23 bits)
pub const offset: u32 = 23;
/// Mask (1 bit: 1 << 23)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// UPDDE
pub mod UPDDE {
/// Offset (22 bits)
pub const offset: u32 = 22;
/// Mask (1 bit: 1 << 22)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// REPDE
pub mod REPDE {
/// Offset (20 bits)
pub const offset: u32 = 20;
/// Mask (1 bit: 1 << 20)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP4DE
pub mod CMP4DE {
/// Offset (19 bits)
pub const offset: u32 = 19;
/// Mask (1 bit: 1 << 19)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP3DE
pub mod CMP3DE {
/// Offset (18 bits)
pub const offset: u32 = 18;
/// Mask (1 bit: 1 << 18)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP2DE
pub mod CMP2DE {
/// Offset (17 bits)
pub const offset: u32 = 17;
/// Mask (1 bit: 1 << 17)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP1DE
pub mod CMP1DE {
/// Offset (16 bits)
pub const offset: u32 = 16;
/// Mask (1 bit: 1 << 16)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// DLYPRTIE
pub mod DLYPRTIE {
/// Offset (14 bits)
pub const offset: u32 = 14;
/// Mask (1 bit: 1 << 14)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// RSTIE
pub mod RSTIE {
/// Offset (13 bits)
pub const offset: u32 = 13;
/// Mask (1 bit: 1 << 13)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// RSTx2IE
pub mod RSTx2IE {
/// Offset (12 bits)
pub const offset: u32 = 12;
/// Mask (1 bit: 1 << 12)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// SETx2IE
pub mod SETx2IE {
/// Offset (11 bits)
pub const offset: u32 = 11;
/// Mask (1 bit: 1 << 11)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// RSTx1IE
pub mod RSTx1IE {
/// Offset (10 bits)
pub const offset: u32 = 10;
/// Mask (1 bit: 1 << 10)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// SET1xIE
pub mod SET1xIE {
/// Offset (9 bits)
pub const offset: u32 = 9;
/// Mask (1 bit: 1 << 9)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CPT2IE
pub mod CPT2IE {
/// Offset (8 bits)
pub const offset: u32 = 8;
/// Mask (1 bit: 1 << 8)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CPT1IE
pub mod CPT1IE {
/// Offset (7 bits)
pub const offset: u32 = 7;
/// Mask (1 bit: 1 << 7)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// UPDIE
pub mod UPDIE {
/// Offset (6 bits)
pub const offset: u32 = 6;
/// Mask (1 bit: 1 << 6)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// REPIE
pub mod REPIE {
/// Offset (4 bits)
pub const offset: u32 = 4;
/// Mask (1 bit: 1 << 4)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP4IE
pub mod CMP4IE {
/// Offset (3 bits)
pub const offset: u32 = 3;
/// Mask (1 bit: 1 << 3)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP3IE
pub mod CMP3IE {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP2IE
pub mod CMP2IE {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP1IE
pub mod CMP1IE {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Counter Register
pub mod CNTDR {
/// Timerx Counter value
pub mod CNTx {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (16 bits: 0xffff << 0)
pub const mask: u32 = 0xffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Period Register
pub mod PERDR {
/// Timerx Period value
pub mod PERx {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (16 bits: 0xffff << 0)
pub const mask: u32 = 0xffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Repetition Register
pub mod REPDR {
/// Timerx Repetition counter value
pub mod REPx {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (8 bits: 0xff << 0)
pub const mask: u32 = 0xff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Compare 1 Register
pub mod CMP1DR {
/// Timerx Compare 1 value
pub mod CMP1x {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (16 bits: 0xffff << 0)
pub const mask: u32 = 0xffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Compare 1 Compound Register
pub mod CMP1CDR {
/// Timerx Repetition value (aliased from HRTIM_REPx register)
pub mod REPx {
/// Offset (16 bits)
pub const offset: u32 = 16;
/// Mask (8 bits: 0xff << 16)
pub const mask: u32 = 0xff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timerx Compare 1 value
pub mod CMP1x {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (16 bits: 0xffff << 0)
pub const mask: u32 = 0xffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Compare 2 Register
pub mod CMP2DR {
/// Timerx Compare 2 value
pub mod CMP2x {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (16 bits: 0xffff << 0)
pub const mask: u32 = 0xffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Compare 3 Register
pub mod CMP3DR {
/// Timerx Compare 3 value
pub mod CMP3x {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (16 bits: 0xffff << 0)
pub const mask: u32 = 0xffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Compare 4 Register
pub mod CMP4DR {
/// Timerx Compare 4 value
pub mod CMP4x {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (16 bits: 0xffff << 0)
pub const mask: u32 = 0xffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Capture 1 Register
pub mod CPT1DR {
/// Timerx Capture 1 value
pub mod CPT1x {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (16 bits: 0xffff << 0)
pub const mask: u32 = 0xffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Capture 2 Register
pub mod CPT2DR {
/// Timerx Capture 2 value
pub mod CPT2x {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (16 bits: 0xffff << 0)
pub const mask: u32 = 0xffff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Deadtime Register
pub mod DTDR {
/// Deadtime Falling Lock
pub mod DTFLKx {
/// Offset (31 bits)
pub const offset: u32 = 31;
/// Mask (1 bit: 1 << 31)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Deadtime Falling Sign Lock
pub mod DTFSLKx {
/// Offset (30 bits)
pub const offset: u32 = 30;
/// Mask (1 bit: 1 << 30)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Sign Deadtime Falling value
pub mod SDTFx {
/// Offset (25 bits)
pub const offset: u32 = 25;
/// Mask (1 bit: 1 << 25)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Deadtime Falling value
pub mod DTFx {
/// Offset (16 bits)
pub const offset: u32 = 16;
/// Mask (9 bits: 0x1ff << 16)
pub const mask: u32 = 0x1ff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Deadtime Rising Lock
pub mod DTRLKx {
/// Offset (15 bits)
pub const offset: u32 = 15;
/// Mask (1 bit: 1 << 15)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Deadtime Rising Sign Lock
pub mod DTRSLKx {
/// Offset (14 bits)
pub const offset: u32 = 14;
/// Mask (1 bit: 1 << 14)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Deadtime Prescaler
pub mod DTPRSC {
/// Offset (10 bits)
pub const offset: u32 = 10;
/// Mask (3 bits: 0b111 << 10)
pub const mask: u32 = 0b111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Sign Deadtime Rising value
pub mod SDTRx {
/// Offset (9 bits)
pub const offset: u32 = 9;
/// Mask (1 bit: 1 << 9)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Deadtime Rising value
pub mod DTRx {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (9 bits: 0x1ff << 0)
pub const mask: u32 = 0x1ff << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Output1 Set Register
pub mod SETD1R {
/// Registers update (transfer preload to active)
pub mod UPDATE {
/// Offset (31 bits)
pub const offset: u32 = 31;
/// Mask (1 bit: 1 << 31)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 10
pub mod EXTEVNT10 {
/// Offset (30 bits)
pub const offset: u32 = 30;
/// Mask (1 bit: 1 << 30)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 9
pub mod EXTEVNT9 {
/// Offset (29 bits)
pub const offset: u32 = 29;
/// Mask (1 bit: 1 << 29)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 8
pub mod EXTEVNT8 {
/// Offset (28 bits)
pub const offset: u32 = 28;
/// Mask (1 bit: 1 << 28)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 7
pub mod EXTEVNT7 {
/// Offset (27 bits)
pub const offset: u32 = 27;
/// Mask (1 bit: 1 << 27)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 6
pub mod EXTEVNT6 {
/// Offset (26 bits)
pub const offset: u32 = 26;
/// Mask (1 bit: 1 << 26)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 5
pub mod EXTEVNT5 {
/// Offset (25 bits)
pub const offset: u32 = 25;
/// Mask (1 bit: 1 << 25)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 4
pub mod EXTEVNT4 {
/// Offset (24 bits)
pub const offset: u32 = 24;
/// Mask (1 bit: 1 << 24)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 3
pub mod EXTEVNT3 {
/// Offset (23 bits)
pub const offset: u32 = 23;
/// Mask (1 bit: 1 << 23)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 2
pub mod EXTEVNT2 {
/// Offset (22 bits)
pub const offset: u32 = 22;
/// Mask (1 bit: 1 << 22)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 1
pub mod EXTEVNT1 {
/// Offset (21 bits)
pub const offset: u32 = 21;
/// Mask (1 bit: 1 << 21)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer Event 9
pub mod TIMEVNT9 {
/// Offset (20 bits)
pub const offset: u32 = 20;
/// Mask (1 bit: 1 << 20)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer Event 8
pub mod TIMEVNT8 {
/// Offset (19 bits)
pub const offset: u32 = 19;
/// Mask (1 bit: 1 << 19)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer Event 7
pub mod TIMEVNT7 {
/// Offset (18 bits)
pub const offset: u32 = 18;
/// Mask (1 bit: 1 << 18)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer Event 6
pub mod TIMEVNT6 {
/// Offset (17 bits)
pub const offset: u32 = 17;
/// Mask (1 bit: 1 << 17)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer Event 5
pub mod TIMEVNT5 {
/// Offset (16 bits)
pub const offset: u32 = 16;
/// Mask (1 bit: 1 << 16)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer Event 4
pub mod TIMEVNT4 {
/// Offset (15 bits)
pub const offset: u32 = 15;
/// Mask (1 bit: 1 << 15)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer Event 3
pub mod TIMEVNT3 {
/// Offset (14 bits)
pub const offset: u32 = 14;
/// Mask (1 bit: 1 << 14)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer Event 2
pub mod TIMEVNT2 {
/// Offset (13 bits)
pub const offset: u32 = 13;
/// Mask (1 bit: 1 << 13)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer Event 1
pub mod TIMEVNT1 {
/// Offset (12 bits)
pub const offset: u32 = 12;
/// Mask (1 bit: 1 << 12)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Master Compare 4
pub mod MSTCMP4 {
/// Offset (11 bits)
pub const offset: u32 = 11;
/// Mask (1 bit: 1 << 11)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Master Compare 3
pub mod MSTCMP3 {
/// Offset (10 bits)
pub const offset: u32 = 10;
/// Mask (1 bit: 1 << 10)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Master Compare 2
pub mod MSTCMP2 {
/// Offset (9 bits)
pub const offset: u32 = 9;
/// Mask (1 bit: 1 << 9)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Master Compare 1
pub mod MSTCMP1 {
/// Offset (8 bits)
pub const offset: u32 = 8;
/// Mask (1 bit: 1 << 8)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Master Period
pub mod MSTPER {
/// Offset (7 bits)
pub const offset: u32 = 7;
/// Mask (1 bit: 1 << 7)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A compare 4
pub mod CMP4 {
/// Offset (6 bits)
pub const offset: u32 = 6;
/// Mask (1 bit: 1 << 6)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A compare 3
pub mod CMP3 {
/// Offset (5 bits)
pub const offset: u32 = 5;
/// Mask (1 bit: 1 << 5)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A compare 2
pub mod CMP2 {
/// Offset (4 bits)
pub const offset: u32 = 4;
/// Mask (1 bit: 1 << 4)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A compare 1
pub mod CMP1 {
/// Offset (3 bits)
pub const offset: u32 = 3;
/// Mask (1 bit: 1 << 3)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A Period
pub mod PER {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A resynchronizaton
pub mod RESYNC {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Software Set trigger
pub mod SST {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Output1 Reset Register
pub mod RSTD1R {
/// UPDATE
pub mod UPDATE {
/// Offset (31 bits)
pub const offset: u32 = 31;
/// Mask (1 bit: 1 << 31)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// EXTEVNT10
pub mod EXTEVNT10 {
/// Offset (30 bits)
pub const offset: u32 = 30;
/// Mask (1 bit: 1 << 30)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// EXTEVNT9
pub mod EXTEVNT9 {
/// Offset (29 bits)
pub const offset: u32 = 29;
/// Mask (1 bit: 1 << 29)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// EXTEVNT8
pub mod EXTEVNT8 {
/// Offset (28 bits)
pub const offset: u32 = 28;
/// Mask (1 bit: 1 << 28)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// EXTEVNT7
pub mod EXTEVNT7 {
/// Offset (27 bits)
pub const offset: u32 = 27;
/// Mask (1 bit: 1 << 27)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// EXTEVNT6
pub mod EXTEVNT6 {
/// Offset (26 bits)
pub const offset: u32 = 26;
/// Mask (1 bit: 1 << 26)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// EXTEVNT5
pub mod EXTEVNT5 {
/// Offset (25 bits)
pub const offset: u32 = 25;
/// Mask (1 bit: 1 << 25)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// EXTEVNT4
pub mod EXTEVNT4 {
/// Offset (24 bits)
pub const offset: u32 = 24;
/// Mask (1 bit: 1 << 24)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// EXTEVNT3
pub mod EXTEVNT3 {
/// Offset (23 bits)
pub const offset: u32 = 23;
/// Mask (1 bit: 1 << 23)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// EXTEVNT2
pub mod EXTEVNT2 {
/// Offset (22 bits)
pub const offset: u32 = 22;
/// Mask (1 bit: 1 << 22)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// EXTEVNT1
pub mod EXTEVNT1 {
/// Offset (21 bits)
pub const offset: u32 = 21;
/// Mask (1 bit: 1 << 21)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TIMEVNT9
pub mod TIMEVNT9 {
/// Offset (20 bits)
pub const offset: u32 = 20;
/// Mask (1 bit: 1 << 20)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TIMEVNT8
pub mod TIMEVNT8 {
/// Offset (19 bits)
pub const offset: u32 = 19;
/// Mask (1 bit: 1 << 19)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TIMEVNT7
pub mod TIMEVNT7 {
/// Offset (18 bits)
pub const offset: u32 = 18;
/// Mask (1 bit: 1 << 18)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TIMEVNT6
pub mod TIMEVNT6 {
/// Offset (17 bits)
pub const offset: u32 = 17;
/// Mask (1 bit: 1 << 17)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TIMEVNT5
pub mod TIMEVNT5 {
/// Offset (16 bits)
pub const offset: u32 = 16;
/// Mask (1 bit: 1 << 16)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TIMEVNT4
pub mod TIMEVNT4 {
/// Offset (15 bits)
pub const offset: u32 = 15;
/// Mask (1 bit: 1 << 15)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TIMEVNT3
pub mod TIMEVNT3 {
/// Offset (14 bits)
pub const offset: u32 = 14;
/// Mask (1 bit: 1 << 14)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TIMEVNT2
pub mod TIMEVNT2 {
/// Offset (13 bits)
pub const offset: u32 = 13;
/// Mask (1 bit: 1 << 13)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// TIMEVNT1
pub mod TIMEVNT1 {
/// Offset (12 bits)
pub const offset: u32 = 12;
/// Mask (1 bit: 1 << 12)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// MSTCMP4
pub mod MSTCMP4 {
/// Offset (11 bits)
pub const offset: u32 = 11;
/// Mask (1 bit: 1 << 11)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// MSTCMP3
pub mod MSTCMP3 {
/// Offset (10 bits)
pub const offset: u32 = 10;
/// Mask (1 bit: 1 << 10)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// MSTCMP2
pub mod MSTCMP2 {
/// Offset (9 bits)
pub const offset: u32 = 9;
/// Mask (1 bit: 1 << 9)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// MSTCMP1
pub mod MSTCMP1 {
/// Offset (8 bits)
pub const offset: u32 = 8;
/// Mask (1 bit: 1 << 8)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// MSTPER
pub mod MSTPER {
/// Offset (7 bits)
pub const offset: u32 = 7;
/// Mask (1 bit: 1 << 7)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP4
pub mod CMP4 {
/// Offset (6 bits)
pub const offset: u32 = 6;
/// Mask (1 bit: 1 << 6)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP3
pub mod CMP3 {
/// Offset (5 bits)
pub const offset: u32 = 5;
/// Mask (1 bit: 1 << 5)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP2
pub mod CMP2 {
/// Offset (4 bits)
pub const offset: u32 = 4;
/// Mask (1 bit: 1 << 4)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// CMP1
pub mod CMP1 {
/// Offset (3 bits)
pub const offset: u32 = 3;
/// Mask (1 bit: 1 << 3)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// PER
pub mod PER {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// RESYNC
pub mod RESYNC {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// SRT
pub mod SRT {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Output2 Set Register
pub mod SETD2R {
pub use super::SETD1R::CMP1;
pub use super::SETD1R::CMP2;
pub use super::SETD1R::CMP3;
pub use super::SETD1R::CMP4;
pub use super::SETD1R::EXTEVNT1;
pub use super::SETD1R::EXTEVNT10;
pub use super::SETD1R::EXTEVNT2;
pub use super::SETD1R::EXTEVNT3;
pub use super::SETD1R::EXTEVNT4;
pub use super::SETD1R::EXTEVNT5;
pub use super::SETD1R::EXTEVNT6;
pub use super::SETD1R::EXTEVNT7;
pub use super::SETD1R::EXTEVNT8;
pub use super::SETD1R::EXTEVNT9;
pub use super::SETD1R::MSTCMP1;
pub use super::SETD1R::MSTCMP2;
pub use super::SETD1R::MSTCMP3;
pub use super::SETD1R::MSTCMP4;
pub use super::SETD1R::MSTPER;
pub use super::SETD1R::PER;
pub use super::SETD1R::RESYNC;
pub use super::SETD1R::SST;
pub use super::SETD1R::TIMEVNT1;
pub use super::SETD1R::TIMEVNT2;
pub use super::SETD1R::TIMEVNT3;
pub use super::SETD1R::TIMEVNT4;
pub use super::SETD1R::TIMEVNT5;
pub use super::SETD1R::TIMEVNT6;
pub use super::SETD1R::TIMEVNT7;
pub use super::SETD1R::TIMEVNT8;
pub use super::SETD1R::TIMEVNT9;
pub use super::SETD1R::UPDATE;
}
/// Timerx Output2 Reset Register
pub mod RSTD2R {
pub use super::RSTD1R::CMP1;
pub use super::RSTD1R::CMP2;
pub use super::RSTD1R::CMP3;
pub use super::RSTD1R::CMP4;
pub use super::RSTD1R::EXTEVNT1;
pub use super::RSTD1R::EXTEVNT10;
pub use super::RSTD1R::EXTEVNT2;
pub use super::RSTD1R::EXTEVNT3;
pub use super::RSTD1R::EXTEVNT4;
pub use super::RSTD1R::EXTEVNT5;
pub use super::RSTD1R::EXTEVNT6;
pub use super::RSTD1R::EXTEVNT7;
pub use super::RSTD1R::EXTEVNT8;
pub use super::RSTD1R::EXTEVNT9;
pub use super::RSTD1R::MSTCMP1;
pub use super::RSTD1R::MSTCMP2;
pub use super::RSTD1R::MSTCMP3;
pub use super::RSTD1R::MSTCMP4;
pub use super::RSTD1R::MSTPER;
pub use super::RSTD1R::PER;
pub use super::RSTD1R::RESYNC;
pub use super::RSTD1R::SRT;
pub use super::RSTD1R::TIMEVNT1;
pub use super::RSTD1R::TIMEVNT2;
pub use super::RSTD1R::TIMEVNT3;
pub use super::RSTD1R::TIMEVNT4;
pub use super::RSTD1R::TIMEVNT5;
pub use super::RSTD1R::TIMEVNT6;
pub use super::RSTD1R::TIMEVNT7;
pub use super::RSTD1R::TIMEVNT8;
pub use super::RSTD1R::TIMEVNT9;
pub use super::RSTD1R::UPDATE;
}
/// Timerx External Event Filtering Register 1
pub mod EEFDR1 {
/// External Event 5 filter
pub mod EE5FLTR {
/// Offset (25 bits)
pub const offset: u32 = 25;
/// Mask (4 bits: 0b1111 << 25)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 5 latch
pub mod EE5LTCH {
/// Offset (24 bits)
pub const offset: u32 = 24;
/// Mask (1 bit: 1 << 24)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 4 filter
pub mod EE4FLTR {
/// Offset (19 bits)
pub const offset: u32 = 19;
/// Mask (4 bits: 0b1111 << 19)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 4 latch
pub mod EE4LTCH {
/// Offset (18 bits)
pub const offset: u32 = 18;
/// Mask (1 bit: 1 << 18)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 3 filter
pub mod EE3FLTR {
/// Offset (13 bits)
pub const offset: u32 = 13;
/// Mask (4 bits: 0b1111 << 13)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 3 latch
pub mod EE3LTCH {
/// Offset (12 bits)
pub const offset: u32 = 12;
/// Mask (1 bit: 1 << 12)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 2 filter
pub mod EE2FLTR {
/// Offset (7 bits)
pub const offset: u32 = 7;
/// Mask (4 bits: 0b1111 << 7)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 2 latch
pub mod EE2LTCH {
/// Offset (6 bits)
pub const offset: u32 = 6;
/// Mask (1 bit: 1 << 6)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 1 filter
pub mod EE1FLTR {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (4 bits: 0b1111 << 1)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 1 latch
pub mod EE1LTCH {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx External Event Filtering Register 2
pub mod EEFDR2 {
/// External Event 10 filter
pub mod EE10FLTR {
/// Offset (25 bits)
pub const offset: u32 = 25;
/// Mask (4 bits: 0b1111 << 25)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 10 latch
pub mod EE10LTCH {
/// Offset (24 bits)
pub const offset: u32 = 24;
/// Mask (1 bit: 1 << 24)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 9 filter
pub mod EE9FLTR {
/// Offset (19 bits)
pub const offset: u32 = 19;
/// Mask (4 bits: 0b1111 << 19)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 9 latch
pub mod EE9LTCH {
/// Offset (18 bits)
pub const offset: u32 = 18;
/// Mask (1 bit: 1 << 18)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 8 filter
pub mod EE8FLTR {
/// Offset (13 bits)
pub const offset: u32 = 13;
/// Mask (4 bits: 0b1111 << 13)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 8 latch
pub mod EE8LTCH {
/// Offset (12 bits)
pub const offset: u32 = 12;
/// Mask (1 bit: 1 << 12)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 7 filter
pub mod EE7FLTR {
/// Offset (7 bits)
pub const offset: u32 = 7;
/// Mask (4 bits: 0b1111 << 7)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 7 latch
pub mod EE7LTCH {
/// Offset (6 bits)
pub const offset: u32 = 6;
/// Mask (1 bit: 1 << 6)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 6 filter
pub mod EE6FLTR {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (4 bits: 0b1111 << 1)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 6 latch
pub mod EE6LTCH {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// TimerA Reset Register
pub mod RSTDR {
/// Timer E Compare 4
pub mod TIMECMP4 {
/// Offset (30 bits)
pub const offset: u32 = 30;
/// Mask (1 bit: 1 << 30)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer E Compare 2
pub mod TIMECMP2 {
/// Offset (29 bits)
pub const offset: u32 = 29;
/// Mask (1 bit: 1 << 29)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer E Compare 1
pub mod TIMECMP1 {
/// Offset (28 bits)
pub const offset: u32 = 28;
/// Mask (1 bit: 1 << 28)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer C Compare 4
pub mod TIMCCMP4 {
/// Offset (27 bits)
pub const offset: u32 = 27;
/// Mask (1 bit: 1 << 27)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer C Compare 2
pub mod TIMCCMP2 {
/// Offset (26 bits)
pub const offset: u32 = 26;
/// Mask (1 bit: 1 << 26)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer C Compare 1
pub mod TIMCCMP1 {
/// Offset (25 bits)
pub const offset: u32 = 25;
/// Mask (1 bit: 1 << 25)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer B Compare 4
pub mod TIMBCMP4 {
/// Offset (24 bits)
pub const offset: u32 = 24;
/// Mask (1 bit: 1 << 24)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer B Compare 2
pub mod TIMBCMP2 {
/// Offset (23 bits)
pub const offset: u32 = 23;
/// Mask (1 bit: 1 << 23)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer B Compare 1
pub mod TIMBCMP1 {
/// Offset (22 bits)
pub const offset: u32 = 22;
/// Mask (1 bit: 1 << 22)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A Compare 4
pub mod TIMACMP4 {
/// Offset (21 bits)
pub const offset: u32 = 21;
/// Mask (1 bit: 1 << 21)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A Compare 2
pub mod TIMACMP2 {
/// Offset (20 bits)
pub const offset: u32 = 20;
/// Mask (1 bit: 1 << 20)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A Compare 1
pub mod TIMACMP1 {
/// Offset (19 bits)
pub const offset: u32 = 19;
/// Mask (1 bit: 1 << 19)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 10
pub mod EXTEVNT10 {
/// Offset (18 bits)
pub const offset: u32 = 18;
/// Mask (1 bit: 1 << 18)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 9
pub mod EXTEVNT9 {
/// Offset (17 bits)
pub const offset: u32 = 17;
/// Mask (1 bit: 1 << 17)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 8
pub mod EXTEVNT8 {
/// Offset (16 bits)
pub const offset: u32 = 16;
/// Mask (1 bit: 1 << 16)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 7
pub mod EXTEVNT7 {
/// Offset (15 bits)
pub const offset: u32 = 15;
/// Mask (1 bit: 1 << 15)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 6
pub mod EXTEVNT6 {
/// Offset (14 bits)
pub const offset: u32 = 14;
/// Mask (1 bit: 1 << 14)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 5
pub mod EXTEVNT5 {
/// Offset (13 bits)
pub const offset: u32 = 13;
/// Mask (1 bit: 1 << 13)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 4
pub mod EXTEVNT4 {
/// Offset (12 bits)
pub const offset: u32 = 12;
/// Mask (1 bit: 1 << 12)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 3
pub mod EXTEVNT3 {
/// Offset (11 bits)
pub const offset: u32 = 11;
/// Mask (1 bit: 1 << 11)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 2
pub mod EXTEVNT2 {
/// Offset (10 bits)
pub const offset: u32 = 10;
/// Mask (1 bit: 1 << 10)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 1
pub mod EXTEVNT1 {
/// Offset (9 bits)
pub const offset: u32 = 9;
/// Mask (1 bit: 1 << 9)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Master compare 4
pub mod MSTCMP4 {
/// Offset (8 bits)
pub const offset: u32 = 8;
/// Mask (1 bit: 1 << 8)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Master compare 3
pub mod MSTCMP3 {
/// Offset (7 bits)
pub const offset: u32 = 7;
/// Mask (1 bit: 1 << 7)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Master compare 2
pub mod MSTCMP2 {
/// Offset (6 bits)
pub const offset: u32 = 6;
/// Mask (1 bit: 1 << 6)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Master compare 1
pub mod MSTCMP1 {
/// Offset (5 bits)
pub const offset: u32 = 5;
/// Mask (1 bit: 1 << 5)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Master timer Period
pub mod MSTPER {
/// Offset (4 bits)
pub const offset: u32 = 4;
/// Mask (1 bit: 1 << 4)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A compare 4 reset
pub mod CMP4 {
/// Offset (3 bits)
pub const offset: u32 = 3;
/// Mask (1 bit: 1 << 3)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A compare 2 reset
pub mod CMP2 {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A Update reset
pub mod UPDT {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Chopper Register
pub mod CHPDR {
/// STRTPW
pub mod STRTPW {
/// Offset (7 bits)
pub const offset: u32 = 7;
/// Mask (4 bits: 0b1111 << 7)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timerx chopper duty cycle value
pub mod CHPDTY {
/// Offset (4 bits)
pub const offset: u32 = 4;
/// Mask (3 bits: 0b111 << 4)
pub const mask: u32 = 0b111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timerx carrier frequency value
pub mod CHPFRQ {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (4 bits: 0b1111 << 0)
pub const mask: u32 = 0b1111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Capture 2 Control Register
pub mod CPT1DCR {
/// Timer E Compare 2
pub mod TECMP2 {
/// Offset (31 bits)
pub const offset: u32 = 31;
/// Mask (1 bit: 1 << 31)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer E Compare 1
pub mod TECMP1 {
/// Offset (30 bits)
pub const offset: u32 = 30;
/// Mask (1 bit: 1 << 30)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer E output 1 Reset
pub mod TE1RST {
/// Offset (29 bits)
pub const offset: u32 = 29;
/// Mask (1 bit: 1 << 29)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer E output 1 Set
pub mod TE1SET {
/// Offset (28 bits)
pub const offset: u32 = 28;
/// Mask (1 bit: 1 << 28)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer C Compare 2
pub mod TCCMP2 {
/// Offset (23 bits)
pub const offset: u32 = 23;
/// Mask (1 bit: 1 << 23)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer C Compare 1
pub mod TCCMP1 {
/// Offset (22 bits)
pub const offset: u32 = 22;
/// Mask (1 bit: 1 << 22)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer C output 1 Reset
pub mod TC1RST {
/// Offset (21 bits)
pub const offset: u32 = 21;
/// Mask (1 bit: 1 << 21)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer C output 1 Set
pub mod TC1SET {
/// Offset (20 bits)
pub const offset: u32 = 20;
/// Mask (1 bit: 1 << 20)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer B Compare 2
pub mod TBCMP2 {
/// Offset (19 bits)
pub const offset: u32 = 19;
/// Mask (1 bit: 1 << 19)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer B Compare 1
pub mod TBCMP1 {
/// Offset (18 bits)
pub const offset: u32 = 18;
/// Mask (1 bit: 1 << 18)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer B output 1 Reset
pub mod TB1RST {
/// Offset (17 bits)
pub const offset: u32 = 17;
/// Mask (1 bit: 1 << 17)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer B output 1 Set
pub mod TB1SET {
/// Offset (16 bits)
pub const offset: u32 = 16;
/// Mask (1 bit: 1 << 16)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A Compare 2
pub mod TACMP2 {
/// Offset (15 bits)
pub const offset: u32 = 15;
/// Mask (1 bit: 1 << 15)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A Compare 1
pub mod TACMP1 {
/// Offset (14 bits)
pub const offset: u32 = 14;
/// Mask (1 bit: 1 << 14)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A output 1 Reset
pub mod TA1RST {
/// Offset (13 bits)
pub const offset: u32 = 13;
/// Mask (1 bit: 1 << 13)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Timer A output 1 Set
pub mod TA1SET {
/// Offset (12 bits)
pub const offset: u32 = 12;
/// Mask (1 bit: 1 << 12)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 10 Capture
pub mod EXEV10CPT {
/// Offset (11 bits)
pub const offset: u32 = 11;
/// Mask (1 bit: 1 << 11)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 9 Capture
pub mod EXEV9CPT {
/// Offset (10 bits)
pub const offset: u32 = 10;
/// Mask (1 bit: 1 << 10)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 8 Capture
pub mod EXEV8CPT {
/// Offset (9 bits)
pub const offset: u32 = 9;
/// Mask (1 bit: 1 << 9)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 7 Capture
pub mod EXEV7CPT {
/// Offset (8 bits)
pub const offset: u32 = 8;
/// Mask (1 bit: 1 << 8)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 6 Capture
pub mod EXEV6CPT {
/// Offset (7 bits)
pub const offset: u32 = 7;
/// Mask (1 bit: 1 << 7)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 5 Capture
pub mod EXEV5CPT {
/// Offset (6 bits)
pub const offset: u32 = 6;
/// Mask (1 bit: 1 << 6)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 4 Capture
pub mod EXEV4CPT {
/// Offset (5 bits)
pub const offset: u32 = 5;
/// Mask (1 bit: 1 << 5)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 3 Capture
pub mod EXEV3CPT {
/// Offset (4 bits)
pub const offset: u32 = 4;
/// Mask (1 bit: 1 << 4)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 2 Capture
pub mod EXEV2CPT {
/// Offset (3 bits)
pub const offset: u32 = 3;
/// Mask (1 bit: 1 << 3)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// External Event 1 Capture
pub mod EXEV1CPT {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Update Capture
pub mod UDPCPT {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Software Capture
pub mod SWCPT {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// CPT2xCR
pub mod CPT2DCR {
pub use super::CPT1DCR::EXEV10CPT;
pub use super::CPT1DCR::EXEV1CPT;
pub use super::CPT1DCR::EXEV2CPT;
pub use super::CPT1DCR::EXEV3CPT;
pub use super::CPT1DCR::EXEV4CPT;
pub use super::CPT1DCR::EXEV5CPT;
pub use super::CPT1DCR::EXEV6CPT;
pub use super::CPT1DCR::EXEV7CPT;
pub use super::CPT1DCR::EXEV8CPT;
pub use super::CPT1DCR::EXEV9CPT;
pub use super::CPT1DCR::SWCPT;
pub use super::CPT1DCR::TA1RST;
pub use super::CPT1DCR::TA1SET;
pub use super::CPT1DCR::TACMP1;
pub use super::CPT1DCR::TACMP2;
pub use super::CPT1DCR::TB1RST;
pub use super::CPT1DCR::TB1SET;
pub use super::CPT1DCR::TBCMP1;
pub use super::CPT1DCR::TBCMP2;
pub use super::CPT1DCR::TC1RST;
pub use super::CPT1DCR::TC1SET;
pub use super::CPT1DCR::TCCMP1;
pub use super::CPT1DCR::TCCMP2;
pub use super::CPT1DCR::TE1RST;
pub use super::CPT1DCR::TE1SET;
pub use super::CPT1DCR::TECMP1;
pub use super::CPT1DCR::TECMP2;
pub use super::CPT1DCR::UDPCPT;
}
/// Timerx Output Register
pub mod OUTDR {
/// Output 2 Deadtime upon burst mode Idle entry
pub mod DIDL2 {
/// Offset (23 bits)
pub const offset: u32 = 23;
/// Mask (1 bit: 1 << 23)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 2 Chopper enable
pub mod CHP2 {
/// Offset (22 bits)
pub const offset: u32 = 22;
/// Mask (1 bit: 1 << 22)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 2 Fault state
pub mod FAULT2 {
/// Offset (20 bits)
pub const offset: u32 = 20;
/// Mask (2 bits: 0b11 << 20)
pub const mask: u32 = 0b11 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 2 Idle State
pub mod IDLES2 {
/// Offset (19 bits)
pub const offset: u32 = 19;
/// Mask (1 bit: 1 << 19)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 2 Idle mode
pub mod IDLEM2 {
/// Offset (18 bits)
pub const offset: u32 = 18;
/// Mask (1 bit: 1 << 18)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 2 polarity
pub mod POL2 {
/// Offset (17 bits)
pub const offset: u32 = 17;
/// Mask (1 bit: 1 << 17)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Delayed Protection
pub mod DLYPRT {
/// Offset (10 bits)
pub const offset: u32 = 10;
/// Mask (3 bits: 0b111 << 10)
pub const mask: u32 = 0b111 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Delayed Protection Enable
pub mod DLYPRTEN {
/// Offset (9 bits)
pub const offset: u32 = 9;
/// Mask (1 bit: 1 << 9)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Deadtime enable
pub mod DTEN {
/// Offset (8 bits)
pub const offset: u32 = 8;
/// Mask (1 bit: 1 << 8)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 1 Deadtime upon burst mode Idle entry
pub mod DIDL1 {
/// Offset (7 bits)
pub const offset: u32 = 7;
/// Mask (1 bit: 1 << 7)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 1 Chopper enable
pub mod CHP1 {
/// Offset (6 bits)
pub const offset: u32 = 6;
/// Mask (1 bit: 1 << 6)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 1 Fault state
pub mod FAULT1 {
/// Offset (4 bits)
pub const offset: u32 = 4;
/// Mask (2 bits: 0b11 << 4)
pub const mask: u32 = 0b11 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 1 Idle State
pub mod IDLES1 {
/// Offset (3 bits)
pub const offset: u32 = 3;
/// Mask (1 bit: 1 << 3)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 1 Idle mode
pub mod IDLEM1 {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Output 1 polarity
pub mod POL1 {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
/// Timerx Fault Register
pub mod FLTDR {
/// Fault sources Lock
pub mod FLTLCK {
/// Offset (31 bits)
pub const offset: u32 = 31;
/// Mask (1 bit: 1 << 31)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Fault 5 enable
pub mod FLT5EN {
/// Offset (4 bits)
pub const offset: u32 = 4;
/// Mask (1 bit: 1 << 4)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Fault 4 enable
pub mod FLT4EN {
/// Offset (3 bits)
pub const offset: u32 = 3;
/// Mask (1 bit: 1 << 3)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Fault 3 enable
pub mod FLT3EN {
/// Offset (2 bits)
pub const offset: u32 = 2;
/// Mask (1 bit: 1 << 2)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Fault 2 enable
pub mod FLT2EN {
/// Offset (1 bits)
pub const offset: u32 = 1;
/// Mask (1 bit: 1 << 1)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
/// Fault 1 enable
pub mod FLT1EN {
/// Offset (0 bits)
pub const offset: u32 = 0;
/// Mask (1 bit: 1 << 0)
pub const mask: u32 = 1 << offset;
/// Read-only values (empty)
pub mod R {}
/// Write-only values (empty)
pub mod W {}
/// Read-write values (empty)
pub mod RW {}
}
}
#[repr(C)]
pub struct RegisterBlock {
/// Timerx Control Register
pub TIMDCR: RWRegister<u32>,
/// Timerx Interrupt Status Register
pub TIMDISR: RORegister<u32>,
/// Timerx Interrupt Clear Register
pub TIMDICR: WORegister<u32>,
/// TIMxDIER5
pub TIMDDIER5: RWRegister<u32>,
/// Timerx Counter Register
pub CNTDR: RWRegister<u32>,
/// Timerx Period Register
pub PERDR: RWRegister<u32>,
/// Timerx Repetition Register
pub REPDR: RWRegister<u32>,
/// Timerx Compare 1 Register
pub CMP1DR: RWRegister<u32>,
/// Timerx Compare 1 Compound Register
pub CMP1CDR: RWRegister<u32>,
/// Timerx Compare 2 Register
pub CMP2DR: RWRegister<u32>,
/// Timerx Compare 3 Register
pub CMP3DR: RWRegister<u32>,
/// Timerx Compare 4 Register
pub CMP4DR: RWRegister<u32>,
/// Timerx Capture 1 Register
pub CPT1DR: RORegister<u32>,
/// Timerx Capture 2 Register
pub CPT2DR: RORegister<u32>,
/// Timerx Deadtime Register
pub DTDR: RWRegister<u32>,
/// Timerx Output1 Set Register
pub SETD1R: RWRegister<u32>,
/// Timerx Output1 Reset Register
pub RSTD1R: RWRegister<u32>,
/// Timerx Output2 Set Register
pub SETD2R: RWRegister<u32>,
/// Timerx Output2 Reset Register
pub RSTD2R: RWRegister<u32>,
/// Timerx External Event Filtering Register 1
pub EEFDR1: RWRegister<u32>,
/// Timerx External Event Filtering Register 2
pub EEFDR2: RWRegister<u32>,
/// TimerA Reset Register
pub RSTDR: RWRegister<u32>,
/// Timerx Chopper Register
pub CHPDR: RWRegister<u32>,
/// Timerx Capture 2 Control Register
pub CPT1DCR: RWRegister<u32>,
/// CPT2xCR
pub CPT2DCR: RWRegister<u32>,
/// Timerx Output Register
pub OUTDR: RWRegister<u32>,
/// Timerx Fault Register
pub FLTDR: RWRegister<u32>,
}
pub struct ResetValues {
pub TIMDCR: u32,
pub TIMDISR: u32,
pub TIMDICR: u32,
pub TIMDDIER5: u32,
pub CNTDR: u32,
pub PERDR: u32,
pub REPDR: u32,
pub CMP1DR: u32,
pub CMP1CDR: u32,
pub CMP2DR: u32,
pub CMP3DR: u32,
pub CMP4DR: u32,
pub CPT1DR: u32,
pub CPT2DR: u32,
pub DTDR: u32,
pub SETD1R: u32,
pub RSTD1R: u32,
pub SETD2R: u32,
pub RSTD2R: u32,
pub EEFDR1: u32,
pub EEFDR2: u32,
pub RSTDR: u32,
pub CHPDR: u32,
pub CPT1DCR: u32,
pub CPT2DCR: u32,
pub OUTDR: u32,
pub FLTDR: u32,
}
#[cfg(not(feature = "nosync"))]
pub struct Instance {
pub(crate) addr: u32,
pub(crate) _marker: PhantomData<*const RegisterBlock>,
}
#[cfg(not(feature = "nosync"))]
impl ::core::ops::Deref for Instance {
type Target = RegisterBlock;
#[inline(always)]
fn deref(&self) -> &RegisterBlock {
unsafe { &*(self.addr as *const _) }
}
}
#[cfg(feature = "rtic")]
unsafe impl Send for Instance {}
| 26.425253 | 96 | 0.476805 |
c13c0d3179afffc2aa130ba3f1a8f9408c8b076a | 7,476 | // 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.
#[allow(dead_code)]
mod support;
use croaring::Bitmap;
use digest::Digest;
use support::{create_mmr, int_to_hash, Hasher};
use tari_crypto::tari_utilities::hex::Hex;
use tari_mmr::{Hash, HashSlice, MutableMmr};
fn hash_with_bitmap(hash: &HashSlice, bitmap: &mut Bitmap) -> Hash {
bitmap.run_optimize();
let hasher = Hasher::new();
hasher.chain(hash).chain(&bitmap.serialize()).result().to_vec()
}
/// MMRs with no elements should provide sane defaults. The merkle root must be the hash of an empty string, b"".
#[test]
fn zero_length_mmr() {
let mmr = MutableMmr::<Hasher, _>::new(Vec::default(), Bitmap::create());
assert_eq!(mmr.len(), 0);
assert_eq!(mmr.is_empty(), Ok(true));
let empty_hash = Hasher::digest(b"").to_vec();
assert_eq!(
mmr.get_merkle_root(),
Ok(hash_with_bitmap(&empty_hash, &mut Bitmap::create()))
);
}
#[test]
// Note the hardcoded hashes are only valid when using Blake256 as the Hasher
fn delete() {
let mut mmr = MutableMmr::<Hasher, _>::new(Vec::default(), Bitmap::create());
assert_eq!(mmr.is_empty(), Ok(true));
for i in 0..5 {
assert!(mmr.push(&int_to_hash(i)).is_ok());
}
assert_eq!(mmr.len(), 5);
let root = mmr.get_merkle_root().unwrap();
assert_eq!(
&root.to_hex(),
"7b7ddec2af4f3d0b9b165750cf2ff15813e965d29ecd5318e0c8fea901ceaef4"
);
// Can't delete past bounds
assert_eq!(mmr.delete_and_compress(5, true), false);
assert_eq!(mmr.len(), 5);
assert_eq!(mmr.is_empty(), Ok(false));
assert_eq!(mmr.get_merkle_root(), Ok(root));
// Delete some nodes
assert!(mmr.push(&int_to_hash(5)).is_ok());
assert!(mmr.delete_and_compress(0, false));
assert!(mmr.delete_and_compress(2, false));
assert!(mmr.delete_and_compress(4, true));
let root = mmr.get_merkle_root().unwrap();
assert_eq!(
&root.to_hex(),
"69e69ba0c6222f2d9caa68282de0ba7f1259a0fa2b8d84af68f907ef4ec05054"
);
assert_eq!(mmr.len(), 3);
assert_eq!(mmr.is_empty(), Ok(false));
// Can't delete that which has already been deleted
assert!(!mmr.delete_and_compress(0, false));
assert!(!mmr.delete_and_compress(2, false));
assert!(!mmr.delete_and_compress(0, true));
// .. or beyond bounds of MMR
assert!(!mmr.delete_and_compress(99, true));
assert_eq!(mmr.len(), 3);
assert_eq!(mmr.is_empty(), Ok(false));
// Merkle root should not have changed:
assert_eq!(mmr.get_merkle_root(), Ok(root));
assert!(mmr.delete_and_compress(1, false));
assert!(mmr.delete_and_compress(5, false));
assert!(mmr.delete(3));
assert_eq!(mmr.len(), 0);
assert_eq!(mmr.is_empty(), Ok(true));
let root = mmr.get_merkle_root().unwrap();
assert_eq!(
&root.to_hex(),
"2a540797d919e63cff8051e54ae13197315000bcfde53efd3f711bb3d24995bc"
);
}
/// Successively build up an MMR and check that the roots, heights and indices are all correct.
#[test]
fn build_mmr() {
// Check the mutable MMR against a standard MMR and a roaring bitmap. Create one with 5 leaf nodes *8 MMR nodes)
let mmr_check = create_mmr(5);
assert_eq!(mmr_check.len(), Ok(8));
let mut bitmap = Bitmap::create();
// Create a small mutable MMR
let mut mmr = MutableMmr::<Hasher, _>::new(Vec::default(), Bitmap::create());
for i in 0..5 {
assert!(mmr.push(&int_to_hash(i)).is_ok());
}
// MutableMmr::len gives the size in terms of leaf nodes:
assert_eq!(mmr.len(), 5);
let mmr_root = mmr_check.get_merkle_root().unwrap();
let root_check = hash_with_bitmap(&mmr_root, &mut bitmap);
assert_eq!(mmr.get_merkle_root(), Ok(root_check));
// Delete a node
assert!(mmr.delete_and_compress(3, true));
bitmap.add(3);
let root_check = hash_with_bitmap(&mmr_root, &mut bitmap);
assert_eq!(mmr.get_merkle_root(), Ok(root_check));
}
#[test]
fn equality_check() {
let mut ma = MutableMmr::<Hasher, _>::new(Vec::default(), Bitmap::create());
let mut mb = MutableMmr::<Hasher, _>::new(Vec::default(), Bitmap::create());
assert!(ma == mb);
assert!(ma.push(&int_to_hash(1)).is_ok());
assert!(ma != mb);
assert!(mb.push(&int_to_hash(1)).is_ok());
assert!(ma == mb);
assert!(ma.push(&int_to_hash(2)).is_ok());
assert!(ma != mb);
assert!(ma.delete(1));
// Even though the two trees have the same apparent elements, they're still not equal, because we don't actually
// delete anything
assert!(ma != mb);
// Add the same hash to mb and then delete it
assert!(mb.push(&int_to_hash(2)).is_ok());
assert!(mb.delete(1));
// Now they're equal!
assert!(ma == mb);
}
#[test]
fn restore_from_leaf_nodes() {
let mut mmr = MutableMmr::<Hasher, _>::new(Vec::default(), Bitmap::create());
for i in 0..12 {
assert!(mmr.push(&int_to_hash(i)).is_ok());
}
assert!(mmr.delete_and_compress(2, true));
assert!(mmr.delete_and_compress(4, true));
assert!(mmr.delete_and_compress(5, true));
// Request state of MMR with single call
let leaf_count = mmr.get_leaf_count();
let mmr_state1 = mmr.to_leaf_nodes(0, leaf_count).unwrap();
// Request state of MMR with multiple calls
let mut mmr_state2 = mmr.to_leaf_nodes(0, 3).unwrap();
mmr_state2.combine(mmr.to_leaf_nodes(3, 3).unwrap());
mmr_state2.combine(mmr.to_leaf_nodes(6, leaf_count - 6).unwrap());
assert_eq!(mmr_state1, mmr_state2);
// Change the state more before the restore
let mmr_root = mmr.get_merkle_root();
assert!(mmr.push(&int_to_hash(7)).is_ok());
assert!(mmr.push(&int_to_hash(8)).is_ok());
assert!(mmr.delete_and_compress(3, true));
// Restore from compact state
assert!(mmr.assign(mmr_state1.clone()).is_ok());
assert_eq!(mmr.get_merkle_root(), mmr_root);
let restored_mmr_state = mmr.to_leaf_nodes(0, mmr.get_leaf_count()).unwrap();
assert_eq!(restored_mmr_state, mmr_state2);
}
| 41.076923 | 118 | 0.683654 |
4a600ffcb6c7703075a74dae162e091b58c78878 | 12,644 | use ethereum_types::{H256, U256};
use evmodin::{host::*, opcode::*, util::*, *};
use hex_literal::hex;
#[tokio::test]
async fn eip2929_case1() {
// https://gist.github.com/holiman/174548cad102096858583c6fbbb0649a#case-1
EvmTester::new()
.revision(Revision::Berlin)
.sender(hex!("0000000000000000000000000000000000000000"))
.destination(hex!("000000000000000000000000636F6E7472616374"))
.gas(13653)
.code(hex!("60013f5060023b506003315060f13f5060f23b5060f3315060f23f5060f33b5060f1315032315030315000"))
.status(StatusCode::Success)
.gas_used(8653)
.output_data([])
.inspect_host(|host, msg| {
assert_eq!(
host.recorded.lock().account_accesses,
[
msg.sender,
msg.destination,
hex!("0000000000000000000000000000000000000001").into(),
hex!("0000000000000000000000000000000000000001").into(),
hex!("0000000000000000000000000000000000000002").into(),
hex!("0000000000000000000000000000000000000002").into(),
hex!("0000000000000000000000000000000000000003").into(),
hex!("0000000000000000000000000000000000000003").into(),
hex!("00000000000000000000000000000000000000f1").into(),
hex!("00000000000000000000000000000000000000f1").into(),
hex!("00000000000000000000000000000000000000f2").into(),
hex!("00000000000000000000000000000000000000f2").into(),
hex!("00000000000000000000000000000000000000f3").into(),
hex!("00000000000000000000000000000000000000f3").into(),
hex!("00000000000000000000000000000000000000f2").into(),
hex!("00000000000000000000000000000000000000f2").into(),
hex!("00000000000000000000000000000000000000f3").into(),
hex!("00000000000000000000000000000000000000f3").into(),
hex!("00000000000000000000000000000000000000f1").into(),
hex!("00000000000000000000000000000000000000f1").into(),
hex!("0000000000000000000000000000000000000000").into(),
hex!("0000000000000000000000000000000000000000").into(),
msg.destination,
msg.destination,
]
);
})
.check()
.await
}
#[tokio::test]
async fn eip2929_case2() {
// https://gist.github.com/holiman/174548cad102096858583c6fbbb0649a#case-2
EvmTester::new()
.revision(Revision::Berlin)
.sender(hex!("0000000000000000000000000000000000000000"))
.destination(hex!("000000000000000000000000636F6E7472616374"))
.code(hex!(
"60006000600060ff3c60006000600060ff3c600060006000303c00"
))
.status(StatusCode::Success)
.gas_used(2835)
.output_data([])
.inspect_host(|host, msg| {
assert_eq!(
host.recorded.lock().account_accesses,
[
msg.sender,
msg.destination,
hex!("00000000000000000000000000000000000000ff").into(),
hex!("00000000000000000000000000000000000000ff").into(),
msg.destination,
]
);
})
.check()
.await
}
#[tokio::test]
async fn eip2929_case3() {
// https://gist.github.com/holiman/174548cad102096858583c6fbbb0649a#case-3
EvmTester::new()
.revision(Revision::Berlin)
.sender(hex!("0000000000000000000000000000000000000000"))
.destination(hex!("000000000000000000000000636F6E7472616374"))
.code(hex!("60015450601160015560116002556011600255600254600154"))
.status(StatusCode::Success)
.gas_used(44529)
.output_data([])
.check()
.await
}
#[tokio::test]
async fn eip2929_case4() {
// https://gist.github.com/holiman/174548cad102096858583c6fbbb0649a#case-4
EvmTester::new()
.revision(Revision::Berlin)
.sender(hex!("0000000000000000000000000000000000000000"))
.destination(hex!("000000000000000000000000636F6E7472616374"))
.code(hex!(
"60008080808060046000f15060008080808060ff6000f15060008080808060ff6000fa50"
))
.status(StatusCode::Success)
.gas_used(2869)
.output_data([])
.check()
.await
}
#[tokio::test]
async fn eip2929_op_oog() {
for (op, gas) in [
(OpCode::BALANCE, 2603),
(OpCode::EXTCODESIZE, 2603),
(OpCode::EXTCODEHASH, 2603),
] {
let t = EvmTester::new()
.revision(Revision::Berlin)
.code(Bytecode::new().pushv(0x0a).opcode(op));
t.clone()
.gas(gas)
.status(StatusCode::Success)
.gas_used(gas)
.check()
.await;
t.clone()
.gas(gas - 1)
.status(StatusCode::OutOfGas)
.gas_used(gas - 1)
.check()
.await;
}
}
#[tokio::test]
async fn eip2929_extcodecopy_oog() {
let t = EvmTester::new().revision(Revision::Berlin).code(
Bytecode::new()
.pushv(0)
.opcode(OpCode::DUP1)
.opcode(OpCode::DUP1)
.pushv(0xa)
.opcode(OpCode::EXTCODECOPY),
);
t.clone()
.gas(2612)
.status(StatusCode::Success)
.gas_used(2612)
.check()
.await;
t.clone()
.gas(2611)
.status(StatusCode::OutOfGas)
.gas_used(2611)
.check()
.await;
}
#[tokio::test]
async fn eip2929_sload_cold() {
let key = H256(U256::one().into());
let t = EvmTester::new()
.revision(Revision::Berlin)
.code(Bytecode::new().pushv(1).opcode(OpCode::SLOAD))
.apply_host_fn(move |host, msg| {
let mut st = host
.accounts
.entry(msg.destination)
.or_default()
.storage
.entry(key)
.or_default();
st.value = H256(U256::from(2).into());
assert_eq!(st.access_status, AccessStatus::Cold);
});
t.clone()
.gas(2103)
.status(StatusCode::Success)
.gas_used(2103)
.inspect_host(move |host, msg| {
assert_eq!(
host.accounts[&msg.destination].storage[&key].access_status,
AccessStatus::Warm
);
})
.check()
.await;
t.clone()
.gas(2102)
.status(StatusCode::OutOfGas)
.gas_used(2102)
.check()
.await;
}
#[tokio::test]
async fn eip2929_sload_two_slots() {
let key0 = H256(U256::from(0).into());
let key1 = H256(U256::from(1).into());
EvmTester::new()
.revision(Revision::Berlin)
.code(
Bytecode::new()
.pushv(key0.0)
.opcode(OpCode::SLOAD)
.opcode(OpCode::POP)
.pushv(key1.0)
.opcode(OpCode::SLOAD)
.opcode(OpCode::POP),
)
.gas(30000)
.status(StatusCode::Success)
.gas_used(4210)
.inspect_host(move |host, msg| {
assert_eq!(
host.accounts[&msg.destination].storage[&key0].access_status,
AccessStatus::Warm
);
assert_eq!(
host.accounts[&msg.destination].storage[&key1].access_status,
AccessStatus::Warm
);
})
.check()
.await
}
#[tokio::test]
async fn eip2929_sload_warm() {
let key = H256(U256::from(1).into());
let t = EvmTester::new()
.revision(Revision::Berlin)
.code(Bytecode::new().pushv(1).opcode(OpCode::SLOAD))
.apply_host_fn(move |host, msg| {
let st = host
.accounts
.entry(msg.destination)
.or_default()
.storage
.entry(key)
.or_default();
st.value = H256(U256::from(2).into());
st.access_status = AccessStatus::Warm;
});
t.clone()
.gas(103)
.status(StatusCode::Success)
.gas_used(103)
.inspect_host(move |host, msg| {
assert_eq!(
host.accounts[&msg.destination].storage[&key].access_status,
AccessStatus::Warm
);
})
.check()
.await;
t.clone()
.gas(102)
.status(StatusCode::OutOfGas)
.gas_used(102)
.check()
.await;
}
#[tokio::test]
async fn eip2929_sstore_modify_cold() {
let key = H256(U256::from(1).into());
let t = EvmTester::new()
.revision(Revision::Berlin)
.code(Bytecode::new().sstore(1, 3))
.apply_host_fn(move |host, msg| {
host.accounts
.entry(msg.destination)
.or_default()
.storage
.entry(key)
.or_default()
.value = H256(U256::from(2).into());
});
t.clone()
.gas(5006)
.status(StatusCode::Success)
.gas_used(5006)
.inspect_host(move |host, msg| {
assert_eq!(
host.accounts[&msg.destination].storage[&key].value,
H256(U256::from(3).into())
);
assert_eq!(
host.accounts[&msg.destination].storage[&key].access_status,
AccessStatus::Warm
);
})
.check()
.await;
t.clone()
.gas(5005)
.status(StatusCode::OutOfGas)
.gas_used(5005)
.inspect_host(move |host, msg| {
// The storage will be modified anyway, because the cost is checked after.
assert_eq!(
host.accounts[&msg.destination].storage[&key].value,
H256(U256::from(3).into())
);
assert_eq!(
host.accounts[&msg.destination].storage[&key].access_status,
AccessStatus::Warm
);
})
.check()
.await;
}
#[tokio::test]
async fn eip2929_selfdestruct_cold_beneficiary() {
let t = EvmTester::new()
.revision(Revision::Berlin)
.code(Bytecode::new().pushv(0xbe).opcode(OpCode::SELFDESTRUCT));
t.clone()
.gas(7603)
.status(StatusCode::Success)
.gas_used(7603)
.check()
.await;
t.clone()
.gas(7602)
.status(StatusCode::OutOfGas)
.gas_used(7602)
.check()
.await;
}
#[tokio::test]
async fn eip2929_selfdestruct_warm_beneficiary() {
let t = EvmTester::new()
.revision(Revision::Berlin)
.code(Bytecode::new().pushv(0xbe).opcode(OpCode::SELFDESTRUCT))
.apply_host_fn_async(|mut host, msg| async {
host.access_account(hex!("00000000000000000000000000000000000000be").into())
.await
.unwrap();
(host, msg)
});
t.clone()
.gas(5003)
.status(StatusCode::Success)
.gas_used(5003)
.check()
.await;
t.clone()
.gas(5002)
.status(StatusCode::OutOfGas)
.gas_used(5002)
.check()
.await;
}
#[tokio::test]
async fn eip2929_delegatecall_cold() {
let t = EvmTester::new()
.revision(Revision::Berlin)
.code(CallInstruction::delegatecall(0xde));
t.clone()
.gas(2618)
.status(StatusCode::Success)
.gas_used(2618)
.inspect_host(|host, msg| {
assert_eq!(
host.recorded.lock().account_accesses,
[
msg.sender,
msg.destination,
hex!("00000000000000000000000000000000000000de").into(),
hex!("00000000000000000000000000000000000000de").into(),
]
);
})
.check()
.await;
t.clone()
.gas(2617)
.status(StatusCode::OutOfGas)
.gas_used(2617)
.inspect_host(|host, msg| {
assert_eq!(
host.recorded.lock().account_accesses,
[
msg.sender,
msg.destination,
hex!("00000000000000000000000000000000000000de").into(),
]
);
})
.check()
.await;
}
| 30.104762 | 109 | 0.526653 |
dbbe8a9349faa5aa53be206a5ca99fdf1826e768 | 11,097 | #[doc = r" Value read from the register"]
pub struct R {
bits: u8,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u8,
}
impl super::TCCR_B {
#[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 ICNCR {
bits: bool,
}
impl ICNCR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct ICESR {
bits: bool,
}
impl ICESR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct WGM2R {
bits: u8,
}
impl WGM2R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = "Possible values of the field `CS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CSR {
#[doc = "No clock source (Timer/Counter stopped)"]
STOPPED,
#[doc = "clkIO/1 (No prescaling)"]
IO,
#[doc = "clkIO/8 (From prescaler)"]
IO_8,
#[doc = "clkIO/64 (From prescaler)"]
IO_64,
#[doc = "clkIO/256 (From prescaler)"]
IO_256,
#[doc = "clkIO/1024 (From prescaler)"]
IO_1024,
#[doc = "External clock source on T0 pin. Clock on falling edge."]
EXT_FALLING,
#[doc = "External clock source on T0 pin. Clock on rising edge."]
EXT_RISING,
}
impl CSR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
CSR::STOPPED => 0,
CSR::IO => 1,
CSR::IO_8 => 2,
CSR::IO_64 => 3,
CSR::IO_256 => 4,
CSR::IO_1024 => 5,
CSR::EXT_FALLING => 6,
CSR::EXT_RISING => 7,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> CSR {
match value {
0 => CSR::STOPPED,
1 => CSR::IO,
2 => CSR::IO_8,
3 => CSR::IO_64,
4 => CSR::IO_256,
5 => CSR::IO_1024,
6 => CSR::EXT_FALLING,
7 => CSR::EXT_RISING,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `STOPPED`"]
#[inline]
pub fn is_stopped(&self) -> bool {
*self == CSR::STOPPED
}
#[doc = "Checks if the value of the field is `IO`"]
#[inline]
pub fn is_io(&self) -> bool {
*self == CSR::IO
}
#[doc = "Checks if the value of the field is `IO_8`"]
#[inline]
pub fn is_io_8(&self) -> bool {
*self == CSR::IO_8
}
#[doc = "Checks if the value of the field is `IO_64`"]
#[inline]
pub fn is_io_64(&self) -> bool {
*self == CSR::IO_64
}
#[doc = "Checks if the value of the field is `IO_256`"]
#[inline]
pub fn is_io_256(&self) -> bool {
*self == CSR::IO_256
}
#[doc = "Checks if the value of the field is `IO_1024`"]
#[inline]
pub fn is_io_1024(&self) -> bool {
*self == CSR::IO_1024
}
#[doc = "Checks if the value of the field is `EXT_FALLING`"]
#[inline]
pub fn is_ext_falling(&self) -> bool {
*self == CSR::EXT_FALLING
}
#[doc = "Checks if the value of the field is `EXT_RISING`"]
#[inline]
pub fn is_ext_rising(&self) -> bool {
*self == CSR::EXT_RISING
}
}
#[doc = r" Proxy"]
pub struct _ICNCW<'a> {
w: &'a mut W,
}
impl<'a> _ICNCW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _ICESW<'a> {
w: &'a mut W,
}
impl<'a> _ICESW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _WGM2W<'a> {
w: &'a mut W,
}
impl<'a> _WGM2W<'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 = 3;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `CS`"]
pub enum CSW {
#[doc = "No clock source (Timer/Counter stopped)"]
STOPPED,
#[doc = "clkIO/1 (No prescaling)"]
IO,
#[doc = "clkIO/8 (From prescaler)"]
IO_8,
#[doc = "clkIO/64 (From prescaler)"]
IO_64,
#[doc = "clkIO/256 (From prescaler)"]
IO_256,
#[doc = "clkIO/1024 (From prescaler)"]
IO_1024,
#[doc = "External clock source on T0 pin. Clock on falling edge."]
EXT_FALLING,
#[doc = "External clock source on T0 pin. Clock on rising edge."]
EXT_RISING,
}
impl CSW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
CSW::STOPPED => 0,
CSW::IO => 1,
CSW::IO_8 => 2,
CSW::IO_64 => 3,
CSW::IO_256 => 4,
CSW::IO_1024 => 5,
CSW::EXT_FALLING => 6,
CSW::EXT_RISING => 7,
}
}
}
#[doc = r" Proxy"]
pub struct _CSW<'a> {
w: &'a mut W,
}
impl<'a> _CSW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: CSW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "No clock source (Timer/Counter stopped)"]
#[inline]
pub fn stopped(self) -> &'a mut W {
self.variant(CSW::STOPPED)
}
#[doc = "clkIO/1 (No prescaling)"]
#[inline]
pub fn io(self) -> &'a mut W {
self.variant(CSW::IO)
}
#[doc = "clkIO/8 (From prescaler)"]
#[inline]
pub fn io_8(self) -> &'a mut W {
self.variant(CSW::IO_8)
}
#[doc = "clkIO/64 (From prescaler)"]
#[inline]
pub fn io_64(self) -> &'a mut W {
self.variant(CSW::IO_64)
}
#[doc = "clkIO/256 (From prescaler)"]
#[inline]
pub fn io_256(self) -> &'a mut W {
self.variant(CSW::IO_256)
}
#[doc = "clkIO/1024 (From prescaler)"]
#[inline]
pub fn io_1024(self) -> &'a mut W {
self.variant(CSW::IO_1024)
}
#[doc = "External clock source on T0 pin. Clock on falling edge."]
#[inline]
pub fn ext_falling(self) -> &'a mut W {
self.variant(CSW::EXT_FALLING)
}
#[doc = "External clock source on T0 pin. Clock on rising edge."]
#[inline]
pub fn ext_rising(self) -> &'a mut W {
self.variant(CSW::EXT_RISING)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u8) << OFFSET);
self.w.bits |= ((value & MASK) as u8) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
#[doc = "Bit 7 - Input Capture Noise Canceler"]
#[inline]
pub fn icnc(&self) -> ICNCR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u8) != 0
};
ICNCR { bits }
}
#[doc = "Bit 6 - Input Capture Edge Set"]
#[inline]
pub fn ices(&self) -> ICESR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u8) != 0
};
ICESR { bits }
}
#[doc = "Bits 3:4 - Waveform Generation Mode 3:2"]
#[inline]
pub fn wgm2(&self) -> WGM2R {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u8) as u8
};
WGM2R { bits }
}
#[doc = "Bits 0:2 - Clock Select"]
#[inline]
pub fn cs(&self) -> CSR {
CSR::_from({
const MASK: u8 = 7;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u8) as u8
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u8) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 7 - Input Capture Noise Canceler"]
#[inline]
pub fn icnc(&mut self) -> _ICNCW {
_ICNCW { w: self }
}
#[doc = "Bit 6 - Input Capture Edge Set"]
#[inline]
pub fn ices(&mut self) -> _ICESW {
_ICESW { w: self }
}
#[doc = "Bits 3:4 - Waveform Generation Mode 3:2"]
#[inline]
pub fn wgm2(&mut self) -> _WGM2W {
_WGM2W { w: self }
}
#[doc = "Bits 0:2 - Clock Select"]
#[inline]
pub fn cs(&mut self) -> _CSW {
_CSW { w: self }
}
}
| 25.92757 | 70 | 0.496621 |
1eca98e94c17d1f1ad34c71c7a5321262952cb59 | 580 | fn main() {
let s = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind .";
println!("{}", s);
let result = s.split_whitespace().map(
|s|
if s.len() > 4 {
let mut cs = s.chars();
let h = cs.next().unwrap();
let mut m = cs.rev();
let t = m.next().unwrap();
let m: String = m.collect();
format!("{}{}{}", h, m, t)
}
else {s.to_string()}
).collect::<Vec<_>>().join(" ");
println!("{}", result);
}
| 30.526316 | 128 | 0.467241 |
ab281991d62007d1e5d92e1ea074e8279097a32a | 2,271 | use crate::components::Vector2;
use specs::Component;
use specs::VecStorage;
use specs_derive::Component;
pub type CollisionWorld = ncollide2d::world::CollisionWorld<f32, specs::Entity>;
pub struct ColliderBuilder {
pub offset: Vector2,
pub shape: ncollide2d::shape::Cuboid<f32>,
pub collision_group: ncollide2d::world::CollisionGroups,
}
#[derive(Clone)]
pub struct Collider {
pub enabled: bool,
pub handle: ncollide2d::world::CollisionObjectHandle,
pub offset: Vector2,
// Vector 2 in this case is normal
pub collides_with: Vec<(specs::Entity, Vector2)>,
}
#[derive(Clone, Component)]
#[storage(VecStorage)]
pub struct Colliders(pub Vec<Collider>);
pub fn init_collision_world() -> CollisionWorld {
CollisionWorld::new(0.02)
}
#[allow(dead_code)]
impl ColliderBuilder {
pub fn new() -> Self {
Self {
offset: na::zero(),
shape: ncollide2d::shape::Cuboid::new(na::Vector2::repeat(1.0)),
collision_group: ncollide2d::world::CollisionGroups::new(),
}
}
pub fn offset(mut self, offset: Vector2) -> Self {
self.offset = offset;
self
}
pub fn bounds(mut self, bounds: Vector2) -> Self {
self.shape = ncollide2d::shape::Cuboid::new(bounds);
self
}
pub fn membership(mut self, group_id: &[usize]) -> Self {
self.collision_group.set_membership(group_id);
self
}
pub fn whitelist(mut self, group_id: &[usize]) -> Self {
self.collision_group.set_whitelist(group_id);
self
}
pub fn blacklist(mut self, group_id: &[usize]) -> Self {
self.collision_group.set_blacklist(group_id);
self
}
pub fn build(self, collision_world: &mut CollisionWorld, entity: specs::Entity) -> Collider {
let object = collision_world.add(
na::Isometry2::new(self.offset, na::zero()),
ncollide2d::shape::ShapeHandle::new(self.shape.clone()),
self.collision_group,
ncollide2d::world::GeometricQueryType::Contacts(0.0001, 0.0),
entity,
);
Collider {
enabled: true,
handle: object.handle(),
offset: self.offset,
collides_with: vec![],
}
}
}
| 29.493506 | 97 | 0.620872 |
ddf8dd9a9070794f3d143b3c750b3a4b2b7bf29e | 4,643 | use png::{ColorType, Decoder, DecodingError};
use std::{
fs::{read_dir, File},
io,
io::BufReader,
path::Path,
slice::{from_raw_parts, from_raw_parts_mut},
};
use integral_geometry::Size;
use vec2d::Vec2D;
pub struct ThemeSprite {
pixels: Vec2D<u32>,
}
impl ThemeSprite {
#[inline]
pub fn size(&self) -> Size {
self.pixels.size()
}
#[inline]
pub fn width(&self) -> usize {
self.size().width
}
#[inline]
pub fn height(&self) -> usize {
self.size().height
}
#[inline]
pub fn rows(&self) -> impl DoubleEndedIterator<Item = &[u32]> {
self.pixels.rows()
}
#[inline]
pub fn get_row(&self, index: usize) -> &[u32] {
&self.pixels[index]
}
#[inline]
pub fn get_pixel(&self, x: usize, y: usize) -> u32 {
self.pixels[y][x]
}
pub fn to_transposed(&self) -> ThemeSprite {
let size = self.size().transpose();
let mut pixels = Vec2D::new(size, 0u32);
for (y, row) in self.pixels.rows().enumerate() {
for (x, v) in row.iter().enumerate() {
pixels[x][y] = *v;
}
}
ThemeSprite { pixels }
}
pub fn to_tiled(&self) -> TiledSprite {
let size = self.size();
assert!(size.is_power_of_two());
let tile_width_shift = size.width.trailing_zeros() as usize + 2;
let mut pixels = vec![0u32; size.area()];
for (y, row) in self.pixels.rows().enumerate() {
for (x, v) in row.iter().enumerate() {
pixels[get_tiled_index(x, y, tile_width_shift)] = *v;
}
}
TiledSprite {
tile_width_shift,
size,
pixels,
}
}
}
#[inline]
fn get_tiled_index(x: usize, y: usize, tile_width_shift: usize) -> usize {
(((y >> 2) << tile_width_shift) + ((x >> 2) << 4)) + ((y & 0b11) << 2) + (x & 0b11)
}
pub struct TiledSprite {
tile_width_shift: usize,
size: Size,
pixels: Vec<u32>,
}
impl TiledSprite {
#[inline]
pub fn size(&self) -> Size {
self.size
}
#[inline]
pub fn width(&self) -> usize {
self.size().width
}
#[inline]
pub fn height(&self) -> usize {
self.size().height
}
#[inline]
pub fn get_pixel(&self, x: usize, y: usize) -> u32 {
self.pixels[get_tiled_index(x, y, self.tile_width_shift)]
}
}
pub struct Theme {
land_texture: Option<ThemeSprite>,
border_texture: Option<ThemeSprite>,
}
impl Theme {
pub fn land_texture(&self) -> Option<&ThemeSprite> {
self.land_texture.as_ref()
}
pub fn border_texture(&self) -> Option<&ThemeSprite> {
self.border_texture.as_ref()
}
}
#[derive(Debug)]
pub enum ThemeLoadError {
File(io::Error),
Decoding(DecodingError),
Format(String),
}
impl From<io::Error> for ThemeLoadError {
fn from(e: io::Error) -> Self {
ThemeLoadError::File(e)
}
}
impl From<DecodingError> for ThemeLoadError {
fn from(e: DecodingError) -> Self {
ThemeLoadError::Decoding(e)
}
}
impl Theme {
pub fn new() -> Self {
Theme {
land_texture: None,
border_texture: None,
}
}
pub fn load(path: &Path) -> Result<Theme, ThemeLoadError> {
let mut theme = Self::new();
for entry in read_dir(path)? {
let file = entry?;
if file.file_name() == "LandTex.png" {
theme.land_texture = Some(load_sprite(&file.path())?)
} else if file.file_name() == "Border.png" {
theme.border_texture = Some(load_sprite(&file.path())?)
}
}
Ok(theme)
}
}
fn load_sprite(path: &Path) -> Result<ThemeSprite, ThemeLoadError> {
let decoder = Decoder::new(BufReader::new(File::open(path)?));
let (info, mut reader) = decoder.read_info()?;
if info.color_type != ColorType::RGBA {
return Err(ThemeLoadError::Format(format!(
"Unexpected format: {:?}",
info.color_type
)));
}
let size = Size::new(info.width as usize, info.height as usize);
let mut pixels: Vec2D<u32> = Vec2D::new(size, 0);
reader.next_frame(slice_u32_to_u8_mut(pixels.as_mut_slice()))?;
Ok(ThemeSprite { pixels })
}
pub fn slice_u32_to_u8(slice_u32: &[u32]) -> &[u8] {
unsafe { from_raw_parts::<u8>(slice_u32.as_ptr() as *const u8, slice_u32.len() * 4) }
}
pub fn slice_u32_to_u8_mut(slice_u32: &mut [u32]) -> &mut [u8] {
unsafe { from_raw_parts_mut::<u8>(slice_u32.as_mut_ptr() as *mut u8, slice_u32.len() * 4) }
}
| 23.810256 | 95 | 0.558691 |
3972cde7d4e534cdae5fabf8f30723b12ce50449 | 195 | fn add(a: i8, b: i8) -> i8 {
return a + b;
}
fn print_int(num: u8) {
println!("{}", num);
}
fn main() {
let a = 5;
let b = -6;
println!("{}", add(a, b));
print_int(5)
}
| 13 | 30 | 0.435897 |
aba39966110ad98111ffde174fa7dceda39f96ff | 20,657 | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::indexed_vec::IndexVec;
use rustc_data_structures::sync::Lrc;
use rustc::ty::query::Providers;
use rustc::ty::{self, TyCtxt};
use rustc::hir;
use rustc::hir::def_id::DefId;
use rustc::lint::builtin::{SAFE_EXTERN_STATICS, SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
use rustc::mir::*;
use rustc::mir::visit::{PlaceContext, Visitor};
use syntax::ast;
use syntax::symbol::Symbol;
use util;
pub struct UnsafetyChecker<'a, 'tcx: 'a> {
mir: &'a Mir<'tcx>,
source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
violations: Vec<UnsafetyViolation>,
source_info: SourceInfo,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
used_unsafe: FxHashSet<ast::NodeId>,
inherited_blocks: Vec<(ast::NodeId, bool)>,
}
impl<'a, 'gcx, 'tcx> UnsafetyChecker<'a, 'tcx> {
fn new(mir: &'a Mir<'tcx>,
source_scope_local_data: &'a IndexVec<SourceScope, SourceScopeLocalData>,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
param_env: ty::ParamEnv<'tcx>) -> Self {
Self {
mir,
source_scope_local_data,
violations: vec![],
source_info: SourceInfo {
span: mir.span,
scope: OUTERMOST_SOURCE_SCOPE
},
tcx,
param_env,
used_unsafe: FxHashSet(),
inherited_blocks: vec![],
}
}
}
impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
fn visit_terminator(&mut self,
block: BasicBlock,
terminator: &Terminator<'tcx>,
location: Location)
{
self.source_info = terminator.source_info;
match terminator.kind {
TerminatorKind::Goto { .. } |
TerminatorKind::SwitchInt { .. } |
TerminatorKind::Drop { .. } |
TerminatorKind::Yield { .. } |
TerminatorKind::Assert { .. } |
TerminatorKind::DropAndReplace { .. } |
TerminatorKind::GeneratorDrop |
TerminatorKind::Resume |
TerminatorKind::Abort |
TerminatorKind::Return |
TerminatorKind::Unreachable |
TerminatorKind::FalseEdges { .. } |
TerminatorKind::FalseUnwind { .. } => {
// safe (at least as emitted during MIR construction)
}
TerminatorKind::Call { ref func, .. } => {
let func_ty = func.ty(self.mir, self.tcx);
let sig = func_ty.fn_sig(self.tcx);
if let hir::Unsafety::Unsafe = sig.unsafety() {
self.require_unsafe("call to unsafe function",
"consult the function's documentation for information on how to avoid \
undefined behavior")
}
}
}
self.super_terminator(block, terminator, location);
}
fn visit_statement(&mut self,
block: BasicBlock,
statement: &Statement<'tcx>,
location: Location)
{
self.source_info = statement.source_info;
match statement.kind {
StatementKind::Assign(..) |
StatementKind::ReadForMatch(..) |
StatementKind::SetDiscriminant { .. } |
StatementKind::StorageLive(..) |
StatementKind::StorageDead(..) |
StatementKind::EndRegion(..) |
StatementKind::Validate(..) |
StatementKind::UserAssertTy(..) |
StatementKind::Nop => {
// safe (at least as emitted during MIR construction)
}
StatementKind::InlineAsm { .. } => {
self.require_unsafe("use of inline assembly",
"inline assembly is entirely unchecked and can cause undefined behavior")
},
}
self.super_statement(block, statement, location);
}
fn visit_rvalue(&mut self,
rvalue: &Rvalue<'tcx>,
location: Location)
{
if let &Rvalue::Aggregate(box ref aggregate, _) = rvalue {
match aggregate {
&AggregateKind::Array(..) |
&AggregateKind::Tuple |
&AggregateKind::Adt(..) => {}
&AggregateKind::Closure(def_id, _) |
&AggregateKind::Generator(def_id, _, _) => {
let UnsafetyCheckResult {
violations, unsafe_blocks
} = self.tcx.unsafety_check_result(def_id);
self.register_violations(&violations, &unsafe_blocks);
}
}
}
self.super_rvalue(rvalue, location);
}
fn visit_place(&mut self,
place: &Place<'tcx>,
context: PlaceContext<'tcx>,
location: Location) {
if let PlaceContext::Borrow { .. } = context {
if util::is_disaligned(self.tcx, self.mir, self.param_env, place) {
let source_info = self.source_info;
let lint_root =
self.source_scope_local_data[source_info.scope].lint_root;
self.register_violations(&[UnsafetyViolation {
source_info,
description: Symbol::intern("borrow of packed field").as_interned_str(),
details:
Symbol::intern("fields of packed structs might be misaligned: \
dereferencing a misaligned pointer or even just creating a \
misaligned reference is undefined behavior")
.as_interned_str(),
kind: UnsafetyViolationKind::BorrowPacked(lint_root)
}], &[]);
}
}
match place {
&Place::Projection(box Projection {
ref base, ref elem
}) => {
let old_source_info = self.source_info;
if let &Place::Local(local) = base {
if self.mir.local_decls[local].internal {
// Internal locals are used in the `move_val_init` desugaring.
// We want to check unsafety against the source info of the
// desugaring, rather than the source info of the RHS.
self.source_info = self.mir.local_decls[local].source_info;
}
}
let base_ty = base.ty(self.mir, self.tcx).to_ty(self.tcx);
match base_ty.sty {
ty::TyRawPtr(..) => {
self.require_unsafe("dereference of raw pointer",
"raw pointers may be NULL, dangling or unaligned; they can violate \
aliasing rules and cause data races: all of these are undefined \
behavior")
}
ty::TyAdt(adt, _) => {
if adt.is_union() {
if context == PlaceContext::Store ||
context == PlaceContext::AsmOutput ||
context == PlaceContext::Drop
{
let elem_ty = match elem {
&ProjectionElem::Field(_, ty) => ty,
_ => span_bug!(
self.source_info.span,
"non-field projection {:?} from union?",
place)
};
if elem_ty.moves_by_default(self.tcx, self.param_env,
self.source_info.span) {
self.require_unsafe(
"assignment to non-`Copy` union field",
"the previous content of the field will be dropped, which \
causes undefined behavior if the field was not properly \
initialized")
} else {
// write to non-move union, safe
}
} else {
self.require_unsafe("access to union field",
"the field may not be properly initialized: using \
uninitialized data will cause undefined behavior")
}
}
}
_ => {}
}
self.source_info = old_source_info;
}
&Place::Local(..) => {
// locals are safe
}
&Place::Promoted(_) => {
bug!("unsafety checking should happen before promotion")
}
&Place::Static(box Static { def_id, ty: _ }) => {
if self.tcx.is_static(def_id) == Some(hir::Mutability::MutMutable) {
self.require_unsafe("use of mutable static",
"mutable statics can be mutated by multiple threads: aliasing violations \
or data races will cause undefined behavior");
} else if self.tcx.is_foreign_item(def_id) {
let source_info = self.source_info;
let lint_root =
self.source_scope_local_data[source_info.scope].lint_root;
self.register_violations(&[UnsafetyViolation {
source_info,
description: Symbol::intern("use of extern static").as_interned_str(),
details:
Symbol::intern("extern statics are not controlled by the Rust type \
system: invalid data, aliasing violations or data \
races will cause undefined behavior")
.as_interned_str(),
kind: UnsafetyViolationKind::ExternStatic(lint_root)
}], &[]);
}
}
};
self.super_place(place, context, location);
}
}
impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
fn require_unsafe(&mut self,
description: &'static str,
details: &'static str)
{
let source_info = self.source_info;
self.register_violations(&[UnsafetyViolation {
source_info,
description: Symbol::intern(description).as_interned_str(),
details: Symbol::intern(details).as_interned_str(),
kind: UnsafetyViolationKind::General,
}], &[]);
}
fn register_violations(&mut self,
violations: &[UnsafetyViolation],
unsafe_blocks: &[(ast::NodeId, bool)]) {
let within_unsafe = match self.source_scope_local_data[self.source_info.scope].safety {
Safety::Safe => {
for violation in violations {
if !self.violations.contains(violation) {
self.violations.push(violation.clone())
}
}
false
}
Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
Safety::ExplicitUnsafe(node_id) => {
if !violations.is_empty() {
self.used_unsafe.insert(node_id);
}
true
}
};
self.inherited_blocks.extend(unsafe_blocks.iter().map(|&(node_id, is_used)| {
(node_id, is_used && !within_unsafe)
}));
}
}
pub(crate) fn provide(providers: &mut Providers) {
*providers = Providers {
unsafety_check_result,
unsafe_derive_on_repr_packed,
..*providers
};
}
struct UnusedUnsafeVisitor<'a> {
used_unsafe: &'a FxHashSet<ast::NodeId>,
unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>,
}
impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
fn nested_visit_map<'this>(&'this mut self) ->
hir::intravisit::NestedVisitorMap<'this, 'tcx>
{
hir::intravisit::NestedVisitorMap::None
}
fn visit_block(&mut self, block: &'tcx hir::Block) {
hir::intravisit::walk_block(self, block);
if let hir::UnsafeBlock(hir::UserProvided) = block.rules {
self.unsafe_blocks.push((block.id, self.used_unsafe.contains(&block.id)));
}
}
}
fn check_unused_unsafe<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
def_id: DefId,
used_unsafe: &FxHashSet<ast::NodeId>,
unsafe_blocks: &'a mut Vec<(ast::NodeId, bool)>)
{
let body_id =
tcx.hir.as_local_node_id(def_id).and_then(|node_id| {
tcx.hir.maybe_body_owned_by(node_id)
});
let body_id = match body_id {
Some(body) => body,
None => {
debug!("check_unused_unsafe({:?}) - no body found", def_id);
return
}
};
let body = tcx.hir.body(body_id);
debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})",
def_id, body, used_unsafe);
let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
hir::intravisit::Visitor::visit_body(&mut visitor, body);
}
fn unsafety_check_result<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
-> UnsafetyCheckResult
{
debug!("unsafety_violations({:?})", def_id);
// NB: this borrow is valid because all the consumers of
// `mir_built` force this.
let mir = &tcx.mir_built(def_id).borrow();
let source_scope_local_data = match mir.source_scope_local_data {
ClearCrossCrate::Set(ref data) => data,
ClearCrossCrate::Clear => {
debug!("unsafety_violations: {:?} - remote, skipping", def_id);
return UnsafetyCheckResult {
violations: Lrc::new([]),
unsafe_blocks: Lrc::new([])
}
}
};
let param_env = tcx.param_env(def_id);
let mut checker = UnsafetyChecker::new(
mir, source_scope_local_data, tcx, param_env);
checker.visit_mir(mir);
check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
UnsafetyCheckResult {
violations: checker.violations.into(),
unsafe_blocks: checker.inherited_blocks.into()
}
}
fn unsafe_derive_on_repr_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
let lint_node_id = match tcx.hir.as_local_node_id(def_id) {
Some(node_id) => node_id,
None => bug!("checking unsafety for non-local def id {:?}", def_id)
};
// FIXME: when we make this a hard error, this should have its
// own error code.
let message = if tcx.generics_of(def_id).own_counts().types != 0 {
"#[derive] can't be used on a #[repr(packed)] struct with \
type parameters (error E0133)".to_string()
} else {
"#[derive] can't be used on a #[repr(packed)] struct that \
does not derive Copy (error E0133)".to_string()
};
tcx.lint_node(SAFE_PACKED_BORROWS,
lint_node_id,
tcx.def_span(def_id),
&message);
}
/// Return the NodeId for an enclosing scope that is also `unsafe`
fn is_enclosed(tcx: TyCtxt,
used_unsafe: &FxHashSet<ast::NodeId>,
id: ast::NodeId) -> Option<(String, ast::NodeId)> {
let parent_id = tcx.hir.get_parent_node(id);
if parent_id != id {
if used_unsafe.contains(&parent_id) {
Some(("block".to_string(), parent_id))
} else if let Some(hir::map::NodeItem(&hir::Item {
node: hir::ItemKind::Fn(_, header, _, _),
..
})) = tcx.hir.find(parent_id) {
match header.unsafety {
hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
hir::Unsafety::Normal => None,
}
} else {
is_enclosed(tcx, used_unsafe, parent_id)
}
} else {
None
}
}
fn report_unused_unsafe(tcx: TyCtxt, used_unsafe: &FxHashSet<ast::NodeId>, id: ast::NodeId) {
let span = tcx.sess.codemap().def_span(tcx.hir.span(id));
let msg = "unnecessary `unsafe` block";
let mut db = tcx.struct_span_lint_node(UNUSED_UNSAFE, id, span, msg);
db.span_label(span, msg);
if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
db.span_label(tcx.sess.codemap().def_span(tcx.hir.span(id)),
format!("because it's nested under this `unsafe` {}", kind));
}
db.emit();
}
fn builtin_derive_def_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<DefId> {
debug!("builtin_derive_def_id({:?})", def_id);
if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
if tcx.has_attr(impl_def_id, "automatically_derived") {
debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
Some(impl_def_id)
} else {
debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
None
}
} else {
debug!("builtin_derive_def_id({:?}) - not a method", def_id);
None
}
}
pub fn check_unsafety<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
debug!("check_unsafety({:?})", def_id);
// closures are handled by their parent fn.
if tcx.is_closure(def_id) {
return;
}
let UnsafetyCheckResult {
violations,
unsafe_blocks
} = tcx.unsafety_check_result(def_id);
for &UnsafetyViolation {
source_info, description, details, kind
} in violations.iter() {
// Report an error.
match kind {
UnsafetyViolationKind::General => {
struct_span_err!(
tcx.sess, source_info.span, E0133,
"{} is unsafe and requires unsafe function or block", description)
.span_label(source_info.span, &description.as_str()[..])
.note(&details.as_str()[..])
.emit();
}
UnsafetyViolationKind::ExternStatic(lint_node_id) => {
tcx.lint_node_note(SAFE_EXTERN_STATICS,
lint_node_id,
source_info.span,
&format!("{} is unsafe and requires unsafe function or block \
(error E0133)", &description.as_str()[..]),
&details.as_str()[..]);
}
UnsafetyViolationKind::BorrowPacked(lint_node_id) => {
if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
tcx.unsafe_derive_on_repr_packed(impl_def_id);
} else {
tcx.lint_node_note(SAFE_PACKED_BORROWS,
lint_node_id,
source_info.span,
&format!("{} is unsafe and requires unsafe function or block \
(error E0133)", &description.as_str()[..]),
&details.as_str()[..]);
}
}
}
}
let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
unsafe_blocks.sort();
let used_unsafe: FxHashSet<_> = unsafe_blocks.iter()
.flat_map(|&&(id, used)| if used { Some(id) } else { None })
.collect();
for &(block_id, is_used) in unsafe_blocks {
if !is_used {
report_unused_unsafe(tcx, &used_unsafe, block_id);
}
}
}
| 40.188716 | 100 | 0.516532 |
9cad2bd97620684f3b23d8ea65385a41353f16b7 | 35,604 | #![allow(unused_imports, non_camel_case_types)]
use crate::models::r5::CodeableConcept::CodeableConcept;
use crate::models::r5::ContactDetail::ContactDetail;
use crate::models::r5::Element::Element;
use crate::models::r5::Extension::Extension;
use crate::models::r5::Identifier::Identifier;
use crate::models::r5::ImplementationGuide_Definition::ImplementationGuide_Definition;
use crate::models::r5::ImplementationGuide_DependsOn::ImplementationGuide_DependsOn;
use crate::models::r5::ImplementationGuide_Global::ImplementationGuide_Global;
use crate::models::r5::ImplementationGuide_Manifest::ImplementationGuide_Manifest;
use crate::models::r5::Meta::Meta;
use crate::models::r5::Narrative::Narrative;
use crate::models::r5::ResourceList::ResourceList;
use crate::models::r5::UsageContext::UsageContext;
use serde_json::json;
use serde_json::value::Value;
use std::borrow::Cow;
/// A set of rules of how a particular interoperability or standards problem is solved
/// - typically through the use of FHIR resources. This resource is used to gather
/// all the parts of an implementation guide into a logical whole and to publish a
/// computable definition of all the parts.
#[derive(Debug)]
pub struct ImplementationGuide<'a> {
pub(crate) value: Cow<'a, Value>,
}
impl ImplementationGuide<'_> {
pub fn new(value: &Value) -> ImplementationGuide {
ImplementationGuide {
value: Cow::Borrowed(value),
}
}
pub fn to_json(&self) -> Value {
(*self.value).clone()
}
/// Extensions for copyright
pub fn _copyright(&self) -> Option<Element> {
if let Some(val) = self.value.get("_copyright") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for date
pub fn _date(&self) -> Option<Element> {
if let Some(val) = self.value.get("_date") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for description
pub fn _description(&self) -> Option<Element> {
if let Some(val) = self.value.get("_description") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for experimental
pub fn _experimental(&self) -> Option<Element> {
if let Some(val) = self.value.get("_experimental") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for fhirVersion
pub fn _fhir_version(&self) -> Option<Vec<Element>> {
if let Some(Value::Array(val)) = self.value.get("_fhirVersion") {
return Some(
val.into_iter()
.map(|e| Element {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// Extensions for implicitRules
pub fn _implicit_rules(&self) -> Option<Element> {
if let Some(val) = self.value.get("_implicitRules") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for language
pub fn _language(&self) -> Option<Element> {
if let Some(val) = self.value.get("_language") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for license
pub fn _license(&self) -> Option<Element> {
if let Some(val) = self.value.get("_license") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for name
pub fn _name(&self) -> Option<Element> {
if let Some(val) = self.value.get("_name") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for packageId
pub fn _package_id(&self) -> Option<Element> {
if let Some(val) = self.value.get("_packageId") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for publisher
pub fn _publisher(&self) -> Option<Element> {
if let Some(val) = self.value.get("_publisher") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for purpose
pub fn _purpose(&self) -> Option<Element> {
if let Some(val) = self.value.get("_purpose") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for status
pub fn _status(&self) -> Option<Element> {
if let Some(val) = self.value.get("_status") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for title
pub fn _title(&self) -> Option<Element> {
if let Some(val) = self.value.get("_title") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for url
pub fn _url(&self) -> Option<Element> {
if let Some(val) = self.value.get("_url") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Extensions for version
pub fn _version(&self) -> Option<Element> {
if let Some(val) = self.value.get("_version") {
return Some(Element {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Contact details to assist a user in finding and communicating with the publisher.
pub fn contact(&self) -> Option<Vec<ContactDetail>> {
if let Some(Value::Array(val)) = self.value.get("contact") {
return Some(
val.into_iter()
.map(|e| ContactDetail {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// These resources do not have an independent existence apart from the resource that
/// contains them - they cannot be identified independently, nor can they have their
/// own independent transaction scope.
pub fn contained(&self) -> Option<Vec<ResourceList>> {
if let Some(Value::Array(val)) = self.value.get("contained") {
return Some(
val.into_iter()
.map(|e| ResourceList {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// A copyright statement relating to the implementation guide and/or its contents.
/// Copyright statements are generally legal restrictions on the use and publishing of
/// the implementation guide.
pub fn copyright(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("copyright") {
return Some(string);
}
return None;
}
/// The date (and optionally time) when the implementation guide was published.
/// The date must change when the business version changes and it must change if the
/// status code changes. In addition, it should change when the substantive content of
/// the implementation guide changes.
pub fn date(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("date") {
return Some(string);
}
return None;
}
/// The information needed by an IG publisher tool to publish the whole implementation
/// guide.
pub fn definition(&self) -> Option<ImplementationGuide_Definition> {
if let Some(val) = self.value.get("definition") {
return Some(ImplementationGuide_Definition {
value: Cow::Borrowed(val),
});
}
return None;
}
/// Another implementation guide that this implementation depends on. Typically, an
/// implementation guide uses value sets, profiles etc.defined in other implementation
/// guides.
pub fn depends_on(&self) -> Option<Vec<ImplementationGuide_DependsOn>> {
if let Some(Value::Array(val)) = self.value.get("dependsOn") {
return Some(
val.into_iter()
.map(|e| ImplementationGuide_DependsOn {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// A free text natural language description of the implementation guide from a
/// consumer's perspective.
pub fn description(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("description") {
return Some(string);
}
return None;
}
/// A Boolean value to indicate that this implementation guide is authored for testing
/// purposes (or education/evaluation/marketing) and is not intended to be used for
/// genuine usage.
pub fn experimental(&self) -> Option<bool> {
if let Some(val) = self.value.get("experimental") {
return Some(val.as_bool().unwrap());
}
return None;
}
/// May be used to represent additional information that is not part of the basic
/// definition of the resource. To make the use of extensions safe and manageable,
/// there is a strict set of governance applied to the definition and use of
/// extensions. Though any implementer can define an extension, there is a set of
/// requirements that SHALL be met as part of the definition of the extension.
pub fn extension(&self) -> Option<Vec<Extension>> {
if let Some(Value::Array(val)) = self.value.get("extension") {
return Some(
val.into_iter()
.map(|e| Extension {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The version(s) of the FHIR specification that this ImplementationGuide targets -
/// e.g. describes how to use. The value of this element is the formal version of the
/// specification, without the revision number, e.g. [publication].[major].[minor],
/// which is 5.0.0-snapshot1. for this version.
pub fn fhir_version(&self) -> Option<Vec<&str>> {
if let Some(Value::Array(val)) = self.value.get("fhirVersion") {
return Some(
val.into_iter()
.map(|e| e.as_str().unwrap())
.collect::<Vec<_>>(),
);
}
return None;
}
/// A set of profiles that all resources covered by this implementation guide must
/// conform to.
pub fn global(&self) -> Option<Vec<ImplementationGuide_Global>> {
if let Some(Value::Array(val)) = self.value.get("global") {
return Some(
val.into_iter()
.map(|e| ImplementationGuide_Global {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The logical id of the resource, as used in the URL for the resource. Once
/// assigned, this value never changes.
pub fn id(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("id") {
return Some(string);
}
return None;
}
/// A formal identifier that is used to identify this {{title}} when it is represented
/// in other formats, or referenced in a specification, model, design or an instance.
pub fn identifier(&self) -> Option<Vec<Identifier>> {
if let Some(Value::Array(val)) = self.value.get("identifier") {
return Some(
val.into_iter()
.map(|e| Identifier {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// A reference to a set of rules that were followed when the resource was
/// constructed, and which must be understood when processing the content. Often, this
/// is a reference to an implementation guide that defines the special rules along
/// with other profiles etc.
pub fn implicit_rules(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("implicitRules") {
return Some(string);
}
return None;
}
/// A legal or geographic region in which the implementation guide is intended to
/// be used.
pub fn jurisdiction(&self) -> Option<Vec<CodeableConcept>> {
if let Some(Value::Array(val)) = self.value.get("jurisdiction") {
return Some(
val.into_iter()
.map(|e| CodeableConcept {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The base language in which the resource is written.
pub fn language(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("language") {
return Some(string);
}
return None;
}
/// The license that applies to this Implementation Guide, using an SPDX license code,
/// or 'not-open-source'.
pub fn license(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("license") {
return Some(string);
}
return None;
}
/// Information about an assembled implementation guide, created by the publication
/// tooling.
pub fn manifest(&self) -> Option<ImplementationGuide_Manifest> {
if let Some(val) = self.value.get("manifest") {
return Some(ImplementationGuide_Manifest {
value: Cow::Borrowed(val),
});
}
return None;
}
/// The metadata about the resource. This is content that is maintained by the
/// infrastructure. Changes to the content might not always be associated with version
/// changes to the resource.
pub fn meta(&self) -> Option<Meta> {
if let Some(val) = self.value.get("meta") {
return Some(Meta {
value: Cow::Borrowed(val),
});
}
return None;
}
/// May be used to represent additional information that is not part of the basic
/// definition of the resource and that modifies the understanding of the element
/// that contains it and/or the understanding of the containing element's descendants.
/// Usually modifier elements provide negation or qualification. To make the use of
/// extensions safe and manageable, there is a strict set of governance applied to
/// the definition and use of extensions. Though any implementer is allowed to define
/// an extension, there is a set of requirements that SHALL be met as part of the
/// definition of the extension. Applications processing a resource are required to
/// check for modifier extensions. Modifier extensions SHALL NOT change the meaning
/// of any elements on Resource or DomainResource (including cannot change the meaning
/// of modifierExtension itself).
pub fn modifier_extension(&self) -> Option<Vec<Extension>> {
if let Some(Value::Array(val)) = self.value.get("modifierExtension") {
return Some(
val.into_iter()
.map(|e| Extension {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// A natural language name identifying the implementation guide. This name should be
/// usable as an identifier for the module by machine processing applications such as
/// code generation.
pub fn name(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("name") {
return Some(string);
}
return None;
}
/// The NPM package name for this Implementation Guide, used in the NPM package
/// distribution, which is the primary mechanism by which FHIR based tooling manages
/// IG dependencies. This value must be globally unique, and should be assigned with
/// care.
pub fn package_id(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("packageId") {
return Some(string);
}
return None;
}
/// The name of the organization or individual that published the implementation
/// guide.
pub fn publisher(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("publisher") {
return Some(string);
}
return None;
}
/// Explanation of why this {{title}} is needed and why it has been designed as it
/// has.
pub fn purpose(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("purpose") {
return Some(string);
}
return None;
}
/// The status of this implementation guide. Enables tracking the life-cycle of the
/// content.
pub fn status(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("status") {
return Some(string);
}
return None;
}
/// A human-readable narrative that contains a summary of the resource and can be used
/// to represent the content of the resource to a human. The narrative need not encode
/// all the structured data, but is required to contain sufficient detail to make it
/// "clinically safe" for a human to just read the narrative. Resource definitions
/// may define what content should be represented in the narrative to ensure clinical
/// safety.
pub fn text(&self) -> Option<Narrative> {
if let Some(val) = self.value.get("text") {
return Some(Narrative {
value: Cow::Borrowed(val),
});
}
return None;
}
/// A short, descriptive, user-friendly title for the implementation guide.
pub fn title(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("title") {
return Some(string);
}
return None;
}
/// An absolute URI that is used to identify this implementation guide when it is
/// referenced in a specification, model, design or an instance; also called its
/// canonical identifier. This SHOULD be globally unique and SHOULD be a literal
/// address at which at which an authoritative instance of this implementation guide
/// is (or will be) published. This URL can be the target of a canonical reference.
/// It SHALL remain the same when the implementation guide is stored on different
/// servers.
pub fn url(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("url") {
return Some(string);
}
return None;
}
/// The content was developed with a focus and intent of supporting the contexts that
/// are listed. These contexts may be general categories (gender, age, ...) or may be
/// references to specific programs (insurance plans, studies, ...) and may be used to
/// assist with indexing and searching for appropriate implementation guide instances.
pub fn use_context(&self) -> Option<Vec<UsageContext>> {
if let Some(Value::Array(val)) = self.value.get("useContext") {
return Some(
val.into_iter()
.map(|e| UsageContext {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// The identifier that is used to identify this version of the implementation guide
/// when it is referenced in a specification, model, design or instance. This is an
/// arbitrary value managed by the implementation guide author and is not expected
/// to be globally unique. For example, it might be a timestamp (e.g. yyyymmdd) if a
/// managed version is not available. There is also no expectation that versions can
/// be placed in a lexicographical sequence.
pub fn version(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("version") {
return Some(string);
}
return None;
}
pub fn validate(&self) -> bool {
if let Some(_val) = self._copyright() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._date() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._description() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._experimental() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._fhir_version() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self._implicit_rules() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._language() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._license() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._name() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._package_id() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._publisher() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._purpose() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._status() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._title() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._url() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self._version() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.contact() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.contained() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.copyright() {}
if let Some(_val) = self.date() {}
if let Some(_val) = self.definition() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.depends_on() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.description() {}
if let Some(_val) = self.experimental() {}
if let Some(_val) = self.extension() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.fhir_version() {
_val.into_iter().for_each(|_e| {});
}
if let Some(_val) = self.global() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.id() {}
if let Some(_val) = self.identifier() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.implicit_rules() {}
if let Some(_val) = self.jurisdiction() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.language() {}
if let Some(_val) = self.license() {}
if let Some(_val) = self.manifest() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.meta() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.modifier_extension() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.name() {}
if let Some(_val) = self.package_id() {}
if let Some(_val) = self.publisher() {}
if let Some(_val) = self.purpose() {}
if let Some(_val) = self.status() {}
if let Some(_val) = self.text() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.title() {}
if let Some(_val) = self.url() {}
if let Some(_val) = self.use_context() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.version() {}
return true;
}
}
#[derive(Debug)]
pub struct ImplementationGuideBuilder {
pub(crate) value: Value,
}
impl ImplementationGuideBuilder {
pub fn build(&self) -> ImplementationGuide {
ImplementationGuide {
value: Cow::Owned(self.value.clone()),
}
}
pub fn with(existing: ImplementationGuide) -> ImplementationGuideBuilder {
ImplementationGuideBuilder {
value: (*existing.value).clone(),
}
}
pub fn new() -> ImplementationGuideBuilder {
let mut __value: Value = json!({});
return ImplementationGuideBuilder { value: __value };
}
pub fn _copyright<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_copyright"] = json!(val.value);
return self;
}
pub fn _date<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_date"] = json!(val.value);
return self;
}
pub fn _description<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_description"] = json!(val.value);
return self;
}
pub fn _experimental<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_experimental"] = json!(val.value);
return self;
}
pub fn _fhir_version<'a>(
&'a mut self,
val: Vec<Element>,
) -> &'a mut ImplementationGuideBuilder {
self.value["_fhirVersion"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn _implicit_rules<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_implicitRules"] = json!(val.value);
return self;
}
pub fn _language<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_language"] = json!(val.value);
return self;
}
pub fn _license<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_license"] = json!(val.value);
return self;
}
pub fn _name<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_name"] = json!(val.value);
return self;
}
pub fn _package_id<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_packageId"] = json!(val.value);
return self;
}
pub fn _publisher<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_publisher"] = json!(val.value);
return self;
}
pub fn _purpose<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_purpose"] = json!(val.value);
return self;
}
pub fn _status<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_status"] = json!(val.value);
return self;
}
pub fn _title<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_title"] = json!(val.value);
return self;
}
pub fn _url<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_url"] = json!(val.value);
return self;
}
pub fn _version<'a>(&'a mut self, val: Element) -> &'a mut ImplementationGuideBuilder {
self.value["_version"] = json!(val.value);
return self;
}
pub fn contact<'a>(
&'a mut self,
val: Vec<ContactDetail>,
) -> &'a mut ImplementationGuideBuilder {
self.value["contact"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn contained<'a>(
&'a mut self,
val: Vec<ResourceList>,
) -> &'a mut ImplementationGuideBuilder {
self.value["contained"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn copyright<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["copyright"] = json!(val);
return self;
}
pub fn date<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["date"] = json!(val);
return self;
}
pub fn definition<'a>(
&'a mut self,
val: ImplementationGuide_Definition,
) -> &'a mut ImplementationGuideBuilder {
self.value["definition"] = json!(val.value);
return self;
}
pub fn depends_on<'a>(
&'a mut self,
val: Vec<ImplementationGuide_DependsOn>,
) -> &'a mut ImplementationGuideBuilder {
self.value["dependsOn"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn description<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["description"] = json!(val);
return self;
}
pub fn experimental<'a>(&'a mut self, val: bool) -> &'a mut ImplementationGuideBuilder {
self.value["experimental"] = json!(val);
return self;
}
pub fn extension<'a>(&'a mut self, val: Vec<Extension>) -> &'a mut ImplementationGuideBuilder {
self.value["extension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn fhir_version<'a>(&'a mut self, val: Vec<&str>) -> &'a mut ImplementationGuideBuilder {
self.value["fhirVersion"] = json!(val);
return self;
}
pub fn global<'a>(
&'a mut self,
val: Vec<ImplementationGuide_Global>,
) -> &'a mut ImplementationGuideBuilder {
self.value["global"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn id<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["id"] = json!(val);
return self;
}
pub fn identifier<'a>(
&'a mut self,
val: Vec<Identifier>,
) -> &'a mut ImplementationGuideBuilder {
self.value["identifier"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn implicit_rules<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["implicitRules"] = json!(val);
return self;
}
pub fn jurisdiction<'a>(
&'a mut self,
val: Vec<CodeableConcept>,
) -> &'a mut ImplementationGuideBuilder {
self.value["jurisdiction"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn language<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["language"] = json!(val);
return self;
}
pub fn license<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["license"] = json!(val);
return self;
}
pub fn manifest<'a>(
&'a mut self,
val: ImplementationGuide_Manifest,
) -> &'a mut ImplementationGuideBuilder {
self.value["manifest"] = json!(val.value);
return self;
}
pub fn meta<'a>(&'a mut self, val: Meta) -> &'a mut ImplementationGuideBuilder {
self.value["meta"] = json!(val.value);
return self;
}
pub fn modifier_extension<'a>(
&'a mut self,
val: Vec<Extension>,
) -> &'a mut ImplementationGuideBuilder {
self.value["modifierExtension"] =
json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn name<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["name"] = json!(val);
return self;
}
pub fn package_id<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["packageId"] = json!(val);
return self;
}
pub fn publisher<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["publisher"] = json!(val);
return self;
}
pub fn purpose<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["purpose"] = json!(val);
return self;
}
pub fn status<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["status"] = json!(val);
return self;
}
pub fn text<'a>(&'a mut self, val: Narrative) -> &'a mut ImplementationGuideBuilder {
self.value["text"] = json!(val.value);
return self;
}
pub fn title<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["title"] = json!(val);
return self;
}
pub fn url<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["url"] = json!(val);
return self;
}
pub fn use_context<'a>(
&'a mut self,
val: Vec<UsageContext>,
) -> &'a mut ImplementationGuideBuilder {
self.value["useContext"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn version<'a>(&'a mut self, val: &str) -> &'a mut ImplementationGuideBuilder {
self.value["version"] = json!(val);
return self;
}
}
| 34.4 | 99 | 0.551511 |
ac88425a08694b4106784b0e997fe9e55be3230b | 3,476 | /*
* Copyright (C) 2018 Kubos Corporation
*
* 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::*;
use serde_derive::{Deserialize, Serialize};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use toml;
/// The high level metadata of an application derived from the `manifest.toml` file during
/// registration
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AppMetadata {
/// A unique name for the application
pub name: String,
/// Optional. The path of the file which should be called to kick off execution.
/// If not specified, ``name`` will be used.
pub executable: Option<String>,
/// The version of this application
pub version: String,
/// The author of the application
pub author: String,
/// The custom configuration file which should be passed to the application when it is started
pub config: Option<String>,
}
/// Kubos App struct
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct App {
/// The name of the application
pub name: String,
/// The absolute path to the application executable
pub executable: String,
/// The version of this instance of the application
pub version: String,
/// The author of the application
pub author: String,
/// Configuration file to be passed to the application
pub config: String,
}
/// AppRegistryEntry
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct AppRegistryEntry {
/// Whether or not this application is the active installation
pub active_version: bool,
/// The app itself
pub app: App,
}
impl AppRegistryEntry {
// Fetch a registered apps entry information
pub fn from_dir(dir: &PathBuf) -> Result<AppRegistryEntry, AppError> {
let mut app_toml = dir.clone();
app_toml.push("app.toml");
if !app_toml.exists() {
return Err(AppError::FileError {
err: "No app.toml file found".to_owned(),
});
}
let app_entry = fs::read_to_string(app_toml)?;
match toml::from_str::<AppRegistryEntry>(&app_entry) {
Ok(entry) => Ok(entry),
Err(error) => Err(AppError::ParseError {
entity: "app.toml".to_owned(),
err: error.to_string(),
}),
}
}
// Create or update a registered apps entry information
pub fn save(&self) -> Result<(), AppError> {
let mut app_toml = PathBuf::from(self.app.executable.clone());
app_toml.set_file_name("app.toml");
let mut file = fs::File::create(app_toml)?;
let toml_str = match toml::to_string(&self) {
Ok(toml) => toml,
Err(error) => {
return Err(AppError::ParseError {
entity: "app entry".to_owned(),
err: error.to_string(),
});
}
};
file.write_all(&toml_str.into_bytes())?;
Ok(())
}
}
| 33.104762 | 98 | 0.633199 |
5d8ed9eb4eae599260b893a7847f4c79fe321070 | 75,788 | #![allow(unused_extern_crates)]
extern crate serde_ignored;
extern crate tokio_core;
extern crate native_tls;
extern crate hyper_tls;
extern crate openssl;
extern crate mime;
extern crate chrono;
extern crate percent_encoding;
extern crate url;
use std::sync::Arc;
use std::marker::PhantomData;
use futures::{Future, future, Stream, stream};
use hyper;
use hyper::{Request, Response, Error, StatusCode};
use hyper::header::{Headers, ContentType};
use self::url::form_urlencoded;
use mimetypes;
use serde_json;
#[allow(unused_imports)]
use std::collections::{HashMap, BTreeMap};
#[allow(unused_imports)]
use swagger;
use std::io;
#[allow(unused_imports)]
use std::collections::BTreeSet;
pub use swagger::auth::Authorization;
use swagger::{ApiError, XSpanId, XSpanIdString, Has, RequestParser};
use swagger::auth::Scopes;
use swagger::headers::SafeHeaders;
use {Api,
Op10GetResponse,
Op11GetResponse,
Op12GetResponse,
Op13GetResponse,
Op14GetResponse,
Op15GetResponse,
Op16GetResponse,
Op17GetResponse,
Op18GetResponse,
Op19GetResponse,
Op1GetResponse,
Op20GetResponse,
Op21GetResponse,
Op22GetResponse,
Op23GetResponse,
Op24GetResponse,
Op25GetResponse,
Op26GetResponse,
Op27GetResponse,
Op28GetResponse,
Op29GetResponse,
Op2GetResponse,
Op30GetResponse,
Op31GetResponse,
Op32GetResponse,
Op33GetResponse,
Op34GetResponse,
Op35GetResponse,
Op36GetResponse,
Op37GetResponse,
Op3GetResponse,
Op4GetResponse,
Op5GetResponse,
Op6GetResponse,
Op7GetResponse,
Op8GetResponse,
Op9GetResponse
};
#[allow(unused_imports)]
use models;
pub mod context;
header! { (Warning, "Warning") => [String] }
mod paths {
extern crate regex;
lazy_static! {
pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(vec![
r"^/op1$",
r"^/op10$",
r"^/op11$",
r"^/op12$",
r"^/op13$",
r"^/op14$",
r"^/op15$",
r"^/op16$",
r"^/op17$",
r"^/op18$",
r"^/op19$",
r"^/op2$",
r"^/op20$",
r"^/op21$",
r"^/op22$",
r"^/op23$",
r"^/op24$",
r"^/op25$",
r"^/op26$",
r"^/op27$",
r"^/op28$",
r"^/op29$",
r"^/op3$",
r"^/op30$",
r"^/op31$",
r"^/op32$",
r"^/op33$",
r"^/op34$",
r"^/op35$",
r"^/op36$",
r"^/op37$",
r"^/op4$",
r"^/op5$",
r"^/op6$",
r"^/op7$",
r"^/op8$",
r"^/op9$"
]).unwrap();
}
pub static ID_OP1: usize = 0;
pub static ID_OP10: usize = 1;
pub static ID_OP11: usize = 2;
pub static ID_OP12: usize = 3;
pub static ID_OP13: usize = 4;
pub static ID_OP14: usize = 5;
pub static ID_OP15: usize = 6;
pub static ID_OP16: usize = 7;
pub static ID_OP17: usize = 8;
pub static ID_OP18: usize = 9;
pub static ID_OP19: usize = 10;
pub static ID_OP2: usize = 11;
pub static ID_OP20: usize = 12;
pub static ID_OP21: usize = 13;
pub static ID_OP22: usize = 14;
pub static ID_OP23: usize = 15;
pub static ID_OP24: usize = 16;
pub static ID_OP25: usize = 17;
pub static ID_OP26: usize = 18;
pub static ID_OP27: usize = 19;
pub static ID_OP28: usize = 20;
pub static ID_OP29: usize = 21;
pub static ID_OP3: usize = 22;
pub static ID_OP30: usize = 23;
pub static ID_OP31: usize = 24;
pub static ID_OP32: usize = 25;
pub static ID_OP33: usize = 26;
pub static ID_OP34: usize = 27;
pub static ID_OP35: usize = 28;
pub static ID_OP36: usize = 29;
pub static ID_OP37: usize = 30;
pub static ID_OP4: usize = 31;
pub static ID_OP5: usize = 32;
pub static ID_OP6: usize = 33;
pub static ID_OP7: usize = 34;
pub static ID_OP8: usize = 35;
pub static ID_OP9: usize = 36;
}
pub struct NewService<T, C> {
api_impl: Arc<T>,
marker: PhantomData<C>,
}
impl<T, C> NewService<T, C>
where
T: Api<C> + Clone + 'static,
C: Has<XSpanIdString> + 'static
{
pub fn new<U: Into<Arc<T>>>(api_impl: U) -> NewService<T, C> {
NewService{api_impl: api_impl.into(), marker: PhantomData}
}
}
impl<T, C> hyper::server::NewService for NewService<T, C>
where
T: Api<C> + Clone + 'static,
C: Has<XSpanIdString> + 'static
{
type Request = (Request, C);
type Response = Response;
type Error = Error;
type Instance = Service<T, C>;
fn new_service(&self) -> Result<Self::Instance, io::Error> {
Ok(Service::new(self.api_impl.clone()))
}
}
pub struct Service<T, C> {
api_impl: Arc<T>,
marker: PhantomData<C>,
}
impl<T, C> Service<T, C>
where
T: Api<C> + Clone + 'static,
C: Has<XSpanIdString> + 'static {
pub fn new<U: Into<Arc<T>>>(api_impl: U) -> Service<T, C> {
Service{api_impl: api_impl.into(), marker: PhantomData}
}
}
impl<T, C> hyper::server::Service for Service<T, C>
where
T: Api<C> + Clone + 'static,
C: Has<XSpanIdString> + 'static
{
type Request = (Request, C);
type Response = Response;
type Error = Error;
type Future = Box<dyn Future<Item=Response, Error=Error>>;
fn call(&self, (req, mut context): Self::Request) -> Self::Future {
let api_impl = self.api_impl.clone();
let (method, uri, _, headers, body) = req.deconstruct();
let path = paths::GLOBAL_REGEX_SET.matches(uri.path());
// This match statement is duplicated below in `parse_operation_id()`.
// Please update both places if changing how this code is autogenerated.
match &method {
// Op10Get - GET /op10
&hyper::Method::Get if path.matched(paths::ID_OP10) => {
Box::new({
{{
Box::new(api_impl.op10_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op10GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op11Get - GET /op11
&hyper::Method::Get if path.matched(paths::ID_OP11) => {
Box::new({
{{
Box::new(api_impl.op11_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op11GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op12Get - GET /op12
&hyper::Method::Get if path.matched(paths::ID_OP12) => {
Box::new({
{{
Box::new(api_impl.op12_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op12GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op13Get - GET /op13
&hyper::Method::Get if path.matched(paths::ID_OP13) => {
Box::new({
{{
Box::new(api_impl.op13_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op13GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op14Get - GET /op14
&hyper::Method::Get if path.matched(paths::ID_OP14) => {
Box::new({
{{
Box::new(api_impl.op14_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op14GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op15Get - GET /op15
&hyper::Method::Get if path.matched(paths::ID_OP15) => {
Box::new({
{{
Box::new(api_impl.op15_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op15GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op16Get - GET /op16
&hyper::Method::Get if path.matched(paths::ID_OP16) => {
Box::new({
{{
Box::new(api_impl.op16_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op16GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op17Get - GET /op17
&hyper::Method::Get if path.matched(paths::ID_OP17) => {
Box::new({
{{
Box::new(api_impl.op17_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op17GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op18Get - GET /op18
&hyper::Method::Get if path.matched(paths::ID_OP18) => {
Box::new({
{{
Box::new(api_impl.op18_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op18GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op19Get - GET /op19
&hyper::Method::Get if path.matched(paths::ID_OP19) => {
Box::new({
{{
Box::new(api_impl.op19_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op19GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op1Get - GET /op1
&hyper::Method::Get if path.matched(paths::ID_OP1) => {
Box::new({
{{
Box::new(api_impl.op1_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op1GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op20Get - GET /op20
&hyper::Method::Get if path.matched(paths::ID_OP20) => {
Box::new({
{{
Box::new(api_impl.op20_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op20GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op21Get - GET /op21
&hyper::Method::Get if path.matched(paths::ID_OP21) => {
Box::new({
{{
Box::new(api_impl.op21_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op21GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op22Get - GET /op22
&hyper::Method::Get if path.matched(paths::ID_OP22) => {
Box::new({
{{
Box::new(api_impl.op22_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op22GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op23Get - GET /op23
&hyper::Method::Get if path.matched(paths::ID_OP23) => {
Box::new({
{{
Box::new(api_impl.op23_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op23GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op24Get - GET /op24
&hyper::Method::Get if path.matched(paths::ID_OP24) => {
Box::new({
{{
Box::new(api_impl.op24_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op24GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op25Get - GET /op25
&hyper::Method::Get if path.matched(paths::ID_OP25) => {
Box::new({
{{
Box::new(api_impl.op25_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op25GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op26Get - GET /op26
&hyper::Method::Get if path.matched(paths::ID_OP26) => {
Box::new({
{{
Box::new(api_impl.op26_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op26GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op27Get - GET /op27
&hyper::Method::Get if path.matched(paths::ID_OP27) => {
Box::new({
{{
Box::new(api_impl.op27_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op27GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op28Get - GET /op28
&hyper::Method::Get if path.matched(paths::ID_OP28) => {
Box::new({
{{
Box::new(api_impl.op28_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op28GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op29Get - GET /op29
&hyper::Method::Get if path.matched(paths::ID_OP29) => {
Box::new({
{{
Box::new(api_impl.op29_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op29GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op2Get - GET /op2
&hyper::Method::Get if path.matched(paths::ID_OP2) => {
Box::new({
{{
Box::new(api_impl.op2_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op2GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op30Get - GET /op30
&hyper::Method::Get if path.matched(paths::ID_OP30) => {
Box::new({
{{
Box::new(api_impl.op30_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op30GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op31Get - GET /op31
&hyper::Method::Get if path.matched(paths::ID_OP31) => {
Box::new({
{{
Box::new(api_impl.op31_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op31GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op32Get - GET /op32
&hyper::Method::Get if path.matched(paths::ID_OP32) => {
Box::new({
{{
Box::new(api_impl.op32_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op32GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op33Get - GET /op33
&hyper::Method::Get if path.matched(paths::ID_OP33) => {
Box::new({
{{
Box::new(api_impl.op33_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op33GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op34Get - GET /op34
&hyper::Method::Get if path.matched(paths::ID_OP34) => {
Box::new({
{{
Box::new(api_impl.op34_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op34GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op35Get - GET /op35
&hyper::Method::Get if path.matched(paths::ID_OP35) => {
Box::new({
{{
Box::new(api_impl.op35_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op35GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op36Get - GET /op36
&hyper::Method::Get if path.matched(paths::ID_OP36) => {
Box::new({
{{
Box::new(api_impl.op36_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op36GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op37Get - GET /op37
&hyper::Method::Get if path.matched(paths::ID_OP37) => {
Box::new({
{{
Box::new(api_impl.op37_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op37GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op3Get - GET /op3
&hyper::Method::Get if path.matched(paths::ID_OP3) => {
Box::new({
{{
Box::new(api_impl.op3_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op3GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op4Get - GET /op4
&hyper::Method::Get if path.matched(paths::ID_OP4) => {
Box::new({
{{
Box::new(api_impl.op4_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op4GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op5Get - GET /op5
&hyper::Method::Get if path.matched(paths::ID_OP5) => {
Box::new({
{{
Box::new(api_impl.op5_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op5GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op6Get - GET /op6
&hyper::Method::Get if path.matched(paths::ID_OP6) => {
Box::new({
{{
Box::new(api_impl.op6_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op6GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op7Get - GET /op7
&hyper::Method::Get if path.matched(paths::ID_OP7) => {
Box::new({
{{
Box::new(api_impl.op7_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op7GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op8Get - GET /op8
&hyper::Method::Get if path.matched(paths::ID_OP8) => {
Box::new({
{{
Box::new(api_impl.op8_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op8GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
// Op9Get - GET /op9
&hyper::Method::Get if path.matched(paths::ID_OP9) => {
Box::new({
{{
Box::new(api_impl.op9_get(&context)
.then(move |result| {
let mut response = Response::new();
response.headers_mut().set(XSpanId((&context as &dyn Has<XSpanIdString>).get().0.to_string()));
match result {
Ok(rsp) => match rsp {
Op9GetResponse::OK
=> {
response.set_status(StatusCode::try_from(200).unwrap());
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.set_status(StatusCode::InternalServerError);
response.set_body("An internal error occurred");
},
}
future::ok(response)
}
))
}}
}) as Box<dyn Future<Item=Response, Error=Error>>
},
_ => Box::new(future::ok(Response::new().with_status(StatusCode::NotFound))) as Box<dyn Future<Item=Response, Error=Error>>,
}
}
}
impl<T, C> Clone for Service<T, C>
{
fn clone(&self) -> Self {
Service {
api_impl: self.api_impl.clone(),
marker: self.marker.clone(),
}
}
}
/// Request parser for `Api`.
pub struct ApiRequestParser;
impl RequestParser for ApiRequestParser {
fn parse_operation_id(request: &Request) -> Result<&'static str, ()> {
let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path());
match request.method() {
// Op10Get - GET /op10
&hyper::Method::Get if path.matched(paths::ID_OP10) => Ok("Op10Get"),
// Op11Get - GET /op11
&hyper::Method::Get if path.matched(paths::ID_OP11) => Ok("Op11Get"),
// Op12Get - GET /op12
&hyper::Method::Get if path.matched(paths::ID_OP12) => Ok("Op12Get"),
// Op13Get - GET /op13
&hyper::Method::Get if path.matched(paths::ID_OP13) => Ok("Op13Get"),
// Op14Get - GET /op14
&hyper::Method::Get if path.matched(paths::ID_OP14) => Ok("Op14Get"),
// Op15Get - GET /op15
&hyper::Method::Get if path.matched(paths::ID_OP15) => Ok("Op15Get"),
// Op16Get - GET /op16
&hyper::Method::Get if path.matched(paths::ID_OP16) => Ok("Op16Get"),
// Op17Get - GET /op17
&hyper::Method::Get if path.matched(paths::ID_OP17) => Ok("Op17Get"),
// Op18Get - GET /op18
&hyper::Method::Get if path.matched(paths::ID_OP18) => Ok("Op18Get"),
// Op19Get - GET /op19
&hyper::Method::Get if path.matched(paths::ID_OP19) => Ok("Op19Get"),
// Op1Get - GET /op1
&hyper::Method::Get if path.matched(paths::ID_OP1) => Ok("Op1Get"),
// Op20Get - GET /op20
&hyper::Method::Get if path.matched(paths::ID_OP20) => Ok("Op20Get"),
// Op21Get - GET /op21
&hyper::Method::Get if path.matched(paths::ID_OP21) => Ok("Op21Get"),
// Op22Get - GET /op22
&hyper::Method::Get if path.matched(paths::ID_OP22) => Ok("Op22Get"),
// Op23Get - GET /op23
&hyper::Method::Get if path.matched(paths::ID_OP23) => Ok("Op23Get"),
// Op24Get - GET /op24
&hyper::Method::Get if path.matched(paths::ID_OP24) => Ok("Op24Get"),
// Op25Get - GET /op25
&hyper::Method::Get if path.matched(paths::ID_OP25) => Ok("Op25Get"),
// Op26Get - GET /op26
&hyper::Method::Get if path.matched(paths::ID_OP26) => Ok("Op26Get"),
// Op27Get - GET /op27
&hyper::Method::Get if path.matched(paths::ID_OP27) => Ok("Op27Get"),
// Op28Get - GET /op28
&hyper::Method::Get if path.matched(paths::ID_OP28) => Ok("Op28Get"),
// Op29Get - GET /op29
&hyper::Method::Get if path.matched(paths::ID_OP29) => Ok("Op29Get"),
// Op2Get - GET /op2
&hyper::Method::Get if path.matched(paths::ID_OP2) => Ok("Op2Get"),
// Op30Get - GET /op30
&hyper::Method::Get if path.matched(paths::ID_OP30) => Ok("Op30Get"),
// Op31Get - GET /op31
&hyper::Method::Get if path.matched(paths::ID_OP31) => Ok("Op31Get"),
// Op32Get - GET /op32
&hyper::Method::Get if path.matched(paths::ID_OP32) => Ok("Op32Get"),
// Op33Get - GET /op33
&hyper::Method::Get if path.matched(paths::ID_OP33) => Ok("Op33Get"),
// Op34Get - GET /op34
&hyper::Method::Get if path.matched(paths::ID_OP34) => Ok("Op34Get"),
// Op35Get - GET /op35
&hyper::Method::Get if path.matched(paths::ID_OP35) => Ok("Op35Get"),
// Op36Get - GET /op36
&hyper::Method::Get if path.matched(paths::ID_OP36) => Ok("Op36Get"),
// Op37Get - GET /op37
&hyper::Method::Get if path.matched(paths::ID_OP37) => Ok("Op37Get"),
// Op3Get - GET /op3
&hyper::Method::Get if path.matched(paths::ID_OP3) => Ok("Op3Get"),
// Op4Get - GET /op4
&hyper::Method::Get if path.matched(paths::ID_OP4) => Ok("Op4Get"),
// Op5Get - GET /op5
&hyper::Method::Get if path.matched(paths::ID_OP5) => Ok("Op5Get"),
// Op6Get - GET /op6
&hyper::Method::Get if path.matched(paths::ID_OP6) => Ok("Op6Get"),
// Op7Get - GET /op7
&hyper::Method::Get if path.matched(paths::ID_OP7) => Ok("Op7Get"),
// Op8Get - GET /op8
&hyper::Method::Get if path.matched(paths::ID_OP8) => Ok("Op8Get"),
// Op9Get - GET /op9
&hyper::Method::Get if path.matched(paths::ID_OP9) => Ok("Op9Get"),
_ => Err(()),
}
}
}
| 46.696242 | 139 | 0.333272 |
6a6d6f90b2e69acab3553106cd1959620dcd7118 | 1,391 | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -C no-prepopulate-passes
#![crate_type = "lib"]
#![feature(core_intrinsics)]
use std::intrinsics::{fadd_fast, fsub_fast, fmul_fast, fdiv_fast, frem_fast};
// CHECK-LABEL: @add
#[no_mangle]
pub fn add(x: f32, y: f32) -> f32 {
// CHECK: fadd float
// CHECK-NOT: fast
x + y
}
// CHECK-LABEL: @addition
#[no_mangle]
pub fn addition(x: f32, y: f32) -> f32 {
// CHECK: fadd fast float
unsafe {
fadd_fast(x, y)
}
}
// CHECK-LABEL: @subtraction
#[no_mangle]
pub fn subtraction(x: f32, y: f32) -> f32 {
// CHECK: fsub fast float
unsafe {
fsub_fast(x, y)
}
}
// CHECK-LABEL: @multiplication
#[no_mangle]
pub fn multiplication(x: f32, y: f32) -> f32 {
// CHECK: fmul fast float
unsafe {
fmul_fast(x, y)
}
}
// CHECK-LABEL: @division
#[no_mangle]
pub fn division(x: f32, y: f32) -> f32 {
// CHECK: fdiv fast float
unsafe {
fdiv_fast(x, y)
}
}
| 22.803279 | 77 | 0.652049 |
f4a09bb70b8355dfe847b4c598d77709de3281f7 | 13,481 | extern crate env_logger;
extern crate fatfs;
extern crate fscommon;
use std::fs;
use std::io;
use std::io::prelude::*;
use std::mem;
use std::str;
use fatfs::FsOptions;
use fscommon::BufStream;
const FAT12_IMG: &str = "fat12.img";
const FAT16_IMG: &str = "fat16.img";
const FAT32_IMG: &str = "fat32.img";
const IMG_DIR: &str = "resources";
const TMP_DIR: &str = "tmp";
const TEST_STR: &str = "Hi there Rust programmer!\n";
const TEST_STR2: &str = "Rust is cool!\n";
type FileSystem = fatfs::FileSystem<BufStream<fs::File>>;
fn call_with_tmp_img(f: &Fn(&str) -> (), filename: &str, test_seq: u32) {
let _ = env_logger::try_init();
let img_path = format!("{}/{}", IMG_DIR, filename);
let tmp_path = format!("{}/{}-{}", TMP_DIR, test_seq, filename);
fs::create_dir(TMP_DIR).ok();
fs::copy(&img_path, &tmp_path).unwrap();
f(tmp_path.as_str());
fs::remove_file(tmp_path).unwrap();
}
fn open_filesystem_rw(tmp_path: &str) -> FileSystem {
let file = fs::OpenOptions::new().read(true).write(true).open(&tmp_path).unwrap();
let buf_file = BufStream::new(file);
let options = FsOptions::new().update_accessed_date(true);
FileSystem::new(buf_file, options).unwrap()
}
fn call_with_fs(f: &Fn(FileSystem) -> (), filename: &str, test_seq: u32) {
let callback = |tmp_path: &str| {
let fs = open_filesystem_rw(tmp_path);
f(fs);
};
call_with_tmp_img(&callback, filename, test_seq);
}
fn test_write_short_file(fs: FileSystem) {
let root_dir = fs.root_dir();
let mut file = root_dir.open_file("short.txt").expect("open file");
file.truncate().unwrap();
file.write_all(&TEST_STR.as_bytes()).unwrap();
file.seek(io::SeekFrom::Start(0)).unwrap();
let mut buf = Vec::new();
file.read_to_end(&mut buf).unwrap();
assert_eq!(TEST_STR, str::from_utf8(&buf).unwrap());
}
#[test]
fn test_write_file_fat12() {
call_with_fs(&test_write_short_file, FAT12_IMG, 1)
}
#[test]
fn test_write_file_fat16() {
call_with_fs(&test_write_short_file, FAT16_IMG, 1)
}
#[test]
fn test_write_file_fat32() {
call_with_fs(&test_write_short_file, FAT32_IMG, 1)
}
fn test_write_long_file(fs: FileSystem) {
let root_dir = fs.root_dir();
let mut file = root_dir.open_file("long.txt").expect("open file");
file.truncate().unwrap();
let test_str = TEST_STR.repeat(1000);
file.write_all(&test_str.as_bytes()).unwrap();
file.seek(io::SeekFrom::Start(0)).unwrap();
let mut buf = Vec::new();
file.read_to_end(&mut buf).unwrap();
assert_eq!(test_str, str::from_utf8(&buf).unwrap());
file.seek(io::SeekFrom::Start(1234)).unwrap();
file.truncate().unwrap();
file.seek(io::SeekFrom::Start(0)).unwrap();
buf.clear();
file.read_to_end(&mut buf).unwrap();
assert_eq!(&test_str[..1234], str::from_utf8(&buf).unwrap());
}
#[test]
fn test_write_long_file_fat12() {
call_with_fs(&test_write_long_file, FAT12_IMG, 2)
}
#[test]
fn test_write_long_file_fat16() {
call_with_fs(&test_write_long_file, FAT16_IMG, 2)
}
#[test]
fn test_write_long_file_fat32() {
call_with_fs(&test_write_long_file, FAT32_IMG, 2)
}
fn test_remove(fs: FileSystem) {
let root_dir = fs.root_dir();
assert!(root_dir.remove("very/long/path").is_err());
let dir = root_dir.open_dir("very/long/path").unwrap();
let mut names = dir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", "..", "test.txt"]);
root_dir.remove("very/long/path/test.txt").unwrap();
names = dir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", ".."]);
assert!(root_dir.remove("very/long/path").is_ok());
names = root_dir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, ["long.txt", "short.txt", "very", "very-long-dir-name"]);
root_dir.remove("long.txt").unwrap();
names = root_dir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, ["short.txt", "very", "very-long-dir-name"]);
}
#[test]
fn test_remove_fat12() {
call_with_fs(&test_remove, FAT12_IMG, 3)
}
#[test]
fn test_remove_fat16() {
call_with_fs(&test_remove, FAT16_IMG, 3)
}
#[test]
fn test_remove_fat32() {
call_with_fs(&test_remove, FAT32_IMG, 3)
}
fn test_create_file(fs: FileSystem) {
let root_dir = fs.root_dir();
let dir = root_dir.open_dir("very/long/path").unwrap();
let mut names = dir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", "..", "test.txt"]);
{
// test some invalid names
assert!(root_dir.create_file("very/long/path/:").is_err());
assert!(root_dir.create_file("very/long/path/\0").is_err());
// create file
let mut file = root_dir.create_file("very/long/path/new-file-with-long-name.txt").unwrap();
file.write_all(&TEST_STR.as_bytes()).unwrap();
}
// check for dir entry
names = dir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", "..", "test.txt", "new-file-with-long-name.txt"]);
names = dir.iter().map(|r| r.unwrap().short_file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", "..", "TEST.TXT", "NEW-FI~1.TXT"]);
{
// check contents
let mut file = root_dir.open_file("very/long/path/new-file-with-long-name.txt").unwrap();
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
assert_eq!(&content, &TEST_STR);
}
// Create enough entries to allocate next cluster
for i in 0..512 / 32 {
let name = format!("test{}", i);
dir.create_file(&name).unwrap();
}
names = dir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names.len(), 4 + 512 / 32);
// check creating existing file opens it
{
let mut file = root_dir.create_file("very/long/path/new-file-with-long-name.txt").unwrap();
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
assert_eq!(&content, &TEST_STR);
}
// check using create_file with existing directory fails
assert!(root_dir.create_file("very").is_err());
}
#[test]
fn test_create_file_fat12() {
call_with_fs(&test_create_file, FAT12_IMG, 4)
}
#[test]
fn test_create_file_fat16() {
call_with_fs(&test_create_file, FAT16_IMG, 4)
}
#[test]
fn test_create_file_fat32() {
call_with_fs(&test_create_file, FAT32_IMG, 4)
}
fn test_create_dir(fs: FileSystem) {
let root_dir = fs.root_dir();
let parent_dir = root_dir.open_dir("very/long/path").unwrap();
let mut names = parent_dir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", "..", "test.txt"]);
{
let subdir = root_dir.create_dir("very/long/path/new-dir-with-long-name").unwrap();
names = subdir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", ".."]);
}
// check if new entry is visible in parent
names = parent_dir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", "..", "test.txt", "new-dir-with-long-name"]);
{
// Check if new directory can be opened and read
let subdir = root_dir.open_dir("very/long/path/new-dir-with-long-name").unwrap();
names = subdir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", ".."]);
}
// Check if '.' is alias for new directory
{
let subdir = root_dir.open_dir("very/long/path/new-dir-with-long-name/.").unwrap();
names = subdir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", ".."]);
}
// Check if '..' is alias for parent directory
{
let subdir = root_dir.open_dir("very/long/path/new-dir-with-long-name/..").unwrap();
names = subdir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", "..", "test.txt", "new-dir-with-long-name"]);
}
// check if creating existing directory returns it
{
let subdir = root_dir.create_dir("very").unwrap();
names = subdir.iter().map(|r| r.unwrap().file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", "..", "long"]);
}
// check short names validity after create_dir
{
let subdir = root_dir.create_dir("test").unwrap();
names = subdir.iter().map(|r| r.unwrap().short_file_name()).collect::<Vec<String>>();
assert_eq!(names, [".", ".."]);
}
// check using create_dir with existing file fails
assert!(root_dir.create_dir("very/long/path/test.txt").is_err());
}
#[test]
fn test_create_dir_fat12() {
call_with_fs(&test_create_dir, FAT12_IMG, 5)
}
#[test]
fn test_create_dir_fat16() {
call_with_fs(&test_create_dir, FAT16_IMG, 5)
}
#[test]
fn test_create_dir_fat32() {
call_with_fs(&test_create_dir, FAT32_IMG, 5)
}
fn test_rename_file(fs: FileSystem) {
let root_dir = fs.root_dir();
let parent_dir = root_dir.open_dir("very/long/path").unwrap();
let entries = parent_dir.iter().map(|r| r.unwrap()).collect::<Vec<_>>();
let names = entries.iter().map(|r| r.file_name()).collect::<Vec<_>>();
assert_eq!(names, [".", "..", "test.txt"]);
assert_eq!(entries[2].len(), 14);
let stats = fs.stats().unwrap();
parent_dir.rename("test.txt", &parent_dir, "new-long-name.txt").unwrap();
let entries = parent_dir.iter().map(|r| r.unwrap()).collect::<Vec<_>>();
let names = entries.iter().map(|r| r.file_name()).collect::<Vec<_>>();
assert_eq!(names, [".", "..", "new-long-name.txt"]);
assert_eq!(entries[2].len(), TEST_STR2.len() as u64);
let mut file = parent_dir.open_file("new-long-name.txt").unwrap();
let mut buf = Vec::new();
file.read_to_end(&mut buf).unwrap();
assert_eq!(str::from_utf8(&buf).unwrap(), TEST_STR2);
parent_dir.rename("new-long-name.txt", &root_dir, "moved-file.txt").unwrap();
let entries = root_dir.iter().map(|r| r.unwrap()).collect::<Vec<_>>();
let names = entries.iter().map(|r| r.file_name()).collect::<Vec<_>>();
assert_eq!(names, ["long.txt", "short.txt", "very", "very-long-dir-name", "moved-file.txt"]);
assert_eq!(entries[4].len(), TEST_STR2.len() as u64);
let mut file = root_dir.open_file("moved-file.txt").unwrap();
let mut buf = Vec::new();
file.read_to_end(&mut buf).unwrap();
assert_eq!(str::from_utf8(&buf).unwrap(), TEST_STR2);
assert!(root_dir.rename("moved-file.txt", &root_dir, "short.txt").is_err());
let entries = root_dir.iter().map(|r| r.unwrap()).collect::<Vec<_>>();
let names = entries.iter().map(|r| r.file_name()).collect::<Vec<_>>();
assert_eq!(names, ["long.txt", "short.txt", "very", "very-long-dir-name", "moved-file.txt"]);
assert!(root_dir.rename("moved-file.txt", &root_dir, "moved-file.txt").is_ok());
let new_stats = fs.stats().unwrap();
assert_eq!(new_stats.free_clusters(), stats.free_clusters());
}
#[test]
fn test_rename_file_fat12() {
call_with_fs(&test_rename_file, FAT12_IMG, 6)
}
#[test]
fn test_rename_file_fat16() {
call_with_fs(&test_rename_file, FAT16_IMG, 6)
}
#[test]
fn test_rename_file_fat32() {
call_with_fs(&test_rename_file, FAT32_IMG, 6)
}
fn test_dirty_flag(tmp_path: &str) {
// Open filesystem, make change, and forget it - should become dirty
let fs = open_filesystem_rw(tmp_path);
let status_flags = fs.read_status_flags().unwrap();
assert_eq!(status_flags.dirty(), false);
assert_eq!(status_flags.io_error(), false);
fs.root_dir().create_file("abc.txt").unwrap();
mem::forget(fs);
// Check if volume is dirty now
let fs = open_filesystem_rw(tmp_path);
let status_flags = fs.read_status_flags().unwrap();
assert_eq!(status_flags.dirty(), true);
assert_eq!(status_flags.io_error(), false);
fs.unmount().unwrap();
// Make sure remounting does not clear the dirty flag
let fs = open_filesystem_rw(tmp_path);
let status_flags = fs.read_status_flags().unwrap();
assert_eq!(status_flags.dirty(), true);
assert_eq!(status_flags.io_error(), false);
}
#[test]
fn test_dirty_flag_fat12() {
call_with_tmp_img(&test_dirty_flag, FAT12_IMG, 7)
}
#[test]
fn test_dirty_flag_fat16() {
call_with_tmp_img(&test_dirty_flag, FAT16_IMG, 7)
}
#[test]
fn test_dirty_flag_fat32() {
call_with_tmp_img(&test_dirty_flag, FAT32_IMG, 7)
}
fn test_multiple_files_in_directory(fs: FileSystem) {
let dir = fs.root_dir().create_dir("/TMP").unwrap();
for i in 0..8 {
let name = format!("T{}.TXT", i);
let mut file = dir.create_file(&name).unwrap();
file.write_all(TEST_STR.as_bytes()).unwrap();
file.flush().unwrap();
let file = dir.iter()
.map(|r| r.unwrap())
.filter(|e| e.file_name() == name)
.next()
.unwrap();
assert_eq!(TEST_STR.len() as u64, file.len(), "Wrong file len on iteration {}", i);
}
}
#[test]
fn test_multiple_files_in_directory_fat12() {
call_with_fs(&test_multiple_files_in_directory, FAT12_IMG, 8)
}
#[test]
fn test_multiple_files_in_directory_fat16() {
call_with_fs(&test_multiple_files_in_directory, FAT16_IMG, 8)
}
#[test]
fn test_multiple_files_in_directory_fat32() {
call_with_fs(&test_multiple_files_in_directory, FAT32_IMG, 8)
}
| 35.015584 | 99 | 0.638528 |
183947c35b9225ceb56c66e300fc67762def5c53 | 15 | pub fn evaluate | 15 | 15 | 0.866667 |
9b36699bbf112e95f5bd969dfcab6228ee95d916 | 353 | #![feature(generic_const_exprs)]
#![allow(incomplete_features)]
trait Bar<T> {}
impl<T> Bar<T> for [u8; T] {}
//~^ ERROR expected value, found type parameter `T`
struct Foo<const N: usize> {}
impl<const N: usize> Foo<N>
where
[u8; N]: Bar<[(); N]>,
{
fn foo() {}
}
fn main() {
Foo::foo();
//~^ ERROR the function or associated item
}
| 17.65 | 51 | 0.597734 |
d6bbdb1eb7ec689250d9b0133a6eb89592380a83 | 1,262 | use crate::components::player::Player;
use crate::components::{Drawable, Enemy};
use crate::rect::Rect;
use crate::resources::GamePlay;
use specs::join::Join;
use specs::shred::ResourceId;
use specs::{ReadExpect, System};
use specs::{ReadStorage, SystemData};
use specs::{World, WriteStorage};
pub struct CollisionSystem;
#[derive(SystemData)]
pub struct CollisionSystemData<'a> {
game_play: ReadExpect<'a, GamePlay>,
enemies_storage: ReadStorage<'a, Enemy>,
players_storage: WriteStorage<'a, Player>,
drawables_storage: ReadStorage<'a, Drawable>,
}
impl<'a> System<'a> for CollisionSystem {
type SystemData = CollisionSystemData<'a>;
fn run(&mut self, mut data: Self::SystemData) {
if data.game_play.ticked() {
for (player_drawable, mut player) in
(&data.drawables_storage, &mut data.players_storage).join()
{
for (enemy_drawable, _) in (&data.drawables_storage, &data.enemies_storage).join() {
if Rect::intersects(&player_drawable.world_bounds, &enemy_drawable.world_bounds)
{
player.is_hit = true;
return;
}
}
}
}
}
}
| 30.780488 | 100 | 0.608558 |
48d43abce77214bba422d3b8c698d5741e8f6f2a | 18,988 | mod pp;
use crate::{serde_ext, Error, ErrorType};
pub use pp::*;
use serde_ext::ser;
use std::io::Write;
use std::result::Result;
use std::str;
use value_trait::generator::BaseGenerator;
macro_rules! iomap {
($e:expr) => {
($e).map_err(|err| Error::generic(ErrorType::Io(err)))
};
}
/// Write a value to a vector
/// # Errors
/// when the data can not be written
#[inline]
pub fn to_vec<T>(to: &T) -> crate::Result<Vec<u8>>
where
T: ser::Serialize + ?Sized,
{
let v = Vec::with_capacity(512);
let mut s = Serializer(v);
to.serialize(&mut s).map(|_| s.0)
}
/// Write a value to a string
///
/// # Errors
/// when the data can not be written
#[inline]
pub fn to_string<T>(to: &T) -> crate::Result<String>
where
T: ser::Serialize + ?Sized,
{
to_vec(to).map(|v| unsafe { String::from_utf8_unchecked(v) })
}
/// Write a value to a string
/// # Errors
/// when the data can not be written
#[inline]
pub fn to_writer<T, W>(writer: W, to: &T) -> crate::Result<()>
where
T: ser::Serialize + ?Sized,
W: Write,
{
let mut s = Serializer(writer);
to.serialize(&mut s)
}
struct Serializer<W: Write>(W);
impl<'writer, W> BaseGenerator for Serializer<W>
where
W: Write,
{
type T = W;
#[inline]
fn get_writer(&mut self) -> &mut Self::T {
&mut self.0
}
#[inline]
fn write_min(&mut self, _slice: &[u8], min: u8) -> std::io::Result<()> {
self.0.write_all(&[min])
}
}
struct SerializeSeq<'serializer, W: Write + 'serializer> {
s: &'serializer mut Serializer<W>,
first: bool,
}
impl<'serializer, W> ser::SerializeSeq for SerializeSeq<'serializer, W>
where
W: Write,
{
type Ok = ();
type Error = Error;
#[inline]
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: serde_ext::Serialize,
{
let SerializeSeq {
ref mut s,
ref mut first,
..
} = *self;
if *first {
*first = false;
value.serialize(&mut **s)
} else {
iomap!(s.write(b",")).and_then(|_| value.serialize(&mut **s))
}
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
if self.first {
Ok(())
} else {
iomap!(self.s.write(b"]"))
}
}
}
impl<'serializer, W> ser::SerializeTuple for SerializeSeq<'serializer, W>
where
W: Write,
{
type Ok = ();
type Error = Error;
#[inline]
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: serde_ext::Serialize,
{
let SerializeSeq {
ref mut s,
ref mut first,
} = *self;
if *first {
*first = false;
value.serialize(&mut **s)
} else {
iomap!(s.write(b",")).and_then(|_| value.serialize(&mut **s))
}
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
if self.first {
Ok(())
} else {
iomap!(self.s.write(b"]"))
}
}
}
impl<'serializer, W> ser::SerializeTupleStruct for SerializeSeq<'serializer, W>
where
W: Write,
{
type Ok = ();
type Error = Error;
#[inline]
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: serde_ext::Serialize,
{
let SerializeSeq {
ref mut s,
ref mut first,
} = *self;
if *first {
*first = false;
value.serialize(&mut **s)
} else {
iomap!(s.write(b",")).and_then(|_| value.serialize(&mut **s))
}
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
if self.first {
Ok(())
} else {
iomap!(self.s.write(b"]"))
}
}
}
impl<'serializer, W> ser::SerializeTupleVariant for SerializeSeq<'serializer, W>
where
W: Write,
{
type Ok = ();
type Error = Error;
#[inline]
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: serde_ext::Serialize,
{
let SerializeSeq {
ref mut s,
ref mut first,
} = *self;
if *first {
*first = false;
value.serialize(&mut **s)
} else {
iomap!(s.write(b",")).and_then(|_| value.serialize(&mut **s))
}
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
if self.first {
Ok(())
} else {
iomap!(self.s.write(b"}"))
}
}
}
struct SerializeMap<'serializer, W: Write + 'serializer> {
s: &'serializer mut Serializer<W>,
first: bool,
}
impl<'serializer, W> ser::SerializeMap for SerializeMap<'serializer, W>
where
W: Write,
{
type Ok = ();
type Error = Error;
#[inline]
fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
where
T: serde_ext::Serialize,
{
let SerializeMap {
ref mut s,
ref mut first,
..
} = *self;
if *first {
*first = false;
key.serialize(&mut **s).and_then(|_| iomap!(s.write(b":")))
} else {
iomap!(s.write(b","))
.and_then(|_| key.serialize(&mut **s))
.and_then(|_| iomap!(s.write(b":")))
}
}
#[inline]
fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: serde_ext::Serialize,
{
let SerializeMap { ref mut s, .. } = *self;
value.serialize(&mut **s)
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
if self.first {
Ok(())
} else {
iomap!(self.s.write(b"}"))
}
}
}
impl<'serializer, W> ser::SerializeStruct for SerializeMap<'serializer, W>
where
W: Write,
{
type Ok = ();
type Error = Error;
#[inline]
fn serialize_field<T: ?Sized>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), Self::Error>
where
T: serde_ext::Serialize,
{
let SerializeMap {
ref mut s,
ref mut first,
..
} = *self;
if *first {
*first = false;
iomap!(s.write_simple_string(key).and_then(|_| s.write(b":")))
.and_then(|_| value.serialize(&mut **s))
} else {
iomap!(s
.write(b",")
.and_then(|_| s.write_simple_string(key))
.and_then(|_| s.write(b":")))
.and_then(|_| value.serialize(&mut **s))
}
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
if self.first {
Ok(())
} else {
iomap!(self.s.write(b"}"))
}
}
}
struct SerializeStructVariant<'serializer, W: Write + 'serializer> {
s: &'serializer mut Serializer<W>,
first: bool,
}
impl<'serializer, W> ser::SerializeStructVariant for SerializeStructVariant<'serializer, W>
where
W: Write,
{
type Ok = ();
type Error = Error;
#[inline]
fn serialize_field<T: ?Sized>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), Self::Error>
where
T: serde_ext::Serialize,
{
let SerializeStructVariant {
ref mut s,
ref mut first,
..
} = *self;
if *first {
*first = false;
iomap!(s.write_simple_string(key).and_then(|_| s.write(b":")))
.and_then(|_| value.serialize(&mut **s))
} else {
iomap!(s
.write(b",")
.and_then(|_| s.write_simple_string(key))
.and_then(|_| s.write(b":")))
.and_then(|_| value.serialize(&mut **s))
}
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
iomap!(self.s.write(b"}")).and_then(move |_| {
if self.first {
Ok(())
} else {
iomap!(self.s.write(b"}"))
}
})
}
}
impl<'writer, W> ser::Serializer for &'writer mut Serializer<W>
where
W: Write,
{
type Ok = ();
type Error = Error;
type SerializeSeq = SerializeSeq<'writer, W>;
type SerializeTuple = SerializeSeq<'writer, W>;
type SerializeTupleStruct = SerializeSeq<'writer, W>;
type SerializeTupleVariant = SerializeSeq<'writer, W>;
type SerializeMap = SerializeMap<'writer, W>;
type SerializeStruct = SerializeMap<'writer, W>;
type SerializeStructVariant = SerializeStructVariant<'writer, W>;
#[inline]
fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
if v {
iomap!(self.write(b"true"))
} else {
iomap!(self.write(b"false"))
}
}
#[inline]
fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_int(v))
}
#[inline]
fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_int(v))
}
#[inline]
fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_int(v))
}
#[inline]
fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_int(v))
}
#[inline]
fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_int(v))
}
#[inline]
fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_int(v))
}
#[inline]
fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_int(v))
}
#[inline]
fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_int(v))
}
#[inline]
fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_int(v))
}
#[inline]
fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_int(v))
}
#[inline]
fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_float(f64::from(v)))
}
#[inline]
fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_float(v))
}
#[inline]
fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
// A char encoded as UTF-8 takes 4 bytes at most.
// taken from: https://docs.serde.rs/src/serde_json/ser.rs.html#213
let mut buf = [0; 4];
iomap!(self.write_simple_string(v.encode_utf8(&mut buf)))
}
#[inline]
fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_string(v))
}
#[inline]
fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
iomap!(self.write(b"[").and_then(|_| {
if let Some((first, rest)) = v.split_first() {
self.write_int(*first).and_then(|_| {
for v in rest {
if let Err(e) = self.write(b",").and_then(|_| self.write_int(*v)) {
return Err(e);
}
}
self.write(b"]")
})
} else {
self.write(b"]")
}
}))
}
#[inline]
fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
self.serialize_unit()
}
#[inline]
fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
where
T: serde_ext::Serialize,
{
value.serialize(self)
}
#[inline]
fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
iomap!(self.write(b"null"))
}
#[inline]
fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
self.serialize_unit()
}
#[inline]
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<Self::Ok, Self::Error> {
iomap!(self.write_simple_string(variant))
}
#[inline]
fn serialize_newtype_struct<T: ?Sized>(
self,
_name: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde_ext::Serialize,
{
value.serialize(self)
}
#[inline]
fn serialize_newtype_variant<T: ?Sized>(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
value: &T,
) -> Result<Self::Ok, Self::Error>
where
T: serde_ext::Serialize,
{
dbg!();
iomap!(self
.write(b"{")
.and_then(|_| self.write_simple_string(variant))
.and_then(|_| self.write(b":")))
.and_then(|_| value.serialize(&mut *self))
.and_then(|_| iomap!(self.write(b"}")))
}
#[inline]
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
if len == Some(0) {
iomap!(self.write(b"[]"))
} else {
iomap!(self.write(b"["))
}
.map(move |_| SerializeSeq {
s: self,
first: true,
})
}
#[inline]
fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
self.serialize_seq(Some(len))
}
#[inline]
fn serialize_tuple_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeTupleStruct, Self::Error> {
dbg!();
self.serialize_seq(Some(len))
}
#[inline]
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeTupleVariant, Self::Error> {
iomap!(self
.write(b"{")
.and_then(|_| self.write_simple_string(variant))
.and_then(|_| self.write(b":")))?;
self.serialize_seq(Some(len))
}
#[inline]
fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
if len == Some(0) {
iomap!(self.write(b"{}"))
} else {
iomap!(self.write(b"{"))
}
.map(move |_| SerializeMap {
s: self,
first: true,
})
}
#[inline]
fn serialize_struct(
self,
_name: &'static str,
len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
self.serialize_map(Some(len))
}
#[inline]
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
len: usize,
) -> Result<Self::SerializeStructVariant, Self::Error> {
dbg!();
iomap!(self
.write(b"{")
.and_then(|_| self.write_simple_string(variant))
.and_then(|_| self.write(b":")))
.and_then(move |_| {
if len == 0 {
iomap!(self.write(b"{}"))
} else {
iomap!(self.write(b"{"))
}
.map(move |_| SerializeStructVariant {
s: self,
first: true,
})
})
}
}
#[cfg(test)]
mod test {
use crate::{OwnedValue as Value, StaticNode};
use proptest::prelude::*;
#[test]
fn prety_print_serde() {
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
enum Segment {
Id { mid: usize },
}
assert_eq!(
"{\n \"Id\": {\n \"mid\": 0\n }\n}",
crate::to_string_pretty(&Segment::Id { mid: 0 }).unwrap()
);
}
#[test]
fn print_serde() {
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
enum Segment {
Id { mid: usize },
}
assert_eq!(
"{\"Id\":{\"mid\":0}}",
crate::to_string(&Segment::Id { mid: 0 }).unwrap()
);
}
#[cfg(not(feature = "128bit"))]
fn arb_json_value() -> BoxedStrategy<Value> {
let leaf = prop_oneof![
Just(Value::Static(StaticNode::Null)),
any::<bool>().prop_map(Value::from),
//(-1.0e306f64..1.0e306f64).prop_map(Value::from), // damn you float!
any::<i64>().prop_map(Value::from),
any::<u64>().prop_map(Value::from),
".*".prop_map(Value::from),
];
leaf.prop_recursive(
8, // 8 levels deep
256, // Shoot for maximum size of 256 nodes
10, // We put up to 10 items per collection
|inner| {
prop_oneof![
// Take the inner strategy and make the two recursive cases.
prop::collection::vec(inner.clone(), 0..10).prop_map(Value::from),
prop::collection::hash_map(".*", inner, 0..10).prop_map(Value::from),
]
},
)
.boxed()
}
#[cfg(feature = "128bit")]
fn arb_json_value() -> BoxedStrategy<Value> {
let leaf = prop_oneof![
Just(Value::Static(StaticNode::Null)),
any::<bool>().prop_map(Value::from),
//(-1.0e306f64..1.0e306f64).prop_map(Value::from), // damn you float!
any::<i64>().prop_map(Value::from),
any::<u64>().prop_map(Value::from),
any::<i128>().prop_map(Value::from),
any::<u128>().prop_map(Value::from),
".*".prop_map(Value::from),
];
leaf.prop_recursive(
8, // 8 levels deep
256, // Shoot for maximum size of 256 nodes
10, // We put up to 10 items per collection
|inner| {
prop_oneof![
// Take the inner strategy and make the two recursive cases.
prop::collection::vec(inner.clone(), 0..10).prop_map(Value::from),
prop::collection::hash_map(".*", inner, 0..10).prop_map(Value::from),
]
},
)
.boxed()
}
proptest! {
#![proptest_config(ProptestConfig {
// Setting both fork and timeout is redundant since timeout implies
// fork, but both are shown for clarity.
// Disabled for code coverage, enable to track bugs
// fork: true,
.. ProptestConfig::default()
})]
#[test]
fn prop_json_encode_decode(val in arb_json_value()) {
let mut encoded = crate::to_vec(&val).unwrap();
println!("{}", String::from_utf8_lossy(&encoded.clone()));
let res: Value = crate::from_slice(encoded.as_mut_slice()).expect("can't convert");
assert_eq!(val, res);
}
}
}
| 27.399711 | 95 | 0.504477 |
8a626b7fc4ec4e5ed0dacb5ea365cf3bdaae98b4 | 4,768 | use std::io::{Cursor, Result, Error, ErrorKind};
use std::cmp;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use bios::{BiosCompressionType, bios_compression_type};
use utils::same_count;
pub fn decompress_lz77(input: &[u8]) -> Result<Vec<u8>> {
let mut cursor = Cursor::new(input);
if bios_compression_type(cursor.read_u8()?) != Some(BiosCompressionType::Lz77) {
return Err(Error::new(ErrorKind::InvalidData, "compression header mismatch"));
}
let decompressed_size: usize = cursor.read_u24::<LittleEndian>()? as usize;
let mut output = Vec::with_capacity(decompressed_size);
while output.len() < decompressed_size {
let block_types = cursor.read_u8()?;
for i in 0..8 {
if output.len() < decompressed_size {
if block_types & (0x80 >> i) == 0 {
// Uncompressed
output.write_u8(cursor.read_u8()?)?;
} else {
// Reference
let block = cursor.read_u16::<LittleEndian>()? as usize;
let length = ((block >> 4) & 0xF) + 3;
let offset = (((block & 0xF) << 8) | ((block >> 8) & 0xFF)) + 1;
if output.len() + length > decompressed_size {
return Err(Error::new(ErrorKind::InvalidData, "length out of bounds"));
}
if offset > output.len() {
return Err(Error::new(ErrorKind::InvalidData, "offset out of bounds"));
}
for _ in 0..length {
let index = output.len() - offset;
let byte = output[index];
output.write_u8(byte)?;
}
}
}
}
}
assert_eq!(output.len(), decompressed_size);
Ok(output)
}
pub fn compress_lz77(input: &[u8], vram_safe: bool) -> Result<Vec<u8>> {
enum Block {
Uncompressed {
data: u8,
},
Reference {
offset: u16,
length: u8,
}
}
let mut blocks: Vec<Block> = Vec::new();
let mut index = 0;
while index < input.len() {
// When decompressing to VRAM the previous byte cannot be referenced in
// the uncompressed data because it may have not written to the memory yet.
// The data to the VRAM is written in 16-bit words due to 16-bit data bus.
let min_offset = if vram_safe { 2 } else { 1 };
let max_offset = cmp::min(index, 4096);
let min_length = 3;
let max_length = cmp::min(input.len() - index, 18);
let mut best_reference: Option<(usize, usize)> = None;
for current_offset in min_offset..=max_offset {
let current_length = same_count(&input[index..], &input[index - current_offset..], max_length);
if current_length >= min_length {
if let Some((_, best_length)) = best_reference {
if current_length > best_length {
best_reference = Some((current_offset, current_length));
}
} else {
best_reference = Some((current_offset, current_length));
}
}
}
if let Some((best_offset, best_length)) = best_reference {
blocks.push(Block::Reference {
offset: best_offset as u16,
length: best_length as u8,
});
index += best_length;
} else {
blocks.push(Block::Uncompressed { data: input[index] });
index += 1;
}
}
let mut output = Vec::new();
output.write_u8((BiosCompressionType::Lz77 as u8) << 4)?;
output.write_u24::<LittleEndian>(input.len() as u32)?;
for chunk in blocks.chunks(8) {
let mut block_types = 0;
for (i, block) in chunk.iter().enumerate() {
if let Block::Reference { .. } = *block {
block_types |= 0x80 >> i;
}
}
output.write_u8(block_types)?;
for block in chunk {
match *block {
Block::Uncompressed { data } => {
output.write_u8(data)?;
},
Block::Reference { offset, length } => {
assert!((length >= 3) & (length <= 18), "length out of bounds");
assert!((offset >= 1) & (offset <= 4096), "offset out of bounds");
let data = (((offset - 1) & 0xFF) << 8) | ((length - 3) << 4) as u16 | ((offset - 1) >> 8);
output.write_u16::<LittleEndian>(data)?;
},
}
}
}
Ok(output)
}
| 35.058824 | 111 | 0.504824 |
e9b04aaf7cfe3d04b6e0b5e320470324373a0273 | 703 | // if2.rs
// Step 1: Make me compile!
// Step 2: Get the bar_for_fuzz and default_to_baz tests passing!
// Execute the command `rustlings hint if2` if you want a hint :)
pub fn fizz_if_foo(fizzish: &str) -> &str {
if fizzish == "fizz" {
"foo"
} else if fizzish=="fuzz"{
"bar"
}
else {
"baz"
}
}
// No test changes needed!
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn foo_for_fizz() {
assert_eq!(fizz_if_foo("fizz"), "foo")
}
#[test]
fn bar_for_fuzz() {
assert_eq!(fizz_if_foo("fuzz"), "bar")
}
#[test]
fn default_to_baz() {
assert_eq!(fizz_if_foo("literally anything"), "baz")
}
}
| 17.575 | 65 | 0.549075 |
4bfe05d35f0b55458d7bb1ec46242a57ee03a6b1 | 479 | use super::*;
#[derive(Debug)]
pub struct PgAny<'a> {
pub(super) pg_type: PgType,
pub(super) raw_data: &'a [u8],
}
impl<'a> tokio_postgres::types::FromSql<'a> for PgAny<'a> {
fn from_sql(
pg_type: &PgType,
raw_data: &'a [u8],
) -> Result<Self, Box<dyn std::error::Error + Sync + Send>> {
Ok(Self {
pg_type: pg_type.to_owned(),
raw_data,
})
}
fn accepts(_ty: &PgType) -> bool {
true
}
}
| 21.772727 | 65 | 0.517745 |
03440374dd9f21e637f7a2068ab1ae08605d9f6b | 10,180 | use bevy_ecs::{
entity::Entity,
world::{Mut, World},
};
use naia_shared::{
ComponentUpdate, NetEntityHandleConverter, ProtocolInserter, ProtocolKindType, Protocolize,
ReplicaDynRefWrapper, ReplicaMutWrapper, ReplicaRefWrapper, ReplicateSafe, WorldMutType,
WorldRefType,
};
use super::{
component_ref::{ComponentMut, ComponentRef},
world_data::WorldData,
};
// WorldProxy
pub trait WorldProxy<'w> {
fn proxy(self) -> WorldRef<'w>;
}
impl<'w> WorldProxy<'w> for &'w World {
fn proxy(self) -> WorldRef<'w> {
return WorldRef::new(self);
}
}
// WorldProxyMut
pub trait WorldProxyMut<'w> {
fn proxy_mut(self) -> WorldMut<'w>;
}
impl<'w> WorldProxyMut<'w> for &'w mut World {
fn proxy_mut(self) -> WorldMut<'w> {
return WorldMut::new(self);
}
}
// WorldRef //
pub struct WorldRef<'w> {
world: &'w World,
}
impl<'w> WorldRef<'w> {
pub fn new(world: &'w World) -> Self {
WorldRef { world }
}
}
impl<'w, P: Protocolize> WorldRefType<P, Entity> for WorldRef<'w> {
fn has_entity(&self, entity: &Entity) -> bool {
return has_entity(self.world, entity);
}
fn entities(&self) -> Vec<Entity> {
return entities::<P>(self.world);
}
fn has_component<R: ReplicateSafe<P>>(&self, entity: &Entity) -> bool {
return has_component::<P, R>(self.world, entity);
}
fn has_component_of_kind(&self, entity: &Entity, component_kind: &P::Kind) -> bool {
return has_component_of_kind::<P>(self.world, entity, component_kind);
}
fn component<R: ReplicateSafe<P>>(&self, entity: &Entity) -> Option<ReplicaRefWrapper<P, R>> {
return component(self.world, entity);
}
fn component_of_kind(
&self,
entity: &Entity,
component_kind: &P::Kind,
) -> Option<ReplicaDynRefWrapper<P>> {
return component_of_kind::<P>(self.world, entity, component_kind);
}
}
// WorldMut
pub struct WorldMut<'w> {
world: &'w mut World,
}
impl<'w> WorldMut<'w> {
pub fn new(world: &'w mut World) -> Self {
WorldMut { world }
}
}
impl<'w, P: Protocolize> WorldRefType<P, Entity> for WorldMut<'w> {
fn has_entity(&self, entity: &Entity) -> bool {
return has_entity(self.world, entity);
}
fn entities(&self) -> Vec<Entity> {
return entities::<P>(self.world);
}
fn has_component<R: ReplicateSafe<P>>(&self, entity: &Entity) -> bool {
return has_component::<P, R>(self.world, entity);
}
fn has_component_of_kind(&self, entity: &Entity, component_kind: &P::Kind) -> bool {
return has_component_of_kind::<P>(self.world, entity, component_kind);
}
fn component<R: ReplicateSafe<P>>(&self, entity: &Entity) -> Option<ReplicaRefWrapper<P, R>> {
return component(self.world, entity);
}
fn component_of_kind(
&self,
entity: &Entity,
component_kind: &P::Kind,
) -> Option<ReplicaDynRefWrapper<P>> {
return component_of_kind(self.world, entity, component_kind);
}
}
impl<'w, P: Protocolize> WorldMutType<P, Entity> for WorldMut<'w> {
fn spawn_entity(&mut self) -> Entity {
let entity = self.world.spawn().id();
let mut world_data = world_data_unchecked_mut::<P>(&mut self.world);
world_data.spawn_entity(&entity);
return entity;
}
fn duplicate_entity(&mut self, entity: &Entity) -> Entity {
let new_entity = WorldMutType::<P, Entity>::spawn_entity(self);
WorldMutType::<P, Entity>::duplicate_components(self, &new_entity, entity);
new_entity
}
fn duplicate_components(&mut self, mutable_entity: &Entity, immutable_entity: &Entity) {
for component_kind in WorldMutType::<P, Entity>::component_kinds(self, &immutable_entity) {
let mut component_copy_opt: Option<P> = None;
if let Some(component) = self.component_of_kind(&immutable_entity, &component_kind) {
component_copy_opt = Some(component.protocol_copy());
}
if let Some(component_copy) = component_copy_opt {
Protocolize::extract_and_insert(&component_copy, mutable_entity, self);
}
}
}
fn despawn_entity(&mut self, entity: &Entity) {
let mut world_data = world_data_unchecked_mut::<P>(&self.world);
world_data.despawn_entity(entity);
self.world.despawn(*entity);
}
fn component_kinds(&mut self, entity: &Entity) -> Vec<P::Kind> {
let mut kinds = Vec::new();
let components = self.world.components();
for component_id in self.world.entity(*entity).archetype().components() {
let component_info = components
.get_info(component_id)
.expect("Components need info to instantiate");
let ref_type = component_info
.type_id()
.expect("Components need type_id to instantiate");
if let Some(kind) = P::type_to_kind(ref_type) {
kinds.push(kind);
}
}
return kinds;
}
fn component_mut<R: ReplicateSafe<P>>(
&mut self,
entity: &Entity,
) -> Option<ReplicaMutWrapper<P, R>> {
if let Some(bevy_mut) = self.world.get_mut::<R>(*entity) {
let wrapper = ComponentMut(bevy_mut);
let component_mut = ReplicaMutWrapper::new(wrapper);
return Some(component_mut);
}
return None;
}
fn component_apply_update(
&mut self,
converter: &dyn NetEntityHandleConverter,
entity: &Entity,
component_kind: &P::Kind,
update: ComponentUpdate<P::Kind>,
) {
self.world
.resource_scope(|world: &mut World, data: Mut<WorldData<P>>| {
if let Some(accessor) = data.component_access(component_kind) {
if let Some(mut component) = accessor.component_mut(world, entity) {
component.read_apply_update(converter, update);
}
}
});
}
fn mirror_entities(&mut self, new_entity: &Entity, old_entity: &Entity) {
for component_kind in WorldMutType::<P, Entity>::component_kinds(self, &old_entity) {
WorldMutType::<P, Entity>::mirror_components(
self,
new_entity,
old_entity,
&component_kind,
);
}
}
fn mirror_components(
&mut self,
mutable_entity: &Entity,
immutable_entity: &Entity,
component_kind: &P::Kind,
) {
self.world
.resource_scope(|world: &mut World, data: Mut<WorldData<P>>| {
if let Some(accessor) = data.component_access(component_kind) {
accessor.mirror_components(world, mutable_entity, immutable_entity);
}
});
}
fn insert_component<I: ReplicateSafe<P>>(&mut self, entity: &Entity, component_ref: I) {
// cache type id for later
// todo: can we initialize this map on startup via Protocol derive?
let mut world_data = world_data_unchecked_mut(&self.world);
let component_kind = component_ref.kind();
if !world_data.has_kind(&component_kind) {
world_data.put_kind::<I>(&component_kind);
}
// insert into ecs
self.world.entity_mut(*entity).insert(component_ref);
}
fn remove_component<R: ReplicateSafe<P>>(&mut self, entity: &Entity) -> Option<R> {
return self.world.entity_mut(*entity).remove::<R>();
}
fn remove_component_of_kind(&mut self, entity: &Entity, component_kind: &P::Kind) -> Option<P> {
let mut output: Option<P> = None;
self.world
.resource_scope(|world: &mut World, data: Mut<WorldData<P>>| {
if let Some(accessor) = data.component_access(component_kind) {
output = accessor.remove_component(world, entity);
}
});
return output;
}
}
impl<'w, P: Protocolize> ProtocolInserter<P, Entity> for WorldMut<'w> {
fn insert<I: ReplicateSafe<P>>(&mut self, entity: &Entity, impl_ref: I) {
self.insert_component::<I>(entity, impl_ref);
}
}
// private static methods
fn has_entity(world: &World, entity: &Entity) -> bool {
return world.get_entity(*entity).is_some();
}
fn entities<P: Protocolize>(world: &World) -> Vec<Entity> {
let world_data = world_data::<P>(world);
return world_data.entities();
}
fn has_component<P: Protocolize, R: ReplicateSafe<P>>(world: &World, entity: &Entity) -> bool {
return world.get::<R>(*entity).is_some();
}
fn has_component_of_kind<P: Protocolize>(
world: &World,
entity: &Entity,
component_kind: &P::Kind,
) -> bool {
return world
.entity(*entity)
.contains_type_id(component_kind.to_type_id());
}
fn component<'a, P: Protocolize, R: ReplicateSafe<P>>(
world: &'a World,
entity: &Entity,
) -> Option<ReplicaRefWrapper<'a, P, R>> {
if let Some(bevy_ref) = world.get::<R>(*entity) {
let wrapper = ComponentRef(bevy_ref);
let component_ref = ReplicaRefWrapper::new(wrapper);
return Some(component_ref);
}
return None;
}
fn component_of_kind<'a, P: Protocolize>(
world: &'a World,
entity: &Entity,
component_kind: &P::Kind,
) -> Option<ReplicaDynRefWrapper<'a, P>> {
let world_data = world_data(world);
if let Some(component_access) = world_data.component_access(component_kind) {
return component_access.component(world, entity);
}
return None;
}
fn world_data<P: Protocolize>(world: &World) -> &WorldData<P> {
return world
.get_resource::<WorldData<P>>()
.expect("Need to instantiate by adding WorldData<Protocol> resource at startup!");
}
fn world_data_unchecked_mut<P: Protocolize>(world: &World) -> Mut<WorldData<P>> {
unsafe {
return world
.get_resource_unchecked_mut::<WorldData<P>>()
.expect("Need to instantiate by adding WorldData<Protocol> resource at startup!");
}
}
| 30.570571 | 100 | 0.608153 |
79bc95ce414d3575464614d11b702698864b6e94 | 2,943 | use super::*;
pub(super) fn opt_type_param_list(p: &mut Parser) {
if !p.at(L_ANGLE) {
return;
}
let m = p.start();
p.bump();
while !p.at(EOF) && !p.at(R_ANGLE) {
match p.current() {
LIFETIME => lifetime_param(p),
IDENT => type_param(p),
_ => p.err_and_bump("expected type parameter"),
}
if !p.at(R_ANGLE) && !p.expect(COMMA) {
break;
}
}
p.expect(R_ANGLE);
m.complete(p, TYPE_PARAM_LIST);
fn lifetime_param(p: &mut Parser) {
assert!(p.at(LIFETIME));
let m = p.start();
p.bump();
if p.at(COLON) {
lifetime_bounds(p);
}
m.complete(p, LIFETIME_PARAM);
}
fn type_param(p: &mut Parser) {
assert!(p.at(IDENT));
let m = p.start();
name(p);
if p.at(COLON) {
bounds(p);
}
// test type_param_default
// struct S<T = i32>;
if p.at(EQ) {
p.bump();
types::type_(p)
}
m.complete(p, TYPE_PARAM);
}
}
// test type_param_bounds
// struct S<T: 'a + ?Sized + (Copy)>;
pub(super) fn bounds(p: &mut Parser) {
assert!(p.at(COLON));
p.bump();
bounds_without_colon(p);
}
fn lifetime_bounds(p: &mut Parser) {
assert!(p.at(COLON));
p.bump();
while p.at(LIFETIME) {
p.bump();
if !p.eat(PLUS) {
break;
}
}
}
pub(super) fn bounds_without_colon(p: &mut Parser) {
loop {
let has_paren = p.eat(L_PAREN);
p.eat(QUESTION);
match p.current() {
LIFETIME => p.bump(),
FOR_KW => {
types::for_type(p)
}
_ if paths::is_path_start(p) => {
types::path_type(p)
}
_ => break,
}
if has_paren {
p.expect(R_PAREN);
}
if !p.eat(PLUS) {
break;
}
}
}
// test where_clause
// fn foo()
// where
// 'a: 'b + 'c,
// T: Clone + Copy + 'static,
// Iterator::Item: 'a,
// {}
pub(super) fn opt_where_clause(p: &mut Parser) {
if !p.at(WHERE_KW) {
return;
}
let m = p.start();
p.bump();
loop {
if !(paths::is_path_start(p) || p.current() == LIFETIME) {
break
}
where_predicate(p);
if p.current() != L_CURLY && p.current() != SEMI {
p.expect(COMMA);
}
}
m.complete(p, WHERE_CLAUSE);
}
fn where_predicate(p: &mut Parser) {
let m = p.start();
if p.at(LIFETIME) {
p.eat(LIFETIME);
if p.at(COLON) {
lifetime_bounds(p)
} else {
p.error("expected colon")
}
} else {
types::path_type(p);
if p.at(COLON) {
bounds(p);
} else {
p.error("expected colon")
}
}
m.complete(p, WHERE_PRED);
}
| 21.481752 | 66 | 0.457356 |
390bbe51179b1b1eb1b8f62deadbd64bd676d01c | 7,935 | use crate::{
ast::{Directive, Field, InputValue},
parser::Spanning,
schema::meta::Argument,
validation::{ValidatorContext, Visitor},
value::ScalarValue,
};
use std::fmt::Debug;
#[derive(Debug)]
enum ArgumentPosition<'a> {
Directive(&'a str),
Field(&'a str, &'a str),
}
pub struct KnownArgumentNames<'a, S: Debug + 'a> {
current_args: Option<(ArgumentPosition<'a>, &'a Vec<Argument<'a, S>>)>,
}
pub fn factory<'a, S: Debug>() -> KnownArgumentNames<'a, S> {
KnownArgumentNames { current_args: None }
}
impl<'a, S> Visitor<'a, S> for KnownArgumentNames<'a, S>
where
S: ScalarValue,
{
fn enter_directive(
&mut self,
ctx: &mut ValidatorContext<'a, S>,
directive: &'a Spanning<Directive<S>>,
) {
self.current_args = ctx
.schema
.directive_by_name(directive.item.name.item)
.map(|d| {
(
ArgumentPosition::Directive(directive.item.name.item),
&d.arguments,
)
});
}
fn exit_directive(&mut self, _: &mut ValidatorContext<'a, S>, _: &'a Spanning<Directive<S>>) {
self.current_args = None;
}
fn enter_field(&mut self, ctx: &mut ValidatorContext<'a, S>, field: &'a Spanning<Field<S>>) {
self.current_args = ctx
.parent_type()
.and_then(|t| t.field_by_name(field.item.name.item))
.and_then(|f| f.arguments.as_ref())
.map(|args| {
(
ArgumentPosition::Field(
field.item.name.item,
ctx.parent_type()
.expect("Parent type should exist")
.name()
.expect("Parent type should be named"),
),
args,
)
});
}
fn exit_field(&mut self, _: &mut ValidatorContext<'a, S>, _: &'a Spanning<Field<S>>) {
self.current_args = None;
}
fn enter_argument(
&mut self,
ctx: &mut ValidatorContext<'a, S>,
&(ref arg_name, _): &'a (Spanning<&'a str>, Spanning<InputValue<S>>),
) {
if let Some((ref pos, args)) = self.current_args {
if args.iter().find(|a| a.name == arg_name.item).is_none() {
let message = match *pos {
ArgumentPosition::Field(field_name, type_name) => {
field_error_message(arg_name.item, field_name, type_name)
}
ArgumentPosition::Directive(directive_name) => {
directive_error_message(arg_name.item, directive_name)
}
};
ctx.report_error(&message, &[arg_name.start]);
}
}
}
}
fn field_error_message(arg_name: &str, field_name: &str, type_name: &str) -> String {
format!(
r#"Unknown argument "{}" on field "{}" of type "{}""#,
arg_name, field_name, type_name
)
}
fn directive_error_message(arg_name: &str, directive_name: &str) -> String {
format!(
r#"Unknown argument "{}" on directive "{}""#,
arg_name, directive_name
)
}
#[cfg(test)]
mod tests {
use super::{directive_error_message, factory, field_error_message};
use crate::{
parser::SourcePosition,
validation::{expect_fails_rule, expect_passes_rule, RuleError},
value::DefaultScalarValue,
};
#[test]
fn single_arg_is_known() {
expect_passes_rule::<_, _, DefaultScalarValue>(
factory,
r#"
fragment argOnRequiredArg on Dog {
doesKnowCommand(dogCommand: SIT)
}
"#,
);
}
#[test]
fn multiple_args_are_known() {
expect_passes_rule::<_, _, DefaultScalarValue>(
factory,
r#"
fragment multipleArgs on ComplicatedArgs {
multipleReqs(req1: 1, req2: 2)
}
"#,
);
}
#[test]
fn ignores_args_of_unknown_fields() {
expect_passes_rule::<_, _, DefaultScalarValue>(
factory,
r#"
fragment argOnUnknownField on Dog {
unknownField(unknownArg: SIT)
}
"#,
);
}
#[test]
fn multiple_args_in_reverse_order_are_known() {
expect_passes_rule::<_, _, DefaultScalarValue>(
factory,
r#"
fragment multipleArgsReverseOrder on ComplicatedArgs {
multipleReqs(req2: 2, req1: 1)
}
"#,
);
}
#[test]
fn no_args_on_optional_arg() {
expect_passes_rule::<_, _, DefaultScalarValue>(
factory,
r#"
fragment noArgOnOptionalArg on Dog {
isHousetrained
}
"#,
);
}
#[test]
fn args_are_known_deeply() {
expect_passes_rule::<_, _, DefaultScalarValue>(
factory,
r#"
{
dog {
doesKnowCommand(dogCommand: SIT)
}
human {
pet {
... on Dog {
doesKnowCommand(dogCommand: SIT)
}
}
}
}
"#,
);
}
#[test]
fn directive_args_are_known() {
expect_passes_rule::<_, _, DefaultScalarValue>(
factory,
r#"
{
dog @skip(if: true)
}
"#,
);
}
#[test]
fn undirective_args_are_invalid() {
expect_fails_rule::<_, _, DefaultScalarValue>(
factory,
r#"
{
dog @skip(unless: true)
}
"#,
&[RuleError::new(
&directive_error_message("unless", "skip"),
&[SourcePosition::new(35, 2, 22)],
)],
);
}
#[test]
fn invalid_arg_name() {
expect_fails_rule::<_, _, DefaultScalarValue>(
factory,
r#"
fragment invalidArgName on Dog {
doesKnowCommand(unknown: true)
}
"#,
&[RuleError::new(
&field_error_message("unknown", "doesKnowCommand", "Dog"),
&[SourcePosition::new(72, 2, 28)],
)],
);
}
#[test]
fn unknown_args_amongst_known_args() {
expect_fails_rule::<_, _, DefaultScalarValue>(
factory,
r#"
fragment oneGoodArgOneInvalidArg on Dog {
doesKnowCommand(whoknows: 1, dogCommand: SIT, unknown: true)
}
"#,
&[
RuleError::new(
&field_error_message("whoknows", "doesKnowCommand", "Dog"),
&[SourcePosition::new(81, 2, 28)],
),
RuleError::new(
&field_error_message("unknown", "doesKnowCommand", "Dog"),
&[SourcePosition::new(111, 2, 58)],
),
],
);
}
#[test]
fn unknown_args_deeply() {
expect_fails_rule::<_, _, DefaultScalarValue>(
factory,
r#"
{
dog {
doesKnowCommand(unknown: true)
}
human {
pet {
... on Dog {
doesKnowCommand(unknown: true)
}
}
}
}
"#,
&[
RuleError::new(
&field_error_message("unknown", "doesKnowCommand", "Dog"),
&[SourcePosition::new(61, 3, 30)],
),
RuleError::new(
&field_error_message("unknown", "doesKnowCommand", "Dog"),
&[SourcePosition::new(193, 8, 34)],
),
],
);
}
}
| 26.898305 | 98 | 0.472716 |
e863e84837abd3bf92b096ec83462a4f8f509e94 | 24,351 | //! Robust domain name parsing using the Public Suffix List
//!
//! This library allows you to easily and accurately parse any given domain name.
//!
//! ## Examples
//!
//! ```rust,norun
//! extern crate publicsuffix;
//!
//! use publicsuffix::List;
//! # use publicsuffix::Result;
//!
//! # fn examples() -> Result<()> {
//! // Fetch the list from the official URL,
//! # #[cfg(feature = "remote_list")]
//! let list = List::fetch()?;
//!
//! // from your own URL
//! # #[cfg(feature = "remote_list")]
//! let list = List::from_url("https://example.com/path/to/public_suffix_list.dat")?;
//!
//! // or from a local file.
//! let list = List::from_path("/path/to/public_suffix_list.dat")?;
//!
//! // Using the list you can find out the root domain
//! // or extension of any given domain name
//! let domain = list.parse_domain("www.example.com")?;
//! assert_eq!(domain.root(), Some("example.com"));
//! assert_eq!(domain.suffix(), Some("com"));
//!
//! let domain = list.parse_domain("www.食狮.中国")?;
//! assert_eq!(domain.root(), Some("食狮.中国"));
//! assert_eq!(domain.suffix(), Some("中国"));
//!
//! let domain = list.parse_domain("www.xn--85x722f.xn--55qx5d.cn")?;
//! assert_eq!(domain.root(), Some("xn--85x722f.xn--55qx5d.cn"));
//! assert_eq!(domain.suffix(), Some("xn--55qx5d.cn"));
//!
//! let domain = list.parse_domain("a.b.example.uk.com")?;
//! assert_eq!(domain.root(), Some("example.uk.com"));
//! assert_eq!(domain.suffix(), Some("uk.com"));
//!
//! let name = list.parse_dns_name("_tcp.example.com.")?;
//! assert_eq!(name.domain().and_then(|domain| domain.root()), Some("example.com"));
//! assert_eq!(name.domain().and_then(|domain| domain.suffix()), Some("com"));
//!
//! // You can also find out if this is an ICANN domain
//! assert!(!domain.is_icann());
//!
//! // or a private one
//! assert!(domain.is_private());
//!
//! // In any case if the domain's suffix is in the list
//! // then this is definately a registrable domain name
//! assert!(domain.has_known_suffix());
//! # Ok(())
//! # }
//! # fn main() {}
//! ```
#![recursion_limit = "1024"]
use lazy_static::lazy_static;
#[cfg(feature = "remote_list")]
use native_tls;
#[cfg(feature = "remote_list")]
#[cfg(test)]
mod tests;
use std::{collections::HashMap, fmt, fs::File, io::Read, net::IpAddr, path::Path, str::FromStr};
#[cfg(feature = "remote_list")]
use std::{io::Write, net::TcpStream, time::Duration};
pub mod errors;
pub use crate::errors::{Error, ErrorKind, Result, ResultExt};
use idna::domain_to_unicode;
#[cfg(feature = "remote_list")]
use native_tls::TlsConnector;
use regex::RegexSet;
use url::Url;
/// The official URL of the list
pub const LIST_URL: &'static str = "https://publicsuffix.org/list/public_suffix_list.dat";
const PREVAILING_STAR_RULE: &'static str = "*";
#[derive(Debug, PartialEq, Eq, Hash)]
struct Suffix {
rule: String,
typ: Type,
}
#[derive(Debug)]
struct ListLeaf {
typ: Type,
is_exception_rule: bool,
}
impl ListLeaf {
fn new(typ: Type, is_exception_rule: bool) -> Self {
Self {
typ,
is_exception_rule,
}
}
}
#[derive(Debug)]
struct ListNode {
children: HashMap<String, ListNode>,
leaf: Option<ListLeaf>,
}
impl ListNode {
fn new() -> Self {
Self {
children: HashMap::new(),
leaf: None,
}
}
}
/// Stores the public suffix list
///
/// You can use the methods, `fetch`, `from_url` or `from_path` to build the list.
/// If you are using this in a long running server it's recommended you use either
/// `fetch` or `from_url` to download updates at least once a week.
#[derive(Debug)]
pub struct List {
root: ListNode,
all: Vec<Suffix>, // to support all(), icann(), private()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Type {
Icann,
Private,
}
/// Holds information about a particular domain
///
/// This is created by `List::parse_domain`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Domain {
full: String,
typ: Option<Type>,
suffix: Option<String>,
registrable: Option<String>,
}
/// Holds information about a particular host
///
/// This is created by `List::parse_host`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Host {
Ip(IpAddr),
Domain(Domain),
}
/// Holds information about a particular DNS name
///
/// This is created by `List::parse_dns_name`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DnsName {
name: String,
domain: Option<Domain>,
}
lazy_static! {
// Regex for matching domain name labels
static ref LABEL: RegexSet = {
let exprs = vec![
// can be any combination of alphanumeric characters
r"^[[:alnum:]]+$",
// or it can start with an alphanumeric character
// then optionally be followed by any combination of
// alphanumeric characters and dashes before finally
// ending with an alphanumeric character
r"^[[:alnum:]]+[[:alnum:]-]*[[:alnum:]]+$",
];
RegexSet::new(exprs).unwrap()
};
// Regex for matching the local-part of an
// email address
static ref LOCAL: RegexSet = {
// these characters can be anywhere in the expresion
let global = r#"[[:alnum:]!#$%&'*+/=?^_`{|}~-]"#;
// non-ascii characters (an also be unquoted)
let non_ascii = r#"[^\x00-\x7F]"#;
// the pattern to match
let quoted = r#"["(),\\:;<>@\[\]. ]"#;
// combined regex
let combined = format!(r#"({}*{}*)"#, global, non_ascii);
let exprs = vec![
// can be any combination of allowed characters
format!(r#"^{}+$"#, combined),
// can be any combination of allowed charaters
// separated by a . in between
format!(r#"^({0}+[.]?{0}+)+$"#, combined),
// can be a quoted string with allowed plus
// additional characters
format!(r#"^"({}*{}*)*"$"#, combined, quoted),
];
RegexSet::new(exprs).unwrap()
};
}
/// Converts a type into a Url object
pub trait IntoUrl {
fn into_url(self) -> Result<Url>;
}
impl IntoUrl for Url {
fn into_url(self) -> Result<Url> {
Ok(self)
}
}
impl<'a> IntoUrl for &'a str {
fn into_url(self) -> Result<Url> {
Ok(Url::parse(self)?)
}
}
impl<'a> IntoUrl for &'a String {
fn into_url(self) -> Result<Url> {
Ok(Url::parse(self)?)
}
}
impl IntoUrl for String {
fn into_url(self) -> Result<Url> {
Ok(Url::parse(&self)?)
}
}
#[cfg(feature = "remote_list")]
fn request<U: IntoUrl>(u: U) -> Result<String> {
let url = u.into_url()?;
let host = match url.host_str() {
Some(host) => host,
None => {
return Err(ErrorKind::NoHost.into());
}
};
let port = match url.port_or_known_default() {
Some(port) => port,
None => {
return Err(ErrorKind::NoPort.into());
}
};
let data = format!("GET {} HTTP/1.0\r\nHost: {}\r\n\r\n", url.path(), host);
let addr = format!("{}:{}", host, port);
let stream = TcpStream::connect(addr)?;
let timeout = Duration::from_secs(2);
stream.set_read_timeout(Some(timeout))?;
stream.set_write_timeout(Some(timeout))?;
let mut res = String::new();
match url.scheme() {
scheme if scheme == "https" => {
let connector = TlsConnector::builder().build()?;
let mut stream = connector.connect(host, stream)?;
stream.write_all(data.as_bytes())?;
stream.read_to_string(&mut res)?;
}
scheme if scheme == "http" => {
let mut stream = stream;
stream.write_all(data.as_bytes())?;
stream.read_to_string(&mut res)?;
}
_ => {
return Err(ErrorKind::UnsupportedScheme.into());
}
}
Ok(res)
}
impl List {
fn append(&mut self, mut rule: &str, typ: Type) -> Result<()> {
let mut is_exception_rule = false;
if rule.starts_with("!") {
is_exception_rule = true;
rule = &rule[1..];
}
let mut current = &mut self.root;
for label in rule.rsplit('.') {
if label.is_empty() {
return Err(ErrorKind::InvalidRule(rule.into()).into());
}
let cur = current;
current = cur
.children
.entry(label.to_owned())
.or_insert(ListNode::new());
}
current.leaf = Some(ListLeaf::new(typ, is_exception_rule));
// to support all(), icann(), private()
self.all.push(Suffix {
rule: rule.to_owned(),
typ,
});
Ok(())
}
fn build(res: &str) -> Result<List> {
let mut typ = None;
let mut list = List::empty();
for line in res.lines() {
match line {
line if line.contains("BEGIN ICANN DOMAINS") => {
typ = Some(Type::Icann);
}
line if line.contains("BEGIN PRIVATE DOMAINS") => {
typ = Some(Type::Private);
}
line if line.starts_with("//") => {
continue;
}
line => match typ {
Some(typ) => {
let rule = match line.split_whitespace().next() {
Some(rule) => rule,
None => continue,
};
list.append(rule, typ)?;
}
None => {
continue;
}
},
}
}
if list.root.children.is_empty() || list.all().is_empty() {
return Err(ErrorKind::InvalidList.into());
}
list.append(PREVAILING_STAR_RULE, Type::Icann)?; // add the default rule
Ok(list)
}
/// Creates an empty List without any rules
///
/// Sometimes all you want is to do syntax checks. If you don't really care whether
/// the domain has a known suffix or not you can just create an empty list and use
/// that to parse domain names and email addresses.
pub fn empty() -> List {
List {
root: ListNode::new(),
all: Vec::new(),
}
}
/// Pull the list from a URL
#[cfg(feature = "remote_list")]
pub fn from_url<U: IntoUrl>(url: U) -> Result<List> {
request(url).and_then(Self::from_string)
}
/// Fetch the list from a local file
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<List> {
File::open(path)
.map_err(|err| ErrorKind::Io(err).into())
.and_then(|mut data| {
let mut res = String::new();
data.read_to_string(&mut res)?;
Ok(res)
})
.and_then(Self::from_string)
}
/// Build the list from the result of anything that implements `std::io::Read`
///
/// If you don't already have your list on the filesystem but want to use your
/// own library to fetch the list you can use this method so you don't have to
/// save it first.
pub fn from_reader<R: Read>(mut reader: R) -> Result<List> {
let mut res = String::new();
reader.read_to_string(&mut res)?;
Self::build(&res)
}
/// Build the list from a string
///
/// The list doesn't always have to come from a file. You can maintain your own
/// list, say in a DBMS. You can then pull it at runtime and build the list from
/// the resulting String.
pub fn from_string(string: String) -> Result<List> {
Self::from_str(&string)
}
/// Build the list from a str
///
/// The list doesn't always have to come from a file. You can maintain your own
/// list, say in a DBMS. You can then pull it at runtime and build the list from
/// the resulting str.
pub fn from_str(string: &str) -> Result<List> {
Self::build(string)
}
/// Pull the list from the official URL
#[cfg(feature = "remote_list")]
pub fn fetch() -> Result<List> {
let github =
"https://raw.githubusercontent.com/publicsuffix/list/master/public_suffix_list.dat";
Self::from_url(LIST_URL)
// Fallback to the Github repo if the official link
// is down for some reason.
.or_else(|_| Self::from_url(github))
}
fn find_type(&self, typ: Type) -> Vec<&str> {
self.all_internal()
.filter(|s| s.typ == typ)
.map(|s| s.rule.as_str())
.collect()
}
/// Gets a list of all ICANN domain suffices
pub fn icann(&self) -> Vec<&str> {
self.find_type(Type::Icann)
}
/// Gets a list of all private domain suffices
pub fn private(&self) -> Vec<&str> {
self.find_type(Type::Private)
}
/// Gets a list of all domain suffices
pub fn all(&self) -> Vec<&str> {
self.all_internal().map(|s| s.rule.as_str()).collect()
}
fn all_internal(&self) -> impl Iterator<Item = &Suffix> {
self.all
.iter()
// remove the default rule
.filter(|s| s.rule != PREVAILING_STAR_RULE)
}
/// Parses a domain using the list
pub fn parse_domain(&self, domain: &str) -> Result<Domain> {
Domain::parse(domain, self, true)
}
/// Parses a host using the list
///
/// A host, for the purposes of this library, is either
/// an IP address or a domain name.
pub fn parse_host(&self, host: &str) -> Result<Host> {
Host::parse(host, self)
}
/// Extracts Host from a URL
pub fn parse_url<U: IntoUrl>(&self, url: U) -> Result<Host> {
let url = url.into_url()?;
match url.scheme() {
"mailto" => match url.host_str() {
Some(host) => self.parse_email(&format!("{}@{}", url.username(), host)),
None => Err(ErrorKind::InvalidEmail.into()),
},
_ => match url.host_str() {
Some(host) => self.parse_host(host),
None => Err(ErrorKind::NoHost.into()),
},
}
}
/// Extracts Host from an email address
///
/// This method can also be used, simply to validate an email address.
/// If it returns an error, the email address is not valid.
// https://en.wikipedia.org/wiki/Email_address#Syntax
// https://en.wikipedia.org/wiki/International_email#Email_addresses
// http://girders.org/blog/2013/01/31/dont-rfc-validate-email-addresses/
// https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
// https://hackernoon.com/the-100-correct-way-to-validate-email-addresses-7c4818f24643#.pgcir4z3e
// http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/
// https://tools.ietf.org/html/rfc6530#section-10.1
// http://rumkin.com/software/email/rules.php
pub fn parse_email(&self, address: &str) -> Result<Host> {
let mut parts = address.rsplitn(2, "@");
let host = match parts.next() {
Some(host) => host,
None => {
return Err(ErrorKind::InvalidEmail.into());
}
};
let local = match parts.next() {
Some(local) => local,
None => {
return Err(ErrorKind::InvalidEmail.into());
}
};
if local.chars().count() > 64
|| address.chars().count() > 254
|| (!local.starts_with('"') && local.contains(".."))
|| !LOCAL.is_match(local)
{
return Err(ErrorKind::InvalidEmail.into());
}
self.parse_host(host)
}
/// Parses any arbitrary string
///
/// Effectively this means that the string is either a URL, an email address or a host.
pub fn parse_str(&self, string: &str) -> Result<Host> {
if string.contains("://") {
self.parse_url(string)
} else if string.contains("@") {
self.parse_email(string)
} else {
self.parse_host(string)
}
}
/// Parses any arbitrary string that can be used as a key in a DNS database
pub fn parse_dns_name(&self, name: &str) -> Result<DnsName> {
let mut dns_name = DnsName {
name: Domain::to_ascii(name).chain_err(|| ErrorKind::InvalidDomain(name.into()))?,
domain: None,
};
if let Ok(mut domain) = Domain::parse(name, self, false) {
if let Some(root) = domain.root() {
if Domain::has_valid_syntax(&root) {
domain.full = root.to_string();
dns_name.domain = Some(domain);
}
}
}
Ok(dns_name)
}
}
impl Host {
fn parse(mut host: &str, list: &List) -> Result<Host> {
if let Ok(domain) = Domain::parse(host, list, true) {
return Ok(Host::Domain(domain));
}
if host.starts_with("[")
&& !host.starts_with("[[")
&& host.ends_with("]")
&& !host.ends_with("]]")
{
host = host.trim_start_matches("[").trim_end_matches("]");
};
if let Ok(ip) = IpAddr::from_str(host) {
return Ok(Host::Ip(ip));
}
Err(ErrorKind::InvalidHost.into())
}
/// A convenient method to simply check if a host is an IP address
pub fn is_ip(&self) -> bool {
if let &Host::Ip(_) = self {
return true;
}
false
}
/// A convenient method to simply check if a host is a domain name
pub fn is_domain(&self) -> bool {
if let &Host::Domain(_) = self {
return true;
}
false
}
}
impl fmt::Display for Host {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Host::Ip(ref ip) => write!(f, "{}", ip),
&Host::Domain(ref domain) => write!(f, "{}", domain),
}
}
}
impl Domain {
/// Check if a domain has valid syntax
// https://en.wikipedia.org/wiki/Domain_name#Domain_name_syntax
// http://blog.sacaluta.com/2011/12/dns-domain-names-253-or-255-bytesoctets.html
// https://blogs.msdn.microsoft.com/oldnewthing/20120412-00/?p=7873/
pub fn has_valid_syntax(domain: &str) -> bool {
// we are explicitly checking for this here before calling `domain_to_ascii`
// because `domain_to_ascii` strips of leading dots so we won't be able to
// check for this later
if domain.starts_with('.') {
return false;
}
// let's convert the domain to ascii early on so we can validate
// internationalised domain names as well
let domain = match Self::to_ascii(domain) {
Ok(domain) => domain,
Err(_) => {
return false;
}
};
let mut labels: Vec<&str> = domain.split('.').collect();
// strip of the first dot from a domain to support fully qualified domain names
if domain.ends_with(".") {
labels.pop();
}
// a domain must not have more than 127 labels
if labels.len() > 127 {
return false;
}
labels.reverse();
for (i, label) in labels.iter().enumerate() {
// the tld must not be a number
if i == 0 && label.parse::<f64>().is_ok() {
return false;
}
// any label must only contain allowed characters
if !LABEL.is_match(label) {
return false;
}
}
true
}
/// Get the full domain
pub fn full(&self) -> &str {
&self.full
}
fn assemble(input: &str, s_len: usize) -> String {
let domain = input.to_lowercase();
let d_labels: Vec<&str> = domain.trim_end_matches('.').split('.').rev().collect();
(&d_labels[..s_len])
.iter()
.rev()
.map(|part| *part)
.collect::<Vec<_>>()
.join(".")
}
fn find_match(input: &str, domain: &str, list: &List) -> Result<Domain> {
let mut longest_valid = None;
let mut current = &list.root;
let mut s_labels_len = 0;
for label in domain.rsplit('.') {
if let Some(child) = current.children.get(label) {
current = child;
s_labels_len += 1;
} else if let Some(child) = current.children.get("*") {
// wildcard rule
current = child;
s_labels_len += 1;
} else {
// no match rules
break;
}
if let Some(list_leaf) = ¤t.leaf {
longest_valid = Some((list_leaf, s_labels_len));
}
}
match longest_valid {
Some((leaf, suffix_len)) => {
let typ = Some(leaf.typ);
let suffix_len = if leaf.is_exception_rule {
suffix_len - 1
} else {
suffix_len
};
let suffix = Some(Self::assemble(input, suffix_len));
let d_labels_len = domain.match_indices(".").count() + 1;
let registrable = if d_labels_len > suffix_len {
Some(Self::assemble(input, suffix_len + 1))
} else {
None
};
Ok(Domain {
full: input.to_owned(),
typ,
suffix,
registrable,
})
}
None => Ok(Domain {
full: input.to_owned(),
typ: None,
suffix: None,
registrable: None,
}),
}
}
fn to_ascii(domain: &str) -> Result<String> {
let result = idna::Config::default()
.transitional_processing(true)
.verify_dns_length(true)
.to_ascii(domain);
result.map_err(|error| ErrorKind::Uts46(error).into())
}
fn parse(domain: &str, list: &List, check_syntax: bool) -> Result<Domain> {
if check_syntax && !Self::has_valid_syntax(domain) {
return Err(ErrorKind::InvalidDomain(domain.into()).into());
}
let input = domain.trim_end_matches('.');
let (domain, res) = domain_to_unicode(input);
if let Err(errors) = res {
return Err(ErrorKind::Uts46(errors).into());
}
Self::find_match(input, &domain, list)
}
/// Gets the root domain portion if any
pub fn root(&self) -> Option<&str> {
self.registrable.as_ref().map(|x| &x[..])
}
/// Gets the suffix if any
pub fn suffix(&self) -> Option<&str> {
self.suffix.as_ref().map(|x| &x[..])
}
/// Whether the domain has a private suffix
pub fn is_private(&self) -> bool {
self.typ.map(|t| t == Type::Private).unwrap_or(false)
}
/// Whether the domain has an ICANN suffix
pub fn is_icann(&self) -> bool {
self.typ.map(|t| t == Type::Icann).unwrap_or(false)
}
/// Whether this domain's suffix is in the list
///
/// If it is, this is definately a valid domain. If it's not
/// chances are very high that this isn't a valid domain name,
/// however, it might simply be because the suffix is new and
/// it hasn't been added to the list yet.
///
/// If you want to validate a domain name, use this as a quick
/// check but fall back to a DNS lookup if it returns false.
pub fn has_known_suffix(&self) -> bool {
self.typ.is_some()
}
}
impl fmt::Display for Domain {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.full.trim_end_matches(".").to_lowercase())
}
}
impl DnsName {
/// Extracts the root domain from a DNS name, if any
pub fn domain(&self) -> Option<&Domain> {
self.domain.as_ref()
}
}
impl fmt::Display for DnsName {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.name.fmt(f)
}
}
| 30.980916 | 101 | 0.54162 |
9143b340f7fde9765910f4d6f9d61329bf0a0a2d | 1,506 | /**
* @file main.rs
* Copyright © 2021 Neeraj Singhal
* All rights reserved
*/
//Import external crates
extern crate rand;
use rand::Rng;
use std::io;
// Import user-defined modules
mod file;
mod math;
mod temp;
fn main() {
println!("Hello World!\nI'm a Rustacean!\n");
let x: i8 = -9;
println!("Result= {}", x);
let secret_number = rand::thread_rng().gen_range(1..101);
println!("The secret number= {}", secret_number);
let mut a = String::new();
io::stdin().read_line(&mut a).expect("failed to read line");
let a = 2;
let b = 9;
let sum = math::add(a, b);
println!("Result {} + {} = {}", a, b, sum);
let sub = math::sub(a, b);
println!("Result {} - {} = {}", a, b, sub);
let mul = math::mul(a, b);
println!("Result {} * {} = {}", a, b, mul);
let average = math::average(13, 2.3, 120.0);
assert_eq!(average, 45.1);
println!("Test# {} Passed!", std::stringify!(average));
let celsius_temp = 23.0;
let fahrenheit_temp = temp::celsius_to_fahrenheit(celsius_temp);
assert_eq!(fahrenheit_temp, 73.4);
println!("Test# {} Passed!", std::stringify!(celsius_to_fahrenheit));
let fahrenheit_temp = 73.4;
let celsius_temp = temp::fahrenheit_to_celsius(fahrenheit_temp);
assert_eq!(celsius_temp, 23.0);
println!("Test# {} Passed!", std::stringify!(fahrenheit_to_celsius));
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 5);
}
}
}
| 25.525424 | 73 | 0.583665 |
eb118a2ed4cf9293581f26941967f0292d2f51ad | 824 | // https://leetcode-cn.com/problems/xor-queries-of-a-subarray/
// Runtime: 24 ms
// Memory Usage: 3.8 MB
pub fn xor_queries(mut arr: Vec<i32>, queries: Vec<Vec<i32>>) -> Vec<i32> {
let n = arr.len();
for i in 1..n {
arr[i] ^= arr[i - 1];
}
let mut res = Vec::new();
for query in queries {
let l = query[0] as usize;
let r = query[1] as usize;
let x = if l > 0 { arr[r] ^ arr[l - 1] } else { arr[r] };
res.push(x);
}
res
}
// bit_manipulation
#[test]
fn test1_1310() {
use leetcode_prelude::vec2;
assert_eq!(
xor_queries(vec![1, 3, 4, 8], vec2![[0, 1], [1, 2], [0, 3], [3, 3]]),
vec![2, 7, 14, 8]
);
assert_eq!(
xor_queries(vec![4, 8, 2, 10], vec2![[2, 3], [1, 3], [0, 0], [0, 3]]),
vec![8, 0, 4, 4]
);
}
| 26.580645 | 78 | 0.48665 |
90152a73224fbc46b2c5dd79bdfc05b6e9cadb68 | 155 | mod modules;
mod spec;
use lazy_static::lazy_static;
use modules::TestLock;
lazy_static! {
pub(crate) static ref LOCK: TestLock = TestLock::new();
}
| 15.5 | 59 | 0.716129 |
e4cea50cba2728d655cee64b65a26a636a9493d0 | 3,684 | use num_traits::AsPrimitive;
use serde::{Deserialize, Serialize};
/// This struct provides some basic number statistics.
///
/// All operations run in constant time.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct NumberStatistics {
min_value: f64,
max_value: f64,
value_count: usize,
value_nan_count: usize,
mean_value: f64,
m2: f64,
}
impl Default for NumberStatistics {
fn default() -> Self {
Self {
min_value: f64::MAX,
max_value: f64::MIN,
value_count: 0,
value_nan_count: 0,
mean_value: 0.0,
m2: 0.0,
}
}
}
impl NumberStatistics {
#[inline]
pub fn add<V>(&mut self, value: V)
where
V: AsPrimitive<f64>,
{
let value = value.as_();
if value.is_nan() {
self.value_nan_count += 1;
return;
}
self.min_value = f64::min(self.min_value, value);
self.max_value = f64::max(self.max_value, value);
// Welford's algorithm
self.value_count += 1;
let delta = value - self.mean_value;
self.mean_value += delta / (self.value_count as f64);
let delta2 = value - self.mean_value;
self.m2 += delta * delta2;
}
#[inline]
pub fn add_no_data(&mut self) {
self.value_nan_count += 1;
}
#[inline]
pub fn add_no_data_batch(&mut self, batch_size: usize) {
self.value_nan_count += batch_size;
}
pub fn count(&self) -> usize {
self.value_count
}
pub fn nan_count(&self) -> usize {
self.value_nan_count
}
pub fn min(&self) -> f64 {
if self.value_count > 0 {
self.min_value
} else {
f64::NAN
}
}
pub fn max(&self) -> f64 {
if self.value_count > 0 {
self.max_value
} else {
f64::NAN
}
}
pub fn mean(&self) -> f64 {
if self.value_count > 0 {
self.mean_value
} else {
f64::NAN
}
}
pub fn var(&self) -> f64 {
if self.value_count > 0 {
self.m2 / (self.value_count as f64)
} else {
f64::NAN
}
}
pub fn std_dev(&self) -> f64 {
if self.value_count > 1 {
f64::sqrt(self.m2 / (self.value_count as f64))
} else {
f64::NAN
}
}
pub fn sample_std_dev(&self) -> f64 {
if self.value_count > 1 {
f64::sqrt(self.m2 / ((self.value_count - 1) as f64))
} else {
f64::NAN
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[allow(clippy::float_cmp)]
fn example_data() {
let mut number_statistics = NumberStatistics::default();
for &v in &[2, 4, 4, 4, 5, 5, 7, 9] {
number_statistics.add(v);
}
assert_eq!(number_statistics.count(), 8);
assert_eq!(number_statistics.nan_count(), 0);
assert_eq!(number_statistics.min(), 2.);
assert_eq!(number_statistics.max(), 9.);
assert_eq!(number_statistics.mean(), 5.);
assert_eq!(number_statistics.var(), 4.);
assert_eq!(number_statistics.std_dev(), 2.);
assert_eq!(number_statistics.sample_std_dev(), 2.138_089_935_299_395);
}
#[test]
fn nan_data() {
let mut number_statistics = NumberStatistics::default();
number_statistics.add(1);
number_statistics.add(f64::NAN);
number_statistics.add_no_data();
assert_eq!(number_statistics.count(), 1);
assert_eq!(number_statistics.nan_count(), 2);
}
}
| 23.615385 | 78 | 0.536916 |
c150e8d29fbfd3acba6826489a3af1ae7aa22610 | 5,818 | use tokio::fs::File;
#[cfg(unix)]
use crate::unix::async_impl::tokio_impl as sys;
#[cfg(windows)]
use crate::windows::async_impl::tokio_impl as sys;
async_file_ext!(File, "tokio::fs::File");
#[cfg(test)]
mod test {
extern crate tempdir;
extern crate test;
use tokio::fs;
use tokio::io::{SeekFrom, AsyncWriteExt, AsyncReadExt, AsyncSeekExt};
use crate::{allocation_granularity, available_space, tokio::AsyncFileExt, free_space, lock_contended_error, total_space};
/// Tests file duplication.
#[tokio::test]
async fn duplicate() {
let tempdir = tempdir::TempDir::new("fs4").unwrap();
let path = tempdir.path().join("fs4");
let mut file1 =
fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap();
let mut file2 = file1.duplicate().unwrap();
// Write into the first file and then drop it.
file1.write_all(b"foo").await.unwrap();
drop(file1);
let mut buf = vec![];
// Read from the second file; since the position is shared it will already be at EOF.
file2.read_to_end(&mut buf).await.unwrap();
assert_eq!(0, buf.len());
// Rewind and read.
file2.seek(SeekFrom::Start(0)).await.unwrap();
file2.read_to_end(&mut buf).await.unwrap();
assert_eq!(&buf, &b"foo");
}
/// Tests shared file lock operations.
#[tokio::test]
async fn lock_shared() {
let tempdir = tempdir::TempDir::new("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap();
let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap();
let file3 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap();
// Concurrent shared access is OK, but not shared and exclusive.
file1.lock_shared().unwrap();
file2.lock_shared().unwrap();
assert_eq!(file3.try_lock_exclusive().unwrap_err().kind(),
lock_contended_error().kind());
file1.unlock().unwrap();
assert_eq!(file3.try_lock_exclusive().unwrap_err().kind(),
lock_contended_error().kind());
// Once all shared file locks are dropped, an exclusive lock may be created;
file2.unlock().unwrap();
file3.lock_exclusive().unwrap();
}
/// Tests exclusive file lock operations.
#[tokio::test]
async fn lock_exclusive() {
let tempdir = tempdir::TempDir::new("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap();
let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap();
// No other access is possible once an exclusive lock is created.
file1.lock_exclusive().unwrap();
assert_eq!(file2.try_lock_exclusive().unwrap_err().kind(),
lock_contended_error().kind());
assert_eq!(file2.try_lock_shared().unwrap_err().kind(),
lock_contended_error().kind());
// Once the exclusive lock is dropped, the second file is able to create a lock.
file1.unlock().unwrap();
file2.lock_exclusive().unwrap();
}
/// Tests that a lock is released after the file that owns it is dropped.
#[tokio::test]
async fn lock_cleanup() {
let tempdir = tempdir::TempDir::new("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap();
let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap();
file1.lock_exclusive().unwrap();
assert_eq!(file2.try_lock_shared().unwrap_err().kind(),
lock_contended_error().kind());
// Drop file1; the lock should be released.
drop(file1);
file2.lock_shared().unwrap();
}
/// Tests file allocation.
#[tokio::test]
async fn allocate() {
let tempdir = tempdir::TempDir::new("fs4").unwrap();
let path = tempdir.path().join("fs4");
let file = fs::OpenOptions::new().write(true).create(true).open(&path).await.unwrap();
let blksize = allocation_granularity(&path).unwrap();
// New files are created with no allocated size.
assert_eq!(0, file.allocated_size().await.unwrap());
assert_eq!(0, file.metadata().await.unwrap().len());
// Allocate space for the file, checking that the allocated size steps
// up by block size, and the file length matches the allocated size.
file.allocate(2 * blksize - 1).await.unwrap();
assert_eq!(2 * blksize, file.allocated_size().await.unwrap());
assert_eq!(2 * blksize - 1, file.metadata().await.unwrap().len());
// Truncate the file, checking that the allocated size steps down by
// block size.
file.set_len(blksize + 1).await.unwrap();
assert_eq!(2 * blksize, file.allocated_size().await.unwrap());
assert_eq!(blksize + 1, file.metadata().await.unwrap().len());
}
/// Checks filesystem space methods.
#[tokio::test]
async fn filesystem_space() {
let tempdir = tempdir::TempDir::new("fs4").unwrap();
let total_space = total_space(&tempdir.path()).unwrap();
let free_space = free_space(&tempdir.path()).unwrap();
let available_space = available_space(&tempdir.path()).unwrap();
assert!(total_space > free_space);
assert!(total_space > available_space);
assert!(available_space <= free_space);
}
} | 40.685315 | 125 | 0.619113 |
623d07bff295cc019dd70948e084d7fd4abed0fe | 142 | use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct GameMode {
pub id: i32,
pub name: String,
}
| 17.75 | 40 | 0.683099 |
03879c80d645e8ff321288360da66ab3ddef9a0a | 677 |
use config;
use crate::db_config::DbConfig;
#[derive(Debug)]
pub struct AppConfig {
pub config: config::Config
}
impl AppConfig {
pub fn new() -> AppConfig {
let mut config = config::Config::default();
config
.merge(config::File::with_name("src/resources/config.json")).unwrap();
AppConfig { config: config }
}
pub fn db_config( &self ) -> DbConfig {
let url = self.config.get_str("datasource.url").unwrap();
let username = self.config.get_str("datasource.username").unwrap();
let password = self.config.get_str("datasource.password").unwrap();
DbConfig::new( url, username, password )
}
} | 28.208333 | 78 | 0.629247 |
0a47acdc9b753a1b568f75e72d99c37df0e29403 | 5,387 | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn vdbpsadbw_1() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM7)), operand3: Some(Direct(XMM2)), operand4: Some(Literal8(93)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None }, &[98, 243, 69, 142, 66, 202, 93], OperandSize::Dword)
}
#[test]
fn vdbpsadbw_2() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM3)), operand3: Some(IndirectScaledDisplaced(EDI, Four, 1875484248, Some(OperandSize::Xmmword), None)), operand4: Some(Literal8(97)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None }, &[98, 243, 101, 140, 66, 4, 189, 88, 158, 201, 111, 97], OperandSize::Dword)
}
#[test]
fn vdbpsadbw_3() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM13)), operand2: Some(Direct(XMM21)), operand3: Some(Direct(XMM21)), operand4: Some(Literal8(109)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None }, &[98, 51, 85, 132, 66, 237, 109], OperandSize::Qword)
}
#[test]
fn vdbpsadbw_4() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(XMM22)), operand2: Some(Direct(XMM6)), operand3: Some(IndirectScaledDisplaced(RCX, Four, 341913354, Some(OperandSize::Xmmword), None)), operand4: Some(Literal8(3)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 227, 77, 139, 66, 52, 141, 10, 47, 97, 20, 3], OperandSize::Qword)
}
#[test]
fn vdbpsadbw_5() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM7)), operand2: Some(Direct(YMM0)), operand3: Some(Direct(YMM0)), operand4: Some(Literal8(89)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 243, 125, 175, 66, 248, 89], OperandSize::Dword)
}
#[test]
fn vdbpsadbw_6() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM6)), operand2: Some(Direct(YMM0)), operand3: Some(IndirectScaledDisplaced(ESI, Four, 1441455171, Some(OperandSize::Ymmword), None)), operand4: Some(Literal8(82)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 243, 125, 170, 66, 52, 181, 67, 220, 234, 85, 82], OperandSize::Dword)
}
#[test]
fn vdbpsadbw_7() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM13)), operand2: Some(Direct(YMM29)), operand3: Some(Direct(YMM22)), operand4: Some(Literal8(51)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 51, 21, 162, 66, 238, 51], OperandSize::Qword)
}
#[test]
fn vdbpsadbw_8() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(YMM28)), operand2: Some(Direct(YMM11)), operand3: Some(IndirectScaledIndexed(RDX, RDX, Eight, Some(OperandSize::Ymmword), None)), operand4: Some(Literal8(93)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None }, &[98, 99, 37, 173, 66, 36, 210, 93], OperandSize::Qword)
}
#[test]
fn vdbpsadbw_9() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM1)), operand2: Some(Direct(ZMM1)), operand3: Some(Direct(ZMM4)), operand4: Some(Literal8(36)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 243, 117, 203, 66, 204, 36], OperandSize::Dword)
}
#[test]
fn vdbpsadbw_10() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM2)), operand2: Some(Direct(ZMM0)), operand3: Some(IndirectScaledIndexed(ESI, EAX, Eight, Some(OperandSize::Zmmword), None)), operand4: Some(Literal8(73)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 243, 125, 207, 66, 20, 198, 73], OperandSize::Dword)
}
#[test]
fn vdbpsadbw_11() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM26)), operand2: Some(Direct(ZMM7)), operand3: Some(Direct(ZMM27)), operand4: Some(Literal8(123)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K3), broadcast: None }, &[98, 3, 69, 203, 66, 211, 123], OperandSize::Qword)
}
#[test]
fn vdbpsadbw_12() {
run_test(&Instruction { mnemonic: Mnemonic::VDBPSADBW, operand1: Some(Direct(ZMM12)), operand2: Some(Direct(ZMM25)), operand3: Some(IndirectScaledIndexedDisplaced(RDX, RBX, Eight, 938432062, Some(OperandSize::Zmmword), None)), operand4: Some(Literal8(83)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None }, &[98, 115, 53, 198, 66, 164, 218, 62, 86, 239, 55, 83], OperandSize::Qword)
}
| 78.072464 | 461 | 0.709115 |
e926affcd6d6c87d9f8a525efb611aef838f2748 | 8,794 | //! Volume API: Create and manage persistent storage that can be attached to containers.
use http::request::Builder;
use hyper::{Body, Method};
use serde::Serialize;
use std::cmp::Eq;
use std::collections::HashMap;
use std::hash::Hash;
use super::Docker;
use crate::errors::Error;
use crate::models::*;
/// Parameters used in the [List Volume API](Docker::list_volumes())
#[derive(Debug, Clone, Default, Serialize)]
pub struct ListVolumesOptions<T>
where
T: Into<String> + Eq + Hash + Serialize,
{
/// JSON encoded value of the filters (a `map[string][]string`) to process on the volumes list. Available filters:
/// - `dangling=<boolean>` When set to `true` (or `1`), returns all volumes that are not in use by a container. When set to `false` (or `0`), only volumes that are in use by one or more containers are returned.
/// - `driver=<volume-driver-name>` Matches volumes based on their driver.
/// - `label=<key>` or `label=<key>:<value>` Matches volumes based on the presence of a `label` alone or a `label` and a value.
/// - `name=<volume-name>` Matches all or part of a volume name.
#[serde(serialize_with = "crate::docker::serialize_as_json")]
pub filters: HashMap<T, Vec<T>>,
}
/// Volume configuration used in the [Create Volume
/// API](Docker::create_volume())
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct CreateVolumeOptions<T>
where
T: Into<String> + Eq + Hash + Serialize,
{
/// The new volume's name. If not specified, Docker generates a name.
pub name: T,
/// Name of the volume driver to use.
pub driver: T,
/// A mapping of driver options and values. These options are passed directly to the driver and
/// are driver specific.
pub driver_opts: HashMap<T, T>,
/// User-defined key/value metadata.
pub labels: HashMap<T, T>,
}
/// Parameters used in the [Remove Volume API](super::Docker::remove_volume())
#[derive(Debug, Clone, Copy, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoveVolumeOptions {
/// Force the removal of the volume.
pub force: bool,
}
/// Parameters used in the [Prune Volumes API](Docker::prune_volumes())
///
/// ## Examples
///
/// ```rust
/// use bollard::volume::PruneVolumesOptions;
///
/// use std::collections::HashMap;
///
/// let mut filters = HashMap::new();
/// filters.insert("label!", vec!["maintainer=some_maintainer"]);
///
/// PruneVolumesOptions{
/// filters
/// };
/// ```
///
/// ```rust
/// # use bollard::volume::PruneVolumesOptions;
/// # use std::default::Default;
///
/// PruneVolumesOptions::<&str>{
/// ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Default, Serialize)]
pub struct PruneVolumesOptions<T>
where
T: Into<String> + Eq + Hash + Serialize,
{
/// Filters to process on the prune list, encoded as JSON.
/// - `label` (`label=<key>`, `label=<key>=<value>`, `label!=<key>`, or
/// `label!=<key>=<value>`) Prune volumes with (or without, in case `label!=...` is used) the
/// specified labels.
#[serde(serialize_with = "crate::docker::serialize_as_json")]
pub filters: HashMap<T, Vec<T>>,
}
impl Docker {
/// ---
///
/// # List volumes
///
/// # Arguments
///
/// - [List Volumes Options](ListVolumesOptions) struct.
///
/// # Returns
///
/// - A [Volume List Response]VolumeListResponse) struct, wrapped in a
/// Future.
///
/// # Examples
///
/// ```rust
/// # use bollard::Docker;
/// # let docker = Docker::connect_with_http_defaults().unwrap();
///
/// use bollard::volume::ListVolumesOptions;
///
/// use std::collections::HashMap;
///
/// let mut filters = HashMap::new();
/// filters.insert("dangling", vec!("1"));
///
/// let options = ListVolumesOptions {
/// filters,
/// };
///
/// docker.list_volumes(Some(options));
/// ```
pub async fn list_volumes<T>(
&self,
options: Option<ListVolumesOptions<T>>,
) -> Result<VolumeListResponse, Error>
where
T: Into<String> + Eq + Hash + Serialize,
{
let url = "/volumes";
let req = self.build_request(
&url,
Builder::new().method(Method::GET),
options,
Ok(Body::empty()),
);
self.process_into_value(req).await
}
/// ---
///
/// # Create Volume
///
/// Create a new volume.
///
/// # Arguments
///
/// - [Create Volume Options](CreateVolumeOptions) struct.
///
/// # Returns
///
/// - A [Volume](Volume) struct, wrapped in a
/// Future.
///
/// # Examples
///
/// ```rust
/// # use bollard::Docker;
/// # let docker = Docker::connect_with_http_defaults().unwrap();
///
/// use bollard::volume::CreateVolumeOptions;
///
/// use std::default::Default;
///
/// let config = CreateVolumeOptions {
/// name: "certs",
/// ..Default::default()
/// };
///
/// docker.create_volume(config);
/// ```
pub async fn create_volume<T>(&self, config: CreateVolumeOptions<T>) -> Result<Volume, Error>
where
T: Into<String> + Eq + Hash + Serialize,
{
let url = "/volumes/create";
let req = self.build_request(
&url,
Builder::new().method(Method::POST),
None::<String>,
Docker::serialize_payload(Some(config)),
);
self.process_into_value(req).await
}
/// ---
///
/// # Inspect a Volume
///
/// # Arguments
///
/// - Volume name as a string slice.
///
/// # Returns
///
/// - A [Volume](Volume) struct, wrapped in a
/// Future.
///
/// # Examples
///
/// ```rust
/// # use bollard::Docker;
/// # let docker = Docker::connect_with_http_defaults().unwrap();
///
/// docker.inspect_volume("my_volume_name");
/// ```
pub async fn inspect_volume(&self, volume_name: &str) -> Result<Volume, Error> {
let url = format!("/volumes/{}", volume_name);
let req = self.build_request(
&url,
Builder::new().method(Method::GET),
None::<String>,
Ok(Body::empty()),
);
self.process_into_value(req).await
}
/// ---
///
/// # Remove a Volume
///
/// # Arguments
///
/// - Volume name as a string slice.
///
/// # Arguments
///
/// - [Remove Volume Options](RemoveVolumeOptions) struct.
///
/// # Returns
///
/// - unit type `()`, wrapped in a Future.
///
/// # Examples
///
/// ```rust
/// # use bollard::Docker;
/// # let docker = Docker::connect_with_http_defaults().unwrap();
///
/// use bollard::volume::RemoveVolumeOptions;
///
/// let options = RemoveVolumeOptions {
/// force: true,
/// };
///
/// docker.remove_volume("my_volume_name", Some(options));
/// ```
pub async fn remove_volume(
&self,
volume_name: &str,
options: Option<RemoveVolumeOptions>,
) -> Result<(), Error> {
let url = format!("/volumes/{}", volume_name);
let req = self.build_request(
&url,
Builder::new().method(Method::DELETE),
options,
Ok(Body::empty()),
);
self.process_into_unit(req).await
}
/// ---
///
/// # Prune Volumes
///
/// Delete unused volumes.
///
/// # Arguments
///
/// - A [Prune Volumes Options](PruneVolumesOptions) struct.
///
/// # Returns
///
/// - A [Volume Prune Response](VolumePruneResponse) struct.
///
/// # Examples
///
/// ```rust
/// # use bollard::Docker;
/// # let docker = Docker::connect_with_http_defaults().unwrap();
///
/// use bollard::volume::PruneVolumesOptions;
///
/// use std::collections::HashMap;
///
/// let mut filters = HashMap::new();
/// filters.insert("label", vec!["maintainer=some_maintainer"]);
///
/// let options = PruneVolumesOptions {
/// filters,
/// };
///
/// docker.prune_volumes(Some(options));
/// ```
pub async fn prune_volumes<T>(
&self,
options: Option<PruneVolumesOptions<T>>,
) -> Result<VolumePruneResponse, Error>
where
T: Into<String> + Eq + Hash + Serialize,
{
let url = "/volumes/prune";
let req = self.build_request(
&url,
Builder::new().method(Method::POST),
options,
Ok(Body::empty()),
);
self.process_into_value(req).await
}
}
| 26.810976 | 215 | 0.552991 |
eff0af335c8f29bfc3d4748977c65320d7eb4595 | 10,586 | //! Compress the body of a response.
use std::io::{Error as IoError, ErrorKind};
use async_compression::tokio::bufread::{BrotliEncoder, DeflateEncoder, GzipEncoder};
use tokio_stream::{self, StreamExt};
use tokio_util::io::{ReaderStream, StreamReader};
use salvo_core::async_trait;
use salvo_core::http::header::{HeaderValue, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE};
use salvo_core::http::response::Body;
use salvo_core::prelude::*;
/// CompressionAlgo
#[derive(Clone, Copy, Debug)]
pub enum CompressionAlgo {
/// Brotli
Brotli,
/// Deflate
Deflate,
/// Gzip
Gzip,
}
impl From<CompressionAlgo> for HeaderValue {
#[inline]
fn from(algo: CompressionAlgo) -> Self {
match algo {
CompressionAlgo::Gzip => HeaderValue::from_static("gzip"),
CompressionAlgo::Deflate => HeaderValue::from_static("deflate"),
CompressionAlgo::Brotli => HeaderValue::from_static("br"),
}
}
}
/// CompressionHandler
#[derive(Clone, Debug)]
pub struct CompressionHandler {
algo: CompressionAlgo,
content_types: Vec<String>,
min_length: usize,
}
impl Default for CompressionHandler {
#[inline]
fn default() -> Self {
Self::new(CompressionAlgo::Gzip)
}
}
impl CompressionHandler {
/// Create a new `CompressionHandler`.
#[inline]
pub fn new(algo: CompressionAlgo) -> Self {
CompressionHandler {
algo,
content_types: vec![
"text/".into(),
"application/javascript".into(),
"application/json".into(),
"application/xml".into(),
"application/rss+xml".into(),
"image/svg+xml".into(),
],
min_length: 1024,
}
}
/// Create a new `CompressionHandler` with algo.
#[inline]
pub fn with_algo(mut self, algo: CompressionAlgo) -> Self {
self.algo = algo;
self
}
/// get min_length.
#[inline]
pub fn min_length(&mut self) -> usize {
self.min_length
}
/// Set minimum compression size, if body less than this value, no compression
/// default is 1kb
#[inline]
pub fn set_min_length(&mut self, size: usize) {
self.min_length = size;
}
/// Create a new `CompressionHandler` with min_length.
#[inline]
pub fn with_min_length(mut self, min_length: usize) -> Self {
self.min_length = min_length;
self
}
/// Get content type list reference.
#[inline]
pub fn content_types(&self) -> &Vec<String> {
&self.content_types
}
/// Get content type list mutable reference.
#[inline]
pub fn content_types_mut(&mut self) -> &mut Vec<String> {
&mut self.content_types
}
/// Create a new `CompressionHandler` with content types list.
#[inline]
pub fn with_content_types(mut self, content_types: &[String]) -> Self {
self.content_types = content_types.to_vec();
self
}
}
#[async_trait]
impl Handler for CompressionHandler {
async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
ctrl.call_next(req, depot, res).await;
if ctrl.is_ceased() {
return;
}
let content_type = res
.headers()
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or_default();
if content_type.is_empty()
|| res.body().is_none()
|| !self.content_types.iter().any(|c| content_type.starts_with(&**c))
{
return;
}
if let Some(body) = res.take_body() {
match body {
Body::Empty => {
return;
}
Body::Bytes(body) => {
if body.len() < self.min_length {
res.set_body(Some(Body::Bytes(body)));
return;
}
let reader = StreamReader::new(tokio_stream::once(Result::<_, IoError>::Ok(body)));
match self.algo {
CompressionAlgo::Gzip => {
let stream = ReaderStream::new(GzipEncoder::new(reader));
if let Err(e) = res.streaming(stream) {
tracing::error!(error = ?e, "request streaming error");
}
}
CompressionAlgo::Deflate => {
let stream = ReaderStream::new(DeflateEncoder::new(reader));
if let Err(e) = res.streaming(stream) {
tracing::error!(error = ?e, "request streaming error");
}
}
CompressionAlgo::Brotli => {
let stream = ReaderStream::new(BrotliEncoder::new(reader));
if let Err(e) = res.streaming(stream) {
tracing::error!(error = ?e, "request streaming error");
}
}
}
}
Body::Stream(body) => {
let body = body.map(|item| item.map_err(|_| ErrorKind::Other));
let reader = StreamReader::new(body);
match self.algo {
CompressionAlgo::Gzip => {
let stream = ReaderStream::new(GzipEncoder::new(reader));
if let Err(e) = res.streaming(stream) {
tracing::error!(error = ?e, "request streaming error");
}
}
CompressionAlgo::Deflate => {
let stream = ReaderStream::new(DeflateEncoder::new(reader));
if let Err(e) = res.streaming(stream) {
tracing::error!(error = ?e, "request streaming error");
}
}
CompressionAlgo::Brotli => {
let stream = ReaderStream::new(BrotliEncoder::new(reader));
if let Err(e) = res.streaming(stream) {
tracing::error!(error = ?e, "request streaming error");
}
}
}
}
}
}
res.headers_mut().remove(CONTENT_LENGTH);
res.headers_mut().append(CONTENT_ENCODING, self.algo.into());
}
}
/// Create a middleware that compresses the [`Body`](salvo_core::http::response::Body)
/// using gzip, adding `content-encoding: gzip` to the Response's [`HeaderMap`](hyper::HeaderMap)
///
/// # Example
///
/// ```
/// use salvo_core::prelude::*;
/// use salvo_extra::compression;
/// use salvo_extra::serve_static::FileHandler;
///
/// let router = Router::new()
/// .hoop(compression::gzip())
/// .get(FileHandler::new("./README.md"));
/// ```
pub fn gzip() -> CompressionHandler {
CompressionHandler::new(CompressionAlgo::Gzip)
}
/// Create a middleware that compresses the [`Body`](salvo_core::http::response::Body)
/// using deflate, adding `content-encoding: deflate` to the Response's [`HeaderMap`](hyper::HeaderMap)
///
/// # Example
///
/// ```
/// use salvo_core::prelude::*;
/// use salvo_extra::compression;
/// use salvo_extra::serve_static::FileHandler;
///
/// let router = Router::new()
/// .hoop(compression::deflate())
/// .get(FileHandler::new("./README.md"));
/// ```
pub fn deflate() -> CompressionHandler {
CompressionHandler::new(CompressionAlgo::Deflate)
}
/// Create a middleware that compresses the [`Body`](salvo_core::http::response::Body)
/// using brotli, adding `content-encoding: br` to the Response's [`HeaderMap`](hyper::HeaderMap)
///
/// # Example
///
/// ```
/// use salvo_core::prelude::*;
/// use salvo_extra::compression;
/// use salvo_extra::serve_static::FileHandler;
///
/// let router = Router::new()
/// .hoop(compression::brotli())
/// .get(FileHandler::new("./README.md"));
/// ```
pub fn brotli() -> CompressionHandler {
CompressionHandler::new(CompressionAlgo::Brotli)
}
#[cfg(test)]
mod tests {
use salvo_core::hyper;
use salvo_core::prelude::*;
use super::*;
#[fn_handler]
async fn hello() -> &'static str {
"hello"
}
#[tokio::test]
async fn test_gzip() {
let comp_handler = gzip().with_min_length(1);
let router = Router::with_hoop(comp_handler).push(Router::with_path("hello").get(hello));
let service = Service::new(router);
let req: Request = hyper::Request::builder()
.method("GET")
.uri("http://127.0.0.1:7979/hello")
.body(hyper::Body::empty())
.unwrap()
.into();
let mut res = service.handle(req).await;
assert_eq!(res.headers().get("content-encoding").unwrap(), "gzip");
let content = res.take_text().await.unwrap();
assert_eq!(content, "hello");
}
#[tokio::test]
async fn test_brotli() {
let comp_handler = brotli().with_min_length(1);
let router = Router::with_hoop(comp_handler).push(Router::with_path("hello").get(hello));
let service = Service::new(router);
let req: Request = hyper::Request::builder()
.method("GET")
.uri("http://127.0.0.1:7979/hello")
.body(hyper::Body::empty())
.unwrap()
.into();
let mut res = service.handle(req).await;
assert_eq!(res.headers().get("content-encoding").unwrap(), "br");
let content = res.take_text().await.unwrap();
assert_eq!(content, "hello");
}
#[tokio::test]
async fn test_deflate() {
let comp_handler = deflate().with_min_length(1);
let router = Router::with_hoop(comp_handler).push(Router::with_path("hello").get(hello));
let service = Service::new(router);
let request = hyper::Request::builder()
.method("GET")
.uri("http://127.0.0.1:7979/hello");
let req: Request = request.body(hyper::Body::empty()).unwrap().into();
let mut res = service.handle(req).await;
assert_eq!(res.headers().get("content-encoding").unwrap(), "deflate");
let content = res.take_text().await.unwrap();
assert_eq!(content, "hello");
}
}
| 34.2589 | 107 | 0.535708 |
03bd3e45a83b53db72ce0f49c5790d9af45a04f0 | 7,794 | use std::collections::HashMap;
use na::{Isometry2, Vector2};
use ncollide::shape::{self, Shape};
use nphysics::force_generator::DefaultForceGeneratorSet;
use nphysics::joint::DefaultJointConstraintSet;
use nphysics::material::BasicMaterial;
use nphysics::object::{
Collider, ColliderAnchor, DefaultBodyHandle, DefaultBodySet, DefaultColliderSet, RigidBody,
};
use nphysics::world::DefaultMechanicalWorld;
use std::f32;
use wrapped2d::b2;
use wrapped2d::user_data::NoUserData;
fn na_vec_to_b2_vec(v: &Vector2<f32>) -> b2::Vec2 {
b2::Vec2 { x: v.x, y: v.y }
}
fn b2_vec_to_na_vec(v: &b2::Vec2) -> Vector2<f32> {
Vector2::new(v.x, v.y)
}
fn b2_transform_to_na_isometry(v: &b2::Transform) -> Isometry2<f32> {
Isometry2::new(b2_vec_to_na_vec(&v.pos), v.rot.angle())
}
pub struct Box2dWorld {
world: b2::World<NoUserData>,
nphysics2box2d: HashMap<DefaultBodyHandle, b2::BodyHandle>,
}
impl Box2dWorld {
pub fn from_nphysics(
mechanical_world: &DefaultMechanicalWorld<f32>,
bodies: &DefaultBodySet<f32>,
colliders: &DefaultColliderSet<f32>,
_joint_constraints: &DefaultJointConstraintSet<f32>,
_force_generators: &DefaultForceGeneratorSet<f32>,
) -> Self {
let world = b2::World::new(&na_vec_to_b2_vec(&mechanical_world.gravity));
let mut res = Box2dWorld {
world,
nphysics2box2d: HashMap::new(),
};
res.insert_bodies(bodies, colliders);
res
}
fn insert_bodies(&mut self, bodies: &DefaultBodySet<f32>, colliders: &DefaultColliderSet<f32>) {
for (handle, body) in bodies.iter() {
let part = body.part(0).unwrap();
let pos = part.position();
let vel = part.velocity();
let body_type = if body.is_static() {
b2::BodyType::Static
} else {
b2::BodyType::Dynamic
};
let linear_damping;
let angular_damping;
if let Some(rb) = body.downcast_ref::<RigidBody<f32>>() {
linear_damping = rb.linear_damping();
angular_damping = rb.angular_damping();
} else {
linear_damping = 0.0;
angular_damping = 0.0;
}
let def = b2::BodyDef {
body_type,
position: na_vec_to_b2_vec(&pos.translation.vector),
angle: pos.rotation.angle(),
linear_velocity: na_vec_to_b2_vec(&vel.linear),
angular_velocity: vel.angular,
linear_damping,
angular_damping,
..b2::BodyDef::new()
};
let b2_handle = self.world.create_body(&def);
self.nphysics2box2d.insert(handle, b2_handle);
}
for (_, collider) in colliders.iter() {
match collider.anchor() {
ColliderAnchor::OnBodyPart { body_part, .. } => {
if let Some(b2_handle) = self.nphysics2box2d.get(&body_part.0) {
let mut b2_body = self.world.body_mut(*b2_handle);
if collider.is_ccd_enabled() {
b2_body.set_bullet(true);
}
Self::create_fixtures(
collider,
collider.shape(),
&collider.position_wrt_body(),
&mut *b2_body,
);
}
}
ColliderAnchor::OnDeformableBody { .. } => {
println!("Deformable bodies are not supported by Box2D.")
}
}
}
}
fn create_fixtures(
collider: &Collider<f32, DefaultBodyHandle>,
shape: &dyn Shape<f32>,
dpos: &Isometry2<f32>,
body: &mut b2::MetaBody<NoUserData>,
) {
let center = na_vec_to_b2_vec(&dpos.translation.vector);
let mut fixture_def = b2::FixtureDef::new();
fixture_def.restitution = 0.0;
fixture_def.friction = 0.5;
fixture_def.density = collider.density();
fixture_def.is_sensor = collider.is_sensor();
fixture_def.filter = b2::Filter::new();
if let Some(material) = collider.material().downcast_ref::<BasicMaterial<f32>>() {
fixture_def.restitution = material.restitution;
fixture_def.friction = material.friction;
}
if let Some(_s) = shape.as_shape::<shape::Plane<f32>>() {
} else if let Some(s) = shape.as_shape::<shape::Ball<f32>>() {
let mut b2_shape = b2::CircleShape::new();
b2_shape.set_radius(s.radius());
b2_shape.set_position(center);
body.create_fixture(&b2_shape, &mut fixture_def);
} else if let Some(s) = shape.as_shape::<shape::Cuboid<f32>>() {
let half_extents = s.half_extents();
let b2_shape = b2::PolygonShape::new_oriented_box(
half_extents.x,
half_extents.y,
¢er,
dpos.rotation.angle(),
);
body.create_fixture(&b2_shape, &mut fixture_def);
} else if let Some(_s) = shape.as_shape::<shape::Capsule<f32>>() {
// let geom = PhysicsGeometry::from(&ColliderDesc::Capsule(s.radius(), s.height()));
// result.push((geom, Isometry3::rotation(Vector3::z() * f32::consts::PI / r!(2.0))))
} else if let Some(cp) = shape.as_shape::<shape::Compound<f32>>() {
for (shift, shape) in cp.shapes() {
Self::create_fixtures(collider, &**shape, &(dpos * shift), body)
}
} else if let Some(ch) = shape.as_shape::<shape::ConvexPolygon<f32>>() {
let points: Vec<_> = ch
.points()
.iter()
.map(|p| dpos * p)
.map(|p| na_vec_to_b2_vec(&p.coords))
.collect();
let b2_shape = b2::PolygonShape::new_with(&points);
body.create_fixture(&b2_shape, &mut fixture_def);
} else if let Some(_s) = shape.as_shape::<shape::Polyline<f32>>() {
} else if let Some(_s) = shape.as_shape::<shape::HeightField<f32>>() {
}
}
pub fn step(&mut self, mechanical_world: &mut DefaultMechanicalWorld<f32>) {
self.world
.set_continuous_physics(mechanical_world.integration_parameters.max_ccd_substeps != 0);
mechanical_world.counters.step_started();
self.world.step(
mechanical_world.integration_parameters.dt(),
mechanical_world
.integration_parameters
.max_velocity_iterations as i32,
mechanical_world
.integration_parameters
.max_position_iterations as i32,
);
mechanical_world.counters.step_completed();
}
pub fn sync(&self, _bodies: &mut DefaultBodySet<f32>, colliders: &mut DefaultColliderSet<f32>) {
for (_, collider) in colliders.iter_mut() {
match collider.anchor() {
ColliderAnchor::OnBodyPart {
body_part,
position_wrt_body_part,
} => {
if let Some(pb2_handle) = self.nphysics2box2d.get(&body_part.0) {
let body = self.world.body(*pb2_handle);
let pos = b2_transform_to_na_isometry(body.transform());
let new_pos = pos * position_wrt_body_part;
collider.set_position(new_pos)
}
}
ColliderAnchor::OnDeformableBody { .. } => {}
}
}
}
}
| 37.652174 | 108 | 0.547857 |
e5b87dec42de00348a323b3daf3bc31b55ca8a22 | 314 | extern crate trezor_client;
fn main() {
let trezors = trezor_client::find_devices(false).unwrap();
println!("Found {} devices: ", trezors.len());
for t in trezors.into_iter() {
println!("- {}", t);
{
let mut client = t.connect().unwrap();
println!("{:?}", client.initialize(None).unwrap());
}
}
}
| 22.428571 | 59 | 0.617834 |
1182e657848746487d3c90a8e14d8274fffe81d0 | 4,321 | use std::io::{Error, Read, Write};
use std::convert::TryInto;
use std::path::Path;
use std::fs::File;
use tetra::{Context};
use tetra::graphics::{Texture, DrawParams, Rectangle};
use tetra::math::Vec2;
pub type MapLayer = Vec<Vec<(u8, u8)>>;
pub struct Map {
pub base: MapLayer,
pub collide: MapLayer,
pub decor: MapLayer,
pub overlay: MapLayer,
}
impl Map {
pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
let mut file = File::open(path)?;
let width = read_u8(&mut file)?;
let height = read_u8(&mut file)?;
let base = load_layer(&mut file, width, height)?;
let collide = load_layer(&mut file, width, height)?;
let decor = load_layer(&mut file, width, height)?;
let overlay = load_layer(&mut file, width, height)?;
Ok(Map {
base,
collide,
decor,
overlay,
})
}
pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
let mut file = File::create(path)?;
let width = self.get_width();
let height = self.get_height();
file.write(&width.to_be_bytes())?;
file.write(&height.to_be_bytes())?;
save_layer(&mut file, &self.base)?;
save_layer(&mut file, &self.collide)?;
save_layer(&mut file, &self.decor)?;
save_layer(&mut file, &self.overlay)?;
Ok(())
}
pub fn add_row(&mut self, tile: (u8, u8)) {
let width = self.get_width().into();
self.base.push(vec![tile; width]);
self.collide.push(vec![(0, 0); width]);
self.decor.push(vec![(0, 0); width]);
self.overlay.push(vec![(0, 0); width]);
}
pub fn add_col(&mut self, tile: (u8, u8)) {
for row in &mut self.base {
row.push(tile);
}
for row in &mut self.collide {
row.push((0, 0));
}
for row in &mut self.decor {
row.push((0, 0));
}
for row in &mut self.overlay {
row.push((0, 0));
}
}
pub fn get_layer(&mut self, layer: &LayerType) -> &mut MapLayer {
match layer {
LayerType::Base => &mut self.base,
LayerType::Collide => &mut self.collide,
LayerType::Decor => &mut self.decor,
LayerType::Overlay => &mut self.overlay,
}
}
pub fn get_width(&self) -> u8 {
self.base[0].len().try_into().unwrap()
}
pub fn get_height(&self) -> u8 {
self.base.len().try_into().unwrap()
}
}
pub fn draw_layer(ctx: &mut Context, tiles: &MapLayer, tilemap: &Texture, scale: f32) {
for (row, cols) in tiles.iter().enumerate() {
for (col, tile) in cols.iter().enumerate() {
draw_tile(
ctx,
Vec2::new(col as f32 * 16.0 * scale, row as f32 * 16.0 * scale),
*tile,
tilemap,
scale,
)
}
}
}
pub fn draw_tile(
ctx: &mut Context,
position: Vec2<f32>,
tile: (u8, u8),
tilemap: &Texture,
scale: f32,
) {
if tile.0 != 0 {
tilemap.draw_region(
ctx,
Rectangle::new((tile.0 - 1) as f32 * 16.0, tile.1 as f32 * 16.0, 16.0, 16.0),
DrawParams::new()
.position(position)
.scale(Vec2::new(scale, scale)),
);
}
}
fn load_layer<R: Read>(reader: &mut R, width: u8, height: u8) -> Result<MapLayer, Error> {
let mut layer = Vec::new();
for _ in 0..height {
let mut row = Vec::new();
for _ in 0..width {
let x = read_u8(reader)?;
let y = read_u8(reader)?;
row.push((x, y));
}
layer.push(row);
}
Ok(layer)
}
fn save_layer<W: Write>(writer: &mut W, layer: &MapLayer) -> Result<(), Error> {
for row in layer {
for col in row {
writer.write(&col.0.to_be_bytes())?;
writer.write(&col.1.to_be_bytes())?;
}
}
Ok(())
}
fn read_u8<R: Read>(reader: &mut R) -> Result<u8, Error> {
let mut buf = [0];
reader.read_exact(&mut buf)?;
Ok(u8::from_be_bytes(buf))
}
#[derive(Debug)]
pub enum LayerType {
Base,
Collide,
Decor,
Overlay,
}
impl LayerType {
pub fn higher(&self) -> LayerType {
match self {
LayerType::Base => LayerType::Collide,
LayerType::Collide => LayerType::Decor,
LayerType::Decor => LayerType::Overlay,
LayerType::Overlay => LayerType::Overlay,
}
}
pub fn lower(&self) -> LayerType {
match self {
LayerType::Base => LayerType::Base,
LayerType::Collide => LayerType::Base,
LayerType::Decor => LayerType::Collide,
LayerType::Overlay => LayerType::Decor,
}
}
}
| 23.612022 | 90 | 0.579495 |
7595ecd322dc369c3c0692aee99750747590ffea | 6,447 | use crate::RecoveryResult;
use crate::{error::RecoveryError, RecoveryArgs};
use clap::Parser;
use ic_base_types::SubnetId;
use ic_types::ReplicaVersion;
use slog::{warn, Logger};
use std::net::IpAddr;
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
use crate::{NeuronArgs, Recovery, Step};
#[derive(Debug, Copy, Clone, EnumIter)]
pub enum StepType {
Halt,
DownloadState,
UpdateConfig,
ICReplay,
ValidateReplayOutput,
BlessVersion,
UpgradeVersion,
ProposeCup,
UploadState,
WaitForCUP,
Unhalt,
Cleanup,
}
#[derive(Parser)]
#[clap(version = "1.0")]
pub struct AppSubnetRecoveryArgs {
/// Id of the broken subnet
#[clap(long, parse(try_from_str=crate::util::subnet_id_from_str))]
pub subnet_id: SubnetId,
/// Replica version to upgrade the broken subnet to
#[clap(long, parse(try_from_str=::std::convert::TryFrom::try_from))]
pub upgrade_version: Option<ReplicaVersion>,
#[clap(long, multiple_values(true))]
/// Replace the members of the given subnet with these nodes
pub replacement_nodes: Option<Vec<String>>, //PrincipalId
/// Public ssh key to be deployed to the subnet for read only access
#[clap(long)]
pub pub_key: Option<String>,
/// IP address of the node to download the subnet state from
#[clap(long)]
pub download_node: Option<IpAddr>,
/// IP address of the node to upload the new subnet state to
#[clap(long)]
pub upload_node: Option<IpAddr>,
}
pub struct AppSubnetRecovery {
step_iterator: Box<dyn Iterator<Item = StepType>>,
success: bool,
pub params: AppSubnetRecoveryArgs,
recovery: Recovery,
logger: Logger,
}
impl AppSubnetRecovery {
pub fn new(
logger: Logger,
recovery_args: RecoveryArgs,
neuron_args: Option<NeuronArgs>,
subnet_args: AppSubnetRecoveryArgs,
) -> Self {
Self {
step_iterator: Box::new(StepType::iter()),
success: false,
params: subnet_args,
recovery: Recovery::new(logger.clone(), recovery_args, neuron_args)
.expect("Failed to init recovery"),
logger,
}
}
pub fn get_recovery_api(&self) -> &Recovery {
&self.recovery
}
pub fn success(&self) -> bool {
self.success
}
pub fn get_step_impl(&self, step_type: StepType) -> RecoveryResult<Box<dyn Step>> {
match step_type {
StepType::Halt => {
let keys = if let Some(pub_key) = &self.params.pub_key {
vec![pub_key.clone()]
} else {
vec![]
};
Ok(Box::new(self.recovery.halt_subnet(
self.params.subnet_id,
true,
&keys,
)))
}
StepType::DownloadState => {
if let Some(node_ip) = self.params.download_node {
Ok(Box::new(self.recovery.get_download_state_step(
node_ip,
self.params.pub_key.is_some(),
)))
} else {
Err(RecoveryError::StepSkipped)
}
}
StepType::UpdateConfig => Ok(Box::new(self.recovery.get_update_config_step())),
StepType::ICReplay => Ok(Box::new(
self.recovery.get_replay_step(self.params.subnet_id),
)),
StepType::ValidateReplayOutput => Ok(Box::new(
self.recovery
.get_validate_replay_step(self.params.subnet_id),
)),
StepType::UploadState => {
if let Some(node_ip) = self.params.upload_node {
Ok(Box::new(self.recovery.get_upload_and_restart_step(node_ip)))
} else {
Err(RecoveryError::StepSkipped)
}
}
StepType::BlessVersion => {
if let Some(upgrade_version) = &self.params.upgrade_version {
let step = self.recovery.bless_replica_version(upgrade_version)?;
Ok(Box::new(step))
} else {
Err(RecoveryError::StepSkipped)
}
}
StepType::UpgradeVersion => {
if let Some(upgrade_version) = &self.params.upgrade_version {
Ok(Box::new(self.recovery.update_subnet_replica_version(
self.params.subnet_id,
upgrade_version,
)))
} else {
Err(RecoveryError::StepSkipped)
}
}
StepType::ProposeCup => {
let (latest_height, state_hash) = self.recovery.get_replay_output()?;
let recovery_height = Recovery::get_recovery_height(latest_height);
let default = vec![];
Ok(Box::new(self.recovery.update_recovery_cup(
self.params.subnet_id,
recovery_height,
state_hash,
self.params.replacement_nodes.as_ref().unwrap_or(&default),
)))
}
StepType::WaitForCUP => {
if let Some(node_ip) = self.params.upload_node {
Ok(Box::new(self.recovery.get_wait_for_cup_step(node_ip)))
} else {
Err(RecoveryError::StepSkipped)
}
}
StepType::Unhalt => Ok(Box::new(self.recovery.halt_subnet(
self.params.subnet_id,
false,
&["".to_string()],
))),
StepType::Cleanup => Ok(Box::new(self.recovery.get_cleanup_step())),
}
}
}
impl Iterator for AppSubnetRecovery {
type Item = (StepType, Box<dyn Step>);
fn next(&mut self) -> Option<Self::Item> {
if let Some(current_step) = self.step_iterator.next() {
match self.get_step_impl(current_step) {
Ok(step) => Some((current_step, step)),
Err(RecoveryError::StepSkipped) => self.next(),
Err(e) => {
warn!(self.logger, "Step generation failed: {}", e);
None
}
}
} else {
self.success = true;
None
}
}
}
| 31.44878 | 91 | 0.534202 |
90ecc099da1407f3c9dcbdaa0f5d3700711042d9 | 122 | pub const ORIGINAL_MIN: u64 = u64::max_value();
pub const ORIGINAL_MAX: u64 = 0;
pub const F64_SIGN_MASK: u64 = 1 << 63;
| 24.4 | 47 | 0.704918 |
d973016ba02be359c5604a4ccb36ab35e15534b4 | 2,623 | use std::time::Duration;
pub use self::cfg::{Cfg, CfgExpr};
pub use self::config::{homedir, Config, ConfigValue};
pub use self::dependency_queue::{DependencyQueue, Dirty, Fresh, Freshness};
pub use self::diagnostic_server::RustfixDiagnosticServer;
pub use self::errors::{internal, process_error};
pub use self::errors::{CargoResult, CargoResultExt, CliResult, Test};
pub use self::errors::{CargoTestError, CliError, ProcessError};
pub use self::flock::{FileLock, Filesystem};
pub use self::graph::Graph;
pub use self::hex::{hash_u64, short_hash, to_hex};
pub use self::lev_distance::lev_distance;
pub use self::lockserver::{LockServer, LockServerClient, LockServerStarted};
pub use self::paths::{bytes2path, dylib_path, join_paths, path2bytes};
pub use self::paths::{dylib_path_envvar, normalize_path};
pub use self::process_builder::{process, ProcessBuilder};
pub use self::progress::{Progress, ProgressStyle};
pub use self::read2::read2;
pub use self::rustc::Rustc;
pub use self::sha256::Sha256;
pub use self::to_semver::ToSemver;
pub use self::to_url::ToUrl;
pub use self::vcs::{existing_vcs_repo, FossilRepo, GitRepo, HgRepo, PijulRepo};
pub use self::workspace::{
print_available_benches, print_available_binaries, print_available_examples,
print_available_tests,
};
mod cfg;
pub mod command_prelude;
pub mod config;
mod dependency_queue;
pub mod diagnostic_server;
pub mod errors;
mod flock;
pub mod graph;
pub mod hex;
pub mod important_paths;
pub mod job;
pub mod lev_distance;
mod lockserver;
pub mod machine_message;
pub mod network;
pub mod paths;
pub mod process_builder;
pub mod profile;
mod progress;
mod read2;
mod rustc;
mod sha256;
pub mod to_semver;
pub mod to_url;
pub mod toml;
mod vcs;
mod workspace;
pub fn elapsed(duration: Duration) -> String {
let secs = duration.as_secs();
if secs >= 60 {
format!("{}m {:02}s", secs / 60, secs % 60)
} else {
format!("{}.{:02}s", secs, duration.subsec_nanos() / 10_000_000)
}
}
/// Check the base requirements for a package name.
///
/// This can be used for other things than package names, to enforce some
/// level of sanity. Note that package names have other restrictions
/// elsewhere. `cargo new` has a few restrictions, such as checking for
/// reserved names. crates.io has even more restrictions.
pub fn validate_package_name(name: &str, what: &str, help: &str) -> CargoResult<()> {
if let Some(ch) = name
.chars()
.find(|ch| !ch.is_alphanumeric() && *ch != '_' && *ch != '-')
{
failure::bail!("Invalid character `{}` in {}: `{}`{}", ch, what, name, help);
}
Ok(())
}
| 31.60241 | 85 | 0.712924 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.