kwik 1.19.2

A set of useful tools I use for my Ph.D. research.
Documentation
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/*
 * Copyright (c) Kia Shakiba
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

use std::{
	cmp::Ordering,
	fmt::Debug,
	io::{self, StdoutLock, Write},
	time::{Duration, Instant},
};

use num_traits::AsPrimitive;

use crate::{fmt, math};

const DEFAULT_WIDTH: u64 = 70;

const DEFAULT_FILLED_CHARACTER: char = '=';
const DEFAULT_CURRENT_CHARACTER: char = '>';
const DEFAULT_REMAINING_CHARACTER: char = ' ';

const PULSE_INTERVAL: Duration = Duration::from_secs(1);

/// Displays a progress bar in terminal
pub struct Progress {
	width: u64,

	filled_character:    char,
	current_character:   char,
	remaining_character: char,

	total:   u64,
	current: u64,

	stopped: bool,

	tags: Vec<Tag>,

	rate_count:    u64,
	previous_rate: u64,

	instants:      [Option<Instant>; 101],
	pulse_instant: Instant,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Tag {
	/// Ticks per second
	Tps,

	/// Estimated remaining time
	Eta,

	/// Elapsed time
	Time,
}

impl Progress {
	/// Initializes and prints a new progress bar
	///
	/// # Examples
	/// ```
	/// use kwik::progress::Progress;
	///
	/// let progress = Progress::new(100);
	/// ```
	///
	/// # Panics
	///
	/// Panics if the total is zero.
	#[must_use]
	pub fn new(total: impl AsPrimitive<u64>) -> Self {
		let total = total.as_();

		assert_ne!(total, 0, "Total cannot be zero.");

		let now = Instant::now();
		let mut instants = [None; 101];

		instants[0] = Some(now);

		let progress = Progress {
			width: DEFAULT_WIDTH,

			filled_character: DEFAULT_FILLED_CHARACTER,
			current_character: DEFAULT_CURRENT_CHARACTER,
			remaining_character: DEFAULT_REMAINING_CHARACTER,

			total,
			current: 0,

			stopped: false,

			tags: Vec::new(),

			rate_count: 0,
			previous_rate: 0,

			instants,
			pulse_instant: now,
		};

		progress.draw(0, 0, None, Duration::ZERO);

		progress
	}

	/// Sets the progress bar's width. The default is 70.
	///
	/// # Panics
	///
	/// Panics if the width is zero.
	#[inline]
	pub fn set_width(&mut self, width: impl AsPrimitive<u64>) {
		let width = width.as_();

		assert_ne!(width, 0, "Width cannot be zero.");
		self.width = width;
	}

	/// Sets the progress bar's width. The default is 70.
	///
	/// # Panics
	///
	/// Panics if the width is zero.
	#[inline]
	#[must_use]
	pub fn with_width(mut self, width: impl AsPrimitive<u64>) -> Self {
		self.set_width(width);
		self
	}

	/// Sets the progress bar's filled character. The default is '='.
	#[inline]
	pub fn set_filled_character(&mut self, filled_character: char) {
		self.filled_character = filled_character;
	}

	/// Sets the progress bar's filled character. The default is '='.
	#[inline]
	#[must_use]
	pub fn with_filled_character(mut self, filled_character: char) -> Self {
		self.set_filled_character(filled_character);
		self
	}

	/// Sets the progress bar's current character. The default is '>'.
	#[inline]
	pub fn set_current_character(&mut self, current_character: char) {
		self.current_character = current_character;
	}

	/// Sets the progress bar's current character. The default is '>'.
	#[inline]
	#[must_use]
	pub fn with_current_character(mut self, current_character: char) -> Self {
		self.set_current_character(current_character);
		self
	}

	/// Sets the progress bar's remaining character. The default is ' '.
	#[inline]
	pub fn set_remaining_character(&mut self, remaining_character: char) {
		self.remaining_character = remaining_character;
	}

	/// Sets the progress bar's remaining character. The default is ' '.
	#[inline]
	#[must_use]
	pub fn with_remaining_character(mut self, remaining_character: char) -> Self {
		self.set_remaining_character(remaining_character);
		self
	}

	/// Adds the supplied tag to the enabled tags.
	///
	/// # Examples
	/// ```
	/// use kwik::progress::{Progress, Tag};
	///
	/// let mut progress = Progress::new(100);
	///
	/// progress.set_tag(Tag::Tps);
	/// progress.set_tag(Tag::Eta);
	/// progress.set_tag(Tag::Time);
	/// ```
	///
	/// # Panics
	///
	/// Panics if the tag is already enabled.
	#[inline]
	pub fn set_tag(&mut self, tag: Tag) {
		assert!(
			!self.tags.contains(&tag),
			"Progress tag {tag:?} is already enabled.",
		);

		self.tags.push(tag);
	}

	/// Adds the supplied tag to the enabled tags.
	///
	/// # Examples
	/// ```
	/// use kwik::progress::{Progress, Tag};
	///
	/// let progress = Progress::new(100)
	///     .with_tag(Tag::Tps)
	///     .with_tag(Tag::Eta)
	///     .with_tag(Tag::Time);
	/// ```
	///
	/// # Panics
	///
	/// Panics if the tag is already enabled.
	#[inline]
	#[must_use]
	pub fn with_tag(mut self, tag: Tag) -> Self {
		self.set_tag(tag);
		self
	}

	/// Checks if the progress is complete.
	#[inline]
	#[must_use]
	pub fn is_complete(&self) -> bool {
		self.current == self.total
	}

	/// Ticks the progress bar by the supplied amount.
	///
	/// # Panics
	///
	/// Panics if the tick amount is greater than the total.
	#[inline]
	pub fn tick(&mut self, value: impl AsPrimitive<u64>) {
		self.set(self.current + value.as_());
	}

	fn set(&mut self, value: u64) {
		assert!(!self.stopped, "Progress bar has been stopped.");

		assert!(
			value <= self.total,
			"Progress value ({value}) larger than total ({}).",
			self.total,
		);

		let previous = self.current;
		self.current = value;

		let amount = self.get_progress_amount(self.current) as u8;
		let previous_amount = self.get_progress_amount(previous) as u8;

		let now = Instant::now();

		let pulse_duration = self.pulse(&now);
		let rate = self.get_rate(pulse_duration);

		if amount == previous_amount && amount != 100 && pulse_duration.is_none() {
			return;
		}

		for index in (previous_amount + 1)..=amount {
			self.instants[index as usize] = Some(now);
		}

		self.draw(
			amount,
			rate,
			self.get_eta(&now),
			now - self.instants[0].unwrap(),
		);

		self.stopped = amount == 100;
	}

	/// Stops the progress bar and moves the cursor to a new line.
	///
	/// # Examples
	/// ```
	/// use kwik::progress::{Progress, Tag};
	///
	/// let mut progress = Progress::new(100);
	///
	/// progress.tick(50);
	/// progress.stop(); // the progress bar will stop at 50%
	/// ```
	#[inline]
	pub fn stop(&mut self) {
		if self.stopped {
			return;
		}

		self.stopped = true;

		let now = Instant::now();
		let amount = self.get_progress_amount(self.current) as u8;

		self.draw_final(amount, now - self.instants[0].unwrap());
	}

	#[must_use]
	fn pulse(&mut self, now: &Instant) -> Option<Duration> {
		let duration = now.duration_since(self.pulse_instant);

		if duration >= PULSE_INTERVAL {
			self.pulse_instant = *now;
			return Some(duration);
		}

		None
	}

	#[must_use]
	fn get_progress_amount(&self, current: u64) -> f64 {
		100.0 * current as f64 / self.total as f64
	}

	#[must_use]
	fn get_progress_position(&self, amount: u8) -> u64 {
		(self.width as f64 * amount as f64 / 100.0) as u64
	}

	#[must_use]
	fn get_rate(&mut self, pulse_duration: Option<Duration>) -> u64 {
		self.rate_count += 1;

		if let Some(pulse_duration) = pulse_duration {
			let ms = pulse_duration.as_millis() as f64;
			let rate = self.rate_count as f64 / (ms / 1000.0);

			self.previous_rate = rate as u64;
			self.rate_count = 0;

			return rate.round() as u64;
		}

		self.previous_rate
	}

	#[must_use]
	fn get_eta(&self, now: &Instant) -> Option<Duration> {
		let amount = self.get_progress_amount(self.current);
		let elapsed = now.duration_since(self.instants[0].unwrap());

		if amount as u8 == 100 || elapsed.is_zero() {
			return None;
		}

		let x = amount * 2.0 - 100.0;
		let x1 = *math::min(&[x, 98.0]).unwrap() as i64;

		if x1 <= 0 || self.instants[x1 as usize].is_none() {
			let rate = self.current as f64 / elapsed.as_millis() as f64;

			if rate == 0.0 {
				return None;
			}

			let duration_ms = ((self.total - self.current) as f64 / rate) as u64;
			let duration = Duration::from_millis(duration_ms);

			return Some(duration);
		}

		let x2 = x1 as usize + 1;

		let y1 = self.instants[x1 as usize].unwrap();
		let y2 = self.instants[x2].unwrap();

		let m = y2 - y1;
		let b = y1 - m * x1 as u32;

		Some(*now - (b + Duration::from_millis((m.as_millis() as f64 * x) as u64)))
	}

	fn draw(&self, amount: u8, rate: u64, eta: Option<Duration>, elapsed: Duration) {
		if amount == 100 {
			return self.draw_final(amount, elapsed);
		}

		let mut lock = io::stdout().lock();
		let position = self.get_progress_position(amount);

		write!(lock, "\x1B[2K\r[").unwrap();

		for i in 0..self.width {
			let character = match i.cmp(&position) {
				Ordering::Less => self.filled_character,
				Ordering::Greater => self.remaining_character,
				Ordering::Equal => self.current_character,
			};

			write!(lock, "\x1B[33m{character}\x1B[0m").unwrap();
		}

		write!(lock, "] \x1B[33m{amount} %\x1B[0m").unwrap();

		for tag in &self.tags {
			match tag {
				Tag::Tps => {
					if rate > 0 {
						print_rate(&mut lock, rate);
					}
				},

				Tag::Eta => {
					if eta.is_some_and(|eta| !eta.is_zero()) {
						print_eta(&mut lock, eta.unwrap());
					}
				},

				Tag::Time => {
					if !elapsed.is_zero() {
						print_time(&mut lock, elapsed);
					}
				},
			}
		}

		write!(lock, "\r").unwrap();
		lock.flush().unwrap();
	}

	fn draw_final(&self, amount: u8, elapsed: Duration) {
		let mut lock = io::stdout().lock();
		let position = self.get_progress_position(amount);

		write!(lock, "\x1B[2K[").unwrap();

		for i in 0..self.width {
			let character = match i.cmp(&position) {
				Ordering::Less => self.filled_character,
				Ordering::Greater => self.remaining_character,
				Ordering::Equal => self.current_character,
			};

			if amount < 100 {
				write!(lock, "\x1B[31m{character}\x1B[0m").unwrap();
			} else {
				write!(lock, "\x1B[32m{character}\x1B[0m").unwrap();
			}
		}

		if amount < 100 {
			write!(lock, "] \x1B[31m{amount} %\x1B[0m").unwrap();
		} else {
			write!(lock, "] \x1B[32m{amount} %\x1B[0m").unwrap();
		}

		if self.tags.contains(&Tag::Time) {
			print_time(&mut lock, elapsed);
		}

		writeln!(lock).unwrap();
		lock.flush().unwrap();
	}
}

fn print_rate(lock: &mut StdoutLock, rate: u64) {
	write!(lock, " ({} tps)", fmt::number(rate),).unwrap();
}

fn print_eta(lock: &mut StdoutLock, eta: Duration) {
	write!(lock, " (eta {})", fmt::timespan(eta.as_millis()),).unwrap();
}

fn print_time(lock: &mut StdoutLock, elapsed: Duration) {
	write!(lock, " (time {})", fmt::timespan(elapsed.as_millis()),).unwrap();
}