]> git.proxmox.com Git - rustc.git/blob - vendor/heck/src/snake.rs
New upstream version 1.51.0+dfsg1
[rustc.git] / vendor / heck / src / snake.rs
1 use crate::{lowercase, transform};
2
3 /// This trait defines a snake case conversion.
4 ///
5 /// In snake_case, word boundaries are indicated by underscores.
6 ///
7 /// ## Example:
8 ///
9 /// ```rust
10 /// use heck::SnakeCase;
11 ///
12 /// let sentence = "We carry a new world here, in our hearts.";
13 /// assert_eq!(sentence.to_snake_case(), "we_carry_a_new_world_here_in_our_hearts");
14 /// ```
15 pub trait SnakeCase: ToOwned {
16 /// Convert this type to snake case.
17 fn to_snake_case(&self) -> Self::Owned;
18 }
19
20 /// Oh heck, SnekCase is an alias for SnakeCase. See SnakeCase for
21 /// more documentation.
22 pub trait SnekCase: ToOwned {
23 /// Convert this type to snek case.
24 fn to_snek_case(&self) -> Self::Owned;
25 }
26
27 impl<T: ?Sized + SnakeCase> SnekCase for T {
28 fn to_snek_case(&self) -> Self::Owned {
29 self.to_snake_case()
30 }
31 }
32
33 impl SnakeCase for str {
34 fn to_snake_case(&self) -> String {
35 transform(self, lowercase, |s| s.push('_'))
36 }
37 }
38
39 #[cfg(test)]
40 mod tests {
41 use super::SnakeCase;
42
43 macro_rules! t {
44 ($t:ident : $s1:expr => $s2:expr) => {
45 #[test]
46 fn $t() {
47 assert_eq!($s1.to_snake_case(), $s2)
48 }
49 }
50 }
51
52 t!(test1: "CamelCase" => "camel_case");
53 t!(test2: "This is Human case." => "this_is_human_case");
54 t!(test3: "MixedUP CamelCase, with some Spaces" => "mixed_up_camel_case_with_some_spaces");
55 t!(test4: "mixed_up_ snake_case with some _spaces" => "mixed_up_snake_case_with_some_spaces");
56 t!(test5: "kebab-case" => "kebab_case");
57 t!(test6: "SHOUTY_SNAKE_CASE" => "shouty_snake_case");
58 t!(test7: "snake_case" => "snake_case");
59 t!(test8: "this-contains_ ALLKinds OfWord_Boundaries" => "this_contains_all_kinds_of_word_boundaries");
60 t!(test9: "XΣXΣ baffle" => "xσxς_baffle");
61 t!(test10: "XMLHttpRequest" => "xml_http_request");
62 t!(test11: "FIELD_NAME11" => "field_name11");
63 t!(test12: "99BOTTLES" => "99bottles");
64 t!(test13: "FieldNamE11" => "field_nam_e11");
65
66 t!(test14: "abc123def456" => "abc123def456");
67 t!(test16: "abc123DEF456" => "abc123_def456");
68 t!(test17: "abc123Def456" => "abc123_def456");
69 t!(test18: "abc123DEf456" => "abc123_d_ef456");
70 t!(test19: "ABC123def456" => "abc123def456");
71 t!(test20: "ABC123DEF456" => "abc123def456");
72 t!(test21: "ABC123Def456" => "abc123_def456");
73 t!(test22: "ABC123DEf456" => "abc123d_ef456");
74 t!(test23: "ABC123dEEf456FOO" => "abc123d_e_ef456_foo");
75 t!(test24: "abcDEF" => "abc_def");
76 t!(test25: "ABcDE" => "a_bc_de");
77 }