aoutils/lib.rs
1//! aoutils is a tiny library I created and published simply to learn how to publish and use my own crates
2//! As I learn Rust, I may add more useful functions and this may become an actual useful library.
3//! * Examples
4//! ```
5//! fn main() {
6//! let result = aoutils::ensure_newline("alpha");
7//! assert_eq!(result, "alpha\n");
8//!
9//! let result = aoutils::is_alphabetic("alpha");
10//! assert_eq!(result, true);
11//! }
12//! ```
13
14/// Returns a String that ends with a '\n' newline character
15///
16/// # Arguments
17///
18/// * `line` - the &str to ensure ends in a newline
19///
20/// # Examples
21///
22/// ```
23/// use aoutils;
24///
25/// let result = aoutils::ensure_newline("alpha");
26/// assert!(result.ends_with("\n"));
27/// ```
28pub fn ensure_newline(line: &str) -> String {
29 if let Some(c) = line.chars().last() {
30 if c != '\n' {
31 return String::from(format!("{}{}", line, '\n'));
32 }
33 }
34
35 return line.to_string();
36}
37
38/// True if the string is made up solely of alphabetic characters
39///
40/// # Arguments
41///
42/// * `s` - the &str to check
43///
44/// # Examples
45///
46/// ```
47/// use aoutils;
48/// let result = aoutils::is_alphabetic("alpha");
49/// assert_eq!(result, true);
50/// ```
51pub fn is_alphabetic(s : &str) -> bool {
52 for c in s.chars() {
53 if !c.is_alphabetic() {
54 return false
55 }
56 }
57
58 true
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 #[test]
66 fn ensure_newline_without_newline() {
67 let result = ensure_newline("test string");
68 assert!(result.ends_with("\n"));
69 }
70
71 #[test]
72 fn ensure_newline_with_newline() {
73 let test_string = "test_string\n";
74
75 let result = ensure_newline(test_string);
76 assert!(result.ends_with("\n"));
77 assert!(result.matches("\n").count() == 1);
78 }
79
80 #[test]
81 fn is_alphabetic_with_alphabetic() {
82 assert_eq!(is_alphabetic("alpha"), true);
83 }
84
85 #[test]
86 fn is_alphabetic_with_numeric() {
87 assert_eq!(is_alphabetic("alpha1"), false);
88 }
89
90 #[test]
91 fn is_alphabetic_with_special_char() {
92 assert_eq!(is_alphabetic("alpha!"), false);
93 }
94
95 #[test]
96 fn is_alphabetic_with_space() {
97 assert_eq!(is_alphabetic("alpha "), false);
98 }
99}