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

use std::{fmt, io, mem};
use std::io::Read;
use std::fs::File;
use std::path::Path;
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::prelude::AsRawFd;
use std::convert::TryInto;

use byte_parser::{StrParser, ParseIterator};

use libc::c_int;

const DEF_PRECISION: usize = 2;

/// Represents a size, for example `1024 kB`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DataSize {
	bytes: u128
}

impl DataSize {

	// not implemeting FromStr because this is private.
	pub(crate) fn from_str(s: &str) -> Option<Self> {
		let mut iter = StrParser::new(s);
		let float = parse_f64(&mut iter)?;
		// now we need to parse the unit
		let unit = iter.record()
			.consume_to_str()
			.trim();

		let unit = DataSizeUnit::from_str(unit)?;
		Some(Self {
			bytes: unit.to_byte(float)
		})
	}

	pub(crate) fn from_size_bytes(bytes: impl TryInto<u128>) -> Option<Self> {
		bytes.try_into().ok()
			.map(|bytes| Self {bytes})
	}

	/// Convert the data unit into a specific unit.
	pub fn to(self, unit: &DataSizeUnit) -> f64 {
		DataSizeUnit::convert(self.bytes, unit)
	}

}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DataSizeUnit {
	/// Byte
	B,
	/// Kilobyte
	Kb,// 1_000
	/// Megabyte
	Mb,// 1_000_000
	/// Gigabyte
	Gb,// 1_000_000_000
	/// Terabyte
	Tb // 1_000_000_000_000
}

impl DataSizeUnit {

	const fn val(&self) -> u128 {
		match self {
			Self::B => 1,
			Self::Kb => 1_024,
			Self::Mb => 1_024 * 1_024,
			Self::Gb => 1_024 * 1_024 * 1_024,
			Self::Tb => 1_024 * 1_024 * 1_024 * 1_024
		}
	}

	fn from_str(s: &str) -> Option<Self> {
		Some(match s {
			"" => Self::B,
			s if eqs(s, "b") => Self::B,
			s if eqs(s, "kb") => Self::Kb,
			s if eqs(s, "mb") => Self::Mb,
			s if eqs(s, "gb") => Self::Gb,
			s if eqs(s, "tb") => Self::Tb,
			_ => return None
		})
	}

	fn to_byte(&self, val: f64) -> u128 {
		// TODO probably need fix this overflowing
		(val * self.val() as f64) as u128
	}

	fn adjust_to(byte: u128) -> Self {
		match byte {
			b if b < Self::Kb.val() => Self::B,
			b if b < Self::Mb.val() => Self::Kb,
			b if b < Self::Gb.val() => Self::Mb,
			b if b < Self::Tb.val() => Self::Gb,
			_ => Self::Tb
		}
	}

	fn convert(byte: u128, to: &Self) -> f64 {
		byte as f64 / to.val() as f64
	}

	const fn as_str(&self) -> &'static str {
		match self {
			Self::B => "b",
			Self::Kb => "kb",
			Self::Mb => "mb",
			Self::Gb => "gb",
			Self::Tb => "tb"
		}
	}

	// val needs to be already adjusted to self
	fn fmt_val(&self, val: f64, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		if val == 0f64 {
			return write!(f, "{}", val)
		}

		// calculate the precision we wan't to use
		let fract = val.fract();
		let precision = if fract == 0f64 {
			0
		} else {

			let max = f.precision().unwrap_or(DEF_PRECISION);

			if max <= 1 {
				max
			} else {
				calculate_precision(fract, max)
			}
		};

		write!(f, "{:.*} {}", precision, val, self.as_str())
	}

}

fn calculate_precision(mut fract: f64, max: usize) -> usize {
	let max_number = 10usize.pow(max as u32) as f64;

	// round to the max position
	fract *= max_number;
	fract = fract.round();

	// then go slowly back until we hit a fraction
	for m in (1..=max).rev() {
		fract /= 10f64;
		if fract.fract() != 0f64 {
			return m;
		}
	}

	0
}

#[inline(always)]
fn eqs(a: &str, b: &str) -> bool {
	a.eq_ignore_ascii_case(b)
}

impl fmt::Display for DataSize {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let unit = DataSizeUnit::adjust_to(self.bytes);
		let val = DataSizeUnit::convert(self.bytes, &unit);
		unit.fmt_val(val, f)
	}
}

// parses a part of a slice
// Panics if Iterator contains not valid utf8
fn parse_f64<'s, I>(iter: &mut I) -> Option<f64>
where I: ParseIterator<'s> {

	let mut iter = iter.record();

	// consume first digits
	iter.while_byte_fn(u8::is_ascii_digit)
		.consume_at_least(1)
		.ok()?;

	// dot
	let has_dot = iter
		.next_if(|&b| b == b'.')
		.is_some();

	if has_dot {
		// consume next digits
		iter.consume_while_byte_fn(u8::is_ascii_digit);
	}

	iter.to_str()
		.parse().ok()
}

/// Clears the string the writes the entire file to the string.  
/// Does not allocate in advance like std::fs::read_to_string.
pub fn read_to_string_mut(path: impl AsRef<Path>, s: &mut String) -> io::Result<()> {
	s.clear();
	let mut file = File::open(path)?;
	file.read_to_string(s)
		.map(|_| ())
}


fn cstr(path: impl AsRef<Path>) -> io::Result<CString> {
	CString::new(path.as_ref().as_os_str().as_bytes())
		.map_err(From::from)
}

// see https://man7.org/linux/man-pages/man2/fstatfs.2.html
pub fn statfs(path: impl AsRef<Path>) -> io::Result<libc::statfs> {
	unsafe {
		let mut stat = mem::MaybeUninit::<libc::statfs>::uninit();
		let c = cstr(path)?;
		let r = libc::statfs(c.as_ptr(), stat.as_mut_ptr());
		match r {
			0 => Ok(stat.assume_init()),
			-1 => Err(io::Error::last_os_error()),
			_ => panic!("unexpected return value from statfs {:?}", r)
		}
	}
}

// BLKSSZGET

pub fn blkdev_sector_size(fd: impl AsRawFd) -> io::Result<u64> {
	let s = unsafe {
		let mut size: c_int = 0;// todo set default to 512
		match blksszget(fd.as_raw_fd(), &mut size) {
			-1 => return Err(io::Error::last_os_error()),
			_ => size
		}
	};

	s.try_into()
		.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
}

#[cfg(any(
	target_arch = "x86",
	target_arch = "arm",
	target_arch = "x86_64",
	target_arch = "aarch64"
))]
unsafe fn blksszget(fd: c_int, data: *mut c_int) -> c_int {
	let nr = (0x12 << 8) | (104 << 0);
	libc::ioctl(fd, nr, data)
}

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

	#[test]
	fn test_size() {
		let size = DataSize::from_str("24576 kB").unwrap();
		assert_eq!(size.to(&DataSizeUnit::Kb), 24576.0);
	}

	#[test]
	fn size_str() {
		// TODO update the formatter
		let s = DataSize::from_str("1024").unwrap();
		assert_eq!(s.to_string(), "1 kb");
		let s = DataSize::from_str("10 kb").unwrap();
		assert_eq!(s.to_string(), "10 kb");
		let s = DataSize::from_str("42.1 mB").unwrap();
		assert_eq!(s.to_string(), "42.1 mb");
		let s = DataSize::from_str("4.22 Gb").unwrap();
		assert_eq!(s.to_string(), "4.22 gb");
		let s = DataSize::from_str("2000 Tb").unwrap();
		assert_eq!(s.to_string(), "2000 tb");
		// and precision
		assert_eq!(format!("{:.0}", DataSize::from_str("1.2 kb").unwrap()), "1 kb");
	}

	#[test]
	fn test_precision() {
		assert_eq!(calculate_precision(0.00005, 4), 4);
		assert_eq!(calculate_precision(0.00001, 4), 0);
		assert_eq!(calculate_precision(0.0001, 4), 4);
		assert_eq!(calculate_precision(0.001, 4), 3);
		assert_eq!(calculate_precision(0.01, 4), 2);
		assert_eq!(calculate_precision(0.1, 4), 1);
		assert_eq!(calculate_precision(0.0, 4), 0);
	}

	#[test]
	fn run_statfs() {
		statfs("/").unwrap();
	}

}