valust_utils/convert.rs
1//! Type conversion functions for use in the `trans` attribute.
2
3use std::str::FromStr;
4
5/// Parses a string slice into the specified type `F`.
6///
7/// ```rust
8/// # use valust_utils::convert::parse_to;
9/// # use valust::{Validate, Raw, error::display::ErrorDisplay};
10/// # use valust_derive::Valust;
11/// #
12/// #[derive(Valust)]
13/// struct Stringify {
14/// #[trans(func(String => try(parse_to::<i32>)))]
15/// num: i32,
16/// }
17/// ```
18pub fn parse_to<F: FromStr>(s: impl AsRef<str>) -> Result<F, F::Err> {
19 s.as_ref().parse::<F>()
20}
21
22/// Converts a value of type `F` into type `T`.
23///
24/// ```rust
25/// # use valust_utils::convert::into;
26/// # use valust::{Validate, Raw, error::display::ErrorDisplay};
27/// # use valust_derive::Valust;
28/// #
29/// #[derive(Valust)]
30/// struct Stringify {
31/// #[trans(func(&'static str => into))]
32/// num: String,
33/// }
34/// ```
35pub fn into<F: Into<T>, T>(f: F) -> T {
36 f.into()
37}
38
39/// Tries to convert a value of type `F` into type `T`.
40///
41/// ```rust
42/// # use valust_utils::convert::try_into;
43/// # use valust::{Validate, Raw, error::display::ErrorDisplay};
44/// # use valust_derive::Valust;
45/// #
46/// #[derive(Valust)]
47/// struct Stringify {
48/// #[trans(func(i32 => try(try_into)))]
49/// num: i8,
50/// }
51/// ```
52pub fn try_into<F: TryInto<T>, T>(f: F) -> Result<T, F::Error> {
53 f.try_into()
54}