Skip to main content

bonsai_eval_utils/
lib.rs

1#![deny(unconditional_recursion)]
2#![no_std]
3
4use core::fmt;
5
6
7pub mod ram_disk;
8pub mod replay_disk;
9
10
11extern crate alloc;
12
13
14
15/// Implements Display to print the number with metric prefixes
16/// using fixed 4 space plus the metric prefix (you have to print a unit thereafter)
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
18pub struct MetricNumber(pub usize);
19impl fmt::Display for MetricNumber {
20	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21		let suffixes = [" ", "K", "M", "G", "T", "P", "E", "Z", "Y", "R", "Q"];
22
23		let n = self.0;
24
25		let i = (n.checked_ilog10().unwrap_or(0) as usize / 3).min(suffixes.len());
26
27		let div = 10_usize.pow(i as u32 * 3);
28		let full = n / div;
29		let frac = (1000 * (n % div)) / div;
30
31		if full >= 100 || i == 0 {
32			write!(f, "{:4}{}", full, suffixes[i])
33		} else if full >= 10 {
34			write!(f, "{:2}.{:01}{}", full, frac / 100, suffixes[i])
35		} else {
36			write!(f, "{:1}.{:02}{}", full, frac / 10, suffixes[i])
37		}
38	}
39}
40
41/// Implements Display to print the number with IEC-prefixes
42/// using fixed 4 space plus the prefix (you have to print a unit thereafter).
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
44pub struct IecNumber(pub usize);
45impl fmt::Display for IecNumber {
46	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47		let suffixes = [
48			"  ", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi", "Ri", "Qi",
49		];
50
51		let n = self.0;
52
53		let i = (n.checked_ilog2().unwrap_or(0) as usize / 10).min(suffixes.len());
54
55		let div = 2_usize.pow(i as u32 * 10);
56		let full = n / div;
57		let frac = (1000 * (n % div)) / div;
58
59		if full >= 100 || i == 0 {
60			write!(f, "{:4}{}", full, suffixes[i])
61		} else if full >= 10 {
62			write!(f, "{:2}.{:01}{}", full, frac / 100, suffixes[i])
63		} else {
64			write!(f, "{:1}.{:02}{}", full, frac / 10, suffixes[i])
65		}
66	}
67}