Module aws_smithy_runtime_api::shared

source ·
Expand description

Conversion traits for converting an unshared type into a shared type.

The standard From/Into traits can’t be used for this purpose due to the blanket implementation of Into.

This implementation also adds a maybe_shared method and impl_shared_conversions macro to trivially avoid nesting shared types with other shared types.

§What is a shared type?

A shared type is a new-type around a Send + Sync reference counting smart pointer (i.e., an Arc) around an object-safe trait. Shared types are used to share a trait object among multiple threads/clients/requests. For example, SharedHttpConnector, is a shared type for the HttpConnector trait, which allows for sharing a single HTTP connector instance (and its connection pool) among multiple clients.

A shared type implements the FromUnshared trait, which allows any implementation of the trait it wraps to easily be converted into it.

To illustrate, let’s examine the RuntimePlugin/SharedRuntimePlugin duo. The following instantiates a concrete implementation of the RuntimePlugin trait. We can do RuntimePlugin things on this instance.

use aws_smithy_runtime_api::client::runtime_plugin::StaticRuntimePlugin;

let some_plugin = StaticRuntimePlugin::new();

We can convert this instance into a shared type in two different ways.

use aws_smithy_runtime_api::client::runtime_plugin::SharedRuntimePlugin;
use aws_smithy_runtime_api::shared::{IntoShared, FromUnshared};

// Using the `IntoShared` trait
let shared: SharedRuntimePlugin = some_plugin.into_shared();

// Using the `FromUnshared` trait:
let shared = SharedRuntimePlugin::from_unshared(some_plugin);

The IntoShared trait is useful for making functions that take any RuntimePlugin impl and convert it to a shared type. For example, this function will convert the given plugin argument into a SharedRuntimePlugin.

use aws_smithy_runtime_api::shared::IntoShared;

fn take_shared(plugin: impl RuntimePlugin + 'static) {
    let _plugin: SharedRuntimePlugin = plugin.into_shared();
}

This can be called with different types, and even if a SharedRuntimePlugin is passed in, it won’t nest that SharedRuntimePlugin inside of another SharedRuntimePlugin.

// Automatically converts it to `SharedRuntimePlugin(StaticRuntimePlugin)`
take_shared(StaticRuntimePlugin::new());

// This is OK.
// It create a `SharedRuntimePlugin(StaticRuntimePlugin))`
// instead of a nested `SharedRuntimePlugin(SharedRuntimePlugin(StaticRuntimePlugin)))`
take_shared(SharedRuntimePlugin::new(StaticRuntimePlugin::new()));

Traits§

  • Like the From trait, but for converting to a shared type.
  • Like the Into trait, but for (efficiently) converting into a shared type.

Functions§

  • Given a value, determine if that value is already shared. If it is, return it. Otherwise, wrap it in a shared type.