aoutils/
lib.rs

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
//! aoutils is a tiny library I created and published simply to learn how to publish and use my own crates
//! As I learn Rust, I may add more useful functions and this may become an actual useful library.
//! * Examples
//! ``` 
//! fn main() {
//!     let result = aoutils::ensure_newline("alpha");
//!     assert_eq!(result, "alpha\n");
//! 
//!     let result = aoutils::is_alphabetic("alpha");
//!     assert_eq!(result, true);
//! }
//! ```

/// Returns a String that ends with a '\n' newline character
///
/// # Arguments
///
/// * `line` - the &str to ensure ends in a newline
///
/// # Examples
///
/// ```    
/// use aoutils;
///
/// let result = aoutils::ensure_newline("alpha");
/// assert!(result.ends_with("\n")); 
/// ```
pub fn ensure_newline(line: &str) -> String {
    if let Some(c) = line.chars().last() {
        if c != '\n' {
            return String::from(format!("{}{}", line, '\n'));
        }
    }

    return line.to_string();
}

/// True if the string is made up solely of alphabetic characters
///
/// # Arguments
///
/// * `s` - the &str to check
///
/// # Examples
///
/// ```    
/// use aoutils;
/// let result = aoutils::is_alphabetic("alpha");
/// assert_eq!(result, true);
/// ```
pub fn is_alphabetic(s : &str) -> bool {
    for c in s.chars() {
        if !c.is_alphabetic() {            
            return false
        }
    }

    true
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn ensure_newline_without_newline() {        
        let result = ensure_newline("test string");
        assert!(result.ends_with("\n"));
    }
    
    #[test]
    fn ensure_newline_with_newline() { 
        let test_string = "test_string\n";       
        
        let result = ensure_newline(test_string);
        assert!(result.ends_with("\n"));
        assert!(result.matches("\n").count() == 1);
    }

    #[test]
    fn is_alphabetic_with_alphabetic() {
        assert_eq!(is_alphabetic("alpha"), true);
    }

    #[test]
    fn is_alphabetic_with_numeric() {        
        assert_eq!(is_alphabetic("alpha1"), false);
    }

    #[test]
    fn is_alphabetic_with_special_char() {        
        assert_eq!(is_alphabetic("alpha!"), false);
    }

    #[test]
    fn is_alphabetic_with_space() {        
        assert_eq!(is_alphabetic("alpha "), false);
    }
}