From 17f1026c46e6e3797caf3c69737f66bd612c58e1 Mon Sep 17 00:00:00 2001 From: Igor Aleksanov Date: Sat, 3 Oct 2020 16:45:16 +0300 Subject: Improve string helpers functions --- crates/stdx/src/lib.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'crates/stdx/src/lib.rs') diff --git a/crates/stdx/src/lib.rs b/crates/stdx/src/lib.rs index 011935cad..522a9c1ab 100644 --- a/crates/stdx/src/lib.rs +++ b/crates/stdx/src/lib.rs @@ -32,8 +32,12 @@ pub fn to_lower_snake_case(s: &str) -> String { let mut buf = String::with_capacity(s.len()); let mut prev = false; for c in s.chars() { + // `&& prev` is required to not insert `_` before the first symbol. if c.is_ascii_uppercase() && prev { - buf.push('_') + // This check is required to not translate `Weird_Case` into `weird__case`. + if buf.chars().last() != Some('_') { + buf.push('_') + } } prev = true; -- cgit v1.2.3 From f2c91fc5a8c22b8ac80f100b2b666f2dc9baa67c Mon Sep 17 00:00:00 2001 From: Igor Aleksanov Date: Mon, 5 Oct 2020 19:34:23 +0300 Subject: Apply suggestions from code review Co-authored-by: Lukas Wirth --- crates/stdx/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'crates/stdx/src/lib.rs') diff --git a/crates/stdx/src/lib.rs b/crates/stdx/src/lib.rs index 522a9c1ab..b55de813e 100644 --- a/crates/stdx/src/lib.rs +++ b/crates/stdx/src/lib.rs @@ -35,7 +35,7 @@ pub fn to_lower_snake_case(s: &str) -> String { // `&& prev` is required to not insert `_` before the first symbol. if c.is_ascii_uppercase() && prev { // This check is required to not translate `Weird_Case` into `weird__case`. - if buf.chars().last() != Some('_') { + if !buf.ends_with('_') { buf.push('_') } } -- cgit v1.2.3 From 559cc970732d80e3ec624c20da4f8aac219d6b2e Mon Sep 17 00:00:00 2001 From: Igor Aleksanov Date: Thu, 8 Oct 2020 08:33:35 +0300 Subject: Add to_upper_snake_case function to stdx --- crates/stdx/src/lib.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'crates/stdx/src/lib.rs') diff --git a/crates/stdx/src/lib.rs b/crates/stdx/src/lib.rs index b55de813e..59d89f47d 100644 --- a/crates/stdx/src/lib.rs +++ b/crates/stdx/src/lib.rs @@ -28,7 +28,7 @@ pub fn timeit(label: &'static str) -> impl Drop { Guard { label, start: Instant::now() } } -pub fn to_lower_snake_case(s: &str) -> String { +fn to_snake_case char>(s: &str, change_case: F) -> String { let mut buf = String::with_capacity(s.len()); let mut prev = false; for c in s.chars() { @@ -41,11 +41,19 @@ pub fn to_lower_snake_case(s: &str) -> String { } prev = true; - buf.push(c.to_ascii_lowercase()); + buf.push(change_case(&c)); } buf } +pub fn to_lower_snake_case(s: &str) -> String { + to_snake_case(s, char::to_ascii_lowercase) +} + +pub fn to_upper_snake_case(s: &str) -> String { + to_snake_case(s, char::to_ascii_uppercase) +} + pub fn replace(buf: &mut String, from: char, to: &str) { if !buf.contains(from) { return; -- cgit v1.2.3