Struct abi_stable::DynTrait[][src]

#[repr(C)]
pub struct DynTrait<'borr, P, I, EV = ()> where
    P: GetPointerKind
{ /* fields omitted */ }
Expand description

DynTrait implements ffi-safe trait objects, for a selection of traits.

Passing opaque values around with DynTrait<_>

One can pass non-StableAbi types around by using type erasure, using this type.

It generally looks like DynTrait<'borrow, Pointer<()>, Interface>, where:

  • 'borrow is the borrow that the type that was erased had.

  • Pointer is a pointer type that implements AsPtr.

  • Interface is an InterfaceType, which describes what traits are required when constructing the DynTrait<_> and which ones it implements.

The InterfaceType trait allows describing which traits are required when constructing a DynTrait<_>, and which ones it implements.

Construction

To construct a DynTrait<_> one can use these associated functions:

  • from_value: Can be constructed from the value directly. Requires a value that implements ImplType.

  • from_ptr: Can be constructed from a pointer of a value. Requires a value that implements ImplType.

  • from_any_value: Can be constructed from the value directly.Requires a 'static value.

  • from_any_ptr Can be constructed from a pointer of a value.Requires a 'static value.

  • from_borrowing_value: Can be constructed from the value directly.Cannot downcast the DynTrait afterwards.

  • from_borrowing_ptr Can be constructed from a pointer of a value.Cannot downcast the DynTrait afterwards.

DynTrait uses the impls of the value in methods, which means that the pointer itself does not have to implement those traits,

Trait object

DynTrait<'borrow, Pointer<()>, Interface> can be used as a trait object for any combination of the traits listed below.

These are the traits:

  • Send

  • Sync

  • Iterator

  • DoubleEndedIterator

  • std::fmt::Write

  • std::io::Write

  • std::io::Seek

  • std::io::Read

  • std::io::BufRead

  • Clone

  • Display

  • Debug

  • std::error::Error

  • Default: Can be called as an inherent method.

  • Eq

  • PartialEq

  • Ord

  • PartialOrd

  • Hash

  • serde::Deserialize: first deserializes from a string, and then calls the objects’ Deserialize impl.

  • serde::Serialize: first calls the objects’ Deserialize impl, then serializes that as a string.

Deconstruction

DynTrait<_> can then be unwrapped into a concrete type, within the same dynamic library/executable that constructed it, using these (fallible) conversion methods:

  • downcast_into_impltype: Unwraps into a pointer to T. Where DynTrait<P<()>, Interface>’s Interface must equal <T as ImplType>::Interface

  • downcast_as_impltype: Unwraps into a &T. Where DynTrait<P<()>, Interface>’s Interface must equal <T as ImplType>::Interface

  • downcast_as_mut_impltype: Unwraps into a &mut T. Where DynTrait<P<()>, Interface>’s Interface must equal <T as ImplType>::Interface

  • downcast_into: Unwraps into a pointer to T.Requires T:'static.

  • downcast_as: Unwraps into a &T.Requires T:'static.

  • downcast_as_mut: Unwraps into a &mut T.Requires T:'static.

DynTrait cannot be converted back if it was created using DynTrait::from_borrowing_*.

Passing DynTrait between dynamic libraries

Passing DynTrait between dynamic libraries (as in between the dynamic libraries directly loaded by the same binary/dynamic library) may cause the program to panic at runtime with an error message stating that the trait is not implemented for the specific interface.

This can only happen if you are passing DynTrait between dynamic libraries, or if DynTrait was instantiated in the parent passed to a child, a DynTrait instantiated in a child dynamic library passed to the parent should not cause a panic, it would be a bug.

        binary
  _________|___________
lib0      lib1      lib2
  |         |         |
lib00    lib10      lib20

In this diagram passing a DynTrait constructed in lib00 to anything other than the binary or lib0 will cause the panic to happen if:

  • The InterfaceType requires extra traits in the version of the Interface that lib1 and lib2 know about (that the binary does not require).

  • lib1 or lib2 attempt to call methods that require the traits that were added to the InterfaceType, in versions of that interface that only they know about.

serializing/deserializing DynTraits

To be able to serialize and deserialize a DynTrait, the interface it uses must implement SerializeProxyType and DeserializeDyn, and the implementation type must implement SerializeImplType.

For a more realistic example you can look at the “examples/0_modules_and_interface_types” crates in the repository for this crate.

use abi_stable::{
    erased_types::{
        DeserializeDyn, ImplType, InterfaceType, SerializeImplType,
        SerializeProxyType, TypeInfo,
    },
    external_types::{RawValueBox, RawValueRef},
    impl_get_type_info,
    prefix_type::{PrefixTypeTrait, WithMetadata},
    sabi_extern_fn,
    std_types::{RBox, RBoxError, RErr, ROk, RResult, RStr},
    traits::IntoReprC,
    type_level::bools::*,
    DynTrait, StableAbi,
};

//////////////////////////////////
////   In interface crate    /////
//////////////////////////////////

use serde::{Deserialize, Serialize};

/// An `InterfaceType` describing which traits are implemented by FooInterfaceBox.
#[repr(C)]
#[derive(StableAbi)]
#[sabi(impl_InterfaceType(Sync, Debug, Clone, Serialize, Deserialize, PartialEq))]
pub struct FooInterface;

/// The state passed to most functions in the TextOpsMod module.
pub type FooInterfaceBox = DynTrait<'static, RBox<()>, FooInterface>;

/// First <ConcreteType as DeserializeImplType>::serialize_impl returns
/// a RawValueBox containing the serialized data,
/// then the returned RawValueBox is serialized.
impl<'s> SerializeProxyType<'s> for FooInterface {
    type Proxy = RawValueBox;
}

impl<'borr> DeserializeDyn<'borr, FooInterfaceBox> for FooInterface {
    type Proxy = RawValueRef<'borr>;

    fn deserialize_dyn(
        s: RawValueRef<'borr>,
    ) -> Result<FooInterfaceBox, RBoxError> {
        MODULE.deserialize_foo()(s.get_rstr()).into_result()
    }
}

// `#[sabi(kind(Prefix))]` declares this type as being a prefix-type,
// generating both of these types:<br>
//
//     - Module_Prefix`:
//     A struct with the fields up to (and including) the field with the
//     `#[sabi(last_prefix_field)]` attribute.
//
//     - Module_Ref`:
//      An ffi-safe pointer to a `Module`, with methods to get `Module`'s fields.
#[repr(C)]
#[derive(StableAbi)]
#[sabi(kind(Prefix))]
#[sabi(missing_field(panic))]
pub struct Module {
    #[sabi(last_prefix_field)]
    pub deserialize_foo:
        extern "C" fn(s: RStr<'_>) -> RResult<FooInterfaceBox, RBoxError>,
}

// This is how ffi-safe pointers to non-generic prefix types are constructed
// at compile-time.
const MODULE: Module_Ref = {
    const S: &WithMetadata<Module> =
        &WithMetadata::new(PrefixTypeTrait::METADATA, Module { deserialize_foo });

    Module_Ref(S.static_as_prefix())
};

/////////////////////////////////////////////////////////////////////////////////////////
////   In implementation crate (the one that gets compiled as a dynamic library)    /////
/////////////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Foo {
    name: String,
}

impl ImplType for Foo {
    type Interface = FooInterface;

    const INFO: &'static TypeInfo = impl_get_type_info! { Foo };
}

impl<'s> SerializeImplType<'s> for Foo {
    type Interface = FooInterface;

    fn serialize_impl(&'s self) -> Result<RawValueBox, RBoxError> {
        match serde_json::to_string(self) {
            Ok(v) => RawValueBox::try_from_string(v).map_err(RBoxError::new),
            Err(e) => Err(RBoxError::new(e)),
        }
    }
}

#[sabi_extern_fn]
pub fn deserialize_foo(s: RStr<'_>) -> RResult<FooInterfaceBox, RBoxError> {
    match serde_json::from_str::<Foo>(s.into()) {
        Ok(x) => ROk(DynTrait::from_value(x)),
        Err(e) => RErr(RBoxError::new(e)),
    }
}

#[test]
fn testing_serialization_deserialization() {
    let foo = Foo {
        name: "nope".into(),
    };
    let object = DynTrait::from_value(foo.clone());

    assert_eq!(
        serde_json::from_str::<FooInterfaceBox>(
            r##"
        {
            "name":"nope"
        }
    "##
        )
        .unwrap(),
        object
    );

    assert_eq!(
        serde_json::to_string(&object).unwrap(),
        r##"{"name":"nope"}"##
    );
}

Examples

In the Readme

The primary example using DynTrait<_> is in the readme.

Readme is in the repository for this crate, crates.io, lib.rs.

Comparing DynTraits

This is only possible if the erased types don’t contain borrows, and they are not constructed using DynTrait::from_borrowing_* methods.

DynTraits wrapping different pointer types can be compared with each other, it simply uses the values’ implementation of PartialEq.

use abi_stable::{
    erased_types::interfaces::PartialEqInterface,
    std_types::{RArc, RBox},
    DynTrait, RMut, RRef,
};

{
    // `DynTrait`s constructed from `&` are `DynTrait<'_, RRef<'_, ()>, _>`
    // since `&T` can't soundly be transmuted back and forth into `&()`
    let left: DynTrait<'static, RRef<'_, ()>, PartialEqInterface> =
        DynTrait::from_any_ptr(&100, PartialEqInterface);

    let mut n100 = 100;
    // `DynTrait`s constructed from `&mut` are `DynTrait<'_, RMut<'_, ()>, _>`
    // since `&mut T` can't soundly be transmuted back and forth into `&mut ()`
    let right: DynTrait<'static, RMut<'_, ()>, PartialEqInterface> =
        DynTrait::from_any_ptr(&mut n100, PartialEqInterface);

    assert_eq!(left, right);
}
{
    let left: DynTrait<'static, RBox<()>, _> =
        DynTrait::from_any_value(200, PartialEqInterface);

    let right: DynTrait<'static, RArc<()>, _> =
        DynTrait::from_any_ptr(RArc::new(200), PartialEqInterface);

    assert_eq!(left, right);
}

Writing to a DynTrait

This is an example of using the write!() macro with DynTrait.

use abi_stable::{erased_types::interfaces::FmtWriteInterface, DynTrait, RMut};

use std::fmt::Write;

let mut buffer = String::new();

let mut wrapped: DynTrait<'static, RMut<'_, ()>, FmtWriteInterface> =
    DynTrait::from_any_ptr(&mut buffer, FmtWriteInterface);

write!(wrapped, "Foo").unwrap();
write!(wrapped, "Bar").unwrap();
write!(wrapped, "Baz").unwrap();

drop(wrapped);

assert_eq!(&buffer[..], "FooBarBaz");

Iteration

Using DynTrait as an Iterator and DoubleEndedIterator.

use abi_stable::{erased_types::interfaces::DEIteratorInterface, DynTrait};

let mut wrapped = DynTrait::from_any_value(0..=10, DEIteratorInterface::NEW);

assert_eq!(
    wrapped.by_ref().take(5).collect::<Vec<_>>(),
    vec![0, 1, 2, 3, 4]
);

assert_eq!(wrapped.rev().collect::<Vec<_>>(), vec![10, 9, 8, 7, 6, 5]);

Making pointers compatible with DynTrait

To make pointers compatible with DynTrait, they must imlement the abi_stable::pointer_trait::{ GetPointerKind, AsPtr, AsMutPtr, CanTransmuteElement} traits as shown in the example.

GetPointerKind should generally be implemented with type Kind = PK_SmartPointer. The exception is in the case that it is a #[repr(transparent)] wrapper around a RRef/RMut/*const T/*mut T/NonNull, in which case it should implement GetPointerKind<Kind = PK_Reference> (when it has shared reference semantics) or GetPointerKind<Kind = PK_MutReference> (when it has mutable reference semantics).

Example

This is an example of a newtype wrapping an RBox, demonstrating that the pointer type doesn’t have to implement the traits in the InterfaceType, it’s the value it points to.

     
use abi_stable::DynTrait;

fn main() {
    let lines = "line0\nline1\nline2";
    let mut iter = NewtypeBox::new(lines.lines());

    // The type annotation here is just to show the type, it's not necessary.
    let mut wrapper: DynTrait<'_, NewtypeBox<()>, IteratorInterface> =
        DynTrait::from_borrowing_ptr(iter, IteratorInterface);

    // You can clone the DynTrait!
    let clone = wrapper.clone();

    assert_eq!(wrapper.next(), Some("line0"));
    assert_eq!(wrapper.next(), Some("line1"));
    assert_eq!(wrapper.next(), Some("line2"));
    assert_eq!(wrapper.next(), None);

    assert_eq!(
        clone.rev().collect::<Vec<_>>(),
        vec!["line2", "line1", "line0"],
    )
}

#[repr(C)]
#[derive(StableAbi)]
#[sabi(impl_InterfaceType(
    Sync,
    Send,
    Iterator,
    DoubleEndedIterator,
    Clone,
    Debug
))]
pub struct IteratorInterface;

impl<'a> IteratorItem<'a> for IteratorInterface {
    type Item = &'a str;
}

/////////////////////////////////////////

use std::ops::{Deref, DerefMut};

use abi_stable::{
    erased_types::IteratorItem,
    pointer_trait::{
        AsMutPtr, AsPtr, CanTransmuteElement, GetPointerKind, PK_SmartPointer,
    },
    std_types::RBox,
    type_level::bools::True,
    InterfaceType, StableAbi,
};

#[repr(transparent)]
#[derive(Default, Clone, StableAbi)]
pub struct NewtypeBox<T> {
    box_: RBox<T>,
}

impl<T> NewtypeBox<T> {
    pub fn new(value: T) -> Self {
        Self {
            box_: RBox::new(value),
        }
    }
}

unsafe impl<T> GetPointerKind for NewtypeBox<T> {
    // This is a smart pointer because `RBox` is one.
    type Kind = PK_SmartPointer;
    type PtrTarget = T;
}

// safety: Does not create an intermediate `&T` to get a pointer to `T`.
unsafe impl<T> AsPtr for NewtypeBox<T> {
    fn as_ptr(&self) -> *const T {
        self.box_.as_ptr()
    }
}

// safety: Does not create an intermediate `&mut T` to get a pointer to `T`
unsafe impl<T> AsMutPtr for NewtypeBox<T> {
    fn as_mut_ptr(&mut self) -> *mut T {
        self.box_.as_mut_ptr()
    }
}

// safety:
// NewtypeBox is safe to transmute, because RBox (the pointer type it wraps)
// is safe to transmute
unsafe impl<T, O> CanTransmuteElement<O> for NewtypeBox<T> {
    type TransmutedPtr = NewtypeBox<O>;

    unsafe fn transmute_element_(self) -> Self::TransmutedPtr {
        let box_: RBox<O> = self.box_.transmute_element_();
        NewtypeBox { box_ }
    }
}

Implementations

Constructs the DynTrait<_> from a T: ImplType.

Use this whenever possible instead of from_any_value, because it produces better error messages when unerasing the DynTrait<_>

Example
use abi_stable::{
    erased_types::TypeInfo, std_types::RBox, DynTrait, ImplType, StableAbi,
};

fn main() {
    let to: DynTrait<'static, RBox<()>, FooInterface> =
        DynTrait::from_value(Foo(10u32));

    assert_eq!(format!("{:?}", to), "Foo(10)");
}

#[repr(transparent)]
#[derive(Debug, StableAbi)]
struct Foo(u32);

impl ImplType for Foo {
    type Interface = FooInterface;

    const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo);
}

/// An `InterfaceType` describing which traits are implemented by FooInterfaceBox.
#[repr(C)]
#[derive(StableAbi)]
#[sabi(impl_InterfaceType(Sync, Debug))]
pub struct FooInterface;

Constructs the DynTrait<_> from a pointer to a T: ImplType.

Use this whenever possible instead of from_any_ptr, because it produces better error messages when unerasing the DynTrait<_>

Example
use abi_stable::{
    erased_types::TypeInfo,
    std_types::{RArc, RBox},
    DynTrait, ImplType, RMut, RRef, StableAbi,
};

fn main() {
    // Constructing a DynTrait from a `&T`
    {
        // `DynTrait`s constructed from `&` are `DynTrait<'_, RRef<'_, ()>, _>`
        // since `&T` can't soundly be transmuted back and forth into `&()`
        let rref: DynTrait<'static, RRef<'_, ()>, FooInterface> =
            DynTrait::from_ptr(&Foo(10u32));

        assert_eq!(format!("{:?}", rref), "Foo(10)");
    }
    // Constructing a DynTrait from a `&mut T`
    {
        let mmut = &mut Foo(20u32);
        // `DynTrait`s constructed from `&mut` are `DynTrait<'_, RMut<'_, ()>, _>`
        // since `&mut T` can't soundly be transmuted back and forth into `&mut ()`
        let rmut: DynTrait<'static, RMut<'_, ()>, FooInterface> =
            DynTrait::from_ptr(mmut);

        assert_eq!(format!("{:?}", rmut), "Foo(20)");
    }
    // Constructing a DynTrait from a `RBox<T>`
    {
        let boxed: DynTrait<'static, RBox<()>, FooInterface> =
            DynTrait::from_ptr(RBox::new(Foo(30u32)));

        assert_eq!(format!("{:?}", boxed), "Foo(30)");
    }
    // Constructing a DynTrait from an `RArc<T>`
    {
        let arc: DynTrait<'static, RArc<()>, FooInterface> =
            DynTrait::from_ptr(RArc::new(Foo(30u32)));

        assert_eq!(format!("{:?}", arc), "Foo(30)");
    }
}

#[repr(transparent)]
#[derive(Debug, StableAbi)]
struct Foo(u32);

impl ImplType for Foo {
    type Interface = FooInterface;

    const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo);
}

/// An `InterfaceType` describing which traits are implemented by FooInterfaceBox.
#[repr(C)]
#[derive(StableAbi)]
#[sabi(impl_InterfaceType(Sync, Debug))]
pub struct FooInterface;

Constructs the DynTrait<_> from a type that doesn’t borrow anything.

Example
use abi_stable::{
    erased_types::interfaces::DebugDisplayInterface, std_types::RBox, DynTrait,
};

// DebugDisplayInterface is `Debug + Display + Sync + Send`
let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> =
    DynTrait::from_any_value(3u8, DebugDisplayInterface);

assert_eq!(format!("{}", to), "3");
assert_eq!(format!("{:?}", to), "3");

Constructs the DynTrait<_> from a pointer to a type that doesn’t borrow anything.

Example
use abi_stable::{
    erased_types::interfaces::DebugDisplayInterface,
    std_types::{RArc, RBox},
    DynTrait, RMut, RRef,
};

// Constructing a DynTrait from a `&T`
{
    // `DynTrait`s constructed from `&` are `DynTrait<'_, RRef<'_, ()>, _>`
    // since `&T` can't soundly be transmuted back and forth into `&()`
    let rref: DynTrait<'static, RRef<'_, ()>, DebugDisplayInterface> =
        DynTrait::from_any_ptr(&21i32, DebugDisplayInterface);

    assert_eq!(format!("{:?}", rref), "21");
    assert_eq!(format!("{}", rref), "21");
}
// Constructing a DynTrait from a `&mut T`
{
    let mmut = &mut "hello";
    // `DynTrait`s constructed from `&mut` are `DynTrait<'_, RMut<'_, ()>, _>`
    // since `&mut T` can't soundly be transmuted back and forth into `&mut ()`
    let rmut: DynTrait<'static, RMut<'_, ()>, DebugDisplayInterface> =
        DynTrait::from_any_ptr(mmut, DebugDisplayInterface);

    assert_eq!(format!("{:?}", rmut), r#""hello""#);
    assert_eq!(format!("{}", rmut), "hello");
}
// Constructing a DynTrait from a `RBox<T>`
{
    let boxed: DynTrait<'static, RBox<()>, DebugDisplayInterface> =
        DynTrait::from_any_ptr(RBox::new(false), DebugDisplayInterface);

    assert_eq!(format!("{:?}", boxed), "false");
    assert_eq!(format!("{}", boxed), "false");
}
// Constructing a DynTrait from an `RArc<T>`
{
    let arc: DynTrait<'static, RArc<()>, DebugDisplayInterface> =
        DynTrait::from_any_ptr(RArc::new(30u32), DebugDisplayInterface);

    assert_eq!(format!("{:?}", arc), "30");
}

Constructs the DynTrait<_> from a value with a 'borr borrow.

Cannot downcast the DynTrait afterwards.

Example
use abi_stable::{
    erased_types::interfaces::DebugDisplayInterface, std_types::RBox, DynTrait,
};

// DebugDisplayInterface is `Debug + Display + Sync + Send`
let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> =
    DynTrait::from_borrowing_value(3u8, DebugDisplayInterface);

assert_eq!(format!("{}", to), "3");
assert_eq!(format!("{:?}", to), "3");

// `DynTrait`s constructed using the `from_borrowing_*` constructors
// can't be downcasted.
assert_eq!(to.downcast_as::<u8>().ok(), None);

Constructs the DynTrait<_> from a pointer to the erased type with a 'borr borrow.

Cannot downcast the DynTrait afterwards.

Example
use abi_stable::{
    erased_types::interfaces::DebugDisplayInterface,
    std_types::{RArc, RBox},
    DynTrait, RMut, RRef,
};

// Constructing a DynTrait from a `&T`
{
    // `DynTrait`s constructed from `&` are `DynTrait<'_, RRef<'_, ()>, _>`
    // since `&T` can't soundly be transmuted back and forth into `&()`
    let rref: DynTrait<'_, RRef<'_, ()>, DebugDisplayInterface> =
        DynTrait::from_borrowing_ptr(&34i32, DebugDisplayInterface);

    assert_eq!(format!("{:?}", rref), "34");
    assert_eq!(format!("{}", rref), "34");
}
// Constructing a DynTrait from a `&mut T`
{
    let mmut = &mut "world";
    // `DynTrait`s constructed from `&mut` are `DynTrait<'_, RMut<'_, ()>, _>`
    // since `&mut T` can't soundly be transmuted back and forth into `&mut ()`
    let rmut: DynTrait<'_, RMut<'_, ()>, DebugDisplayInterface> =
        DynTrait::from_borrowing_ptr(mmut, DebugDisplayInterface);

    assert_eq!(format!("{:?}", rmut), r#""world""#);
    assert_eq!(format!("{}", rmut), "world");
}
// Constructing a DynTrait from a `RBox<T>`
{
    let boxed: DynTrait<'_, RBox<()>, DebugDisplayInterface> =
        DynTrait::from_borrowing_ptr(RBox::new(true), DebugDisplayInterface);

    assert_eq!(format!("{:?}", boxed), "true");
    assert_eq!(format!("{}", boxed), "true");
}
// Constructing a DynTrait from an `RArc<T>`
{
    let arc: DynTrait<'_, RArc<()>, DebugDisplayInterface> =
        DynTrait::from_borrowing_ptr(RArc::new('a'), DebugDisplayInterface);

    assert_eq!(format!("{:?}", arc), "'a'");
    assert_eq!(format!("{}", arc), "a");
}

Constructs an DynTrait from an erasable pointer and an extra value.

Example
use abi_stable::{
    erased_types::{interfaces::DebugDisplayInterface, TD_Opaque},
    DynTrait, RRef,
};

// DebugDisplayInterface is `Debug + Display + Sync + Send`
let to: DynTrait<'static, RRef<()>, DebugDisplayInterface, usize> =
    DynTrait::with_extra_value::<_, TD_Opaque>(&55u8, 100usize);

assert_eq!(format!("{}", to), "55");
assert_eq!(format!("{:?}", to), "55");

assert_eq!(to.sabi_extra_value(), &100);

This function allows constructing a DynTrait in a constant/static.

Parameters

ptr: This is generally constructed with RRef::new(&value) RRef is a reference-like type that can be erased inside a const fn on stable Rust (once it becomes possible to unsafely cast &T to &() inside a const fn, and the minimum Rust version is bumped, this type will be replaced with a reference)


can_it_downcast can be either:

  • TD_CanDowncast: Which allows the trait object to be downcasted, requires that the value implements any.

  • TD_Opaque: Which does not allow the trait object to be downcasted.


vtable_for: This is constructible with VTableDT::GET. VTableDT wraps the vtable for a DynTrait, while keeping the original type and pointer type that it was constructed for, allowing this function to be safe to call.


extra_value: This is used by #[sabi_trait] trait objects to store their vtable inside DynTrait.

Example
use abi_stable::{
    erased_types::{
        interfaces::DebugDisplayInterface, DynTrait, TD_Opaque, VTableDT,
    },
    sabi_types::RRef,
};

static STRING: &str = "What the heck";

static DYN: DynTrait<'static, RRef<'static, ()>, DebugDisplayInterface, ()> =
    DynTrait::from_const(&STRING, TD_Opaque, VTableDT::GET, ());

fn main() {
    assert_eq!(format!("{}", DYN), format!("{}", STRING));
    assert_eq!(format!("{:?}", DYN), format!("{:?}", STRING));
}

Allows checking whether 2 DynTrait<_>s have a value of the same type.

Notes:

  • Types from different dynamic libraries/executables are never considered equal.

  • DynTraits constructed using DynTrait::from_borrowing_* are never considered to wrap the same type.

A vtable used by #[sabi_trait] derived trait objects.

Gets access to the extra value that was stored in this DynTrait in the with_extra_value constructor.

Example
use abi_stable::{erased_types::TD_Opaque, DynTrait, RRef};

let to: DynTrait<'static, RRef<()>, (), char> =
    DynTrait::with_extra_value::<_, TD_Opaque>(&55u8, 'Z');

assert_eq!(to.sabi_extra_value(), &'Z');

Returns the address of the wrapped object.

Example
use abi_stable::{erased_types::TD_Opaque, DynTrait, RRef};

let reff = &55u8;

let to: DynTrait<'static, RRef<()>, ()> = DynTrait::from_any_ptr(reff, ());

assert_eq!(to.sabi_object_address(), reff as *const _ as usize);

Gets a reference pointing to the erased object.

Example
use abi_stable::{std_types::RBox, DynTrait};

let to: DynTrait<'static, RBox<()>, ()> = DynTrait::from_any_value(66u8, ());

unsafe {
    assert_eq!(to.sabi_erased_ref().transmute_into_ref::<u8>(), &66);
}

Gets a mutable reference pointing to the erased object.

Example
use abi_stable::{std_types::RBox, DynTrait};

let mut to: DynTrait<'static, RBox<()>, ()> = DynTrait::from_any_value("hello", ());

unsafe {
    assert_eq!(
        to.sabi_erased_mut().transmute_into_mut::<&str>(),
        &mut "hello"
    );
}

Gets an RRef pointing to the erased object.

Example
use abi_stable::{std_types::RBox, DynTrait};

let to: DynTrait<'static, RBox<()>, ()> = DynTrait::from_any_value(66u8, ());

unsafe {
    assert_eq!(to.sabi_as_rref().transmute_into_ref::<u8>(), &66);
}

Gets an RMut pointing to the erased object.

Example
use abi_stable::{std_types::RBox, DynTrait};

let mut to: DynTrait<'static, RBox<()>, ()> = DynTrait::from_any_value("hello", ());

unsafe {
    assert_eq!(to.sabi_as_rmut().transmute_into_mut::<&str>(), &mut "hello");
}

Calls the f callback with an MovePtr pointing to the erased object.

Example
use abi_stable::{
    sabi_types::MovePtr,
    std_types::{RBox, RString, RVec},
    DynTrait,
};

let to: DynTrait<'static, RBox<()>, ()> =
    DynTrait::from_any_value(RVec::<u8>::from_slice(b"foobarbaz"), ());

let string = to.sabi_with_value(|x| unsafe {
    MovePtr::into_inner(MovePtr::transmute::<String>(x))
});

assert_eq!(string, "foobarbaz");

Unwraps the DynTrait<_> into a pointer of the concrete type that it was constructed with.

T is required to implement ImplType.

Errors

This will return an error in any of these conditions:

  • It is called in a dynamic library/binary outside the one from which this DynTrait<_> was constructed.

  • The DynTrait was constructed using a from_borrowing_* method

  • T is not the concrete type this DynTrait<_> was constructed with.

Example
use abi_stable::{
    erased_types::TypeInfo,
    std_types::{RArc, RBox},
    DynTrait, ImplType, StableAbi,
};

{
    fn to() -> DynTrait<'static, RBox<()>, FooInterface> {
        DynTrait::from_value(Foo(b'A'))
    }

    assert_eq!(
        to().downcast_into_impltype::<Foo<u8>>().ok(),
        Some(RBox::new(Foo(b'A'))),
    );
    assert_eq!(to().downcast_into_impltype::<Foo<u16>>().ok(), None,);
}
{
    fn to() -> DynTrait<'static, RArc<()>, FooInterface> {
        DynTrait::from_ptr(RArc::new(Foo(b'B')))
    }

    assert_eq!(
        to().downcast_into_impltype::<Foo<u8>>().ok(),
        Some(RArc::new(Foo(b'B'))),
    );
    assert_eq!(to().downcast_into_impltype::<Foo<u16>>().ok(), None,);
}

#[repr(transparent)]
#[derive(Debug, StableAbi, PartialEq)]
struct Foo<T>(T);

impl<T: 'static> ImplType for Foo<T> {
    type Interface = FooInterface;

    const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo<T>);
}

/// An `InterfaceType` describing which traits are implemented by FooInterfaceBox.
#[repr(C)]
#[derive(StableAbi)]
#[sabi(impl_InterfaceType(Sync, Debug))]
pub struct FooInterface;

Unwraps the DynTrait<_> into a reference of the concrete type that it was constructed with.

T is required to implement ImplType.

Errors

This will return an error in any of these conditions:

  • It is called in a dynamic library/binary outside the one from which this DynTrait<_> was constructed.

  • The DynTrait was constructed using a from_borrowing_* method

  • T is not the concrete type this DynTrait<_> was constructed with.

Example
use abi_stable::{
    erased_types::TypeInfo, std_types::RArc, DynTrait, ImplType, RMut, RRef,
    StableAbi,
};

{
    let to: DynTrait<'static, RRef<'_, ()>, FooInterface> =
        DynTrait::from_ptr(&Foo(9u8));

    assert_eq!(to.downcast_as_impltype::<Foo<u8>>().ok(), Some(&Foo(9u8)));
    assert_eq!(to.downcast_as_impltype::<Foo<u16>>().ok(), None);
}
{
    let mut val = Foo(7u8);

    let to: DynTrait<'static, RMut<'_, ()>, FooInterface> =
        DynTrait::from_ptr(&mut val);

    assert_eq!(to.downcast_as_impltype::<Foo<u8>>().ok(), Some(&Foo(7)));
    assert_eq!(to.downcast_as_impltype::<Foo<u16>>().ok(), None);
}
{
    let to: DynTrait<'static, RArc<()>, FooInterface> =
        DynTrait::from_ptr(RArc::new(Foo(1u8)));

    assert_eq!(to.downcast_as_impltype::<Foo<u8>>().ok(), Some(&Foo(1u8)));
    assert_eq!(to.downcast_as_impltype::<Foo<u16>>().ok(), None);
}


#[repr(transparent)]
#[derive(Debug, StableAbi, PartialEq)]
struct Foo<T>(T);

impl<T: 'static> ImplType for Foo<T> {
    type Interface = FooInterface;

    const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo<T>);
}

/// An `InterfaceType` describing which traits are implemented by FooInterfaceBox.
#[repr(C)]
#[derive(StableAbi)]
#[sabi(impl_InterfaceType(Sync, Debug))]
pub struct FooInterface;

Unwraps the DynTrait<_> into a mutable reference of the concrete type that it was constructed with.

T is required to implement ImplType.

Errors

This will return an error in any of these conditions:

  • It is called in a dynamic library/binary outside the one from which this DynTrait<_> was constructed.

  • The DynTrait was constructed using a from_borrowing_* method

  • T is not the concrete type this DynTrait<_> was constructed with.

Example
use abi_stable::{
    erased_types::TypeInfo, std_types::RBox, DynTrait, ImplType, RMut, StableAbi,
};

{
    let mut val = Foo(7u8);

    let mut to: DynTrait<'static, RMut<'_, ()>, FooInterface> =
        DynTrait::from_ptr(&mut val);

    assert_eq!(
        to.downcast_as_mut_impltype::<Foo<u8>>().ok(),
        Some(&mut Foo(7))
    );
    assert_eq!(to.downcast_as_mut_impltype::<Foo<u16>>().ok(), None);
}
{
    let mut to: DynTrait<'static, RBox<()>, FooInterface> =
        DynTrait::from_ptr(RBox::new(Foo(1u8)));

    assert_eq!(
        to.downcast_as_mut_impltype::<Foo<u8>>().ok(),
        Some(&mut Foo(1u8))
    );
    assert_eq!(to.downcast_as_mut_impltype::<Foo<u16>>().ok(), None);
}


#[repr(transparent)]
#[derive(Debug, StableAbi, PartialEq)]
struct Foo<T>(T);

impl<T: 'static> ImplType for Foo<T> {
    type Interface = FooInterface;

    const INFO: &'static TypeInfo = abi_stable::impl_get_type_info!(Foo<T>);
}

/// An `InterfaceType` describing which traits are implemented by FooInterfaceBox.
#[repr(C)]
#[derive(StableAbi)]
#[sabi(impl_InterfaceType(Sync, Debug))]
pub struct FooInterface;

Unwraps the DynTrait<_> into a pointer of the concrete type that it was constructed with.

T is required to not borrow anything.

Errors

This will return an error in any of these conditions:

  • It is called in a dynamic library/binary outside the one from which this DynTrait<_> was constructed.

  • The DynTrait was constructed using a from_borrowing_* method

  • T is not the concrete type this DynTrait<_> was constructed with.

Example
use abi_stable::{
    std_types::{RArc, RBox},
    DynTrait,
};

{
    fn to() -> DynTrait<'static, RBox<()>, ()> {
        DynTrait::from_any_value(b'A', ())
    }

    assert_eq!(to().downcast_into::<u8>().ok(), Some(RBox::new(b'A')));
    assert_eq!(to().downcast_into::<u16>().ok(), None);
}
{
    fn to() -> DynTrait<'static, RArc<()>, ()> {
        DynTrait::from_any_ptr(RArc::new(b'B'), ())
    }

    assert_eq!(to().downcast_into::<u8>().ok(), Some(RArc::new(b'B')));
    assert_eq!(to().downcast_into::<u16>().ok(), None);
}

Unwraps the DynTrait<_> into a reference of the concrete type that it was constructed with.

T is required to not borrow anything.

Errors

This will return an error in any of these conditions:

  • It is called in a dynamic library/binary outside the one from which this DynTrait<_> was constructed.

  • The DynTrait was constructed using a from_borrowing_* method

  • T is not the concrete type this DynTrait<_> was constructed with.

Example
use abi_stable::{std_types::RArc, DynTrait, RMut, RRef};

{
    let to: DynTrait<'static, RRef<'_, ()>, ()> = DynTrait::from_any_ptr(&9u8, ());

    assert_eq!(to.downcast_as::<u8>().ok(), Some(&9u8));
    assert_eq!(to.downcast_as::<u16>().ok(), None);
}
{
    let mut val = 7u8;

    let to: DynTrait<'static, RMut<'_, ()>, ()> =
        DynTrait::from_any_ptr(&mut val, ());

    assert_eq!(to.downcast_as::<u8>().ok(), Some(&7));
    assert_eq!(to.downcast_as::<u16>().ok(), None);
}
{
    let to: DynTrait<'static, RArc<()>, ()> =
        DynTrait::from_any_ptr(RArc::new(1u8), ());

    assert_eq!(to.downcast_as::<u8>().ok(), Some(&1u8));
    assert_eq!(to.downcast_as::<u16>().ok(), None);
}

Unwraps the DynTrait<_> into a mutable reference of the concrete type that it was constructed with.

T is required to not borrow anything.

Errors

This will return an error in any of these conditions:

  • It is called in a dynamic library/binary outside the one from which this DynTrait<_> was constructed.

  • The DynTrait was constructed using a from_borrowing_* method

  • T is not the concrete type this DynTrait<_> was constructed with.

Example
use abi_stable::{std_types::RBox, DynTrait, RMut};

{
    let mut val = 7u8;

    let mut to: DynTrait<'static, RMut<'_, ()>, ()> =
        DynTrait::from_any_ptr(&mut val, ());

    assert_eq!(to.downcast_as_mut::<u8>().ok(), Some(&mut 7));
    assert_eq!(to.downcast_as_mut::<u16>().ok(), None);
}
{
    let mut to: DynTrait<'static, RBox<()>, ()> =
        DynTrait::from_any_ptr(RBox::new(1u8), ());

    assert_eq!(to.downcast_as_mut::<u8>().ok(), Some(&mut 1u8));
    assert_eq!(to.downcast_as_mut::<u16>().ok(), None);
}

Unwraps the DynTrait<_> into a pointer to T, without checking whether T is the type that the DynTrait was constructed with.

Safety

You must check that T is the type that DynTrait was constructed with through other means.

Example
use abi_stable::{
    std_types::{RArc, RBox},
    DynTrait,
};

unsafe {
    fn to() -> DynTrait<'static, RBox<()>, ()> {
        DynTrait::from_any_value(b'A', ())
    }

    assert_eq!(to().unchecked_downcast_into::<u8>(), RBox::new(b'A'));
}
unsafe {
    fn to() -> DynTrait<'static, RArc<()>, ()> {
        DynTrait::from_any_ptr(RArc::new(b'B'), ())
    }

    assert_eq!(to().unchecked_downcast_into::<u8>(), RArc::new(b'B'));
}

Unwraps the DynTrait<_> into a reference to T, without checking whether T is the type that the DynTrait was constructed with.

Safety

You must check that T is the type that DynTrait was constructed with through other means.

Example
use abi_stable::{std_types::RArc, DynTrait, RMut, RRef};

unsafe {
    let to: DynTrait<'static, RRef<'_, ()>, ()> = DynTrait::from_any_ptr(&9u8, ());

    assert_eq!(to.unchecked_downcast_as::<u8>(), &9u8);
}
unsafe {
    let mut val = 7u8;

    let to: DynTrait<'static, RMut<'_, ()>, ()> =
        DynTrait::from_any_ptr(&mut val, ());

    assert_eq!(to.unchecked_downcast_as::<u8>(), &7);
}
unsafe {
    let to: DynTrait<'static, RArc<()>, ()> =
        DynTrait::from_any_ptr(RArc::new(1u8), ());

    assert_eq!(to.unchecked_downcast_as::<u8>(), &1u8);
}

Unwraps the DynTrait<_> into a mutable reference to T, without checking whether T is the type that the DynTrait was constructed with.

Safety

You must check that T is the type that DynTrait was constructed with through other means.

Example
use abi_stable::{std_types::RBox, DynTrait, RMut};

unsafe {
    let mut val = 7u8;

    let mut to: DynTrait<'static, RMut<'_, ()>, ()> =
        DynTrait::from_any_ptr(&mut val, ());

    assert_eq!(to.unchecked_downcast_as_mut::<u8>(), &mut 7);
}
unsafe {
    let mut to: DynTrait<'static, RBox<()>, ()> =
        DynTrait::from_any_ptr(RBox::new(1u8), ());

    assert_eq!(to.unchecked_downcast_as_mut::<u8>(), &mut 1u8);
}

Creates a shared reborrow of this DynTrait.

The reborrowed DynTrait cannot use these methods:

  • DynTrait::default

This is only callable if DynTrait is either Send + Sync or !Send + !Sync.

Example
use abi_stable::{
    erased_types::interfaces::DebugDisplayInterface,
    std_types::RBox,
    type_level::{impl_enum::Implemented, trait_marker},
    DynTrait, InterfaceBound, RRef,
};

let to: DynTrait<'static, RBox<()>, DebugDisplayInterface> =
    DynTrait::from_any_value(1337_u16, DebugDisplayInterface);

assert_eq!(debug_string(to.reborrow()), "1337");

fn debug_string<I>(to: DynTrait<'_, RRef<'_, ()>, I>) -> String
where
    I: InterfaceBound<Debug = Implemented<trait_marker::Debug>>,
{
    format!("{:?}", to)
}

Creates a mutable reborrow of this DynTrait.

The reborrowed DynTrait cannot use these methods:

  • DynTrait::default

  • DynTrait::clone

This is only callable if DynTrait is either Send + Sync or !Send + !Sync.

Example
use abi_stable::{
    erased_types::interfaces::DEIteratorInterface, std_types::RBox, DynTrait,
};

let mut to = DynTrait::from_any_value(0_u8..=255, DEIteratorInterface::NEW);

assert_eq!(both_ends(to.reborrow_mut()), (Some(0), Some(255)));
assert_eq!(both_ends(to.reborrow_mut()), (Some(1), Some(254)));
assert_eq!(both_ends(to.reborrow_mut()), (Some(2), Some(253)));
assert_eq!(both_ends(to.reborrow_mut()), (Some(3), Some(252)));

fn both_ends<I>(mut to: I) -> (Option<I::Item>, Option<I::Item>)
where
    I: DoubleEndedIterator,
{
    (to.next(), to.next_back())
}

Constructs a DynTrait<P, I> with the default value for P.

Reborrowing

This cannot be called with a reborrowed DynTrait:

let object = DynTrait::from_any_value((), DefaultInterface);
let borrow = object.reborrow();
let _ = borrow.default();
let object = DynTrait::from_any_value((), DefaultInterface);
let borrow = object.reborrow_mut();
let _ = borrow.default();
Example
use abi_stable::{erased_types::interfaces::DebugDefEqInterface, DynTrait};

{
    let object = DynTrait::from_any_value(true, DebugDefEqInterface);

    assert_eq!(
        object.default(),
        DynTrait::from_any_value(false, DebugDefEqInterface)
    );
}
{
    let object = DynTrait::from_any_value(123u8, DebugDefEqInterface);

    assert_eq!(
        object.default(),
        DynTrait::from_any_value(0u8, DebugDefEqInterface)
    );
}

It serializes a DynTrait<_> into a string by using <ConcreteType as SerializeImplType>::serialize_impl.

Deserializes a DynTrait<'borr, _> from a proxy type, by using <I as DeserializeDyn<'borr, Self>>::deserialize_dyn.

Eagerly skips n elements from the iterator.

This method is faster than using Iterator::skip.

Example

let mut iter = 0..20;
let mut wrapped = DynTrait::from_any_ptr(&mut iter, IteratorInterface::NEW);

assert_eq!(wrapped.next(), Some(0));

wrapped.skip_eager(2);

assert_eq!(wrapped.next(), Some(3));
assert_eq!(wrapped.next(), Some(4));
assert_eq!(wrapped.next(), Some(5));

wrapped.skip_eager(2);

assert_eq!(wrapped.next(), Some(8));
assert_eq!(wrapped.next(), Some(9));

wrapped.skip_eager(9);

assert_eq!(wrapped.next(), Some(19));
assert_eq!(wrapped.next(), None);

Extends the RVec<Item> with the self Iterator.

Extends buffer with as many elements of the iterator as taking specifies:

  • RNone: Yields all elements.Use this with care, since Iterators can be infinite.

  • RSome(n): Yields n elements.

Example

let mut wrapped = DynTrait::from_any_value(0.., IteratorInterface::NEW);

let mut buffer = vec![101, 102, 103].into_c();
wrapped.extending_rvec(&mut buffer, RSome(5));
assert_eq!(&buffer[..], &*vec![101, 102, 103, 0, 1, 2, 3, 4]);

assert_eq!(wrapped.next(), Some(5));
assert_eq!(wrapped.next(), Some(6));
assert_eq!(wrapped.next(), Some(7));

Gets teh nth element from the back of the iterator.

Example
use abi_stable::{erased_types::interfaces::DEIteratorCloneInterface, DynTrait};

let to = || DynTrait::from_any_value(7..=10, DEIteratorCloneInterface::NEW);

assert_eq!(to().nth_back_(0), Some(10));
assert_eq!(to().nth_back_(1), Some(9));
assert_eq!(to().nth_back_(2), Some(8));
assert_eq!(to().nth_back_(3), Some(7));
assert_eq!(to().nth_back_(4), None);
assert_eq!(to().nth_back_(5), None);

Extends the RVec<Item> with the back of the self DoubleEndedIterator.

Extends buffer with as many elements of the iterator as taking specifies:

  • RNone: Yields all elements.Use this with care, since Iterators can be infinite.

  • RSome(n): Yields n elements.

Example

let mut wrapped = DynTrait::from_any_value(0..=3, DEIteratorInterface::NEW);

let mut buffer = vec![101, 102, 103].into_c();
wrapped.extending_rvec_back(&mut buffer, RNone);
assert_eq!(&buffer[..], &*vec![101, 102, 103, 3, 2, 1, 0])

Trait Implementations

Returns the contents of the internal buffer, filling it with more data from the inner reader if it is empty. Read more

Tells this buffer that amt bytes have been consumed from the buffer, so they should no longer be returned in calls to read. Read more

🔬 This is a nightly-only experimental API. (buf_read_has_data_left)

recently added

Check if the underlying Read has any data left to be read. Read more

Read all bytes into buf until the delimiter byte or EOF is reached. Read more

Read all bytes until a newline (the 0xA byte) is reached, and append them to the provided buffer. Read more

Returns an iterator over the contents of this reader split on the byte byte. Read more

Returns an iterator over the lines of this reader. Read more

Clone is implemented for references and smart pointers, using GetPointerKind to decide whether P is a smart pointer or a reference.

DynTrait does not implement Clone if P ==RMut<'_, ()> :


let mut object = DynTrait::from_any_value((),());
let borrow = object.reborrow_mut();
let _ = borrow.clone();

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

First it Deserializes a string, then it deserializes into a DynTrait<_>, by using <I as DeserializeOwnedInterface>::deserialize_impl.

Deserialize this value from the given Serde deserializer. Read more

Formats the value using the given formatter. Read more

Removes and returns an element from the end of the iterator. Read more

🔬 This is a nightly-only experimental API. (iter_advance_by)

recently added

Advances the iterator from the back by n elements. Read more

Returns the nth element from the end of the iterator. Read more

This is the reverse version of Iterator::try_fold(): it takes elements starting from the back of the iterator. Read more

An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. Read more

Searches for an element of an iterator from the back that satisfies a predicate. Read more

Executes the destructor for this type. Read more

The lower-level source of this error, if any. Read more

🔬 This is a nightly-only experimental API. (backtrace)

Returns a stack backtrace, if available, of where this error occurred. Read more

👎 Deprecated since 1.42.0:

use the Display impl or to_string()

👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

The type of the elements being iterated over.

Advances the iterator and returns the next value. Read more

Returns the nth element of the iterator. Read more

Returns the bounds on the remaining length of the iterator. Read more

Consumes the iterator, counting the number of iterations and returning it. Read more

Consumes the iterator, returning the last element. Read more

🔬 This is a nightly-only experimental API. (iter_advance_by)

recently added

Advances the iterator by n elements. Read more

Creates an iterator starting at the same point, but stepping by the given amount at each iteration. Read more

Takes two iterators and creates a new iterator over both in sequence. Read more

‘Zips up’ two iterators into a single iterator of pairs. Read more

🔬 This is a nightly-only experimental API. (iter_intersperse)

recently added

Creates a new iterator which places a copy of separator between adjacent items of the original iterator. Read more

🔬 This is a nightly-only experimental API. (iter_intersperse)

recently added

Creates a new iterator which places an item generated by separator between adjacent items of the original iterator. Read more

Takes a closure and creates an iterator which calls that closure on each element. Read more

Calls a closure on each element of an iterator. Read more

Creates an iterator which uses a closure to determine if an element should be yielded. Read more

Creates an iterator that both filters and maps. Read more

Creates an iterator which gives the current iteration count as well as the next value. Read more

Creates an iterator which can use the peek and peek_mut methods to look at the next element of the iterator without consuming it. See their documentation for more information. Read more

Creates an iterator that skips elements based on a predicate. Read more

Creates an iterator that yields elements based on a predicate. Read more

Creates an iterator that both yields elements based on a predicate and maps. Read more

Creates an iterator that skips the first n elements. Read more

Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner. Read more

An iterator adapter similar to fold that holds internal state and produces a new iterator. Read more

Creates an iterator that works like map, but flattens nested structure. Read more

Creates an iterator that flattens nested structure. Read more

Creates an iterator which ends after the first None. Read more

Does something with each element of an iterator, passing the value on. Read more

Borrows an iterator, rather than consuming it. Read more

Transforms an iterator into a collection. Read more

Consumes an iterator, creating two collections from it. Read more

🔬 This is a nightly-only experimental API. (iter_partition_in_place)

new API

Reorders the elements of this iterator in-place according to the given predicate, such that all those that return true precede all those that return false. Returns the number of true elements found. Read more

🔬 This is a nightly-only experimental API. (iter_is_partitioned)

new API

Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return true precede all those that return false. Read more

An iterator method that applies a function as long as it returns successfully, producing a single, final value. Read more

An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. Read more

Folds every element into an accumulator by applying an operation, returning the final result. Read more

Reduces the elements to a single one, by repeatedly applying a reducing operation. Read more

Tests if every element of the iterator matches a predicate. Read more

Tests if any element of the iterator matches a predicate. Read more

Searches for an element of an iterator that satisfies a predicate. Read more

Applies function to the elements of iterator and returns the first non-none result. Read more

🔬 This is a nightly-only experimental API. (try_find)

new API

Applies function to the elements of iterator and returns the first true result or the first error. Read more

Searches for an element in an iterator, returning its index. Read more

Searches for an element in an iterator from the right, returning its index. Read more

Returns the maximum element of an iterator. Read more

Returns the minimum element of an iterator. Read more

Returns the element that gives the maximum value from the specified function. Read more

Returns the element that gives the maximum value with respect to the specified comparison function. Read more

Returns the element that gives the minimum value from the specified function. Read more

Returns the element that gives the minimum value with respect to the specified comparison function. Read more

Reverses an iterator’s direction. Read more

Converts an iterator of pairs into a pair of containers. Read more

Creates an iterator which copies all of its elements. Read more

Creates an iterator which clones all of its elements. Read more

Repeats an iterator endlessly. Read more

Sums the elements of an iterator. Read more

Iterates over the entire iterator, multiplying all the elements Read more

Lexicographically compares the elements of this Iterator with those of another. Read more

🔬 This is a nightly-only experimental API. (iter_order_by)

Lexicographically compares the elements of this Iterator with those of another with respect to the specified comparison function. Read more

Lexicographically compares the elements of this Iterator with those of another. Read more

🔬 This is a nightly-only experimental API. (iter_order_by)

Lexicographically compares the elements of this Iterator with those of another with respect to the specified comparison function. Read more

Determines if the elements of this Iterator are equal to those of another. Read more

🔬 This is a nightly-only experimental API. (iter_order_by)

Determines if the elements of this Iterator are equal to those of another with respect to the specified equality function. Read more

Determines if the elements of this Iterator are unequal to those of another. Read more

Determines if the elements of this Iterator are lexicographically less than those of another. Read more

Determines if the elements of this Iterator are lexicographically less or equal to those of another. Read more

Determines if the elements of this Iterator are lexicographically greater than those of another. Read more

Determines if the elements of this Iterator are lexicographically greater than or equal to those of another. Read more

🔬 This is a nightly-only experimental API. (is_sorted)

new API

Checks if the elements of this iterator are sorted. Read more

🔬 This is a nightly-only experimental API. (is_sorted)

new API

Checks if the elements of this iterator are sorted using the given comparator function. Read more

🔬 This is a nightly-only experimental API. (is_sorted)

new API

Checks if the elements of this iterator are sorted using the given key extraction function. Read more

This method returns an Ordering between self and other. Read more

Compares and returns the maximum of two values. Read more

Compares and returns the minimum of two values. Read more

Restrict a value to a certain interval. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method returns an ordering between self and other values if one exists. Read more

This method tests less than (for self and other) and is used by the < operator. Read more

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

This method tests greater than (for self and other) and is used by the > operator. Read more

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more

Read the exact number of bytes required to fill buf. Read more

Like read, except that it reads into a slice of buffers. Read more

🔬 This is a nightly-only experimental API. (can_vector)

Determines if this Reader has an efficient read_vectored implementation. Read more

🔬 This is a nightly-only experimental API. (read_initializer)

Determines if this Reader can work with buffers of uninitialized memory. Read more

Read all bytes until EOF in this source, placing them into buf. Read more

Read all bytes until EOF in this source, appending them to buf. Read more

Creates a “by reference” adapter for this instance of Read. Read more

Transforms this Read instance to an Iterator over its bytes. Read more

Creates an adapter which will chain this stream with another. Read more

Creates an adapter which will read at most limit bytes from it. Read more

Seek to an offset, in bytes, in a stream. Read more

Rewind to the beginning of a stream. Read more

🔬 This is a nightly-only experimental API. (seek_stream_len)

Returns the length of this stream (in bytes). Read more

Returns the current seek position from the start of the stream. Read more

First it serializes a DynTrait<_> into a string by using ::serialize_impl, then it serializes the string.

Serialize this value into the given Serde serializer. Read more

Whether this type has a single invalid bit-pattern. Read more

The layout of the type provided by implementors.

const-equivalents of the associated types.

Writes a string slice into this writer, returning whether the write succeeded. Read more

Writes a char into this writer, returning whether the write succeeded. Read more

Glue for usage of the write! macro with implementors of this trait. Read more

Write a buffer into this writer, returning how many bytes were written. Read more

Flush this output stream, ensuring that all intermediately buffered contents reach their destination. Read more

Attempts to write an entire buffer into this writer. Read more

Like write, except that it writes from a slice of buffers. Read more

🔬 This is a nightly-only experimental API. (can_vector)

Determines if this Writer has an efficient write_vectored implementation. Read more

🔬 This is a nightly-only experimental API. (write_all_vectored)

Attempts to write multiple buffers into this writer. Read more

Writes a formatted string into this writer, returning any error encountered. Read more

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

The owned type, stored in RCow::Owned

The borrowed type, stored in RCow::Borrowed

Performs the conversion.

This is always WithMetadata_<Self, Self>

Performs the conversion.

The type of the elements being iterated over.

Which kind of iterator are we turning this into?

Creates an iterator from a value. Read more

Collects into an existing collection by extending it. Read more

Collects into a pre-allocated collection,returning it by value. Read more

An Iterator that replaces the nth element with another value. Read more

Sums the items of the iterator, into the item’s type. Read more

Multiplies the items of the iterator, into the item’s type. Read more

Gets a reference to a field, determined by offset. Read more

Gets a muatble reference to a field, determined by offset. Read more

Gets a const pointer to a field, the field is determined by offset. Read more

Gets a mutable pointer to a field, determined by offset. Read more

Replaces a field (determined by offset) with value, returning the previous value of the field. Read more

Swaps a field (determined by offset) with the same field in right. Read more

Gets a copy of a field (determined by offset). The field is determined by offset. Read more

Replaces a field (determined by offset) with value, returning the previous value of the field. Read more

Swaps a field (determined by offset) with the same field in right. Read more

Gets a copy of a field (determined by offset). The field is determined by offset. Read more

Compares the address of self with the address of other. Read more

Emulates the pipeline operator, allowing method syntax in more places. Read more

The same as piped except that the function takes &Self Useful for functions that take &Self instead of Self. Read more

The same as piped, except that the function takes &mut Self. Useful for functions that take &mut Self instead of Self. Read more

Mutates self using a closure taking self by mutable reference, passing it along the method chain. Read more

Observes the value of self, passing it along unmodified. Useful in long method chains. Read more

Performs a conversion with Into. using the turbofish .into_::<_>() syntax. Read more

Performs a reference to reference conversion with AsRef, using the turbofish .as_ref_::<_>() syntax. Read more

Performs a mutable reference to mutable reference conversion with AsMut, using the turbofish .as_mut_::<_>() syntax. Read more

Drops self using method notation. Alternative to std::mem::drop. Read more

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

Converts the given value to a String. Read more

Transmutes the element type of this pointer.. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

This is always Self.

Converts a value back to the original type.

Converts a reference back to the original type.

Converts a mutable reference back to the original type.

This is supported on crate feature alloc only.

Converts a box back to the original type.

This is supported on crate feature alloc only.

Converts an Arc back to the original type. Read more

This is supported on crate feature alloc only.

Converts an Rc back to the original type. Read more

Converts a value back to the original type.

Converts a reference back to the original type.

Converts a mutable reference back to the original type.

This is supported on crate feature alloc only.

Converts a box back to the original type.

This is supported on crate feature alloc only.

Converts an Arc back to the original type.

This is supported on crate feature alloc only.

Converts an Rc back to the original type.