larust_support/strings.rs
1//! PHP string helpers with no direct Rust standard-library equivalent -
2//! `str::trim`/`str::len` already cover PHP's `trim()`/`count()` on a
3//! string, so those translate directly at convert time
4//! (`larust_convert::blade::expr`) without needing anything here. This
5//! module exists for the ones that genuinely don't have a stdlib match.
6
7/// PHP's `ucwords()` (single-argument form): capitalizes the first letter
8/// of each whitespace-separated word, leaving the rest of each word's
9/// casing untouched - unlike `str::to_uppercase()`, which capitalizes the
10/// *whole* string. PHP's own two-argument form additionally treats a
11/// caller-supplied set of other characters (not just whitespace) as word
12/// boundaries; not implemented here, since nothing in this framework's
13/// conversion tooling generates a call with a second argument.
14pub fn ucwords(s: &str) -> String {
15 let mut result = String::with_capacity(s.len());
16 let mut capitalize_next = true;
17 for ch in s.chars() {
18 if capitalize_next && ch.is_alphabetic() {
19 result.extend(ch.to_uppercase());
20 capitalize_next = false;
21 } else {
22 result.push(ch);
23 capitalize_next = ch.is_whitespace();
24 }
25 }
26 result
27}
28
29#[cfg(test)]
30mod tests {
31 use super::*;
32
33 #[test]
34 fn capitalizes_the_first_letter_of_each_word() {
35 assert_eq!(ucwords("hello world"), "Hello World");
36 }
37
38 #[test]
39 fn leaves_the_rest_of_each_words_casing_untouched() {
40 assert_eq!(ucwords("hELLo wORLD"), "HELLo WORLD");
41 }
42
43 #[test]
44 fn handles_multiple_spaces_and_leading_whitespace() {
45 assert_eq!(ucwords(" hello world"), " Hello World");
46 }
47
48 #[test]
49 fn handles_an_empty_string() {
50 assert_eq!(ucwords(""), "");
51 }
52
53 #[test]
54 fn handles_a_single_word() {
55 assert_eq!(ucwords("rust"), "Rust");
56 }
57}