[−][src]Function bin_io::utils::try_cast
pub fn try_cast<R: Read, W: Write, Rf, Wf, I, O>(
f: (Rf, Wf)
) -> (impl ReadFn<R, I>, impl WriteFn<W, I>) where
Rf: ReadFn<R, O>,
Wf: WriteFn<W, O>,
O: TryFrom<I> + TryInto<I>,
I: Clone,
Bidirectional cast.
This is an helper function used in conjuction
with seq!
.
This is the TryFrom
variant of cast
.
Reading
The function tries to casts O into I.
Writing
The function tries to casts I into O.
Remarks
Since this cast is bidirectional, each type must
be constructible from the other. Therefore remember
to implement TryFrom<I> for O
and TryFrom<O> for I
!
Examples
use std::io::Cursor; use bin_io::numbers::{ be_u8 }; use bin_io::{ write, try_cast, seq }; let vec = Vec::new(); let mut cursor = Cursor::new(vec); struct Unicorn { a: usize } let a = seq!( Unicorn { a }, a: try_cast(be_u8()) => ); write(&mut cursor, &Unicorn { a: 20 }, a) .unwrap(); assert_eq!(cursor.get_ref()[0], 20); // Fails to cast! let err = write(&mut cursor, &Unicorn { a: 256 }, a); assert!(err.is_err());