left_pad/lib.rs
1/*!
2This crate provides left-padding for strings (including both `&str` and `String`).
3
4Import with `extern crate left_pad;`.
5
6Usage example:
7
8```
9use left_pad::{leftpad, leftpad_with};
10
11assert_eq!(leftpad("blubb", 7), " blubb");
12assert_eq!(leftpad_with("blubb", 7, '.'), "..blubb");
13
14let s: String = "blubb".to_owned();
15assert_eq!(leftpad(s, 7), " blubb");
16```
17*/
18
19#![deny(missing_docs)]
20
21use std::borrow::Cow;
22use std::borrow::Borrow;
23
24/// Pads a string to the given length `len` by inserting the character `pad_char` from the left.
25///
26/// If the given string has a length longer or equal to the desired length, it will be
27/// returned as-is.
28///
29/// # Examples
30///
31/// ```
32/// use left_pad::leftpad_with;
33///
34/// assert_eq!(leftpad_with("blubb", 7, ' '), " blubb");
35/// assert_eq!(leftpad_with("blubb", 7, '.'), "..blubb");
36///
37/// assert_eq!(leftpad_with("blubb", 5, ' '), "blubb");
38/// assert_eq!(leftpad_with("blubb", 3, ' '), "blubb");
39/// ```
40pub fn leftpad_with<'a, S>(string: S, len: usize, pad_char: char) -> Cow<'a, str>
41 where S: Into<Cow<'a, str>>
42{
43 let cow = string.into();
44
45 if !(len > cow.len()) {
46 return cow;
47 }
48
49 let to_pad = len - cow.len();
50 let mut padded = String::with_capacity(cow.len() + to_pad);
51
52 for _ in 0..to_pad {
53 padded.push(pad_char);
54 }
55
56 padded.push_str(cow.borrow());
57
58 padded.into()
59}
60
61/// Pads a string to the given length `len` by inserting whitespaces from the left.
62///
63/// If the given string has a length longer or equal to the desired length, it will be
64/// returned as-is.
65///
66/// This function is equal to calling `leftpad_with(string, len, ' ')`.
67///
68/// # Examples
69///
70/// ```
71/// use left_pad::leftpad;
72///
73/// assert_eq!(leftpad("blubb", 7), " blubb");
74///
75/// assert_eq!(leftpad("blubb", 5), "blubb");
76/// assert_eq!(leftpad("blubb", 3), "blubb");
77///
78/// use left_pad::leftpad_with;
79///
80/// assert_eq!(leftpad("blubb", 7), leftpad_with("blubb", 7, ' '));
81/// ```
82pub fn leftpad<'a, S>(string: S, len: usize) -> Cow<'a, str>
83 where S: Into<Cow<'a, str>>
84{
85 leftpad_with(string, len, ' ')
86}