pub trait AttemptInto<T>: Sized {
    type Mistake;
    type Failure;

    fn attempt_into(self) -> Outcome<T, Self::Mistake, Self::Failure>;
}
Expand description

An attempted conversion that consumes self, which may or may not be expensive. Outcome’s analogue to TryInto.

Library writers should usually not implement this trait directly, but should prefer implementing the AttemptFrom trait, which offers more flexibility and provides an equivalent AttemptInto implementation for free, thanks to the blanket implementation provided by the outcome crate.

Unlike TryInto, users are free to return a retryable error, which should return the data consumed (however this cannot be enforced in practice).

For more information on this, see the documentation for Into.

Examples

The following example uses the same code from AttemptFrom, but calls attempt_into on each object instead.

use outcome::convert::*;
use outcome::prelude::*;

#[derive(Debug, PartialOrd, PartialEq, Ord, Eq, Hash)]
enum Version { V1, V2 }

#[derive(Debug, PartialOrd, PartialEq, Ord, Eq, Hash)]
struct EmptyInput;

#[derive(Debug, PartialOrd, PartialEq, Ord, Eq, Hash)]
enum ParseError {
  InvalidVersion(u8),
}

impl std::fmt::Display for ParseError {
  fn fmt (&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      Self::InvalidVersion(v) => write!(f, "Expected a valid version, received: {:x?}", v)
    }
  }
}

impl<const N: usize> AttemptFrom<&[u8; N]> for Version {
  type Mistake = EmptyInput;
  type Failure = ParseError;

  fn attempt_from (value: &[u8; N]) -> Outcome<Self, Self::Mistake, Self::Failure> {
    match value.get(0) {
      None => Mistake(EmptyInput),
      Some(&1) => Success(Version::V1),
      Some(&2) => Success(Version::V2),
      Some(&value) => Failure(ParseError::InvalidVersion(value)),
    }
  }
}

type ParseOutcome = Outcome<Version, EmptyInput, ParseError>;

let empty: ParseOutcome = (&[]).attempt_into();
let v1: ParseOutcome = (&[1u8]).attempt_into();
let v2: ParseOutcome = (&[2u8]).attempt_into();
let v3: ParseOutcome = (&[3u8]).attempt_into();
assert_eq!(empty, Mistake(EmptyInput));
assert_eq!(v1, Success(Version::V1));
assert_eq!(v2, Success(Version::V2));
assert_eq!(v3, Failure(ParseError::InvalidVersion(3)));

Required Associated Types

The type returned in the event of a conversion error where the caller may retry the conversion.

The type returned in the event of a conversion error where the caller may not retry the conversion.

Required Methods

Performs the conversion.

Implementors