Skip to content

Commit 21ffabc

Browse files
committed
float: Add f16 parsing and printing
1 parent 650e63f commit 21ffabc

File tree

10 files changed

+269
-14
lines changed

10 files changed

+269
-14
lines changed

library/core/src/fmt/float.rs

+2-8
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ macro_rules! impl_general_format {
2020
}
2121
}
2222

23+
impl_general_format! { f16 }
2324
impl_general_format! { f32 f64 }
2425

2526
// Don't inline this so callers don't use the stack space this function
@@ -227,17 +228,10 @@ macro_rules! floating {
227228
};
228229
}
229230

231+
floating! { f16 }
230232
floating! { f32 }
231233
floating! { f64 }
232234

233-
#[stable(feature = "rust1", since = "1.0.0")]
234-
impl Debug for f16 {
235-
#[inline]
236-
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
237-
write!(f, "{:#06x}", self.to_bits())
238-
}
239-
}
240-
241235
#[stable(feature = "rust1", since = "1.0.0")]
242236
impl Debug for f128 {
243237
#[inline]

library/core/src/num/dec2flt/float.rs

+44
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,50 @@ pub trait RawFloat:
191191
}
192192
}
193193

194+
impl RawFloat for f16 {
195+
type Int = u16;
196+
197+
const INFINITY: Self = Self::INFINITY;
198+
const NEG_INFINITY: Self = Self::NEG_INFINITY;
199+
const NAN: Self = Self::NAN;
200+
const NEG_NAN: Self = -Self::NAN;
201+
202+
const BITS: u32 = 16;
203+
const MANTISSA_BITS: u32 = Self::MANTISSA_DIGITS;
204+
const EXPONENT_MASK: Self::Int = Self::EXP_MASK;
205+
const MANTISSA_MASK: Self::Int = Self::MAN_MASK;
206+
207+
const MIN_EXPONENT_ROUND_TO_EVEN: i32 = -17;
208+
const MAX_EXPONENT_ROUND_TO_EVEN: i32 = 10;
209+
// const SMALLEST_POWER_OF_TEN: i32 = -27;
210+
// const LARGEST_POWER_OF_TEN: i32 = Self::MAX_10_EXP;
211+
212+
#[inline]
213+
fn from_u64(v: u64) -> Self {
214+
debug_assert!(v <= Self::MAX_MANTISSA_FAST_PATH);
215+
v as _
216+
}
217+
218+
#[inline]
219+
fn from_u64_bits(v: u64) -> Self {
220+
Self::from_bits((v & 0xFF) as u16)
221+
}
222+
223+
fn pow10_fast_path(exponent: usize) -> Self {
224+
#[allow(clippy::use_self)]
225+
const TABLE: [f16; 8] = [1e0, 1e1, 1e2, 1e3, 1e4, 0.0, 0.0, 0.];
226+
TABLE[exponent & 15]
227+
}
228+
229+
fn to_bits(self) -> Self::Int {
230+
self.to_bits()
231+
}
232+
233+
fn classify(self) -> FpCategory {
234+
self.classify()
235+
}
236+
}
237+
194238
impl RawFloat for f32 {
195239
type Int = u32;
196240

library/core/src/num/dec2flt/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,8 @@ macro_rules! from_str_float_impl {
171171
}
172172
};
173173
}
174+
175+
from_str_float_impl!(f16);
174176
from_str_float_impl!(f32);
175177
from_str_float_impl!(f64);
176178

library/core/src/num/flt2dec/decoder.rs

+6
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,12 @@ pub trait DecodableFloat: RawFloat + Copy {
4545
fn min_pos_norm_value() -> Self;
4646
}
4747

48+
impl DecodableFloat for f16 {
49+
fn min_pos_norm_value() -> Self {
50+
f16::MIN_POSITIVE
51+
}
52+
}
53+
4854
impl DecodableFloat for f32 {
4955
fn min_pos_norm_value() -> Self {
5056
f32::MIN_POSITIVE

library/core/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
#![feature(error_generic_member_access)]
5252
#![feature(exact_size_is_empty)]
5353
#![feature(extern_types)]
54+
#![feature(f16)]
5455
#![feature(float_minimum_maximum)]
5556
#![feature(flt2dec)]
5657
#![feature(fmt_internals)]

library/core/tests/num/dec2flt/float.rs

+16
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
11
use core::num::dec2flt::float::RawFloat;
22

3+
#[test]
4+
fn test_f16_integer_decode() {
5+
assert_eq!(3.14159265359f16.integer_decode(), (1608, -9, 1));
6+
assert_eq!((-8573.5918555f16).integer_decode(), (1072, 3, -1));
7+
assert_eq!(2f16.powf(4.0).integer_decode(), (1024, -6, 1));
8+
assert_eq!(0f16.integer_decode(), (0, -25, 1));
9+
assert_eq!((-0f16).integer_decode(), (0, -25, -1));
10+
assert_eq!(f16::INFINITY.integer_decode(), (1024, 6, 1));
11+
assert_eq!(f16::NEG_INFINITY.integer_decode(), (1024, 6, -1));
12+
13+
// Ignore the "sign" (quiet / signalling flag) of NAN.
14+
// It can vary between runtime operations and LLVM folding.
15+
let (nan_m, nan_p, _nan_s) = f16::NAN.integer_decode();
16+
assert_eq!((nan_m, nan_p), (1536, 6));
17+
}
18+
319
#[test]
420
fn test_f32_integer_decode() {
521
assert_eq!(3.14159265359f32.integer_decode(), (13176795, -22, 1));

library/core/tests/num/dec2flt/mod.rs

+92-4
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,103 @@ macro_rules! test_literal {
1313
let x64: f64 = $x;
1414
let inputs = &[stringify!($x).into(), format!("{:?}", x64), format!("{:e}", x64)];
1515
for input in inputs {
16-
assert_eq!(input.parse(), Ok(x64));
17-
assert_eq!(input.parse(), Ok(x32));
16+
assert_eq!(input.parse(), Ok(x64), "failed f64 {input}");
17+
assert_eq!(input.parse(), Ok(x32), "failed f32 {input}");
1818
let neg_input = format!("-{input}");
19-
assert_eq!(neg_input.parse(), Ok(-x64));
20-
assert_eq!(neg_input.parse(), Ok(-x32));
19+
assert_eq!(neg_input.parse(), Ok(-x64), "failed f64 {neg_input}");
20+
assert_eq!(neg_input.parse(), Ok(-x32), "failed f32 {neg_input}");
2121
}
2222
}};
2323
}
2424

25+
// macro_rules! test_literal2 {
26+
// ($x: expr) => {{
27+
// // let x32: f32 = $x;
28+
// let x64: f64 = $x;
29+
// x::<f32>(stringify!($x));
30+
// x::<f64>(stringify!($x));
31+
32+
// let inputs = &[stringify!($x).into(), format!("{:?}", x64), format!("{:e}", x64)];
33+
// for input in inputs {
34+
// println!("{}", input.parse::<f32>().unwrap());
35+
// println!("{}", input.parse::<f64>().unwrap());
36+
// // assert_eq!(input.parse(), Ok(x64), "failed f64 {input}");
37+
// // assert_eq!(input.parse(), Ok(x32), "failed f32 {input}");
38+
// // let neg_input = format!("-{input}");
39+
// // assert_eq!(neg_input.parse(), Ok(-x64), "failed f64 {neg_input}");
40+
// // assert_eq!(neg_input.parse(), Ok(-x32), "failed f32 {neg_input}");
41+
// }
42+
// }};
43+
// }
44+
45+
// #[test]
46+
// fn foo() {
47+
// use core::num::dec2flt::float::RawFloat;
48+
// use core::num::dec2flt::parse::parse_number;
49+
50+
// fn x<F: RawFloat + std::fmt::Display>(r: &str) {
51+
// let mut s = r.as_bytes();
52+
// let c = s[0];
53+
// let negative = c == b'-';
54+
// if c == b'-' || c == b'+' {
55+
// s = &s[1..];
56+
// }
57+
// let mut num = parse_number(s).unwrap();
58+
// num.negative = negative;
59+
// if let Some(value) = num.try_fast_path::<F>() {
60+
// // return Ok(value);
61+
// println!("fast path {value}");
62+
// return;
63+
// }
64+
65+
// let q = num.exponent;
66+
// let w = num.mantissa;
67+
68+
// println!(
69+
// "float {r} {q} {w} {q:#066b} {w:#066b} sm10 {} lg10 {} ty {} chk {}",
70+
// F::SMALLEST_POWER_OF_TEN,
71+
// F::LARGEST_POWER_OF_TEN,
72+
// std::any::type_name::<F>(),
73+
// if w == 0 || q < F::SMALLEST_POWER_OF_TEN as i64 {
74+
// "lt small 10"
75+
// } else if q > F::LARGEST_POWER_OF_TEN as i64 {
76+
// "gt big 10"
77+
// } else {
78+
// ""
79+
// }
80+
// );
81+
// }
82+
83+
// // test_literal2!(1e-20);
84+
// // test_literal2!(1e-30);
85+
// // test_literal2!(1e-40);
86+
// // test_literal2!(1e-50);
87+
// // test_literal2!(1e-60);
88+
// // test_literal2!(1e-63);
89+
// // test_literal2!(1e-64);
90+
// // test_literal2!(1e-65);
91+
// // test_literal2!(1e-66);
92+
// // test_literal2!(1e-70);
93+
// // test_literal2!(1e-70);
94+
// // test_literal2!(1e-70);
95+
// // test_literal2!(1e-70);
96+
// // test_literal2!(2.225073858507201136057409796709131975934819546351645648023426109724822222021076945516529523908135087914149158913039621106870086438694594645527657207407820621743379988141063267329253552286881372149012981122451451889849057222307285255133155755015914397476397983411801999323962548289017107081850690630666655994938275772572015763062690663332647565300009245888316433037779791869612049497390377829704905051080609940730262937128958950003583799967207254304360284078895771796150945516748243471030702609144621572289880258182545180325707018860872113128079512233426288368622321503775666622503982534335974568884423900265498198385487948292206894721689831099698365846814022854243330660339850886445804001034933970427567186443383770486037861622771738545623065874679014086723327636718749999999999999999999999999999999999999e-308);
97+
// // test_literal2!(1.175494140627517859246175898662808184331245864732796240031385942718174675986064769972472277004271745681762695312500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e-38);
98+
// // panic!();
99+
// }
100+
101+
// #[test]
102+
// fn foobar() {
103+
// use core::num::dec2flt::float::RawFloat;
104+
// panic!(
105+
// "{} {} {} {}",
106+
// <f32 as RawFloat>::LARGEST_POWER_OF_TEN,
107+
// <f32 as RawFloat>::SMALLEST_POWER_OF_TEN,
108+
// <f64 as RawFloat>::LARGEST_POWER_OF_TEN,
109+
// <f64 as RawFloat>::SMALLEST_POWER_OF_TEN,
110+
// )
111+
// }
112+
25113
#[test]
26114
fn ordinary() {
27115
test_literal!(1.0);

library/core/tests/num/flt2dec/mod.rs

+101
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,10 @@ macro_rules! try_fixed {
7575
})
7676
}
7777

78+
// fn ldexp_f16(a: f16, b: i32) -> f16 {
79+
// ldexp_f64(a as f64, b) as f16
80+
// }
81+
7882
fn ldexp_f32(a: f32, b: i32) -> f32 {
7983
ldexp_f64(a as f64, b) as f32
8084
}
@@ -176,6 +180,12 @@ trait TestableFloat: DecodableFloat + fmt::Display {
176180
fn ldexpi(f: i64, exp: isize) -> Self;
177181
}
178182

183+
// impl TestableFloat for f16 {
184+
// fn ldexpi(f: i64, exp: isize) -> Self {
185+
// f as Self * (exp as Self).exp2()
186+
// }
187+
// }
188+
179189
impl TestableFloat for f32 {
180190
fn ldexpi(f: i64, exp: isize) -> Self {
181191
f as Self * (exp as Self).exp2()
@@ -226,6 +236,97 @@ macro_rules! check_exact_one {
226236
// [1] Vern Paxson, A Program for Testing IEEE Decimal-Binary Conversion
227237
// ftp://ftp.ee.lbl.gov/testbase-report.ps.Z
228238

239+
// pub fn f16_shortest_sanity_test<F>(mut f: F)
240+
// where
241+
// F: for<'a> FnMut(&Decoded, &'a mut [MaybeUninit<u8>]) -> (&'a [u8], i16),
242+
// {
243+
// // 0.0999999940395355224609375
244+
// // 0.100000001490116119384765625
245+
// // 0.10000000894069671630859375
246+
// check_shortest!(f(0.1f16) => b"1", 0);
247+
248+
// // 0.333333313465118408203125
249+
// // 0.3333333432674407958984375 (1/3 in the default rounding)
250+
// // 0.33333337306976318359375
251+
// check_shortest!(f(1.0f16/3.0) => b"33333334", 0);
252+
253+
// // 10^1 * 0.31415917873382568359375
254+
// // 10^1 * 0.31415920257568359375
255+
// // 10^1 * 0.31415922641754150390625
256+
// check_shortest!(f(3.141592f16) => b"3141592", 1);
257+
258+
// // 10^18 * 0.31415916243714048
259+
// // 10^18 * 0.314159196796878848
260+
// // 10^18 * 0.314159231156617216
261+
// check_shortest!(f(3.141592e17f16) => b"3141592", 18);
262+
263+
// // regression test for decoders
264+
// // 10^8 * 0.3355443
265+
// // 10^8 * 0.33554432
266+
// // 10^8 * 0.33554436
267+
// check_shortest!(f(ldexp_f16(1.0, 25)) => b"33554432", 8);
268+
269+
// // 10^39 * 0.340282326356119256160033759537265639424
270+
// // 10^39 * 0.34028234663852885981170418348451692544
271+
// // 10^39 * 0.340282366920938463463374607431768211456
272+
// check_shortest!(f(f16::MAX) => b"34028235", 39);
273+
274+
// // 10^-37 * 0.1175494210692441075487029444849287348827...
275+
// // 10^-37 * 0.1175494350822287507968736537222245677818...
276+
// // 10^-37 * 0.1175494490952133940450443629595204006810...
277+
// check_shortest!(f(f16::MIN_POSITIVE) => b"11754944", -37);
278+
279+
// // 10^-44 * 0
280+
// // 10^-44 * 0.1401298464324817070923729583289916131280...
281+
// // 10^-44 * 0.2802596928649634141847459166579832262560...
282+
// let minf16 = ldexp_f16(1.0, -149);
283+
// check_shortest!(f(minf16) => b"1", -44);
284+
// }
285+
286+
// pub fn f16_exact_sanity_test<F>(mut f: F)
287+
// where
288+
// F: for<'a> FnMut(&Decoded, &'a mut [MaybeUninit<u8>], i16) -> (&'a [u8], i16),
289+
// {
290+
// let minf16 = ldexp_f16(1.0, -149);
291+
292+
// check_exact!(f(0.1f16) => b"100000001490116119384765625 ", 0);
293+
// check_exact!(f(0.5f16) => b"5 ", 0);
294+
// check_exact!(f(1.0f16/3.0) => b"3333333432674407958984375 ", 0);
295+
// check_exact!(f(3.141592f16) => b"31415920257568359375 ", 1);
296+
// check_exact!(f(3.141592e17f16) => b"314159196796878848 ", 18);
297+
// check_exact!(f(f16::MAX) => b"34028234663852885981170418348451692544 ", 39);
298+
// check_exact!(f(f16::MIN_POSITIVE) => b"1175494350822287507968736537222245677818", -37);
299+
// check_exact!(f(minf16) => b"1401298464324817070923729583289916131280", -44);
300+
301+
// // [1], Table 16: Stress Inputs for Converting 24-bit Binary to Decimal, < 1/2 ULP
302+
// check_exact_one!(f(12676506, -102; f16) => b"2", -23);
303+
// check_exact_one!(f(12676506, -103; f16) => b"12", -23);
304+
// check_exact_one!(f(15445013, 86; f16) => b"119", 34);
305+
// check_exact_one!(f(13734123, -138; f16) => b"3941", -34);
306+
// check_exact_one!(f(12428269, -130; f16) => b"91308", -32);
307+
// check_exact_one!(f(15334037, -146; f16) => b"171900", -36);
308+
// check_exact_one!(f(11518287, -41; f16) => b"5237910", -5);
309+
// check_exact_one!(f(12584953, -145; f16) => b"28216440", -36);
310+
// check_exact_one!(f(15961084, -125; f16) => b"375243281", -30);
311+
// check_exact_one!(f(14915817, -146; f16) => b"1672120916", -36);
312+
// check_exact_one!(f(10845484, -102; f16) => b"21388945814", -23);
313+
// check_exact_one!(f(16431059, -61; f16) => b"712583594561", -11);
314+
315+
// // [1], Table 17: Stress Inputs for Converting 24-bit Binary to Decimal, > 1/2 ULP
316+
// check_exact_one!(f(16093626, 69; f16) => b"1", 29);
317+
// check_exact_one!(f( 9983778, 25; f16) => b"34", 15);
318+
// check_exact_one!(f(12745034, 104; f16) => b"259", 39);
319+
// check_exact_one!(f(12706553, 72; f16) => b"6001", 29);
320+
// check_exact_one!(f(11005028, 45; f16) => b"38721", 21);
321+
// check_exact_one!(f(15059547, 71; f16) => b"355584", 29);
322+
// check_exact_one!(f(16015691, -99; f16) => b"2526831", -22);
323+
// check_exact_one!(f( 8667859, 56; f16) => b"62458507", 24);
324+
// check_exact_one!(f(14855922, -82; f16) => b"307213267", -17);
325+
// check_exact_one!(f(14855922, -83; f16) => b"1536066333", -17);
326+
// check_exact_one!(f(10144164, -110; f16) => b"78147796834", -26);
327+
// check_exact_one!(f(13248074, 95; f16) => b"524810279937", 36);
328+
// }
329+
229330
pub fn f32_shortest_sanity_test<F>(mut f: F)
230331
where
231332
F: for<'a> FnMut(&Decoded, &'a mut [MaybeUninit<u8>]) -> (&'a [u8], i16),

src/etc/test-float-parse/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#![feature(f16)]
2+
13
mod traits;
24
mod ui;
35
mod validate;
@@ -114,6 +116,7 @@ pub fn register_tests(cfg: &Config) -> Vec<TestInfo> {
114116
let mut tests = Vec::new();
115117

116118
// Register normal generators for all floats.
119+
register_float::<f16>(&mut tests, cfg);
117120
register_float::<f32>(&mut tests, cfg);
118121
register_float::<f64>(&mut tests, cfg);
119122

src/etc/test-float-parse/src/traits.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ macro_rules! impl_int {
9898
}
9999
}
100100

101-
impl_int!(u32, i32; u64, i64);
101+
impl_int!(u16, i16; u32, i32; u64, i64);
102102

103103
/// Floating point types.
104104
pub trait Float:
@@ -168,7 +168,7 @@ macro_rules! impl_float {
168168
}
169169
}
170170

171-
impl_float!(f32, u32; f64, u64;
171+
impl_float!(f16, u16; f32, u32; f64, u64);
172172

173173
/// A test generator. Should provide an iterator that produces unique patterns to parse.
174174
///

0 commit comments

Comments
 (0)