lexical_parse_float/
api.rs

1////! Implements the algorithm in terms of the lexical API.
2
3#![doc(hidden)]
4
5use crate::options::Options;
6use crate::parse::ParseFloat;
7#[cfg(feature = "f16")]
8use lexical_util::bf16::bf16;
9use lexical_util::error::Error;
10#[cfg(feature = "f16")]
11use lexical_util::f16::f16;
12use lexical_util::format::{is_valid_options_punctuation, NumberFormat, STANDARD};
13use lexical_util::{from_lexical, from_lexical_with_options};
14
15// API
16
17const DEFAULT_OPTIONS: Options = Options::new();
18
19/// Implement FromLexical for numeric type.
20///
21/// Need to inline these, otherwise codegen is suboptimal.
22/// For some reason, it can't determine some of the const evaluations
23/// can actually be evaluated at compile-time, which causes major branching
24/// issues.
25macro_rules! float_from_lexical {
26    ($($t:ident)*) => ($(
27        impl FromLexical for $t {
28            #[cfg_attr(not(feature = "compact"), inline)]
29            fn from_lexical(bytes: &[u8]) -> lexical_util::result::Result<Self>
30            {
31                Self::parse_complete::<STANDARD>(bytes, &DEFAULT_OPTIONS)
32            }
33
34            #[cfg_attr(not(feature = "compact"), inline)]
35            fn from_lexical_partial(
36                bytes: &[u8],
37            ) -> lexical_util::result::Result<(Self, usize)>
38            {
39                Self::parse_partial::<STANDARD>(bytes, &DEFAULT_OPTIONS)
40            }
41        }
42
43        impl FromLexicalWithOptions for $t {
44            type Options = Options;
45
46            #[cfg_attr(not(feature = "compact"), inline)]
47            fn from_lexical_with_options<const FORMAT: u128>(
48                bytes: &[u8],
49                options: &Self::Options,
50            ) -> lexical_util::result::Result<Self>
51            {
52                let format = NumberFormat::<{ FORMAT }> {};
53                if !format.is_valid() {
54                    return Err(format.error());
55                } else if !is_valid_options_punctuation(FORMAT, options.exponent(), options.decimal_point()) {
56                    return Err(Error::InvalidPunctuation);
57                }
58                Self::parse_complete::<FORMAT>(bytes, options)
59            }
60
61            #[cfg_attr(not(feature = "compact"), inline)]
62            fn from_lexical_partial_with_options<const FORMAT: u128>(
63                bytes: &[u8],
64                options: &Self::Options,
65            ) -> lexical_util::result::Result<(Self, usize)>
66            {
67                Self::parse_partial::<FORMAT>(bytes, options)
68            }
69        }
70    )*)
71}
72
73from_lexical! {}
74from_lexical_with_options! {}
75float_from_lexical! { f32 f64 }
76
77#[cfg(feature = "f16")]
78float_from_lexical! { bf16 f16 }