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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*!
# Dactyl: "Nice" Elapsed

Note: this module is "in development". It is subject to change, and may eventually be spun off into its own crate.
*/

use crate::macros;
use std::{
	fmt,
	hash::{
		Hash,
		Hasher,
	},
	ops::Deref,
	time::Duration,
};



/// # Helper: Generate Impl
macro_rules! elapsed_from {
	($($type:ty),+) => ($(
		impl From<$type> for NiceElapsed {
			fn from(num: $type) -> Self {
				// Nothing!
				if 0 == num { Self::min() }
				// Hours, and maybe minutes and/or seconds.
				else if num < 86400 {
					Self::from(Self::hms(num as u32))
				}
				// We're into days, which we don't do.
				else { Self::max() }
			}
		}
	)+);
}



#[derive(Clone, Copy)]
/// This is a very simple struct for efficiently converting a given number of
/// seconds (`u32`) into a nice, human-readable Oxford-joined byte string, like
/// `3 hours, 2 minutes, and 1 second`.
///
/// Note: days are unsupported, or more specifically, any value over `23:59:59`
/// (or `86400+` seconds) will return a fixed value of `>1 day`.
///
/// ## Examples
///
/// ```
/// use dactyl::NiceElapsed;
/// assert_eq!(
///     NiceElapsed::from(61_u32).as_str(),
///     "1 minute and 1 second"
/// );
/// ```
///
/// ## Note
///
/// This module is "in development". It is subject to change, and may eventually be spun off into its own crate.
pub struct NiceElapsed {
	inner: [u8; 36],
	len: usize,
}

macros::as_ref_borrow_cast!(
	NiceElapsed:
		as_bytes [u8],
		as_str str,
);

impl Default for NiceElapsed {
	#[inline]
	fn default() -> Self {
		Self {
			inner: [0; 36],
			len: 0,
		}
	}
}

impl Deref for NiceElapsed {
	type Target = [u8];
	#[inline]
	fn deref(&self) -> &Self::Target { self.as_bytes() }
}

impl fmt::Debug for NiceElapsed {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("NiceElapsed")
		 .field("inner", &self.inner.to_vec())
		 .field("len", &self.len)
		 .finish()
	}
}

macros::display_str!(as_str NiceElapsed);

impl Eq for NiceElapsed {}

macros::from_cast!(NiceElapsed: as_secs Duration);

impl From<[u8; 3]> for NiceElapsed {
	#[allow(clippy::cast_possible_truncation)] // The max is 3.
	#[allow(clippy::cast_sign_loss)] // The value is >= 0.
	/// # From HMS.
	///
	/// This is meant to be a slice of pre-parsed hours, minutes, and seconds.
	///
	/// ## Panics
	///
	/// This is not intended to be used directly, but if it is, values must be
	/// under 100 or it will panic.
	fn from(num: [u8; 3]) -> Self {
		let mut buf = [0_u8; 36];
		let count: u8 = num.iter().filter(|&x| x.ne(&0)).count() as u8;
		let (end, _) = num.iter()
			.zip(&[ElapsedKind::Hour, ElapsedKind::Minute, ElapsedKind::Second])
			.filter(|(&val, _)| val.ne(&0))
			.fold(
				(buf.as_mut_ptr(), false),
				|(mut dst, any), (&val, kind)| {
					dst = unsafe { write_u8_advance(dst, val) };
					dst = kind.write_label(dst, val == 1);

					(kind.write_joiner(dst, count, any), true)
				}
			);

		// Put it all together!
		Self {
			inner: buf,
			len: unsafe { end.offset_from(buf.as_ptr()) as usize },
		}
	}
}

impl From<u32> for NiceElapsed {
	fn from(num: u32) -> Self {
		// Nothing!
		if 0 == num { Self::min() }
		// Hours, and maybe minutes and/or seconds.
		else if num < 86400 {
			Self::from(Self::hms(num))
		}
		// We're into days, which we don't do.
		else { Self::max() }
	}
}

// These all work the same way.
elapsed_from!(usize, u64, u128);

impl Hash for NiceElapsed {
	#[inline]
	fn hash<H: Hasher>(&self, state: &mut H) {
		self.as_bytes().hash(state);
	}
}

impl PartialEq for NiceElapsed {
	#[inline]
	fn eq(&self, other: &Self) -> bool { self.as_bytes() == other.as_bytes() }
}

impl NiceElapsed {
	#[must_use]
	/// # Minimum Value
	///
	/// We can save some processing time by hard-coding the value for `0`,
	/// which comes out to `0 seconds`.
	pub const fn min() -> Self {
		Self {
			//       0   •    s    e   c    o    n    d    s
			inner: [48, 32, 115, 101, 99, 111, 110, 100, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
			len: 9,
		}
	}

	#[must_use]
	/// # Maximum Value
	///
	/// We can save some processing time by hard-coding the maximum value.
	/// Because `NiceElapsed` does not support days, this is equivalent to
	/// `86400`, which comes out to `>1 day`.
	pub const fn max() -> Self {
		Self {
			//       >   1   •    d   a    y
			inner: [62, 49, 32, 100, 97, 121, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
			len: 6,
		}
	}

	#[allow(clippy::cast_possible_truncation)] // Size is previously asserted.
	#[must_use]
	/// # Time Chunks.
	///
	/// This method splits seconds into hours, minutes, and seconds. Days are not
	/// supported; the maximum return value is `[23, 59, 59]`.
	///
	/// Given the limited range of digits involved, we're able to use some data
	/// rounding trickery to achieve conversion, bypassing the need for
	/// (relatively) expensive division and remainder calculations.
	///
	/// ## Example.
	///
	/// ```
	/// use dactyl::NiceElapsed;
	/// assert_eq!(NiceElapsed::hms(121), [0_u8, 2_u8, 1_u8]);
	/// ```
	pub const fn hms(mut num: u32) -> [u8; 3] {
		if num < 60 { [0, 0, num as u8] }
		else if num < 86399 {
			let mut buf = [0_u8; 3];

			// There are hours.
			if num >= 3600 {
				buf[0] = ((num * 0x91A3) >> 27) as u8;
				num -= buf[0] as u32 * 3600;
			}

			// There are minutes.
			if num >= 60 {
				buf[1] = ((num * 0x889) >> 17) as u8;
				buf[2] = (num - buf[1] as u32 * 60) as u8;
			}
			// There are seconds.
			else if num > 0 { buf[2] = num as u8; }

			buf
		}
		else { [23, 59, 59] }
	}

	#[must_use]
	#[inline]
	/// # As Bytes.
	///
	/// Return the nice value as a byte string.
	pub fn as_bytes(&self) -> &[u8] { &self.inner[0..self.len] }

	#[must_use]
	#[inline]
	/// # As Str.
	///
	/// Return the nice value as a string slice.
	pub fn as_str(&self) -> &str {
		unsafe { std::str::from_utf8_unchecked(self.as_bytes()) }
	}
}



#[derive(Debug, Copy, Clone)]
/// # Unit Helpers.
///
/// This abstracts some of the verbosity of formatting, allowing us to
/// instantiate [`NiceElapsed`] with an iterator.
enum ElapsedKind {
	Hour,
	Minute,
	Second,
}

impl ElapsedKind {
	/// # Label.
	///
	/// This is always plural, as singularity can be derived by reducing the
	/// length by one.
	const fn label(self) -> (usize, *const u8) {
		match self {
			Self::Hour => (6, b" hours".as_ptr()),
			Self::Minute => (8, b" minutes".as_ptr()),
			Self::Second => (8, b" seconds".as_ptr()),
		}
	}

	/// # Write Label.
	fn write_label(self, dst: *mut u8, singular: bool) -> *mut u8 {
		let (mut len, label) = self.label();
		if singular { len -= 1; }

		unsafe {
			std::ptr::copy_nonoverlapping(label, dst, len);
			dst.add(len)
		}
	}

	/// # Write Joiner.
	///
	/// This will add commas and/or ands as necessary.
	///
	/// The `any` bool is used to indicate whether or not a value has
	/// previously been printed. This affects the joiner of minutes, as it
	/// varies based on whether or not hours are involved.
	///
	/// Seconds and single-count values never write joiners.
	fn write_joiner(self, dst: *mut u8, count: u8, any: bool) -> *mut u8 {
		match (self, count, any) {
			(Self::Hour, 3, _) => {
				unsafe {
					std::ptr::copy_nonoverlapping(b", ".as_ptr(), dst, 2);
					dst.add(2)
				}
			},
			(Self::Hour, 2, _) | (Self::Minute, 2, false) => {
				unsafe {
					std::ptr::copy_nonoverlapping(b" and ".as_ptr(), dst, 5);
					dst.add(5)
				}
			},
			(Self::Minute, 3, _) => {
				unsafe {
					std::ptr::copy_nonoverlapping(b", and ".as_ptr(), dst, 6);
					dst.add(6)
				}
			},
			_ => { dst },
		}
	}
}



/// # Write u8.
///
/// This will quickly write a `u8` number as a UTF-8 byte slice to the provided
/// pointer.
///
/// ## Panics
///
/// This method is not intended to write the full `u8` spectrum; it will panic
/// if a value is greater than 99.
///
/// ## Safety
///
/// The pointer must have enough space for the value, i.e. 1-2 digits. This
/// isn't a problem in practice given the method calls are all private.
unsafe fn write_u8_advance(buf: *mut u8, num: u8) -> *mut u8 {
	assert!(num < 100);

	if num > 9 {
		std::ptr::copy_nonoverlapping(crate::DOUBLE.as_ptr().add(usize::from(num) << 1), buf, 2);
		buf.add(2)
	}
	else {
		std::ptr::copy_nonoverlapping(crate::DOUBLE.as_ptr().add((usize::from(num) << 1) + 1), buf, 1);
		buf.add(1)
	}
}



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

	#[test]
	fn t_from() {
		_from(0, "0 seconds");
		_from(1, "1 second");
		_from(50, "50 seconds");

		_from(60, "1 minute");
		_from(61, "1 minute and 1 second");
		_from(100, "1 minute and 40 seconds");
		_from(2101, "35 minutes and 1 second");
		_from(2121, "35 minutes and 21 seconds");

		_from(3600, "1 hour");
		_from(3601, "1 hour and 1 second");
		_from(3602, "1 hour and 2 seconds");
		_from(3660, "1 hour and 1 minute");
		_from(3661, "1 hour, 1 minute, and 1 second");
		_from(3662, "1 hour, 1 minute, and 2 seconds");
		_from(3720, "1 hour and 2 minutes");
		_from(3721, "1 hour, 2 minutes, and 1 second");
		_from(3723, "1 hour, 2 minutes, and 3 seconds");
		_from(36001, "10 hours and 1 second");
		_from(36015, "10 hours and 15 seconds");
		_from(36060, "10 hours and 1 minute");
		_from(37732, "10 hours, 28 minutes, and 52 seconds");
		_from(37740, "10 hours and 29 minutes");

		_from(428390, ">1 day");
	}

	fn _from(num: u32, expected: &str) {
		assert_eq!(
			&*NiceElapsed::from(num),
			expected.as_bytes(),
			"{} should be equivalent to {:?}",
			num,
			expected
		);
	}
}