Trait ockam_core::lib::From1.0.0[][src]

pub trait From<T> {
    fn from(T) -> Self;
}
Expand description

Used to do value-to-value conversions while consuming the input value. It is the reciprocal of Into.

One should always prefer implementing From over Into because implementing From automatically provides one with an implementation of Into thanks to the blanket implementation in the standard library.

Only implement Into when targeting a version prior to Rust 1.41 and converting to a type outside the current crate. From was not able to do these types of conversions in earlier versions because of Rust’s orphaning rules. See Into for more details.

Prefer using Into over using From when specifying trait bounds on a generic function. This way, types that directly implement Into can be used as arguments as well.

The From is also very useful when performing error handling. When constructing a function that is capable of failing, the return type will generally be of the form Result<T, E>. The From trait simplifies error handling by allowing a function to return a single error type that encapsulate multiple error types. See the “Examples” section and the book for more details.

Note: This trait must not fail. If the conversion can fail, use TryFrom.

Generic Implementations

  • From<T> for U implies Into<U> for T
  • From is reflexive, which means that From<T> for T is implemented

Examples

String implements From<&str>:

An explicit conversion from a &str to a String is done as follows:

let string = "hello".to_string();
let other_string = String::from("hello");

assert_eq!(string, other_string);

While performing error handling it is often useful to implement From for your own error type. By converting underlying error types to our own custom error type that encapsulates the underlying error type, we can return a single error type without losing information on the underlying cause. The ‘?’ operator automatically converts the underlying error type to our custom error type by calling Into<CliError>::into which is automatically provided when implementing From. The compiler then infers which implementation of Into should be used.

use std::fs;
use std::io;
use std::num;

enum CliError {
    IoError(io::Error),
    ParseError(num::ParseIntError),
}

impl From<io::Error> for CliError {
    fn from(error: io::Error) -> Self {
        CliError::IoError(error)
    }
}

impl From<num::ParseIntError> for CliError {
    fn from(error: num::ParseIntError) -> Self {
        CliError::ParseError(error)
    }
}

fn open_and_parse_file(file_name: &str) -> Result<i32, CliError> {
    let mut contents = fs::read_to_string(&file_name)?;
    let num: i32 = contents.trim().parse()?;
    Ok(num)
}

Required methods

Performs the conversion.

Implementations on Foreign Types

Converts u8 to i64 losslessly.

Converts u8 to i16 losslessly.

Converts u16 to i64 losslessly.

Converts i32 to i128 losslessly.

Converts a bool to a usize. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(usize::from(true), 1);
assert_eq!(usize::from(false), 0);

Converts an u8 into an AtomicU8.

Converts a NonZeroIsize into an isize

Converts u8 to i128 losslessly.

Converts u16 to i32 losslessly.

Converts i8 to f32 losslessly.

Converts i8 to i128 losslessly.

Converts a NonZeroI16 into an i16

Converts u16 to f32 losslessly.

Converts a NonZeroU8 into an u8

Converts an u32 into an AtomicU32.

Converts a char into a u64.

Examples

use std::mem;

let c = '👤';
let u = u64::from(c);
assert!(8 == mem::size_of_val(&u))

Converts i16 to i128 losslessly.

Converts u32 to i64 losslessly.

Converts a bool into an AtomicBool.

Examples

use std::sync::atomic::AtomicBool;
let atomic_bool = AtomicBool::from(true);
assert_eq!(format!("{:?}", atomic_bool), "true")

Converts a NonZeroU32 into an u32

Converts a bool to a i32. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(i32::from(true), 1);
assert_eq!(i32::from(false), 0);

Converts u32 to f64 losslessly.

Converts u64 to u128 losslessly.

Converts a bool to a i64. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(i64::from(true), 1);
assert_eq!(i64::from(false), 0);

Maps a byte in 0x00..=0xFF to a char whose code point has the same value, in U+0000..=U+00FF.

Unicode is designed such that this effectively decodes bytes with the character encoding that IANA calls ISO-8859-1. This encoding is compatible with ASCII.

Note that this is different from ISO/IEC 8859-1 a.k.a. ISO 8859-1 (with one less hyphen), which leaves some “blanks”, byte values that are not assigned to any character. ISO-8859-1 (the IANA one) assigns them to the C0 and C1 control codes.

Note that this is also different from Windows-1252 a.k.a. code page 1252, which is a superset ISO/IEC 8859-1 that assigns some (not all!) blanks to punctuation and various Latin characters.

To confuse things further, on the Web ascii, iso-8859-1, and windows-1252 are all aliases for a superset of Windows-1252 that fills the remaining blanks with corresponding C0 and C1 control codes.

Converts a u8 into a char.

Examples

use std::mem;

let u = 32 as u8;
let c = char::from(u);
assert!(4 == mem::size_of_val(&c))

Converts u32 to u128 losslessly.

Converts an u16 into an AtomicU16.

Converts an usize into an AtomicUsize.

Converts a NonZeroU128 into an u128

Converts a bool to a u64. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(u64::from(true), 1);
assert_eq!(u64::from(false), 0);

Converts u16 to usize losslessly.

Converts i8 to isize losslessly.

Converts f32 to f64 losslessly.

Converts a bool to a u128. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(u128::from(true), 1);
assert_eq!(u128::from(false), 0);

Converts u16 to f64 losslessly.

Converts i64 to i128 losslessly.

Converts u32 to i128 losslessly.

Converts i32 to i64 losslessly.

Converts u8 to u128 losslessly.

Converts u8 to usize losslessly.

Converts a bool to a i16. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(i16::from(true), 1);
assert_eq!(i16::from(false), 0);

Convert to a Ready variant.

Example

assert_eq!(Poll::from(true), Poll::Ready(true));

Converts u8 to f64 losslessly.

Converts a char into a u128.

Examples

use std::mem;

let c = '⚙';
let u = u128::from(c);
assert!(16 == mem::size_of_val(&u))

Converts u8 to u16 losslessly.

Converts a char into a u32.

Examples

use std::mem;

let c = 'c';
let u = u32::from(c);
assert!(4 == mem::size_of_val(&u))

Converts i8 to i16 losslessly.

Converts i8 to i64 losslessly.

Converts a bool to a isize. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(isize::from(true), 1);
assert_eq!(isize::from(false), 0);

Converts an i16 into an AtomicI16.

Converts i16 to f32 losslessly.

Converts u8 to isize losslessly.

Converts a NonZeroU16 into an u16

Converts an i8 into an AtomicI8.

Converts u8 to i32 losslessly.

Converts i32 to f64 losslessly.

Converts i8 to i32 losslessly.

Converts i16 to i64 losslessly.

Converts a bool to a u32. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(u32::from(true), 1);
assert_eq!(u32::from(false), 0);

Converts u16 to u128 losslessly.

Converts u32 to u64 losslessly.

Converts a bool to a u8. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(u8::from(true), 1);
assert_eq!(u8::from(false), 0);

Converts a NonZeroU64 into an u64

Converts an i32 into an AtomicI32.

Converts i8 to f64 losslessly.

Converts u64 to i128 losslessly.

Converts a bool to a i128. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(i128::from(true), 1);
assert_eq!(i128::from(false), 0);

Converts a bool to a i8. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(i8::from(true), 1);
assert_eq!(i8::from(false), 0);

Converts an i64 into an AtomicI64.

Converts u16 to u64 losslessly.

Converts i16 to f64 losslessly.

Converts an u64 into an AtomicU64.

Converts u8 to u64 losslessly.

Converts a NonZeroI32 into an i32

Converts i16 to i32 losslessly.

Converts u16 to i128 losslessly.

Converts an isize into an AtomicIsize.

Converts a bool to a u16. The resulting value is 0 for false and 1 for true values.

Examples

assert_eq!(u16::from(true), 1);
assert_eq!(u16::from(false), 0);

Converts u16 to u32 losslessly.

Converts a NonZeroI64 into an i64

Converts i16 to isize losslessly.

Converts a NonZeroI128 into an i128

Converts u8 to u32 losslessly.

Converts a NonZeroI8 into an i8

Converts a NonZeroUsize into an usize

Converts u8 to f32 losslessly.

Convert an Ipv6Addr into a host byte order u128.

Examples

use std::net::Ipv6Addr;

let addr = Ipv6Addr::new(
    0x1020, 0x3040, 0x5060, 0x7080,
    0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
);
assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr));

Converts a Path into an Rc by copying the Path data into a new Rc buffer.

Converts a SendError<T> into a TrySendError<T>.

This conversion always returns a TrySendError::Disconnected containing the data in the SendError<T>.

No data is allocated on the heap.

Creates a new instance of an RwLock<T> which is unlocked. This is equivalent to RwLock::new.

Converts a ChildStdin into a Stdio

Examples

ChildStdin will be converted to Stdio using Stdio::from under the hood.

use std::process::{Command, Stdio};

let reverse = Command::new("rev")
    .stdin(Stdio::piped())
    .spawn()
    .expect("failed reverse command");

let _echo = Command::new("echo")
    .arg("Hello, world!")
    .stdout(reverse.stdin.unwrap()) // Converted into a Stdio here
    .output()
    .expect("failed echo command");

// "!dlrow ,olleH" echoed to console

Converts a PathBuf into an OsString

This conversion does not allocate or copy memory.

Converts a Path into an Arc by copying the Path data into a new Arc buffer.

Converts a PathBuf into an Arc by moving the PathBuf data into a new Arc buffer.

Converts a NulError into a io::Error.

Converts a File into a Stdio

Examples

File will be converted to Stdio using Stdio::from under the hood.

use std::fs::File;
use std::process::Command;

// With the `foo.txt` file containing `Hello, world!"
let file = File::open("foo.txt").unwrap();

let reverse = Command::new("rev")
    .stdin(file)  // Implicit File conversion into a Stdio
    .output()
    .expect("failed reverse command");

assert_eq!(reverse.stdout, b"!dlrow ,olleH");

Converts an Ipv4Addr into a host byte order u32.

Examples

use std::net::Ipv4Addr;

let addr = Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe);
assert_eq!(0xcafebabe, u32::from(addr));

Converts a [Box]<OsStr> into an OsString without copying or allocating.

Converts a CString into a Arc<CStr> without copying or allocating.

Converts a OsString into a Rc<OsStr> without copying or allocating.

Converts a [Vec]<NonZeroU8> into a CString without copying nor checking for inner null bytes.

Converts a [Box]<CStr> into a CString without copying or allocating.

Converts a borrowed OsStr to a PathBuf.

Allocates a PathBuf and copies the data into it.

Converts a RecvError into a RecvTimeoutError.

This conversion always returns RecvTimeoutError::Disconnected.

No data is allocated on the heap.

Converts an OsString into a PathBuf

This conversion does not allocate or copy memory.

Converts a PathBuf into an Rc by moving the PathBuf data into a new Rc buffer.

Converts a clone-on-write pointer to an owned path.

Converting from a Cow::Owned does not clone or allocate.

Converts a RecvError into a TryRecvError.

This conversion always returns TryRecvError::Disconnected.

No data is allocated on the heap.

Converts a [String] into a PathBuf

This conversion does not allocate or copy memory.

Converts a ChildStdout into a Stdio

Examples

ChildStdout will be converted to Stdio using Stdio::from under the hood.

use std::process::{Command, Stdio};

let hello = Command::new("echo")
    .arg("Hello, world!")
    .stdout(Stdio::piped())
    .spawn()
    .expect("failed echo command");

let reverse = Command::new("rev")
    .stdin(hello.stdout.unwrap())  // Converted into a Stdio here
    .output()
    .expect("failed reverse command");

assert_eq!(reverse.stdout, b"!dlrow ,olleH\n");

Converts a ChildStderr into a Stdio

Examples

use std::process::{Command, Stdio};

let reverse = Command::new("rev")
    .arg("non_existing_file.txt")
    .stderr(Stdio::piped())
    .spawn()
    .expect("failed reverse command");

let cat = Command::new("cat")
    .arg("-")
    .stdin(reverse.stderr.unwrap()) // Converted into a Stdio here
    .output()
    .expect("failed echo command");

assert_eq!(
    String::from_utf8_lossy(&cat.stdout),
    "rev: cannot open non_existing_file.txt: No such file or directory\n"
);

Converts a OsString into a Arc<OsStr> without copying or allocating.

Intended for use for errors not exposed to the user, where allocating onto the heap (for normal construction via Error::new) is too costly.

Converts an ErrorKind into an Error.

This conversion allocates a new error with a simple representation of error kind.

Examples

use std::io::{Error, ErrorKind};

let not_found = ErrorKind::NotFound;
let error = Error::from(not_found);
assert_eq!("entity not found", format!("{}", error));

Converts a Box<Path> into a PathBuf

This conversion does not allocate or copy memory.

Converts a CString into a Rc<CStr> without copying or allocating.

Creates a new mutex in an unlocked state ready for use. This is equivalent to Mutex::new.

Converts a [String] into a OsString.

This conversion does not allocate or copy memory.

Converts a generic type T into a Rc<T>

The conversion allocates on the heap and moves t from the stack into it.

Example

let x = 5;
let rc = Rc::new(5);

assert_eq!(Rc::from(x), rc);

Allocate a reference-counted string slice and copy v into it.

Example

let original: String = "statue".to_owned();
let shared: Rc<str> = Rc::from(original);
assert_eq!("statue", &shared[..]);

Allocate a reference-counted slice and fill it by cloning v’s items.

Example

let original: &[i32] = &[1, 2, 3];
let shared: Arc<[i32]> = Arc::from(original);
assert_eq!(&[1, 2, 3], &shared[..]);

Converts a T into an Arc<T>

The conversion moves the value into a newly allocated Arc. It is equivalent to calling Arc::new(t).

Example

let x = 5;
let arc = Arc::new(5);

assert_eq!(Arc::from(x), arc);

Use a Wake-able type as a Waker.

No heap allocations or atomic operations are used for this conversion.

Create a reference-counted pointer from a clone-on-write pointer by copying its content.

Example

let cow: Cow<str> = Cow::Borrowed("eggplant");
let shared: Rc<str> = Rc::from(cow);
assert_eq!("eggplant", &shared[..]);

Allocate a reference-counted str and copy v into it.

Example

let shared: Arc<str> = Arc::from("eggplant");
assert_eq!("eggplant", &shared[..]);

Use a Wake-able type as a RawWaker.

No heap allocations or atomic operations are used for this conversion.

Move a boxed object to a new, reference-counted allocation.

Example

let unique: Box<str> = Box::from("eggplant");
let shared: Arc<str> = Arc::from(unique);
assert_eq!("eggplant", &shared[..]);

Converts a Box<T> into a Pin<Box<T>>

This conversion does not allocate on the heap and happens in place.

Create an atomically reference-counted pointer from a clone-on-write pointer by copying its content.

Example

let cow: Cow<str> = Cow::Borrowed("eggplant");
let shared: Arc<str> = Arc::from(cow);
assert_eq!("eggplant", &shared[..]);

Allocate a reference-counted str and copy v into it.

Example

let unique: String = "eggplant".to_owned();
let shared: Arc<str> = Arc::from(unique);
assert_eq!("eggplant", &shared[..]);

Allocate a reference-counted slice and move v’s items into it.

Example

let original: Box<Vec<i32>> = Box::new(vec![1, 2, 3]);
let shared: Rc<Vec<i32>> = Rc::from(original);
assert_eq!(vec![1, 2, 3], *shared);

Allocate a reference-counted slice and move v’s items into it.

Example

let unique: Vec<i32> = vec![1, 2, 3];
let shared: Arc<[i32]> = Arc::from(unique);
assert_eq!(&[1, 2, 3], &shared[..]);

Move a boxed object to a new, reference counted, allocation.

Example

let original: Box<i32> = Box::new(1);
let shared: Rc<i32> = Rc::from(original);
assert_eq!(1, *shared);

Allocate a reference-counted slice and fill it by cloning v’s items.

Example

let original: &[i32] = &[1, 2, 3];
let shared: Rc<[i32]> = Rc::from(original);
assert_eq!(&[1, 2, 3], &shared[..]);

Allocate a reference-counted string slice and copy v into it.

Example

let shared: Rc<str> = Rc::from("statue");
assert_eq!("statue", &shared[..]);

Implementors