Expand description

Async TryFrom/TryInto traits.

Why

In async-std we created async versions of FromStream, IntoStream, and Iterator::collect. These traits represent conversions from one type to another. But the canonical way of performing this conversion is through the TryFrom and TryInto traits.

For example when deserializing some MyBody from a Request, you will want to declare a TryFrom<Request> for MyBody which consumes the bytes in the request and tries to create the body. This operation is fallible, and when writing async code also needs to be async.

This crate provides traits for that, through the async_trait crate. This is an experiment, but we’ll likely want to extend async-std with this at some point too.

Examples

use async_convert::{async_trait, TryFrom};

struct GreaterThanZero(i32);

#[async_trait]
impl TryFrom<i32> for GreaterThanZero {
    type Error = &'static str;

    async fn try_from(value: i32) -> Result<Self, Self::Error> {
        // pretend we're actually doing async IO here instead.
        if value <= 0 {
            Err("GreaterThanZero only accepts value superior than zero!")
        } else {
            Ok(GreaterThanZero(value))
        }
    }
}

Modules

A shared prelude.

Traits

Simple and safe type conversions that may fail in a controlled way under some circumstances. It is the reciprocal of TryInto.

An attempted conversion that consumes self, which may or may not be expensive.

Attribute Macros