|
1 | 1 | //! Missing batteries for standard libraries.
|
| 2 | +use std::iter; |
2 | 3 | use std::{cmp::Ordering, ops, time::Instant};
|
3 | 4 |
|
4 | 5 | mod macros;
|
@@ -37,22 +38,44 @@ pub fn to_lower_snake_case(s: &str) -> String {
|
37 | 38 | pub fn to_upper_snake_case(s: &str) -> String {
|
38 | 39 | to_snake_case(s, char::to_ascii_uppercase)
|
39 | 40 | }
|
40 |
| -fn to_snake_case<F: Fn(&char) -> char>(s: &str, change_case: F) -> String { |
41 |
| - let mut buf = String::with_capacity(s.len()); |
42 |
| - let mut prev = false; |
43 |
| - for c in s.chars() { |
44 |
| - // `&& prev` is required to not insert `_` before the first symbol. |
45 |
| - if c.is_ascii_uppercase() && prev { |
46 |
| - // This check is required to not translate `Weird_Case` into `weird__case`. |
47 |
| - if !buf.ends_with('_') { |
48 |
| - buf.push('_'); |
| 41 | + |
| 42 | +// Code partially taken from rust/compiler/rustc_lint/src/nonstandard_style.rs |
| 43 | +// commit: 9626f2b |
| 44 | +fn to_snake_case<F: Fn(&char) -> char>(mut s: &str, change_case: F) -> String { |
| 45 | + let mut words = vec![]; |
| 46 | + |
| 47 | + // Preserve leading underscores |
| 48 | + s = s.trim_start_matches(|c: char| { |
| 49 | + if c == '_' { |
| 50 | + words.push(String::new()); |
| 51 | + true |
| 52 | + } else { |
| 53 | + false |
| 54 | + } |
| 55 | + }); |
| 56 | + |
| 57 | + for s in s.split('_') { |
| 58 | + let mut last_upper = false; |
| 59 | + let mut buf = String::new(); |
| 60 | + |
| 61 | + if s.is_empty() { |
| 62 | + continue; |
| 63 | + } |
| 64 | + |
| 65 | + for ch in s.chars() { |
| 66 | + if !buf.is_empty() && buf != "'" && ch.is_uppercase() && !last_upper { |
| 67 | + words.push(buf); |
| 68 | + buf = String::new(); |
49 | 69 | }
|
| 70 | + |
| 71 | + last_upper = ch.is_uppercase(); |
| 72 | + buf.extend(iter::once(change_case(&ch))); |
50 | 73 | }
|
51 |
| - prev = true; |
52 | 74 |
|
53 |
| - buf.push(change_case(&c)); |
| 75 | + words.push(buf); |
54 | 76 | }
|
55 |
| - buf |
| 77 | + |
| 78 | + words.join("_") |
56 | 79 | }
|
57 | 80 |
|
58 | 81 | pub fn replace(buf: &mut String, from: char, to: &str) {
|
|
0 commit comments