1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
//---------------------------------------------------------------------------------------------------- Use
#[cfg(feature = "serde")]
use serde::{Serialize,Deserialize};

use compact_str::{format_compact,CompactString};
use crate::constants::*;
use crate::macros::*;

//---------------------------------------------------------------------------------------------------- Float
/// Human readable float.
///
/// Takes a floating point number as input and returns a ready-to-[`print!()`] [`Float`].
///
/// The fractional floating point may or may not be rounded up/down in the [`String`].
///
/// The default [`Float::from`] implementation will print `3` decimal numbers.
///
/// This can be changed by using different functions when initially
/// creating the [`Float`], or converting an existing [`Float`], for example:
/// ```
/// # use readable::Float;
/// let f2 = Float::new_2_point(3.0);
/// let f6 = Float::new_6_point(3.0);
/// let f9 = Float::new_9_point(f2.inner());
///
/// assert!(f2 == 3.00);
/// assert!(f6 == 3.000000);
/// assert!(f9 == 3.000000000);
///```
///
/// ## Cloning
/// [`Clone`] may be expensive:
/// ```rust
/// # use readable::Float;
/// // Probably cheap (stack allocated string).
/// let a = Float::from(100.0);
/// let b = a.clone();
///
/// // Probably expensive (heap allocated string).
/// let a = Float::from(f64::MAX);
/// let b = a.clone();
/// ```
///
/// The actual string used internally is not a [`String`](https://doc.rust-lang.org/std/string/struct.String.html),
/// but a [`CompactString`](https://docs.rs/compact_str) so that any string 24 bytes (12 bytes on 32-bit) or less are _stack_ allocated instead of _heap_ allocated.
///
/// The documentation will still refer to the inner string as a `String`. Anything returned will also be a `String`.
///
/// ## Exceptions
/// - [`f64::NAN`] outputs [`NAN`]
/// - [`f64::INFINITY`] outputs [`INFINITY`]
///
/// To disable checks for these, (you are _sure_ you don't have NaN's), enable the `ignore_nan_inf` feature flag.
///
/// # Examples
/// ```rust
/// # use readable::Float;
/// assert!(Float::from(0.0)              == "0.000");
///
/// // This gets rounded up to '.568'
/// assert!(Float::from(1234.5678)        == "1,234.568");
/// // To prevent that, use 4 point.
/// assert!(Float::new_4_point(1234.5678) == "1,234.5678");
/// ```

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct Float(f64, CompactString);

impl_traits!(Float, f64);

impl Float {
	impl_common!(f64);

	#[inline]
	/// Returns a [`Self`] with the [`f64`] value of `0.0`.
	///
	/// The [`String`] is set to [`ZERO_FLOAT`].
	pub fn zero() -> Self {
		Self(0.0, CompactString::new(ZERO_FLOAT))
	}

	#[inline]
	/// Returns a [`Self`] with the [`f64`] value of [`f64::NAN`].
	///
	/// The [`String`] is set to [`UNKNOWN_FLOAT`].
	pub fn unknown() -> Self {
		Self(f64::NAN, CompactString::new(UNKNOWN_FLOAT))
	}

	#[inline]
	/// Returns a [`Self`] with the [`f64`] value of [`f64::NAN`].
	///
	/// The [`String`] is set to [`NAN`].
	pub fn nan() -> Self {
		Self(f64::NAN, CompactString::new(NAN))
	}

	#[inline]
	/// Returns a [`Self`] with the [`f64`] value of [`f64::INFINITY`].
	///
	/// The [`String`] is set to [`INFINITY`].
	pub fn inf() -> Self {
		Self(f64::INFINITY, CompactString::new(INFINITY))
	}

	#[inline]
	/// Same as [`Self::from`] but with no floating point on the inner [`String`].
	///
	/// The inner [`f64`] stays the same as the input.
	///
	/// This does not round _up_ or _down_, it completely ignores the floating point.
	///
	/// ## Examples
	/// | Input  | String Output |
	/// |--------|---------------|
	/// | 0.0    | `0`
	/// | 50.123 | `50`
	/// | 100.1  | `100`
	pub fn new_0_point(f: f64) -> Self {
		handle_nan_string!(f);
		Self(f, format_compact!("{}", num!(f as u64)))
	}

	#[inline]
	/// Create a new [`Self`]  but with `1` floating point.
	pub fn new_1_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.1}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `2` floating point.
	pub fn new_2_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.2}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `4` floating point.
	pub fn new_4_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.4}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `5` floating point.
	pub fn new_5_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.5}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `6` floating point.
	pub fn new_6_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.6}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `7` floating point.
	pub fn new_7_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.7}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `8` floating point.
	pub fn new_8_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.8}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `9` floating point.
	pub fn new_9_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.9}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `10` floating point.
	pub fn new_10_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.10}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `11` floating point.
	pub fn new_11_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.11}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `12` floating point.
	pub fn new_12_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.12}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `13` floating point.
	pub fn new_13_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.13}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}

	#[inline]
	/// Create a new [`Self`]  but with `14` floating point.
	pub fn new_14_point(f: f64) -> Self {
		handle_nan_string!(f);

		let fract = &format_compact!("{:.14}", f.fract())[2..];
		Self(f, format_compact!("{}.{}", num!(f as u64), fract))
	}
}

// Implementation Macro.
macro_rules! impl_number {
	($number:ty) => {
		impl From<$number> for Float {
			#[inline]
			fn from(number: $number) -> Self {
				Self(number as f64, format_compact!("{}.000", num!(number)))
			}
		}
	}
}

impl_number!(u8);
impl_number!(u16);
impl_number!(u32);
impl_number!(u64);
impl_number!(usize);
impl_number!(i8);
impl_number!(i16);
impl_number!(i32);
impl_number!(i64);
impl_number!(isize);

impl From<f32> for Float {
	#[inline]
	fn from(number: f32) -> Self {
		#[cfg(not(feature = "ignore_nan_inf"))]
		{
			let fpcat = number.classify();
			use std::num::FpCategory;
			match fpcat {
				FpCategory::Normal   => (),
				FpCategory::Nan      => return Self(number as f64, CompactString::new(NAN)),
				FpCategory::Infinite => return Self(number as f64, CompactString::new(INFINITY)),
				_ => (),
			}
		}

		let fract = &format_compact!("{:.3}", number.fract())[2..];

		Self(number as f64, format_compact!("{}.{}", num!(number as u64).as_str(), fract))
	}
}

impl From<f64> for Float {
	#[inline]
	fn from(number: f64) -> Self {
		#[cfg(not(feature = "ignore_nan_inf"))]
		{
			let fpcat = number.classify();
			use std::num::FpCategory;
			match fpcat {
				FpCategory::Normal   => (),
				FpCategory::Nan      => return Self(number, CompactString::new(NAN)),
				FpCategory::Infinite => return Self(number, CompactString::new(INFINITY)),
				_ => (),
			}
		}

		let fract = &format_compact!("{:.3}", number.fract())[2..];

		Self(number, format_compact!("{}.{}", num!(number as u64).as_str(), fract))
	}
}

//---------------------------------------------------------------------------------------------------- TESTS
#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn special() {
		assert!(Float::from(0.0) == "0.000");
		assert!(Float::zero()    == "0.000");
		assert!(Float::unknown() == UNKNOWN_FLOAT);
		assert!(Float::nan()     == NAN);
		assert!(Float::inf()     == INFINITY);

		assert!(Float::from(f64::NAN)          == NAN);
		assert!(Float::from(f64::INFINITY)     == INFINITY);
		assert!(Float::from(f64::NEG_INFINITY) == INFINITY);

		assert!(Float::from(f32::NAN)          == NAN);
		assert!(Float::from(f32::INFINITY)     == INFINITY);
		assert!(Float::from(f32::NEG_INFINITY) == INFINITY);
	}

	#[test]
	fn float() {
		assert!(Float::new_0_point( 0.1)              == "0");
		assert!(Float::new_1_point( 0.1)              == "0.1");
		assert!(Float::new_2_point( 0.01)             == "0.01");
		assert!(Float::from(        0.001)            == "0.001");
		assert!(Float::new_4_point( 0.0001)           == "0.0001");
		assert!(Float::new_5_point( 0.00001)          == "0.00001");
		assert!(Float::new_6_point( 0.000001)         == "0.000001");
		assert!(Float::new_7_point( 0.0000001)        == "0.0000001");
		assert!(Float::new_8_point( 0.00000001)       == "0.00000001");
		assert!(Float::new_9_point( 0.000000001)      == "0.000000001");
		assert!(Float::new_10_point(0.0000000001)     == "0.0000000001");
		assert!(Float::new_11_point(0.00000000001)    == "0.00000000001");
		assert!(Float::new_12_point(0.000000000001)   == "0.000000000001");
		assert!(Float::new_13_point(0.0000000000001)  == "0.0000000000001");
		assert!(Float::new_14_point(0.00000000000001) == "0.00000000000001");
	}
}