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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
#![no_std]
#![warn(clippy::indexing_slicing)]

//! This library provides several useful constructs to format data in a human-readable fashion with
//! zero allocations
//! 
//! Some of these functions may seem to partly reinvent existing std functionality, for example
//! [`join`]:
//! 
//! ```rust
//! println!("{}", display_utils::join(&[1, 2, 3], " + ")); // display_utils
//! println!("{}", ["1", "2", "3"].join(" + ")); // std
//! 
//! println!("{}", display_utils::repeat("abc", 4)); // display_utils
//! println!("{}", "abc".repeat(4)); // std
//! ```
//! 
//! The important difference is that the std approach involves 4 allocations, whereas the
//! display_utils approach operates 100% on stack and is therefore no_std compatible and likely 
//! faster.

/// Print a loading-style bar using Unicode block characters.
/// 
/// The bar is very high-resolution: 8 states can be represented per character.
/// 
/// Accepts the total length of the bar and a float from 0.0 to 1.0 as the filled proportion.
/// 
/// Prints exactly max_length chars (not bytes!), right-padded with spaces.
/// 
/// ```rust
/// # use display_utils::*;
/// assert_eq!(unicode_block_bar(13, 0.0).to_string(), "             ");
/// assert_eq!(unicode_block_bar(13, 0.1).to_string(), "█▎           ");
/// assert_eq!(unicode_block_bar(13, 0.2).to_string(), "██▌          ");
/// assert_eq!(unicode_block_bar(13, 0.3).to_string(), "███▉         ");
/// assert_eq!(unicode_block_bar(13, 0.4).to_string(), "█████▏       ");
/// assert_eq!(unicode_block_bar(13, 0.5).to_string(), "██████▌      ");
/// assert_eq!(unicode_block_bar(13, 0.6).to_string(), "███████▊     ");
/// assert_eq!(unicode_block_bar(13, 0.7).to_string(), "█████████    ");
/// assert_eq!(unicode_block_bar(13, 0.8).to_string(), "██████████▍  ");
/// assert_eq!(unicode_block_bar(13, 0.9).to_string(), "███████████▋ ");
/// assert_eq!(unicode_block_bar(13, 1.0).to_string(), "█████████████");
/// # assert_eq!(unicode_block_bar(4, 0.0).to_string(), "    ");
/// # assert_eq!(unicode_block_bar(4, 0.125).to_string(), "▌   ");
/// # assert_eq!(unicode_block_bar(4, 0.25).to_string(), "█   ");
/// # assert_eq!(unicode_block_bar(4, 1.0).to_string(), "████");
/// # assert_eq!(unicode_block_bar(4, 1.5).to_string(), "████");
/// # assert_eq!(unicode_block_bar(4, -1.0).to_string(), "    ");
/// # assert_eq!(unicode_block_bar(1, 1.0).to_string(), "█");
/// # assert_eq!(unicode_block_bar(0, 0.0).to_string(), "");
/// # assert_eq!(unicode_block_bar(0, 1.0).to_string(), "");
/// ```
pub fn unicode_block_bar(max_length: usize, proportion: f32) -> impl core::fmt::Display {
	// index x = x 8ths of a full block
	const BLOCK_CHARS: [&str; 9] = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"];

	struct UnicodeBlockBar {
		num_full_blocks: usize,
		/// may be empty!
		midpoint: &'static str,
		num_spaces: usize,
	}

	impl core::fmt::Display for UnicodeBlockBar {
		fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
			for _ in 0..self.num_full_blocks {
				f.write_str(&BLOCK_CHARS[8])?;
			}
			f.write_str(self.midpoint)?;
			for _ in 0..self.num_spaces {
				f.write_str(&BLOCK_CHARS[0])?;
			}
			Ok(())
		}
	}

	let max_steps = max_length * 8; // number of steps for the bar to be full

	let steps = proportion * max_steps as f32;
	let steps = (steps.max(0.0) as usize).min(max_steps);
	
	if steps == max_steps {
		UnicodeBlockBar  {
			num_full_blocks: max_length,
			midpoint: "",
			num_spaces: 0,
		}
	} else {
		#[allow(clippy::indexing_slicing)] // index will be in 0..8 always due to modulo
		UnicodeBlockBar {
			num_full_blocks: steps / 8,
			midpoint: &BLOCK_CHARS[steps % 8],
			num_spaces: max_length - (steps / 8 + 1),
		}
	}
}

/// Print a sequence of equalizer-style vertical bars using Unicode block characters.
/// 
/// The bars are very high-resolution: 8 states can be represented per character.
/// 
/// Accepts the total maximum height of the bars and an iterator over each bar's fill percentage.
/// 
/// ```rust
/// let expected_output = "\
/// █          
/// █▆         
/// ██▄        
/// ███▁       
/// ████       
/// ████▇      
/// █████▄     
/// ██████▂    
/// ███████    
/// ████████   
/// ████████▅  
/// █████████▃ 
/// ██████████ ";
/// 
/// assert_eq!(
///     display_utils::vertical_unicode_block_bars(
///         13,
///         [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0].iter().copied()
///     ).to_string(),
///     expected_output,
/// );
/// ```
pub fn vertical_unicode_block_bars<I>(max_height: usize, proportions: I) -> impl core::fmt::Display
where
	I: IntoIterator<Item = f32>,
	I::IntoIter: Clone,
{
	// index x = x 8ths of a full block
	const BLOCK_CHARS: [&str; 9] = [" ", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];

	struct VerticalUnicodeBlockBars<I> {
		max_height: usize,
		proportions: I,
	}

	impl<I: Iterator<Item = f32> + Clone> core::fmt::Display for VerticalUnicodeBlockBars<I> {
		fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
			let max_steps = self.max_height * 8;
			for row in 0..self.max_height {
				if row > 0 {
					f.write_str("\n")?;
				}

				for proportion in self.proportions.clone() {
					// steps are measured in terms of whitespace
					let steps = (1.0 - proportion) * max_steps as f32;
					let steps = (steps.max(0.0) as usize).min(max_steps);

					f.write_str(match row.cmp(&(steps / 8)) {
						core::cmp::Ordering::Less => &BLOCK_CHARS[0],
						#[allow(clippy::indexing_slicing)] // that index will always be in 0..=8
						core::cmp::Ordering::Equal => &BLOCK_CHARS[8 - steps % 8],
						core::cmp::Ordering::Greater => &BLOCK_CHARS[8],
					})?;
				}
			}
			Ok(())
		}
	}

	VerticalUnicodeBlockBars { max_height, proportions: proportions.into_iter() }
}

/// Concatenate iterator elements, separating each element pair with a given joiner.
/// 
/// Equivalent to [`slice::join`](https://doc.rust-lang.org/std/primitive.slice.html#method.join).
/// 
/// The iterator must be cloneable, because Display objects may be printed multiple times.
/// 
/// ```rust
/// # use display_utils::*;
/// let strings = &["hello", "wonderful", "world"];
/// 
/// let output = join(strings, ", ");
/// assert_eq!(output.to_string(), "hello, wonderful, world");
/// # assert_eq!(join(&[] as &[u8], ", ").to_string(), "");
/// # assert_eq!(join(&["hello"], ", ").to_string(), "hello");
/// ```
pub fn join<T, I, J>(iterator: I, joiner: J) -> impl core::fmt::Display
where
	T: core::fmt::Display,
	I: IntoIterator<Item = T>,
	I::IntoIter: Clone,
	J: core::fmt::Display,
{
	struct Join<I, J> {
		iterator: I,
		joiner: J,
	}

	impl<T, I, J> core::fmt::Display for Join<I, J>
	where
		T: core::fmt::Display,
		I: Iterator<Item = T> + Clone,
		J: core::fmt::Display,
	{
		fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
			let mut iter = self.iterator.clone();

			if let Some(first_item) = iter.next() {
				first_item.fmt(f)?;
			}
			for remaining_item in iter {
				self.joiner.fmt(f)?;
				remaining_item.fmt(f)?;
			}

			Ok(())
		}
	}
	
	Join { iterator: iterator.into_iter(), joiner }
}

/// Concatenate iterator elements, separating each element pair with a given joiner, where each
/// iterator element can be formatted using a callback.
/// 
/// The callback must be Fn and the iterator must be cloneable, because Display objects may be
/// printed multiple times.
/// 
/// ```rust
/// # use display_utils::*;
/// let strings = &["hello", "wonderful", "world"];
/// 
/// let output = join_format(
///     strings.iter().enumerate(),
///     |(i, string), f| write!(f, "{}={}", i, string),
///     ", ",
/// );
/// assert_eq!(output.to_string(), "0=hello, 1=wonderful, 2=world");
/// ```
pub fn join_format<I, C, J>(iterator: I, callback: C, joiner: J) -> impl core::fmt::Display
where
	I: IntoIterator,
	I::IntoIter: Clone,
	C: Fn(I::Item, &mut core::fmt::Formatter) -> core::fmt::Result,
	J: core::fmt::Display,
{
	struct Join<I, C, J> {
		iterator: I,
		callback: C,
		joiner: J,
	}

	impl<I, C, J> core::fmt::Display for Join<I, C, J>
	where
		I: Iterator + Clone,
		C: Fn(I::Item, &mut core::fmt::Formatter) -> core::fmt::Result,
		J: core::fmt::Display,
	{
		fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
			let mut iter = self.iterator.clone();

			if let Some(first_item) = iter.next() {
				(self.callback)(first_item, f)?;
			}
			for remaining_item in iter {
				self.joiner.fmt(f)?;
				(self.callback)(remaining_item, f)?;
			}

			Ok(())
		}
	}
	
	Join { iterator: iterator.into_iter(), callback, joiner }
}

/// Repeat an object a certain number of times.
/// 
/// Equivalent to `str::repeat`.
/// 
/// ```rust
/// # use display_utils::*;
/// assert_eq!(repeat("fun", 5).to_string(), "funfunfunfunfun");
/// assert_eq!(repeat(7, 7).to_string(), "7777777");
/// # assert_eq!(repeat("a", 0).to_string(), "");
/// # assert_eq!(repeat("", 5).to_string(), "");
/// ```
pub fn repeat<T: core::fmt::Display>(token: T, times: usize) -> impl core::fmt::Display {
	struct Repeat<T> {
		token: T,
		times: usize,
	}

	impl<T: core::fmt::Display> core::fmt::Display for Repeat<T> {
		fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
			for _ in 0..self.times {
				write!(f, "{}", self.token)?;
			}
			Ok(())
		}
	}

	Repeat { token, times }
}

/// Indent to a given depth using the tab character.
/// 
/// This is a shortcut for `repeat("\t", depth)`; please see that function if you wish to use a
/// different indent string.
/// 
/// ```rust
/// # use display_utils::*;
/// assert_eq!(indent(2).to_string(), "\t\t");
/// # assert_eq!(indent(0).to_string(), "");
/// # assert_eq!(indent(1).to_string(), "\t");
/// ```
pub fn indent_tab(depth: usize) -> impl core::fmt::Display {
	repeat("\t", depth)
}

/// Indent to a given depth using 4 spaces.
/// 
/// This is a shortcut for `repeat("    ", depth)`; please see that function if you wish to use a
/// different indent string.
/// 
/// ```rust
/// # use display_utils::*;
/// assert_eq!(indent(2).to_string(), "        ");
/// # assert_eq!(indent(0).to_string(), "");
/// # assert_eq!(indent(1).to_string(), "    ");
/// ```
pub fn indent_4(depth: usize) -> impl core::fmt::Display {
	repeat("    ", depth)
}

/// Print a Unicode-compliant lowercase version of the string.
/// 
/// Equivalent to `str::to_lowercase`.
/// 
/// ```rust
/// # use display_utils::*;
/// assert_eq!(lowercase("GRÜẞE JÜRGEN").to_string(), "grüße jürgen");
/// ```
pub fn lowercase(source: &str) -> impl core::fmt::Display + '_ {
	struct AsciiLowercase<'a> {
		source: &'a str,
	}

	impl<'a> core::fmt::Display for AsciiLowercase<'a> {
		fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
			use core::fmt::Write;
			for input_char in self.source.chars() {
				for output_char in input_char.to_lowercase() {
					f.write_char(output_char)?;
				}
			}
			Ok(())
		}
	}

	AsciiLowercase { source }
}

/// Print a Unicode-compliant uppercase version of the string.
/// 
/// Equivalent to `str::to_uppercase`.
/// 
/// ```rust
/// # use display_utils::*;
/// assert_eq!(uppercase("grüße jürgen").to_string(), "GRÜSSE JÜRGEN");
/// ```
pub fn uppercase(source: &str) -> impl core::fmt::Display + '_ {
	struct AsciiUppercase<'a> {
		source: &'a str,
	}

	impl<'a> core::fmt::Display for AsciiUppercase<'a> {
		fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
			use core::fmt::Write;
			for input_char in self.source.chars() {
				for output_char in input_char.to_uppercase() {
					f.write_char(output_char)?;
				}
			}
			Ok(())
		}
	}

	AsciiUppercase { source }
}

/// Replace instances of the `from` string with the `to` string.
/// 
/// Note: this function, contrary to its std equivalent
/// [`str::replace`](https://doc.rust-lang.org/std/primitive.str.html#method.replace),
/// does not support the Pattern API because that API is not yet stabilized.
/// 
/// ```rust
/// # use display_utils::*;
/// assert_eq!(replace("this is old", "old", "new").to_string(), "this is new");
/// # assert_eq!(replace("", "aaaaa", "xinbuldfgh").to_string(), "");
/// # assert_eq!(replace("old is this", "old", "new").to_string(), "new is this");
/// ```
// TODO: change `from` parameter type to Pattern, once that API is stabilized
pub fn replace<'a>(source: &'a str, from: &'a str, to: &'a str) -> impl core::fmt::Display + 'a {
	struct Replace<'a> {
		source: &'a str,
		from: &'a str,
		to: &'a str,
	}

	impl<'a> core::fmt::Display for Replace<'a> {
		fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
			let mut last_end = 0;
			for (start, part) in self.source.match_indices(self.from) {
				// UNWRAP: match_indices returns well-aligned indices
				f.write_str(self.source.get(last_end..start).unwrap())?;
				f.write_str(self.to)?;
				last_end = start + part.len();
			}
			// UNWRAP: last_end is well-aligned still
			f.write_str(self.source.get(last_end..).unwrap())?;
			Ok(())
		}
	}

	Replace { source, from, to }
}

/// Replace the first n instances of the `from` string with the `to` string.
/// 
/// Note: this function, contrary to its std equivalent
/// [`str::replacen`](https://doc.rust-lang.org/std/primitive.str.html#method.replacen),
/// does not support the Pattern API because that API is not yet stabilized.
/// 
/// ```rust
/// # use display_utils::*;
/// assert_eq!(replace_n("old old old", "old", "new", 2).to_string(), "new new old");
/// # assert_eq!(replace_n("", "aaaaa", "xinbuldfgh", 987).to_string(), "");
/// # assert_eq!(replace_n("old is this", "old", "new", 0).to_string(), "old is this");
/// ```
// TODO: change `from` parameter type to Pattern, once that API is stabilized
pub fn replace_n<'a>(
	source: &'a str,
	from: &'a str,
	to: &'a str,
	n: usize
) -> impl core::fmt::Display + 'a {
	struct ReplaceN<'a> {
		source: &'a str,
		from: &'a str,
		to: &'a str,
		n: usize,
	}

	impl<'a> core::fmt::Display for ReplaceN<'a> {
		fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
			let mut last_end = 0;
			for (start, part) in self.source.match_indices(self.from).take(self.n) {
				// UNWRAP: match_indices returns well-aligned indices
				f.write_str(self.source.get(last_end..start).unwrap())?;
				f.write_str(self.to)?;
				last_end = start + part.len();
			}
			// UNWRAP: last_end is well-aligned still
			f.write_str(self.source.get(last_end..).unwrap())?;
			Ok(())
		}
	}

	ReplaceN { source, from, to, n }
}

/// Concatenate the contents of an iterator.
/// 
/// If you want to insert a separator inbetween elements, use [`join`] or [`join_format`].
/// 
/// ```rust
/// # use display_utils::*;
/// let string = String::from("It's not much, but it's honest work");
/// assert_eq!(concat(&[
///     &string[11..13],
///     &string[25..27],
///     &string[34..35],
/// ]).to_string(), "chonk");
/// # assert_eq!(concat(&[1, 2, 3]).to_string(), "123");
/// # assert_eq!(concat(None::<u8>).to_string(), "");
/// ```
pub fn concat<I>(iterator: I) -> impl core::fmt::Display
where
	I: IntoIterator,
	I::Item: core::fmt::Display,
	I::IntoIter: Clone,
{
	struct Concat<I> {
		iterator: I,
	}

	impl<I> core::fmt::Display for Concat<I>
	where
		I: Iterator + Clone,
		I::Item: core::fmt::Display,
	{
		fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
			for item in self.iterator.clone() {
				write!(f, "{}", item)?;
			}
			Ok(())
		}
	}

	Concat { iterator: iterator.into_iter() }
}