text:
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT

use crate::AccessibleProperty;
use crate::AccessibleRelation;
use crate::AccessibleRole;
use crate::AccessibleState;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;

glib::wrapper! {
    pub struct Accessible(Interface<ffi::GtkAccessible, ffi::GtkAccessibleInterface>);

    match fn {
        get_type => || ffi::gtk_accessible_get_type(),
    }
}

pub const NONE_ACCESSIBLE: Option<&Accessible> = None;

pub trait AccessibleExt: 'static {
    #[doc(alias = "gtk_accessible_get_accessible_role")]
    fn accessible_role(&self) -> AccessibleRole;

    #[doc(alias = "gtk_accessible_reset_property")]
    fn reset_property(&self, property: AccessibleProperty);

    #[doc(alias = "gtk_accessible_reset_relation")]
    fn reset_relation(&self, relation: AccessibleRelation);

    #[doc(alias = "gtk_accessible_reset_state")]
    fn reset_state(&self, state: AccessibleState);

    #[doc(alias = "set_property_accessible_role")]
    fn set_accessible_role(&self, accessible_role: AccessibleRole);

    fn connect_property_accessible_role_notify<F: Fn(&Self) + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId;
}

impl<O: IsA<Accessible>> AccessibleExt for O {
    fn accessible_role(&self) -> AccessibleRole {
        unsafe {
            from_glib(ffi::gtk_accessible_get_accessible_role(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn reset_property(&self, property: AccessibleProperty) {
        unsafe {
            ffi::gtk_accessible_reset_property(self.as_ref().to_glib_none().0, property.to_glib());
        }
    }

    fn reset_relation(&self, relation: AccessibleRelation) {
        unsafe {
            ffi::gtk_accessible_reset_relation(self.as_ref().to_glib_none().0, relation.to_glib());
        }
    }

    fn reset_state(&self, state: AccessibleState) {
        unsafe {
            ffi::gtk_accessible_reset_state(self.as_ref().to_glib_none().0, state.to_glib());
        }
    }

    fn set_accessible_role(&self, accessible_role: AccessibleRole) {
        unsafe {
            glib::gobject_ffi::g_object_set_property(
                self.to_glib_none().0 as *mut glib::gobject_ffi::GObject,
                b"accessible-role\0".as_ptr() as *const _,
                glib::Value::from(&accessible_role).to_glib_none().0,
            );
        }
    }

    fn connect_property_accessible_role_notify<F: Fn(&Self) + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_accessible_role_trampoline<P, F: Fn(&P) + 'static>(
            this: *mut ffi::GtkAccessible,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) where
            P: IsA<Accessible>,
        {
            let f: &F = &*(f as *const F);
            f(&Accessible::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::accessible-role\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_accessible_role_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl fmt::Display for Accessible {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Accessible")
    }
}


text:
#[doc = r" Value read from the register"]
pub struct R {
    bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
    bits: u32,
}
impl super::AIFDIRCFG {
    #[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 RESERVED6R {
    bits: u32,
}
impl RESERVED6R {
    #[doc = r" Value of the field as raw bits"]
    #[inline]
    pub fn bits(&self) -> u32 {
        self.bits
    }
}
#[doc = "Possible values of the field `AD1`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AD1R {
    #[doc = "Output mode"]
    OUT,
    #[doc = "Input mode"]
    IN,
    #[doc = "Not in use (disabled)"]
    DIS,
    #[doc = r" Reserved"]
    _Reserved(u8),
}
impl AD1R {
    #[doc = r" Value of the field as raw bits"]
    #[inline]
    pub fn bits(&self) -> u8 {
        match *self {
            AD1R::OUT => 2,
            AD1R::IN => 1,
            AD1R::DIS => 0,
            AD1R::_Reserved(bits) => bits,
        }
    }
    #[allow(missing_docs)]
    #[doc(hidden)]
    #[inline]
    pub fn _from(value: u8) -> AD1R {
        match value {
            2 => AD1R::OUT,
            1 => AD1R::IN,
            0 => AD1R::DIS,
            i => AD1R::_Reserved(i),
        }
    }
    #[doc = "Checks if the value of the field is `OUT`"]
    #[inline]
    pub fn is_out(&self) -> bool {
        *self == AD1R::OUT
    }
    #[doc = "Checks if the value of the field is `IN`"]
    #[inline]
    pub fn is_in_(&self) -> bool {
        *self == AD1R::IN
    }
    #[doc = "Checks if the value of the field is `DIS`"]
    #[inline]
    pub fn is_dis(&self) -> bool {
        *self == AD1R::DIS
    }
}
#[doc = r" Value of the field"]
pub struct RESERVED2R {
    bits: u8,
}
impl RESERVED2R {
    #[doc = r" Value of the field as raw bits"]
    #[inline]
    pub fn bits(&self) -> u8 {
        self.bits
    }
}
#[doc = "Possible values of the field `AD0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AD0R {
    #[doc = "Output mode"]
    OUT,
    #[doc = "Input mode"]
    IN,
    #[doc = "Not in use (disabled)"]
    DIS,
    #[doc = r" Reserved"]
    _Reserved(u8),
}
impl AD0R {
    #[doc = r" Value of the field as raw bits"]
    #[inline]
    pub fn bits(&self) -> u8 {
        match *self {
            AD0R::OUT => 2,
            AD0R::IN => 1,
            AD0R::DIS => 0,
            AD0R::_Reserved(bits) => bits,
        }
    }
    #[allow(missing_docs)]
    #[doc(hidden)]
    #[inline]
    pub fn _from(value: u8) -> AD0R {
        match value {
            2 => AD0R::OUT,
            1 => AD0R::IN,
            0 => AD0R::DIS,
            i => AD0R::_Reserved(i),
        }
    }
    #[doc = "Checks if the value of the field is `OUT`"]
    #[inline]
    pub fn is_out(&self) -> bool {
        *self == AD0R::OUT
    }
    #[doc = "Checks if the value of the field is `IN`"]
    #[inline]
    pub fn is_in_(&self) -> bool {
        *self == AD0R::IN
    }
    #[doc = "Checks if the value of the field is `DIS`"]
    #[inline]
    pub fn is_dis(&self) -> bool {
        *self == AD0R::DIS
    }
}
#[doc = "Values that can be written to the field `AD1`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AD1W {
    #[doc = "Output mode"]
    OUT,
    #[doc = "Input mode"]
    IN,
    #[doc = "Not in use (disabled)"]
    DIS,
}
impl AD1W {
    #[allow(missing_docs)]
    #[doc(hidden)]
    #[inline]
    pub fn _bits(&self) -> u8 {
        match *self {
            AD1W::OUT => 2,
            AD1W::IN => 1,
            AD1W::DIS => 0,
        }
    }
}
#[doc = r" Proxy"]
pub struct _AD1W<'a> {
    w: &'a mut W,
}
impl<'a> _AD1W<'a> {
    #[doc = r" Writes `variant` to the field"]
    #[inline]
    pub fn variant(self, variant: AD1W) -> &'a mut W {
        unsafe { self.bits(variant._bits()) }
    }
    #[doc = "Output mode"]
    #[inline]
    pub fn out(self) -> &'a mut W {
        self.variant(AD1W::OUT)
    }
    #[doc = "Input mode"]
    #[inline]
    pub fn in_(self) -> &'a mut W {
        self.variant(AD1W::IN)
    }
    #[doc = "Not in use (disabled)"]
    #[inline]
    pub fn dis(self) -> &'a mut W {
        self.variant(AD1W::DIS)
    }
    #[doc = r" Writes raw bits to the field"]
    #[inline]
    pub unsafe fn bits(self, value: u8) -> &'a mut W {
        const MASK: u8 = 3;
        const OFFSET: u8 = 4;
        self.w.bits &= !((MASK as u32) << OFFSET);
        self.w.bits |= ((value & MASK) as u32) << OFFSET;
        self.w
    }
}
#[doc = "Values that can be written to the field `AD0`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AD0W {
    #[doc = "Output mode"]
    OUT,
    #[doc = "Input mode"]
    IN,
    #[doc = "Not in use (disabled)"]
    DIS,
}
impl AD0W {
    #[allow(missing_docs)]
    #[doc(hidden)]
    #[inline]
    pub fn _bits(&self) -> u8 {
        match *self {
            AD0W::OUT => 2,
            AD0W::IN => 1,
            AD0W::DIS => 0,
        }
    }
}
#[doc = r" Proxy"]
pub struct _AD0W<'a> {
    w: &'a mut W,
}
impl<'a> _AD0W<'a> {
    #[doc = r" Writes `variant` to the field"]
    #[inline]
    pub fn variant(self, variant: AD0W) -> &'a mut W {
        unsafe { self.bits(variant._bits()) }
    }
    #[doc = "Output mode"]
    #[inline]
    pub fn out(self) -> &'a mut W {
        self.variant(AD0W::OUT)
    }
    #[doc = "Input mode"]
    #[inline]
    pub fn in_(self) -> &'a mut W {
        self.variant(AD0W::IN)
    }
    #[doc = "Not in use (disabled)"]
    #[inline]
    pub fn dis(self) -> &'a mut W {
        self.variant(AD0W::DIS)
    }
    #[doc = r" Writes raw bits to the field"]
    #[inline]
    pub unsafe fn bits(self, value: u8) -> &'a mut W {
        const MASK: u8 = 3;
        const OFFSET: u8 = 0;
        self.w.bits &= !((MASK as u32) << OFFSET);
        self.w.bits |= ((value & MASK) as u32) << OFFSET;
        self.w
    }
}
impl R {
    #[doc = r" Value of the register as raw bits"]
    #[inline]
    pub fn bits(&self) -> u32 {
        self.bits
    }
    #[doc = "Bits 6:31 - Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
    #[inline]
    pub fn reserved6(&self) -> RESERVED6R {
        let bits = {
            const MASK: u32 = 67108863;
            const OFFSET: u8 = 6;
            ((self.bits >> OFFSET) & MASK as u32) as u32
        };
        RESERVED6R { bits }
    }
    #[doc = "Bits 4:5 - Configures the AD1 audio data pin usage: 0x3: Reserved"]
    #[inline]
    pub fn ad1(&self) -> AD1R {
        AD1R::_from({
            const MASK: u8 = 3;
            const OFFSET: u8 = 4;
            ((self.bits >> OFFSET) & MASK as u32) as u8
        })
    }
    #[doc = "Bits 2:3 - Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
    #[inline]
    pub fn reserved2(&self) -> RESERVED2R {
        let bits = {
            const MASK: u8 = 3;
            const OFFSET: u8 = 2;
            ((self.bits >> OFFSET) & MASK as u32) as u8
        };
        RESERVED2R { bits }
    }
    #[doc = "Bits 0:1 - Configures the AD0 audio data pin usage: 0x3: Reserved"]
    #[inline]
    pub fn ad0(&self) -> AD0R {
        AD0R::_from({
            const MASK: u8 = 3;
            const OFFSET: u8 = 0;
            ((self.bits >> OFFSET) & MASK as u32) 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: u32) -> &mut Self {
        self.bits = bits;
        self
    }
    #[doc = "Bits 4:5 - Configures the AD1 audio data pin usage: 0x3: Reserved"]
    #[inline]
    pub fn ad1(&mut self) -> _AD1W {
        _AD1W { w: self }
    }
    #[doc = "Bits 0:1 - Configures the AD0 audio data pin usage: 0x3: Reserved"]
    #[inline]
    pub fn ad0(&mut self) -> _AD0W {
        _AD0W { w: self }
    }
}

domain: rust


text:
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
use std::fmt::Write;
/// See [`CreateAnomalyMonitorInput`](crate::input::CreateAnomalyMonitorInput)
pub mod create_anomaly_monitor_input {
    /// A builder for [`CreateAnomalyMonitorInput`](crate::input::CreateAnomalyMonitorInput)
    #[non_exhaustive]
    #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
    pub struct Builder {
        pub(crate) anomaly_monitor: std::option::Option<crate::model::AnomalyMonitor>,
        pub(crate) resource_tags: std::option::Option<std::vec::Vec<crate::model::ResourceTag>>,
    }
    impl Builder {
        ///
The cost anomaly detection monitor object that you want to create.

        pub fn anomaly_monitor(mut self, input: crate::model::AnomalyMonitor) -> Self {
            self.anomaly_monitor = Some(input);
            self
        }
        ///
The cost anomaly detection monitor object that you want to create.

        pub fn set_anomaly_monitor(
            mut self,
            input: std::option::Option<crate::model::AnomalyMonitor>,
        ) -> Self {
            self.anomaly_monitor = input;
            self
        }
        /// Appends an item to `resource_tags`.
        ///
        /// To override the contents of this collection use [`set_resource_tags`](Self::set_resource_tags).
        ///
        ///
 An optional list of tags to associate with the specified  AnomalyMonitor . You can use resource tags to control access to your monitor using IAM policies.

        ///
Each tag consists of a key and a value, and each key must be unique for the resource. The following restrictions apply to resource tags:

        ///

        ///

Although the maximum number of array members is 200, you can assign a maximum of 50 user-tags to one resource. The remaining are reserved for Amazon Web Services use

        ///

The maximum length of a key is 128 characters

        ///

The maximum length of a value is 256 characters

        ///

Valid characters for keys and values are: A-Z, a-z, spaces, _.:/=+-

        ///

Keys and values are case sensitive

        ///

Keys and values are trimmed for any leading or trailing whitespaces

        ///

Don’t use aws: as a prefix for your keys. This prefix is reserved for Amazon Web Services use

        ///

        pub fn resource_tags(mut self, input: crate::model::ResourceTag) -> Self {
            let mut v = self.resource_tags.unwrap_or_default();
            v.push(input);
            self.resource_tags = Some(v);
            self
        }
        ///
 An optional list of tags to associate with the specified  AnomalyMonitor . You can use resource tags to control access to your monitor using IAM policies.

        ///
Each tag consists of a key and a value, and each key must be unique for the resource. The following restrictions apply to resource tags:

        ///

        ///

Although the maximum number of array members is 200, you can assign a maximum of 50 user-tags to one resource. The remaining are reserved for Amazon Web Services use

        ///

The maximum length of a key is 128 characters

        ///

The maximum length of a value is 256 characters

        ///

Valid characters for keys and values are: A-Z, a-z, spaces, _.:/=+-

        ///

Keys and values are case sensitive

        ///

Keys and values are trimmed for any leading or trailing whitespaces

        ///

Don’t use aws: as a prefix for your keys. This prefix is reserved for Amazon Web Services use

        ///

        pub fn set_resource_tags(
            mut self,
            input: std::option::Option<std::vec::Vec<crate::model::ResourceTag>>,
        ) -> Self {
            self.resource_tags = input;
            self
        }
        /// Consumes the builder and constructs a [`CreateAnomalyMonitorInput`](crate::input::CreateAnomalyMonitorInput)
        pub fn build(
            self,
        ) -> std::result::Result<
            crate::input::CreateAnomalyMonitorInput,
            aws_smithy_http::operation::BuildError,
        > {
            Ok(crate::input::CreateAnomalyMonitorInput {
                anomaly_monitor: self.anomaly_monitor,
                resource_tags: self.resource_tags,
            })
        }
    }
}
#[doc(hidden)]
pub type CreateAnomalyMonitorInputOperationOutputAlias = crate::operation::CreateAnomalyMonitor;
#[doc(hidden)]
pub type CreateAnomalyMonitorInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl CreateAnomalyMonitorInput {
    /// Consumes the builder and constructs an Operation<[`CreateAnomalyMonitor`](crate::operation::CreateAnomalyMonitor)>
    #[allow(unused_mut)]
    #[allow(clippy::let_and_return)]
    #[allow(clippy::needless_borrow)]
    pub async fn make_operation(
        &self,
        _config: &crate::config::Config,
    ) -> std::result::Result<
        aws_smithy_http::operation::Operation<
            crate::operation::CreateAnomalyMonitor,
            aws_http::retry::AwsErrorRetryPolicy,
        >,
        aws_smithy_http::operation::BuildError,
    > {
        let mut request = {
            fn uri_base(
                _input: &crate::input::CreateAnomalyMonitorInput,
                output: &mut String,
            ) -> Result<(), aws_smithy_http::operation::BuildError> {
                write!(output, "/").expect("formatting should succeed");
                Ok(())
            }
            #[allow(clippy::unnecessary_wraps)]
            fn update_http_builder(
                input: &crate::input::CreateAnomalyMonitorInput,
                builder: http::request::Builder,
            ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
            {
                let mut uri = String::new();
                uri_base(input, &mut uri)?;
                Ok(builder.method("POST").uri(uri))
            }
            let mut builder = update_http_builder(&self, http::request::Builder::new())?;
            builder = aws_smithy_http::header::set_request_header_if_absent(
                builder,
                http::header::CONTENT_TYPE,
                "application/x-amz-json-1.1",
            );
            builder = aws_smithy_http::header::set_request_header_if_absent(
                builder,
                http::header::HeaderName::from_static("x-amz-target"),
                "AWSInsightsIndexService.CreateAnomalyMonitor",
            );
            builder
        };
        let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
        #[allow(clippy::useless_conversion)]
        let body = aws_smithy_http::body::SdkBody::from(
            crate::operation_ser::serialize_operation_crate_operation_create_anomaly_monitor(
                &self,
            )?,
        );
        if let Some(content_length) = body.content_length() {
            request = aws_smithy_http::header::set_request_header_if_absent(
                request,
                http::header::CONTENT_LENGTH,
                content_length,
            );
        }
        let request = request.body(body).expect("should be valid request");
        let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
        request
            .properties_mut()
            .insert(aws_smithy_http::http_versions::DEFAULT_HTTP_VERSION_LIST.clone());
        let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
            aws_types::os_shim_internal::Env::real(),
            crate::API_METADATA.clone(),
        );
        if let Some(app_name) = _config.app_name() {
            user_agent = user_agent.with_app_name(app_name.clone());
        }
        request.properties_mut().insert(user_agent);
        let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
        request.properties_mut().insert(signing_config);
        request
            .properties_mut()
            .insert(aws_types::SigningService::from_static(
                _config.signing_service(),
            ));
        aws_endpoint::set_endpoint_resolver(
            &mut request.properties_mut(),
            _config.endpoint_resolver.clone(),
        );
        if let Some(region) = &_config.region {
            request.properties_mut().insert(region.clone());
        }
        aws_http::auth::set_provider(
            &mut request.properties_mut(),
            _config.credentials_provider.clone(),
        );
        let op = aws_smithy_http::operation::Operation::new(
            request,
            crate::operation::CreateAnomalyMonitor::new(),
        )
        .with_metadata(aws_smithy_http::operation::Metadata::new(
            "CreateAnomalyMonitor",
            "costexplorer",
        ));
        let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
        Ok(op)
    }
    /// Creates a new builder-style object to manufacture [`CreateAnomalyMonitorInput`](crate::input::CreateAnomalyMonitorInput)
    pub fn builder() -> crate::input::create_anomaly_monitor_input::Builder {
        crate::input::create_anomaly_monitor_input::Builder::default()
    }
}

/// See [`CreateAnomalySubscriptionInput`](crate::input::CreateAnomalySubscriptionInput)
pub mod create_anomaly_subscription_input {
    /// A builder for [`CreateAnomalySubscriptionInput`](crate::input::CreateAnomalySubscriptionInput)
    #[non_exhaustive]
    #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
    pub struct Builder {
        pub(crate) anomaly_subscription: std::option::Option<crate::model::AnomalySubscription>,
        pub(crate) resource_tags: std::option::Option<std::vec::Vec<crate::model::ResourceTag>>,
    }
    impl Builder {
        ///
The cost anomaly subscription object that you want to create.

        pub fn anomaly_subscription(mut self, input: crate::model::AnomalySubscription) -> Self {
            self.anomaly_subscription = Some(input);
            self
        }
        ///
The cost anomaly subscription object that you want to create.

        pub fn set_anomaly_subscription(
            mut self,
            input: std::option::Option<crate::model::AnomalySubscription>,
        ) -> Self {
            self.anomaly_subscription = input;
            self
        }
        /// Appends an item to `resource_tags`.
        ///
        /// To override the contents of this collection use [`set_resource_tags`](Self::set_resource_tags).
        ///
        ///
 An optional list of tags to associate with the specified  AnomalySubscription . You can use resource tags to control access to your subscription using IAM policies.

        ///
Each tag consists of a key and a value, and each key must be unique for the resource. The following restrictions apply to resource tags:

        ///

        ///

Although the maximum number of array members is 200, you can assign a maximum of 50 user-tags to one resource. The remaining are reserved for Amazon Web Services use

        ///

The maximum length of a key is 128 characters

        ///

The maximum length of a value is 256 characters

        ///

Valid characters for keys and values are: A-Z, a-z, spaces, _.:/=+-

        ///

Keys and values are case sensitive

        ///

Keys and values are trimmed for any leading or trailing whitespaces

        ///

Don’t use aws: as a prefix for your keys. This prefix is reserved for Amazon Web Services use

        ///

        pub fn resource_tags(mut self, input: crate::model::ResourceTag) -> Self {
            let mut v = self.resource_tags.unwrap_or_default();
            v.push(input);
            self.resource_tags = Some(v);
            self
        }
        ///
 An optional list of tags to associate with the specified  AnomalySubscription . You can use resource tags to control access to your subscription using IAM policies.

        ///
Each tag consists of a key and a value, and each key must be unique for the resource. The following restrictions apply to resource tags:

        ///

        ///

Although the maximum number of array members is 200, you can assign a maximum of 50 user-tags to one resource. The remaining are reserved for Amazon Web Services use

        ///

The maximum length of a key is 128 characters

        ///

The maximum length of a value is 256 characters

        ///

Valid characters for keys and values are: A-Z, a-z, spaces, _.:/=+-

        ///

Keys and values are case sensitive

        ///

Keys and values are trimmed for any leading or trailing whitespaces

        ///

Don’t use aws: as a prefix for your keys. This prefix is reserved for Amazon Web Services use

        ///

        pub fn set_resource_tags(
            mut self,
            input: std::option::Option<std::vec::Vec<crate::model::ResourceTag>>,
        ) -> Self {
            self.resource_tags = input;
            self
        }
        /// Consumes the builder and constructs a [`CreateAnomalySubscriptionInput`](crate::input::CreateAnomalySubscriptionInput)
        pub fn build(
            self,
        ) -> std::result::Result<
            crate::input::CreateAnomalySubscriptionInput,
            aws_smithy_http::operation::BuildError,
        > {
            Ok(crate::input::CreateAnomalySubscriptionInput {
                anomaly_subscription: self.anomaly_subscription,
                resource_tags: self.resource_tags,
            })
        }
    }
}
#[doc(hidden)]
pub type CreateAnomalySubscriptionInputOperationOutputAlias =
    crate::operation::CreateAnomalySubscription;
#[doc(hidden)]
pub type CreateAnomalySubscriptionInputOperationRetryAlias = aws_http::retry::AwsErrorRetryPolicy;
impl CreateAnomalySubscriptionInput {
    /// Consumes the builder and constructs an Operation<[`CreateAnomalySubscription`](crate::operation::CreateAnomalySubscription)>
    #[allow(unused_mut)]
    #[allow(clippy::let_and_return)]
    #[allow(clippy::needless_borrow)]
    pub async fn make_operation(
        &self,
        _config: &crate::config::Config,
    ) -> std::result::Result<
        aws_smithy_http::operation::Operation<
            crate::operation::CreateAnomalySubscription,
            aws_http::retry::AwsErrorRetryPolicy,
        >,
        aws_smithy_http::operation::BuildError,
    > {
        let mut request = {
            fn uri_base(
                _input: &crate::input::CreateAnomalySubscriptionInput,
                output: &mut String,
            ) -> Result<(), aws_smithy_http::operation::BuildError> {
                write!(output, "/").expect("formatting should succeed");
                Ok(())
            }
            #[allow(clippy::unnecessary_wraps)]
            fn update_http_builder(
                input: &crate::input::CreateAnomalySubscriptionInput,
                builder: http::request::Builder,
            ) -> std::result::Result<http::request::Builder, aws_smithy_http::operation::BuildError>
            {
                let mut uri = String::new();
                uri_base(input, &mut uri)?;
                Ok(builder.method("POST").uri(uri))
            }
            let mut builder = update_http_builder(&self, http::request::Builder::new())?;
            builder = aws_smithy_http::header::set_request_header_if_absent(
                builder,
                http::header::CONTENT_TYPE,
                "application/x-amz-json-1.1",
            );
            builder = aws_smithy_http::header::set_request_header_if_absent(
                builder,
                http::header::HeaderName::from_static("x-amz-target"),
                "AWSInsightsIndexService.CreateAnomalySubscription",
            );
            builder
        };
        let mut properties = aws_smithy_http::property_bag::SharedPropertyBag::new();
        #[allow(clippy::useless_conversion)]
        let body = aws_smithy_http::body::SdkBody::from(
            crate::operation_ser::serialize_operation_crate_operation_create_anomaly_subscription(
                &self,
            )?,
        );
        if let Some(content_length) = body.content_length() {
            request = aws_smithy_http::header::set_request_header_if_absent(
                request,
                http::header::CONTENT_LENGTH,
                content_length,
            );
        }
        let request = request.body(body).expect("should be valid request");
        let mut request = aws_smithy_http::operation::Request::from_parts(request, properties);
        request
            .properties_mut()
            .insert(aws_smithy_http::http_versions::DEFAULT_HTTP_VERSION_LIST.clone());
        let mut user_agent = aws_http::user_agent::AwsUserAgent::new_from_environment(
            aws_types::os_shim_internal::Env::real(),
            crate::API_METADATA.clone(),
        );
        if let Some(app_name) = _config.app_name() {
            user_agent = user_agent.with_app_name(app_name.clone());
        }
        request.properties_mut().insert(user_agent);
        let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config();
        request.properties_mut().insert(signing_config);
        request
            .properties_mut()
            .insert(aws_types::SigningService::from_static(
                _config.signing_service(),
            ));
        aws_endpoint::set_endpoint_resolver(
            &mut request.properties_mut(),
            _config.endpoint_resolver.clone(),
        );
        if let Some(region) = &_config.region {
            request.properties_mut().insert(region.clone());
        }
        aws_http::auth::set_provider(
            &mut request.properties_mut(),
            _config.credentials_provider.clone(),
        );
        let op = aws_smithy_http::operation::Operation::new(
            request,
            crate::operation::CreateAnomalySubscription::new(),
        )
        .with_metadata(aws_smithy_http::operation::Metadata::new(
            "CreateAnomalySubscription",
            "costexplorer",
        ));
        let op = op.with_retry_policy(aws_http::retry::AwsErrorRetryPolicy::new());
        Ok(op)
    }
    /// Creates a new builder-style object to manufacture [`CreateAnomalySubscriptionInput`](crate::input::CreateAnomalySubscriptionInput)
    pub fn builder() -> crate::input::create_anomaly_subscription_input::Builder {
        crate::input::create_anomaly_subscription_input::Builder::default()
    }
}

/// See [`CreateCostCategoryDefinitionInput`](crate::input::CreateCostCategoryDefinitionInput)
pub mod create_cost_category_definition_input {
    /// A builder for [`CreateCostCategoryDefinitionInput`](crate::input::CreateCostCategoryDefinitionInput)
    #[non_exhaustive]


text:
#![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
pub mod container_groups {
    use crate::models::*;
    pub async fn list(
        operation_config: &crate::OperationConfig,
        subscription_id: &str,
    ) -> std::result::Result<ContainerGroupListResult, list::Error> {
        let http_client = operation_config.http_client();
        let url_str = &format!(
            "{}/subscriptions/{}/providers/Microsoft.ContainerInstance/containerGroups",
            operation_config.base_path(),
            subscription_id
        );
        let mut url = url::Url::parse(url_str).map_err(|source| list::Error::ParseUrlError { source })?;
        let mut req_builder = http::request::Builder::new();
        req_builder = req_builder.method(http::Method::GET);
        if let Some(token_credential) = operation_config.token_credential() {
            let token_response = token_credential
                .get_token(operation_config.token_credential_resource())
                .await
                .map_err(|source| list::Error::GetTokenError { source })?;
            req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
        }
        url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
        let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
        req_builder = req_builder.uri(url.as_str());
        let req = req_builder
            .body(req_body)
            .map_err(|source| list::Error::BuildRequestError { source })?;
        let rsp = http_client
            .execute_request(req)
            .await
            .map_err(|source| list::Error::ExecuteRequestError { source })?;
        match rsp.status() {
            http::StatusCode::OK => {
                let rsp_body = rsp.body();
                let rsp_value: ContainerGroupListResult =
                    serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError {
                        source,
                        body: rsp_body.clone(),
                    })?;
                Ok(rsp_value)
            }
            status_code => {
                let rsp_body = rsp.body();
                Err(list::Error::UnexpectedResponse {
                    status_code,
                    body: rsp_body.clone(),
                })
            }
        }
    }
    pub mod list {
        use crate::{models, models::*};
        #[derive(Debug, thiserror :: Error)]
        pub enum Error {
            #[error("Unexpected HTTP status code {}", status_code)]
            UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
            #[error("Failed to parse request URL: {}", source)]
            ParseUrlError { source: url::ParseError },
            #[error("Failed to build request: {}", source)]
            BuildRequestError { source: http::Error },
            #[error("Failed to execute request: {}", source)]
            ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
            #[error("Failed to serialize request body: {}", source)]
            SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
            #[error("Failed to deserialize response body: {}", source)]
            DeserializeError { source: serde_json::Error, body: bytes::Bytes },
            #[error("Failed to get access token: {}", source)]
            GetTokenError { source: azure_core::errors::AzureError },
        }
    }
    pub async fn list_by_resource_group(
        operation_config: &crate::OperationConfig,
        subscription_id: &str,
        resource_group_name: &str,
    ) -> std::result::Result<ContainerGroupListResult, list_by_resource_group::Error> {
        let http_client = operation_config.http_client();
        let url_str = &format!(
            "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerInstance/containerGroups",
            operation_config.base_path(),
            subscription_id,
            resource_group_name
        );
        let mut url = url::Url::parse(url_str).map_err(|source| list_by_resource_group::Error::ParseUrlError { source })?;
        let mut req_builder = http::request::Builder::new();
        req_builder = req_builder.method(http::Method::GET);
        if let Some(token_credential) = operation_config.token_credential() {
            let token_response = token_credential
                .get_token(operation_config.token_credential_resource())
                .await
                .map_err(|source| list_by_resource_group::Error::GetTokenError { source })?;
            req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
        }
        url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
        let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
        req_builder = req_builder.uri(url.as_str());
        let req = req_builder
            .body(req_body)
            .map_err(|source| list_by_resource_group::Error::BuildRequestError { source })?;
        let rsp = http_client
            .execute_request(req)
            .await
            .map_err(|source| list_by_resource_group::Error::ExecuteRequestError { source })?;
        match rsp.status() {
            http::StatusCode::OK => {
                let rsp_body = rsp.body();
                let rsp_value: ContainerGroupListResult =
                    serde_json::from_slice(rsp_body).map_err(|source| list_by_resource_group::Error::DeserializeError {
                        source,
                        body: rsp_body.clone(),
                    })?;
                Ok(rsp_value)
            }
            status_code => {
                let rsp_body = rsp.body();
                Err(list_by_resource_group::Error::UnexpectedResponse {
                    status_code,
                    body: rsp_body.clone(),
                })
            }
        }
    }
    pub mod list_by_resource_group {
        use crate::{models, models::*};
        #[derive(Debug, thiserror :: Error)]
        pub enum Error {
            #[error("Unexpected HTTP status code {}", status_code)]
            UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
            #[error("Failed to parse request URL: {}", source)]
            ParseUrlError { source: url::ParseError },
            #[error("Failed to build request: {}", source)]
            BuildRequestError { source: http::Error },
            #[error("Failed to execute request: {}", source)]
            ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
            #[error("Failed to serialize request body: {}", source)]
            SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
            #[error("Failed to deserialize response body: {}", source)]
            DeserializeError { source: serde_json::Error, body: bytes::Bytes },
            #[error("Failed to get access token: {}", source)]
            GetTokenError { source: azure_core::errors::AzureError },
        }
    }
    pub async fn get(
        operation_config: &crate::OperationConfig,
        subscription_id: &str,
        resource_group_name: &str,
        container_group_name: &str,
    ) -> std::result::Result<ContainerGroup, get::Error> {
        let http_client = operation_config.http_client();
        let url_str = &format!(
            "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerInstance/containerGroups/{}",
            operation_config.base_path(),
            subscription_id,
            resource_group_name,
            container_group_name
        );
        let mut url = url::Url::parse(url_str).map_err(|source| get::Error::ParseUrlError { source })?;
        let mut req_builder = http::request::Builder::new();
        req_builder = req_builder.method(http::Method::GET);
        if let Some(token_credential) = operation_config.token_credential() {
            let token_response = token_credential
                .get_token(operation_config.token_credential_resource())
                .await
                .map_err(|source| get::Error::GetTokenError { source })?;
            req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
        }
        url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
        let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
        req_builder = req_builder.uri(url.as_str());
        let req = req_builder
            .body(req_body)
            .map_err(|source| get::Error::BuildRequestError { source })?;
        let rsp = http_client
            .execute_request(req)
            .await
            .map_err(|source| get::Error::ExecuteRequestError { source })?;
        match rsp.status() {
            http::StatusCode::OK => {
                let rsp_body = rsp.body();
                let rsp_value: ContainerGroup = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError {
                    source,
                    body: rsp_body.clone(),
                })?;
                Ok(rsp_value)
            }
            status_code => {
                let rsp_body = rsp.body();
                Err(get::Error::UnexpectedResponse {
                    status_code,
                    body: rsp_body.clone(),
                })
            }
        }
    }
    pub mod get {
        use crate::{models, models::*};
        #[derive(Debug, thiserror :: Error)]
        pub enum Error {
            #[error("Unexpected HTTP status code {}", status_code)]
            UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
            #[error("Failed to parse request URL: {}", source)]
            ParseUrlError { source: url::ParseError },
            #[error("Failed to build request: {}", source)]
            BuildRequestError { source: http::Error },
            #[error("Failed to execute request: {}", source)]
            ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
            #[error("Failed to serialize request body: {}", source)]
            SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
            #[error("Failed to deserialize response body: {}", source)]
            DeserializeError { source: serde_json::Error, body: bytes::Bytes },
            #[error("Failed to get access token: {}", source)]
            GetTokenError { source: azure_core::errors::AzureError },
        }
    }
    pub async fn create_or_update(
        operation_config: &crate::OperationConfig,
        subscription_id: &str,
        resource_group_name: &str,
        container_group_name: &str,
        container_group: &ContainerGroup,
    ) -> std::result::Result<create_or_update::Response, create_or_update::Error> {
        let http_client = operation_config.http_client();
        let url_str = &format!(
            "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerInstance/containerGroups/{}",
            operation_config.base_path(),
            subscription_id,
            resource_group_name,
            container_group_name
        );
        let mut url = url::Url::parse(url_str).map_err(|source| create_or_update::Error::ParseUrlError { source })?;
        let mut req_builder = http::request::Builder::new();
        req_builder = req_builder.method(http::Method::PUT);
        if let Some(token_credential) = operation_config.token_credential() {
            let token_response = token_credential
                .get_token(operation_config.token_credential_resource())
                .await
                .map_err(|source| create_or_update::Error::GetTokenError { source })?;
            req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
        }
        url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
        let req_body = azure_core::to_json(container_group).map_err(|source| create_or_update::Error::SerializeError { source })?;
        req_builder = req_builder.uri(url.as_str());
        let req = req_builder
            .body(req_body)
            .map_err(|source| create_or_update::Error::BuildRequestError { source })?;
        let rsp = http_client
            .execute_request(req)
            .await
            .map_err(|source| create_or_update::Error::ExecuteRequestError { source })?;
        match rsp.status() {
            http::StatusCode::OK => {
                let rsp_body = rsp.body();
                let rsp_value: ContainerGroup =
                    serde_json::from_slice(rsp_body).map_err(|source| create_or_update::Error::DeserializeError {
                        source,
                        body: rsp_body.clone(),
                    })?;
                Ok(create_or_update::Response::Ok200(rsp_value))
            }
            http::StatusCode::CREATED => {
                let rsp_body = rsp.body();
                let rsp_value: ContainerGroup =
                    serde_json::from_slice(rsp_body).map_err(|source| create_or_update::Error::DeserializeError {
                        source,
                        body: rsp_body.clone(),
                    })?;
                Ok(create_or_update::Response::Created201(rsp_value))
            }
            status_code => {
                let rsp_body = rsp.body();
                Err(create_or_update::Error::UnexpectedResponse {
                    status_code,
                    body: rsp_body.clone(),
                })
            }
        }
    }
    pub mod create_or_update {
        use crate::{models, models::*};
        #[derive(Debug)]
        pub enum Response {
            Ok200(ContainerGroup),
            Created201(ContainerGroup),
        }
        #[derive(Debug, thiserror :: Error)]
        pub enum Error {
            #[error("Unexpected HTTP status code {}", status_code)]
            UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
            #[error("Failed to parse request URL: {}", source)]
            ParseUrlError { source: url::ParseError },
            #[error("Failed to build request: {}", source)]
            BuildRequestError { source: http::Error },
            #[error("Failed to execute request: {}", source)]
            ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
            #[error("Failed to serialize request body: {}", source)]
            SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
            #[error("Failed to deserialize response body: {}", source)]
            DeserializeError { source: serde_json::Error, body: bytes::Bytes },
            #[error("Failed to get access token: {}", source)]
            GetTokenError { source: azure_core::errors::AzureError },
        }
    }
    pub async fn update(
        operation_config: &crate::OperationConfig,
        subscription_id: &str,
        resource_group_name: &str,
        container_group_name: &str,
        resource: &Resource,
    ) -> std::result::Result<ContainerGroup, update::Error> {
        let http_client = operation_config.http_client();
        let url_str = &format!(
            "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerInstance/containerGroups/{}",
            operation_config.base_path(),
            subscription_id,
            resource_group_name,
            container_group_name
        );
        let mut url = url::Url::parse(url_str).map_err(|source| update::Error::ParseUrlError { source })?;
        let mut req_builder = http::request::Builder::new();
        req_builder = req_builder.method(http::Method::PATCH);
        if let Some(token_credential) = operation_config.token_credential() {
            let token_response = token_credential
                .get_token(operation_config.token_credential_resource())
                .await
                .map_err(|source| update::Error::GetTokenError { source })?;
            req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
        }
        url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
        let req_body = azure_core::to_json(resource).map_err(|source| update::Error::SerializeError { source })?;
        req_builder = req_builder.uri(url.as_str());
        let req = req_builder
            .body(req_body)
            .map_err(|source| update::Error::BuildRequestError { source })?;
        let rsp = http_client
            .execute_request(req)
            .await
            .map_err(|source| update::Error::ExecuteRequestError { source })?;
        match rsp.status() {
            http::StatusCode::OK => {
                let rsp_body = rsp.body();
                let rsp_value: ContainerGroup = serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError {
                    source,
                    body: rsp_body.clone(),
                })?;
                Ok(rsp_value)
            }
            status_code => {
                let rsp_body = rsp.body();
                Err(update::Error::UnexpectedResponse {
                    status_code,
                    body: rsp_body.clone(),
                })
            }
        }
    }
    pub mod update {
        use crate::{models, models::*};
        #[derive(Debug, thiserror :: Error)]
        pub enum Error {
            #[error("Unexpected HTTP status code {}", status_code)]
            UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
            #[error("Failed to parse request URL: {}", source)]
            ParseUrlError { source: url::ParseError },
            #[error("Failed to build request: {}", source)]
            BuildRequestError { source: http::Error },
            #[error("Failed to execute request: {}", source)]
            ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
            #[error("Failed to serialize request body: {}", source)]
            SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
            #[error("Failed to deserialize response body: {}", source)]
            DeserializeError { source: serde_json::Error, body: bytes::Bytes },
            #[error("Failed to get access token: {}", source)]
            GetTokenError { source: azure_core::errors::AzureError },
        }
    }
    pub async fn delete(
        operation_config: &crate::OperationConfig,
        subscription_id: &str,
        resource_group_name: &str,
        container_group_name: &str,
    ) -> std::result::Result<delete::Response, delete::Error> {
        let http_client = operation_config.http_client();
        let url_str = &format!(
            "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ContainerInstance/containerGroups/{}",
            operation_config.base_path(),
            subscription_id,
            resource_group_name,
            container_group_name
        );
        let mut url = url::Url::parse(url_str).map_err(|source| delete::Error::ParseUrlError { source })?;
        let mut req_builder = http::request::Builder::new();
        req_builder = req_builder.method(http::Method::DELETE);
        if let Some(token_credential) = operation_config.token_credential() {
            let token_response = token_credential
                .get_token(operation_config.token_credential_resource())
                .await
                .map_err(|source| delete::Error::GetTokenError { source })?;
            req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
        }
        url.query_pairs_mut().append_pair("api-version", operation_config.api_version());


text:
use migration_connector::{steps::CreateEnum, *};
use migration_engine_tests::*;
use pretty_assertions::assert_eq;
use quaint::prelude::SqlFamily;

fn empty_migration(name: String) -> Migration {
    Migration {
        name,
        revision: 0,
        status: MigrationStatus::Pending,
        datamodel_string: String::new(),
        datamodel_steps: Vec::new(),
        applied: 0,
        rolled_back: 0,
        database_migration: serde_json::json!({}),
        errors: Vec::new(),
        started_at: Migration::timestamp_without_nanos(),
        finished_at: None,
    }
}

#[test_each_connector]
async fn last_should_return_none_if_there_is_no_migration(api: &TestApi) {
    let persistence = api.migration_persistence();
    let result = persistence.last().await.unwrap();
    assert_eq!(result.is_some(), false);
}

#[test_each_connector]
async fn last_must_return_none_if_there_is_no_successful_migration(api: &TestApi) -> TestResult {
    let persistence = api.migration_persistence();
    persistence.create(empty_migration("my_migration".to_string())).await?;
    let loaded = persistence.last().await?;
    assert_eq!(loaded, None);

    Ok(())
}

#[test_each_connector]
async fn load_all_should_return_empty_if_there_is_no_migration(api: &TestApi) {
    let persistence = api.migration_persistence();
    let result = persistence.load_all().await.unwrap();
    assert_eq!(result.is_empty(), true);
}

#[test_each_connector]
async fn load_all_must_return_all_created_migrations(api: &TestApi) {
    let persistence = api.migration_persistence();
    let migration1 = persistence
        .create(empty_migration("migration_1".to_string()))
        .await
        .unwrap();
    let migration2 = persistence
        .create(empty_migration("migration_2".to_string()))
        .await
        .unwrap();
    let migration3 = persistence
        .create(empty_migration("migration_3".to_string()))
        .await
        .unwrap();

    let mut result = persistence.load_all().await.unwrap();
    if api.sql_family() == SqlFamily::Mysql {
        // TODO: mysql currently looses milli seconds on loading
        result[0].started_at = migration1.started_at;
        result[1].started_at = migration2.started_at;
        result[2].started_at = migration3.started_at;
    }
    assert_eq!(result, vec![migration1, migration2, migration3])
}

#[test_each_connector]
async fn create_should_allow_to_create_a_new_migration(api: &TestApi) {
    let dm = r#"
        model Test {
            id String @id @default(cuid())
        }
    "#;

    let persistence = api.migration_persistence();
    let mut migration = empty_migration("my_migration".to_string());
    migration.status = MigrationStatus::MigrationSuccess;
    migration.datamodel_string = dm.to_owned();
    migration.datamodel_steps = vec![MigrationStep::CreateEnum(CreateEnum {
        r#enum: "MyEnum".to_string(),
        values: vec!["A".to_string(), "B".to_string()],
    })];
    migration.errors = vec!["error1".to_string(), "error2".to_string()];

    let result = persistence.create(migration.clone()).await.unwrap();
    migration.revision = result.revision; // copy over the generated revision so that the assertion can work.`

    assert_eq!(result, migration);
    let mut loaded = persistence.last().await.unwrap().unwrap();

    if api.sql_family() == SqlFamily::Mysql {
        // TODO: mysql currently looses milli seconds on loading
        loaded.started_at = migration.started_at;
    }

    assert_eq!(loaded, migration);
}

#[test_each_connector]
async fn create_should_increment_revisions(api: &TestApi) {
    let persistence = api.migration_persistence();
    let migration1 = persistence
        .create(empty_migration("migration_1".to_string()))
        .await
        .unwrap();
    let migration2 = persistence
        .create(empty_migration("migration_2".to_string()))
        .await
        .unwrap();
    assert_eq!(migration1.revision + 1, migration2.revision);
}

#[test_each_connector]
async fn update_must_work(api: &TestApi) {
    let persistence = api.migration_persistence();
    let migration = persistence
        .create(empty_migration("my_migration".to_string()))
        .await
        .unwrap();

    let mut params = migration.update_params();
    params.status = MigrationStatus::MigrationSuccess;
    params.applied = 10;
    params.rolled_back = 11;
    params.errors = vec!["err1".to_string(), "err2".to_string()];
    params.finished_at = Some(Migration::timestamp_without_nanos());
    params.new_name = "my_new_migration_name".to_string();

    persistence.update(&params).await.unwrap();

    let loaded = persistence.last().await.unwrap().unwrap();
    assert_eq!(loaded.status, params.status);
    assert_eq!(loaded.applied, params.applied);
    assert_eq!(loaded.rolled_back, params.rolled_back);
    assert_eq!(loaded.errors, params.errors);
    if api.sql_family() != SqlFamily::Mysql {
        // TODO: mysql currently looses milli seconds on loading
        assert_eq!(loaded.finished_at, params.finished_at);
    }
    assert_eq!(loaded.name, params.new_name);
}

#[test_each_connector]
async fn migration_is_already_applied_must_work(api: &TestApi) -> TestResult {
    let persistence = api.migration_persistence();

    let mut migration_1 = empty_migration("migration_1".to_string());
    migration_1.status = MigrationStatus::MigrationSuccess;

    persistence.create(migration_1).await?;

    let mut migration_2 = empty_migration("migration_2".to_string());
    migration_2.status = MigrationStatus::MigrationFailure;

    persistence.create(migration_2).await?;

    assert!(persistence.migration_is_already_applied("migration_1").await?);
    assert!(!persistence.migration_is_already_applied("migration_2").await?);
    assert!(!persistence.migration_is_already_applied("another_migration").await?);

    Ok(())
}


text:
use super::*;

mod with_small_integer_time;

// BigInt is not tested because it would take too long and would always count as `long_term` for the
// super shot soon and later wheel sizes used for `cfg(test)`

#[test]
fn without_non_negative_integer_time_errors_badarg() {
    with_process_arc(|arc_process| {
        TestRunner::new(Config::with_source_file(file!()))
            .run(
                &(
                    strategy::term::is_not_non_negative_integer(arc_process.clone()),
                    strategy::term(arc_process.clone()),
                ),
                |(time, message)| {
                    let destination = arc_process.pid_term();
                    let options = options(&arc_process);

                    prop_assert_eq!(
                        erlang::send_after_4(
                            time,
                            destination,
                            message,
                            options,
                            arc_process.clone()
                        ),
                        Err(badarg!().into())
                    );

                    Ok(())
                },
            )
            .unwrap();
    });
}

fn options(process: &Process) -> Term {
    super::options(false.into(), process)
}


text:
//! TCP/UDP/Unix bindings for `tokio`.
//!
//! This module contains the TCP/UDP/Unix networking types, similar to the standard
//! library, which can be used to implement networking protocols.
//!
//! # Organization
//!
//! * [`TcpListener`] and [`TcpStream`] provide functionality for communication over TCP
//! * [`UdpSocket`] and [`UdpFramed`] provide functionality for communication over UDP
//! * [`UnixListener`] and [`UnixStream`] provide functionality for communication over a
//! Unix Domain Socket **(available on Unix only)**
//!
//! [`TcpListener`]: struct.TcpListener.html
//! [`TcpStream`]: struct.TcpStream.html
//! [`UdpSocket`]: struct.UdpSocket.html
//! [`UdpFramed`]: struct.UdpFramed.html
//! [`UnixListener`]: struct.UnixListener.html
//! [`UnixStream`]: struct.UnixStream.html

pub mod tcp {
    //! TCP bindings for `tokio`.
    //!
    //! Connecting to an address, via TCP, can be done using [`TcpStream`]'s
    //! [`connect`] method, which returns [`ConnectFuture`]. `ConnectFuture`
    //! implements a future which returns a `TcpStream`.
    //!
    //! To listen on an address [`TcpListener`] can be used. `TcpListener`'s
    //! [`incoming`][incoming_method] method can be used to accept new connections.
    //! It return the [`Incoming`] struct, which implements a stream which returns
    //! `TcpStream`s.
    //!
    //! [`TcpStream`]: struct.TcpStream.html
    //! [`connect`]: struct.TcpStream.html#method.connect
    //! [`ConnectFuture`]: struct.ConnectFuture.html
    //! [`TcpListener`]: struct.TcpListener.html
    //! [incoming_method]: struct.TcpListener.html#method.incoming
    //! [`Incoming`]: struct.Incoming.html
    pub use tokio_tcp::{ConnectFuture, Incoming, TcpListener, TcpStream};
}
pub use self::tcp::{TcpListener, TcpStream};

#[deprecated(note = "use `tokio::net::tcp::ConnectFuture` instead")]
#[doc(hidden)]
pub type ConnectFuture = self::tcp::ConnectFuture;
#[deprecated(note = "use `tokio::net::tcp::Incoming` instead")]
#[doc(hidden)]
pub type Incoming = self::tcp::Incoming;

pub mod udp {
    //! UDP bindings for `tokio`.
    //!
    //! The main struct for UDP is the [`UdpSocket`], which represents a UDP socket.
    //! Reading and writing to it can be done using futures, which return the
    //! [`RecvDgram`] and [`SendDgram`] structs respectively.
    //!
    //! For convenience it's also possible to convert raw datagrams into higher-level
    //! frames.
    //!
    //! [`UdpSocket`]: struct.UdpSocket.html
    //! [`RecvDgram`]: struct.RecvDgram.html
    //! [`SendDgram`]: struct.SendDgram.html
    //! [`UdpFramed`]: struct.UdpFramed.html
    //! [`framed`]: struct.UdpSocket.html#method.framed
    pub use tokio_udp::{RecvDgram, SendDgram, UdpFramed, UdpSocket};
}
pub use self::udp::{UdpFramed, UdpSocket};

#[deprecated(note = "use `tokio::net::udp::RecvDgram` instead")]
#[doc(hidden)]
pub type RecvDgram<T> = self::udp::RecvDgram<T>;
#[deprecated(note = "use `tokio::net::udp::SendDgram` instead")]
#[doc(hidden)]
pub type SendDgram<T> = self::udp::SendDgram<T>;

#[cfg(unix)]
pub mod unix {
    //! Unix domain socket bindings for `tokio` (only available on unix systems).

    pub use tokio_uds::{
        ConnectFuture, Incoming, RecvDgram, SendDgram, UCred, UnixDatagram, UnixListener,
        UnixStream,
    };
}
#[cfg(unix)]
pub use self::unix::{UnixListener, UnixStream};


text:
use self::Blocker::*;
/// Synchronous channels/ports
///
/// This channel implementation differs significantly from the asynchronous
/// implementations found next to it (oneshot/stream/share). This is an
/// implementation of a synchronous, bounded buffer channel.
///
/// Each channel is created with some amount of backing buffer, and sends will
/// *block* until buffer space becomes available. A buffer size of 0 is valid,
/// which means that every successful send is paired with a successful recv.
///
/// This flavor of channels defines a new `send_opt` method for channels which
/// is the method by which a message is sent but the thread does not panic if it
/// cannot be delivered.
///
/// Another major difference is that send() will *always* return back the data
/// if it couldn't be sent. This is because it is deterministically known when
/// the data is received and when it is not received.
///
/// Implementation-wise, it can all be summed up with "use a mutex plus some
/// logic". The mutex used here is an OS native mutex, meaning that no user code
/// is run inside of the mutex (to prevent context switching). This
/// implementation shares almost all code for the buffered and unbuffered cases
/// of a synchronous channel. There are a few branches for the unbuffered case,
/// but they're mostly just relevant to blocking senders.
pub use self::Failure::*;

use core::intrinsics::abort;
use core::mem;
use core::ptr;

use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sync::mpsc::blocking::{self, SignalToken, WaitToken};
use crate::sync::{Mutex, MutexGuard};
use crate::time::Instant;

const MAX_REFCOUNT: usize = (isize::MAX) as usize;

pub struct Packet<T> {
    /// Only field outside of the mutex. Just done for kicks, but mainly because
    /// the other shared channel already had the code implemented
    channels: AtomicUsize,

    lock: Mutex<State<T>>,
}

unsafe impl<T: Send> Send for Packet<T> {}

unsafe impl<T: Send> Sync for Packet<T> {}

struct State<T> {
    disconnected: bool, // Is the channel disconnected yet?
    queue: Queue,       // queue of senders waiting to send data
    blocker: Blocker,   // currently blocked thread on this channel
    buf: Buffer<T>,     // storage for buffered messages
    cap: usize,         // capacity of this channel

    /// A curious flag used to indicate whether a sender failed or succeeded in
    /// blocking. This is used to transmit information back to the thread that it
    /// must dequeue its message from the buffer because it was not received.
    /// This is only relevant in the 0-buffer case. This obviously cannot be
    /// safely constructed, but it's guaranteed to always have a valid pointer
    /// value.
    canceled: Option<&'static mut bool>,
}

unsafe impl<T: Send> Send for State<T> {}

/// Possible flavors of threads who can be blocked on this channel.
enum Blocker {
    BlockedSender(SignalToken),
    BlockedReceiver(SignalToken),
    NoneBlocked,
}

/// Simple queue for threading threads together. Nodes are stack-allocated, so
/// this structure is not safe at all
struct Queue {
    head: *mut Node,
    tail: *mut Node,
}

struct Node {
    token: Option<SignalToken>,
    next: *mut Node,
}

unsafe impl Send for Node {}

/// A simple ring-buffer
struct Buffer<T> {
    buf: Vec<Option<T>>,
    start: usize,
    size: usize,
}

#[derive(Debug)]
pub enum Failure {
    Empty,
    Disconnected,
}

/// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
/// in the meantime. This re-locks the mutex upon returning.
fn wait<'a, 'b, T>(
    lock: &'a Mutex<State<T>>,
    mut guard: MutexGuard<'b, State<T>>,
    f: fn(SignalToken) -> Blocker,
) -> MutexGuard<'a, State<T>> {
    let (wait_token, signal_token) = blocking::tokens();
    match mem::replace(&mut guard.blocker, f(signal_token)) {
        NoneBlocked => {}
        _ => unreachable!(),
    }
    drop(guard); // unlock
    wait_token.wait(); // block
    lock.lock().unwrap() // relock
}

/// Same as wait, but waiting at most until `deadline`.
fn wait_timeout_receiver<'a, 'b, T>(
    lock: &'a Mutex<State<T>>,
    deadline: Instant,
    mut guard: MutexGuard<'b, State<T>>,
    success: &mut bool,
) -> MutexGuard<'a, State<T>> {
    let (wait_token, signal_token) = blocking::tokens();
    match mem::replace(&mut guard.blocker, BlockedReceiver(signal_token)) {
        NoneBlocked => {}
        _ => unreachable!(),
    }
    drop(guard); // unlock
    *success = wait_token.wait_max_until(deadline); // block
    let mut new_guard = lock.lock().unwrap(); // relock
    if !*success {
        abort_selection(&mut new_guard);
    }
    new_guard
}

fn abort_selection<T>(guard: &mut MutexGuard<'_, State<T>>) -> bool {
    match mem::replace(&mut guard.blocker, NoneBlocked) {
        NoneBlocked => true,
        BlockedSender(token) => {
            guard.blocker = BlockedSender(token);
            true
        }
        BlockedReceiver(token) => {
            drop(token);
            false
        }
    }
}

/// Wakes up a thread, dropping the lock at the correct time
fn wakeup<T>(token: SignalToken, guard: MutexGuard<'_, State<T>>) {
    // We need to be careful to wake up the waiting thread *outside* of the mutex
    // in case it incurs a context switch.
    drop(guard);
    token.signal();
}

impl<T> Packet<T> {
    pub fn new(capacity: usize) -> Packet<T> {
        Packet {
            channels: AtomicUsize::new(1),
            lock: Mutex::new(State {
                disconnected: false,
                blocker: NoneBlocked,
                cap: capacity,
                canceled: None,
                queue: Queue { head: ptr::null_mut(), tail: ptr::null_mut() },
                buf: Buffer {
                    buf: (0..capacity + if capacity == 0 { 1 } else { 0 }).map(|_| None).collect(),
                    start: 0,
                    size: 0,
                },
            }),
        }
    }

    // wait until a send slot is available, returning locked access to
    // the channel state.
    fn acquire_send_slot(&self) -> MutexGuard<'_, State<T>> {
        let mut node = Node { token: None, next: ptr::null_mut() };
        loop {
            let mut guard = self.lock.lock().unwrap();
            // are we ready to go?
            if guard.disconnected || guard.buf.size() < guard.buf.capacity() {
                return guard;
            }
            // no room; actually block
            let wait_token = guard.queue.enqueue(&mut node);
            drop(guard);
            wait_token.wait();
        }
    }

    pub fn send(&self, t: T) -> Result<(), T> {
        let mut guard = self.acquire_send_slot();
        if guard.disconnected {
            return Err(t);
        }
        guard.buf.enqueue(t);

        match mem::replace(&mut guard.blocker, NoneBlocked) {
            // if our capacity is 0, then we need to wait for a receiver to be
            // available to take our data. After waiting, we check again to make
            // sure the port didn't go away in the meantime. If it did, we need
            // to hand back our data.
            NoneBlocked if guard.cap == 0 => {
                let mut canceled = false;
                assert!(guard.canceled.is_none());
                guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
                let mut guard = wait(&self.lock, guard, BlockedSender);
                if canceled { Err(guard.buf.dequeue()) } else { Ok(()) }
            }

            // success, we buffered some data
            NoneBlocked => Ok(()),

            // success, someone's about to receive our buffered data.
            BlockedReceiver(token) => {
                wakeup(token, guard);
                Ok(())
            }

            BlockedSender(..) => panic!("lolwut"),
        }
    }

    pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
        let mut guard = self.lock.lock().unwrap();
        if guard.disconnected {
            Err(super::TrySendError::Disconnected(t))
        } else if guard.buf.size() == guard.buf.capacity() {
            Err(super::TrySendError::Full(t))
        } else if guard.cap == 0 {
            // With capacity 0, even though we have buffer space we can't
            // transfer the data unless there's a receiver waiting.
            match mem::replace(&mut guard.blocker, NoneBlocked) {
                NoneBlocked => Err(super::TrySendError::Full(t)),
                BlockedSender(..) => unreachable!(),
                BlockedReceiver(token) => {
                    guard.buf.enqueue(t);
                    wakeup(token, guard);
                    Ok(())
                }
            }
        } else {
            // If the buffer has some space and the capacity isn't 0, then we
            // just enqueue the data for later retrieval, ensuring to wake up
            // any blocked receiver if there is one.
            assert!(guard.buf.size() < guard.buf.capacity());
            guard.buf.enqueue(t);
            match mem::replace(&mut guard.blocker, NoneBlocked) {
                BlockedReceiver(token) => wakeup(token, guard),
                NoneBlocked => {}
                BlockedSender(..) => unreachable!(),
            }
            Ok(())
        }
    }

    // Receives a message from this channel
    //
    // When reading this, remember that there can only ever be one receiver at
    // time.
    pub fn recv(&self, deadline: Option<Instant>) -> Result<T, Failure> {
        let mut guard = self.lock.lock().unwrap();

        let mut woke_up_after_waiting = false;
        // Wait for the buffer to have something in it. No need for a
        // while loop because we're the only receiver.
        if !guard.disconnected && guard.buf.size() == 0 {
            if let Some(deadline) = deadline {
                guard =
                    wait_timeout_receiver(&self.lock, deadline, guard, &mut woke_up_after_waiting);
            } else {
                guard = wait(&self.lock, guard, BlockedReceiver);
                woke_up_after_waiting = true;
            }
        }

        // N.B., channel could be disconnected while waiting, so the order of
        // these conditionals is important.
        if guard.disconnected && guard.buf.size() == 0 {
            return Err(Disconnected);
        }

        // Pick up the data, wake up our neighbors, and carry on
        assert!(guard.buf.size() > 0 || (deadline.is_some() && !woke_up_after_waiting));

        if guard.buf.size() == 0 {
            return Err(Empty);
        }

        let ret = guard.buf.dequeue();
        self.wakeup_senders(woke_up_after_waiting, guard);
        Ok(ret)
    }

    pub fn try_recv(&self) -> Result<T, Failure> {
        let mut guard = self.lock.lock().unwrap();

        // Easy cases first
        if guard.disconnected && guard.buf.size() == 0 {
            return Err(Disconnected);
        }
        if guard.buf.size() == 0 {
            return Err(Empty);
        }

        // Be sure to wake up neighbors
        let ret = Ok(guard.buf.dequeue());
        self.wakeup_senders(false, guard);
        ret
    }

    // Wake up pending senders after some data has been received
    //
    // * `waited` - flag if the receiver blocked to receive some data, or if it
    //              just picked up some data on the way out
    // * `guard` - the lock guard that is held over this channel's lock
    fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<'_, State<T>>) {
        let pending_sender1: Option<SignalToken> = guard.queue.dequeue();

        // If this is a no-buffer channel (cap == 0), then if we didn't wait we
        // need to ACK the sender. If we waited, then the sender waking us up
        // was already the ACK.
        let pending_sender2 = if guard.cap == 0 && !waited {
            match mem::replace(&mut guard.blocker, NoneBlocked) {
                NoneBlocked => None,
                BlockedReceiver(..) => unreachable!(),
                BlockedSender(token) => {
                    guard.canceled.take();
                    Some(token)
                }
            }
        } else {
            None
        };
        mem::drop(guard);

        // only outside of the lock do we wake up the pending threads
        if let Some(token) = pending_sender1 {
            token.signal();
        }
        if let Some(token) = pending_sender2 {
            token.signal();
        }
    }

    // Prepares this shared packet for a channel clone, essentially just bumping
    // a refcount.
    pub fn clone_chan(&self) {
        let old_count = self.channels.fetch_add(1, Ordering::SeqCst);

        // See comments on Arc::clone() on why we do this (for `mem::forget`).
        if old_count > MAX_REFCOUNT {
            unsafe {
                abort();
            }
        }
    }

    pub fn drop_chan(&self) {
        // Only flag the channel as disconnected if we're the last channel
        match self.channels.fetch_sub(1, Ordering::SeqCst) {
            1 => {}
            _ => return,
        }

        // Not much to do other than wake up a receiver if one's there
        let mut guard = self.lock.lock().unwrap();
        if guard.disconnected {
            return;
        }
        guard.disconnected = true;
        match mem::replace(&mut guard.blocker, NoneBlocked) {
            NoneBlocked => {}
            BlockedSender(..) => unreachable!(),
            BlockedReceiver(token) => wakeup(token, guard),
        }
    }

    pub fn drop_port(&self) {
        let mut guard = self.lock.lock().unwrap();

        if guard.disconnected {
            return;
        }
        guard.disconnected = true;

        // If the capacity is 0, then the sender may want its data back after
        // we're disconnected. Otherwise it's now our responsibility to destroy
        // the buffered data. As with many other portions of this code, this
        // needs to be careful to destroy the data *outside* of the lock to
        // prevent deadlock.
        let _data = if guard.cap != 0 { mem::take(&mut guard.buf.buf) } else { Vec::new() };
        let mut queue =
            mem::replace(&mut guard.queue, Queue { head: ptr::null_mut(), tail: ptr::null_mut() });

        let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
            NoneBlocked => None,
            BlockedSender(token) => {
                *guard.canceled.take().unwrap() = true;
                Some(token)
            }
            BlockedReceiver(..) => unreachable!(),
        };
        mem::drop(guard);

        while let Some(token) = queue.dequeue() {
            token.signal();
        }
        if let Some(token) = waiter {
            token.signal();
        }
    }
}

impl<T> Drop for Packet<T> {
    fn drop(&mut self) {
        assert_eq!(self.channels.load(Ordering::SeqCst), 0);
        let mut guard = self.lock.lock().unwrap();
        assert!(guard.queue.dequeue().is_none());
        assert!(guard.canceled.is_none());
    }
}

////////////////////////////////////////////////////////////////////////////////
// Buffer, a simple ring buffer backed by Vec<T>
////////////////////////////////////////////////////////////////////////////////

impl<T> Buffer<T> {
    fn enqueue(&mut self, t: T) {
        let pos = (self.start + self.size) % self.buf.len();
        self.size += 1;
        let prev = mem::replace(&mut self.buf[pos], Some(t));
        assert!(prev.is_none());
    }

    fn dequeue(&mut self) -> T {
        let start = self.start;
        self.size -= 1;
        self.start = (self.start + 1) % self.buf.len();
        let result = &mut self.buf[start];
        result.take().unwrap()
    }

    fn size(&self) -> usize {
        self.size
    }
    fn capacity(&self) -> usize {
        self.buf.len()
    }
}

////////////////////////////////////////////////////////////////////////////////
// Queue, a simple queue to enqueue threads with (stack-allocated nodes)
////////////////////////////////////////////////////////////////////////////////

impl Queue {
    fn enqueue(&mut self, node: &mut Node) -> WaitToken {
        let (wait_token, signal_token) = blocking::tokens();
        node.token = Some(signal_token);
        node.next = ptr::null_mut();

        if self.tail.is_null() {
            self.head = node as *mut Node;
            self.tail = node as *mut Node;
        } else {
            unsafe {
                (*self.tail).next = node as *mut Node;
                self.tail = node as *mut Node;
            }
        }

        wait_token
    }

    fn dequeue(&mut self) -> Option<SignalToken> {
        if self.head.is_null() {
            return None;
        }
        let node = self.head;
        self.head = unsafe { (*node).next };
        if self.head.is_null() {
            self.tail = ptr::null_mut();
        }
        unsafe {
            (*node).next = ptr::null_mut();
            Some((*node).token.take().unwrap())
        }
    }
}


text:
//! A very basic example of a program blinking a LED diode using native library API.
//!
//! This example assumes that physical pin #7 is connected to diode's anode (+).
//! Make sure to put resistor to reduce current flowing through the diode.

use c2_mmap_gpio::{Device, PinId, Value};
use std::error::Error;
use std::thread::sleep;
use std::time::Duration;

fn main() -> Result<(), Box<dyn Error>> {
    let mut odroid = Device::new()?;
    let mut led_pin = odroid.output_pin(PinId::Phy7)?;
    let blink_interval = Duration::from_millis(500);

    loop {
        led_pin.set_value(Value::High);
        sleep(blink_interval);
        led_pin.set_value(Value::Low);
        sleep(blink_interval);
    }
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use cssparser::Parser as CssParser;
use document_loader::LoadType;
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLLinkElementBinding;
use dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference};
use dom::bindings::refcounted::Trusted;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::domtokenlist::DOMTokenList;
use dom::element::{AttributeMutation, Element, ElementCreator};
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use encoding::EncodingRef;
use encoding::all::UTF_8;
use hyper::header::ContentType;
use hyper::mime::{Mime, TopLevel, SubLevel};
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use layout_interface::Msg;
use net_traits::{AsyncResponseListener, AsyncResponseTarget, Metadata, NetworkError};
use network_listener::{NetworkListener, PreInvoke};
use script_traits::{MozBrowserEvent, ScriptMsg as ConstellationMsg};
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::default::Default;
use std::mem;
use std::sync::{Arc, Mutex};
use string_cache::Atom;
use style::attr::AttrValue;
use style::media_queries::{MediaQueryList, parse_media_query_list};
use style::parser::ParserContextExtraData;
use style::servo::Stylesheet;
use style::stylesheets::Origin;
use url::Url;
use util::str::HTML_SPACE_CHARACTERS;

no_jsmanaged_fields!(Stylesheet);

#[dom_struct]
pub struct HTMLLinkElement {
    htmlelement: HTMLElement,
    rel_list: MutNullableHeap<JS<DOMTokenList>>,
    stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>,

    /// https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts
    parser_inserted: Cell<bool>,
}

impl HTMLLinkElement {
    fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document,
                     creator: ElementCreator) -> HTMLLinkElement {
        HTMLLinkElement {
            htmlelement: HTMLElement::new_inherited(localName, prefix, document),
            rel_list: Default::default(),
            parser_inserted: Cell::new(creator == ElementCreator::ParserCreated),
            stylesheet: DOMRefCell::new(None),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(localName: Atom,
               prefix: Option<DOMString>,
               document: &Document,
               creator: ElementCreator) -> Root<HTMLLinkElement> {
        let element = HTMLLinkElement::new_inherited(localName, prefix, document, creator);
        Node::reflect_node(box element, document, HTMLLinkElementBinding::Wrap)
    }

    pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
        self.stylesheet.borrow().clone()
    }
}

fn get_attr(element: &Element, local_name: &Atom) -> Option<String> {
    let elem = element.get_attribute(&ns!(), local_name);
    elem.map(|e| {
        let value = e.value();
        (**value).to_owned()
    })
}

fn string_is_stylesheet(value: &Option<String>) -> bool {
    match *value {
        Some(ref value) => {
            let mut found_stylesheet = false;
            for s in value.split(HTML_SPACE_CHARACTERS).into_iter() {
                if s.eq_ignore_ascii_case("alternate") {
                    return false;
                }

                if s.eq_ignore_ascii_case("stylesheet") {
                    found_stylesheet = true;
                }
            }
            found_stylesheet
        },
        None => false,
    }
}

/// Favicon spec usage in accordance with CEF implementation:
/// only url of icon is required/used
/// https://html.spec.whatwg.org/multipage/#rel-icon
fn is_favicon(value: &Option<String>) -> bool {
    match *value {
        Some(ref value) => {
            value.split(HTML_SPACE_CHARACTERS)
                .any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon"))
        },
        None => false,
    }
}

impl VirtualMethods for HTMLLinkElement {
    fn super_type(&self) -> Option<&VirtualMethods> {
        Some(self.upcast::<HTMLElement>() as &VirtualMethods)
    }

    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
        self.super_type().unwrap().attribute_mutated(attr, mutation);
        if !self.upcast::<Node>().is_in_doc() || mutation == AttributeMutation::Removed {
            return;
        }

        let rel = get_attr(self.upcast(), &atom!("rel"));
        match attr.local_name() {
            &atom!("href") => {
                if string_is_stylesheet(&rel) {
                    self.handle_stylesheet_url(&attr.value());
                } else if is_favicon(&rel) {
                    let sizes = get_attr(self.upcast(), &atom!("sizes"));
                    self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes);
                }
            },
            &atom!("sizes") => {
                if is_favicon(&rel) {
                    if let Some(ref href) = get_attr(self.upcast(), &atom!("href")) {
                        self.handle_favicon_url(rel.as_ref().unwrap(), href, &Some(attr.value().to_string()));
                    }
                }
            },
            &atom!("media") => {
                if string_is_stylesheet(&rel) {
                    self.handle_stylesheet_url(&attr.value());
                }
            },
            _ => {},
        }
    }

    fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
        match name {
            &atom!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
            _ => self.super_type().unwrap().parse_plain_attribute(name, value),
        }
    }

    fn bind_to_tree(&self, tree_in_doc: bool) {
        if let Some(ref s) = self.super_type() {
            s.bind_to_tree(tree_in_doc);
        }

        if tree_in_doc {
            let element = self.upcast();

            let rel = get_attr(element, &atom!("rel"));
            let href = get_attr(element, &atom!("href"));
            let sizes = get_attr(self.upcast(), &atom!("sizes"));

            match href {
                Some(ref href) if string_is_stylesheet(&rel) => {
                    self.handle_stylesheet_url(href);
                }
                Some(ref href) if is_favicon(&rel) => {
                    self.handle_favicon_url(rel.as_ref().unwrap(), href, &sizes);
                }
                _ => {}
            }
        }
    }
}

impl HTMLLinkElement {
    fn handle_stylesheet_url(&self, href: &str) {
        let document = document_from_node(self);
        match document.base_url().join(href) {
            Ok(url) => {
                let element = self.upcast::<Element>();

                let mq_attribute = element.get_attribute(&ns!(), &atom!("media"));
                let value = mq_attribute.r().map(|a| a.value());
                let mq_str = match value {
                    Some(ref value) => &***value,
                    None => "",
                };
                let mut css_parser = CssParser::new(&mq_str);
                let media = parse_media_query_list(&mut css_parser);

                // TODO: #8085 - Don't load external stylesheets if the node's mq doesn't match.
                let elem = Trusted::new(self);

                let context = Arc::new(Mutex::new(StylesheetContext {
                    elem: elem,
                    media: Some(media),
                    data: vec!(),
                    metadata: None,
                    url: url.clone(),
                }));

                let (action_sender, action_receiver) = ipc::channel().unwrap();
                let listener = NetworkListener {
                    context: context,
                    script_chan: document.window().networking_task_source(),
                };
                let response_target = AsyncResponseTarget {
                    sender: action_sender,
                };
                ROUTER.add_route(action_receiver.to_opaque(), box move |message| {
                    listener.notify_action(message.to().unwrap());
                });

                if self.parser_inserted.get() {
                    document.increment_script_blocking_stylesheet_count();
                }
                document.load_async(LoadType::Stylesheet(url), response_target);
            }
            Err(e) => debug!("Parsing url {} failed: {}", href, e)
        }
    }

    fn handle_favicon_url(&self, rel: &str, href: &str, sizes: &Option<String>) {
        let document = document_from_node(self);
        match document.base_url().join(href) {
            Ok(url) => {
                let event = ConstellationMsg::NewFavicon(url.clone());
                document.window().constellation_chan().send(event).unwrap();

                let mozbrowser_event = match *sizes {
                    Some(ref sizes) => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), sizes.to_owned()),
                    None => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), "".to_owned())
                };
                document.trigger_mozbrowser_event(mozbrowser_event);
            }
            Err(e) => debug!("Parsing url {} failed: {}", href, e)
        }
    }
}

/// The context required for asynchronously loading an external stylesheet.
struct StylesheetContext {
    /// The element that initiated the request.
    elem: Trusted<HTMLLinkElement>,
    media: Option<MediaQueryList>,
    /// The response body received to date.
    data: Vec<u8>,
    /// The response metadata received to date.
    metadata: Option<Metadata>,
    /// The initial URL requested.
    url: Url,
}

impl PreInvoke for StylesheetContext {}

impl AsyncResponseListener for StylesheetContext {
    fn headers_available(&mut self, metadata: Result<Metadata, NetworkError>) {
        self.metadata = metadata.ok();
        if let Some(ref meta) = self.metadata {
            if let Some(ContentType(Mime(TopLevel::Text, SubLevel::Css, _))) = meta.content_type {
            } else {
                self.elem.root().upcast::<EventTarget>().fire_simple_event("error");
            }
        }
    }

    fn data_available(&mut self, payload: Vec<u8>) {
        let mut payload = payload;
        self.data.append(&mut payload);
    }

    fn response_complete(&mut self, status: Result<(), NetworkError>) {
        if status.is_err() {
            self.elem.root().upcast::<EventTarget>().fire_simple_event("error");
            return;
        }
        let data = mem::replace(&mut self.data, vec!());
        let metadata = match self.metadata.take() {
            Some(meta) => meta,
            None => return,
        };
        // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding
        let environment_encoding = UTF_8 as EncodingRef;
        let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s);
        let final_url = metadata.final_url;

        let elem = self.elem.root();
        let win = window_from_node(&*elem);

        let mut sheet = Stylesheet::from_bytes(&data, final_url, protocol_encoding_label,
                                               Some(environment_encoding), Origin::Author,
                                               win.css_error_reporter(),
                                               ParserContextExtraData::default());
        let media = self.media.take().unwrap();
        sheet.set_media(Some(media));
        let sheet = Arc::new(sheet);

        let elem = elem.r();
        let document = document_from_node(elem);
        let document = document.r();

        let win = window_from_node(elem);
        win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap();

        *elem.stylesheet.borrow_mut() = Some(sheet);
        document.invalidate_stylesheets();
        if elem.parser_inserted.get() {
            document.decrement_script_blocking_stylesheet_count();
        }
        document.finish_load(LoadType::Stylesheet(self.url.clone()));
    }
}

impl HTMLLinkElementMethods for HTMLLinkElement {
    // https://html.spec.whatwg.org/multipage/#dom-link-href
    make_url_getter!(Href, "href");

    // https://html.spec.whatwg.org/multipage/#dom-link-href
    make_setter!(SetHref, "href");

    // https://html.spec.whatwg.org/multipage/#dom-link-rel
    make_getter!(Rel, "rel");

    // https://html.spec.whatwg.org/multipage/#dom-link-rel
    make_setter!(SetRel, "rel");

    // https://html.spec.whatwg.org/multipage/#dom-link-media
    make_getter!(Media, "media");

    // https://html.spec.whatwg.org/multipage/#dom-link-media
    make_setter!(SetMedia, "media");

    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
    make_getter!(Hreflang, "hreflang");

    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
    make_setter!(SetHreflang, "hreflang");

    // https://html.spec.whatwg.org/multipage/#dom-link-type
    make_getter!(Type, "type");

    // https://html.spec.whatwg.org/multipage/#dom-link-type
    make_setter!(SetType, "type");

    // https://html.spec.whatwg.org/multipage/#dom-link-rellist
    fn RelList(&self) -> Root<DOMTokenList> {
        self.rel_list.or_init(|| DOMTokenList::new(self.upcast(), &atom!("rel")))
    }

    // https://html.spec.whatwg.org/multipage/#dom-link-charset
    make_getter!(Charset, "charset");

    // https://html.spec.whatwg.org/multipage/#dom-link-charset
    make_setter!(SetCharset, "charset");

    // https://html.spec.whatwg.org/multipage/#dom-link-rev
    make_getter!(Rev, "rev");

    // https://html.spec.whatwg.org/multipage/#dom-link-rev
    make_setter!(SetRev, "rev");

    // https://html.spec.whatwg.org/multipage/#dom-link-target
    make_getter!(Target, "target");

    // https://html.spec.whatwg.org/multipage/#dom-link-target
    make_setter!(SetTarget, "target");
}


text:
use crate::native_types::{Arithmetic, Witness};
use noir_field::FieldElement;

use std::ops::{Add, Mul, Neg, Sub};

#[derive(Clone, Copy, Debug)]
pub struct Linear {
    pub mul_scale: FieldElement,
    pub witness: Witness,
    pub add_scale: FieldElement,
}

impl Linear {
    pub fn is_unit(&self) -> bool {
        self.mul_scale.is_one() && self.add_scale.is_zero()
    }
    pub fn from_witness(witness: Witness) -> Linear {
        Linear {
            mul_scale: FieldElement::one(),
            witness,
            add_scale: FieldElement::zero(),
        }
    }
    // XXX: This is true for the NPC languages that we use, are there any where this is not true?
    pub const fn can_defer_constraint(&self) -> bool {
        true
    }
}

impl From<Witness> for Linear {
    fn from(w: Witness) -> Linear {
        Linear::from_witness(w)
    }
}
impl From<FieldElement> for Linear {
    fn from(element: FieldElement) -> Linear {
        Linear {
            add_scale: element,
            witness: Witness::default(),
            mul_scale: FieldElement::zero(),
        }
    }
}

impl Add<&Linear> for &Linear {
    type Output = Arithmetic;
    fn add(self, rhs: &Linear) -> Self::Output {
        // (Ax+B) + ( Cx + D) = (Ax + Cx) + ( B+D)
        // (Ax + B) + (Cy + D) = Ax + Cy + (B+D)
        Arithmetic {
            mul_terms: Vec::new(),
            linear_combinations: vec![(self.mul_scale, self.witness), (rhs.mul_scale, rhs.witness)],
            q_c: self.add_scale + rhs.add_scale,
        }
    }
}

impl Neg for &Linear {
    type Output = Linear;
    fn neg(self) -> Self::Output {
        // -(Ax + B) = -Ax - B
        Linear {
            add_scale: -self.add_scale,
            witness: self.witness,
            mul_scale: -self.mul_scale,
        }
    }
}

impl Mul<&Linear> for &Linear {
    type Output = Arithmetic;
    fn mul(self, rhs: &Linear) -> Self::Output {
        // (Ax+B)(Cy+D) = ACxy + ADx + BCy + BD
        let a = self.mul_scale;
        let b = self.add_scale;
        let x = self.witness;

        let c = rhs.mul_scale;
        let d = rhs.add_scale;
        let y = rhs.witness;

        let ac = a * c;
        let ad = a * d;
        let bc = b * c;
        let bd = b * d;

        let mul_terms = {
            let mut mt = Vec::with_capacity(1);
            if ac != FieldElement::zero() {
                mt.push((ac, x, y))
            }
            mt
        };

        let linear_combinations = {
            let mut lc = Vec::with_capacity(2);

            if ad != FieldElement::zero() {
                lc.push((ad, x));
            }
            if bc != FieldElement::zero() {
                lc.push((bc, y));
            }
            lc
        };

        Arithmetic {
            mul_terms,
            linear_combinations,
            q_c: bd,
        }
    }
}
impl Mul<&FieldElement> for &Linear {
    type Output = Linear;
    fn mul(self, rhs: &FieldElement) -> Self::Output {
        Linear {
            mul_scale: self.mul_scale * *rhs,
            witness: self.witness,
            add_scale: self.add_scale * *rhs,
        }
    }
}
impl Add<&FieldElement> for &Linear {
    type Output = Linear;
    fn add(self, rhs: &FieldElement) -> Self::Output {
        Linear {
            mul_scale: self.mul_scale,
            witness: self.witness,
            add_scale: self.add_scale + *rhs,
        }
    }
}

/// Convenience Trait implementations
impl Add<Linear> for Linear {
    type Output = Arithmetic;
    fn add(self, rhs: Linear) -> Self::Output {
        &self + &rhs
    }
}
impl Mul<Linear> for Linear {
    type Output = Arithmetic;
    fn mul(self, rhs: Linear) -> Self::Output {
        &self * &rhs
    }
}
impl Add<&Linear> for Linear {
    type Output = Arithmetic;
    fn add(self, rhs: &Linear) -> Self::Output {
        &self + rhs
    }
}
impl Mul<&Linear> for Linear {
    type Output = Arithmetic;
    fn mul(self, rhs: &Linear) -> Self::Output {
        &self * rhs
    }
}
impl Sub<&Linear> for &Linear {
    type Output = Arithmetic;
    fn sub(self, rhs: &Linear) -> Self::Output {
        self + &-rhs
    }
}
impl Sub<&FieldElement> for &Linear {
    type Output = Linear;
    fn sub(self, rhs: &FieldElement) -> Self::Output {
        self + &-*rhs
    }
}


text:
// rustfmt-enum_discrim_align_threshold: 40

enum Standard {
    A = 1,
    Bcdef = 2,
}

enum NoDiscrims {
    ThisIsAFairlyLongEnumVariantWithoutDiscrimLongerThan40,
    A = 1,
    ThisIsAnotherFairlyLongEnumVariantWithoutDiscrimLongerThan40,
    Bcdef = 2,
}

enum TooLong {
    ThisOneHasDiscrimAaaaaaaaaaaaaaaaaaaaaaChar40 = 10,
    A = 1,
    Bcdef = 2,
}

enum Borderline {
    ThisOneHasDiscrimAaaaaaaaaaaaaaaaaaaaaa = 10,
    A = 1,
    Bcdef = 2,
}

// Live specimen from #1686
enum LongWithSmallDiff {
    SceneColorimetryEstimates = 0x73636F65,
    SceneAppearanceEstimates = 0x73617065,
    FocalPlaneColorimetryEstimates = 0x66706365,
    ReflectionHardcopyOriginalColorimetry = 0x72686F63,
    ReflectionPrintOutputColorimetry = 0x72706F63,
}