local_strtools/lib.rs
1//! # String tools
2//!
3//! `strtools` is a collection of string related utilities, not provided by standart
4//! library. Especially useful when your project deals with lot of manipulations
5//! around `String` or `&str`
6
7/// Pads a string with zeros, resulted string would be in length given in second argument
8///
9/// # Examples
10/// ```
11/// let str = String::from("9");
12/// let padded_string = strtools::pad(str, 3);
13///
14/// assert_eq!(padded_string, "009");
15/// ```
16/// # Panics
17/// When length of given string is bigger than the wanted to be length, program panics:
18/// ```
19/// #[should_panic]
20/// fn can_panic() {
21/// let str = String::from("98798");
22/// strtools::pad(str, 3);
23/// }
24/// ```
25///
26pub fn pad(str: String, l: usize) -> String {
27 let len = str.len();
28 if len > l {
29 panic!("Cannot pad string that is bigger than needed to be");
30 }
31
32 let padded = l - len;
33 let mut zeros: Vec<&str> = vec![];
34
35 for _ in 1..=padded {
36 zeros.push("0");
37 }
38
39 format!("{}{}", zeros.join(""), str)
40}