hexf/
lib.rs

1//! Hexadecimal float support for Rust 1.45 or later.
2//!
3//! ```rust
4//! use hexf::{hexf32, hexf64};
5//!
6//! # fn main() {
7//! assert_eq!(hexf32!("0x1.99999ap-4"), 0.1f32);
8//! assert_eq!(hexf64!("0x1.999999999999ap-4"), 0.1f64);
9//! # }
10//! ```
11
12use proc_macro::TokenStream;
13
14/// Expands to a `f32` value with given hexadecimal representation.
15///
16/// # Example
17///
18/// ```rust
19/// # use hexf::hexf32; fn main() {
20/// assert_eq!(hexf32!("0x1.99999ap-4"), 0.1f32);
21/// # }
22/// ```
23#[proc_macro]
24pub fn hexf32(input: TokenStream) -> TokenStream {
25    let lit = syn::parse_macro_input!(input as syn::LitStr);
26    match hexf_parse::parse_hexf32(&lit.value(), true) {
27        Ok(v) => format!("{:?}f32", v) // should keep the sign even for -0.0
28            .parse()
29            .expect("formatted a f32 literal"),
30        Err(e) => syn::Error::new(lit.span(), format!("hexf32! failed: {}", e))
31            .to_compile_error()
32            .into(),
33    }
34}
35
36/// Expands to a `f64` value with given hexadecimal representation.
37///
38/// # Example
39///
40/// ```rust
41/// # use hexf::hexf64; fn main() {
42/// assert_eq!(hexf64!("0x1.999999999999ap-4"), 0.1f64);
43/// # }
44/// ```
45#[proc_macro]
46pub fn hexf64(input: TokenStream) -> TokenStream {
47    let lit = syn::parse_macro_input!(input as syn::LitStr);
48    match hexf_parse::parse_hexf64(&lit.value(), true) {
49        Ok(v) => format!("{:?}f64", v) // should keep the sign even for -0.0
50            .parse()
51            .expect("formatted a f64 literal"),
52        Err(e) => syn::Error::new(lit.span(), format!("hexf64! failed: {}", e))
53            .to_compile_error()
54            .into(),
55    }
56}