Skip to content
Snippets Groups Projects
Commit 5c0bf291 authored by Jason Volk's avatar Jason Volk
Browse files

add util for camel to snake case conversion


Signed-off-by: default avatarJason Volk <jason@zemos.net>
parent 91b49a77
No related branches found
No related tags found
1 merge request!530de-global services
use crate::Result; use crate::{utils::exchange, Result};
pub const EMPTY: &str = ""; pub const EMPTY: &str = "";
...@@ -26,6 +26,41 @@ macro_rules! is_format { ...@@ -26,6 +26,41 @@ macro_rules! is_format {
}; };
} }
#[inline]
#[must_use]
pub fn camel_to_snake_string(s: &str) -> String {
let est_len = s
.chars()
.fold(s.len(), |est, c| est.saturating_add(usize::from(c.is_ascii_uppercase())));
let mut ret = String::with_capacity(est_len);
camel_to_snake_case(&mut ret, s.as_bytes()).expect("string-to-string stream error");
ret
}
#[inline]
pub fn camel_to_snake_case<I, O>(output: &mut O, input: I) -> Result<()>
where
I: std::io::Read,
O: std::fmt::Write,
{
let mut state = false;
input
.bytes()
.take_while(Result::is_ok)
.map(Result::unwrap)
.map(char::from)
.try_for_each(|ch| {
let m = ch.is_ascii_uppercase();
let s = exchange(&mut state, !m);
if m && s {
output.write_char('_')?;
}
output.write_char(ch.to_ascii_lowercase())?;
Result::<()>::Ok(())
})
}
/// Find the common prefix from a collection of strings and return a slice /// Find the common prefix from a collection of strings and return a slice
/// ``` /// ```
/// use conduit_core::utils::string::common_prefix; /// use conduit_core::utils::string::common_prefix;
......
...@@ -134,3 +134,19 @@ async fn mutex_map_contend() { ...@@ -134,3 +134,19 @@ async fn mutex_map_contend() {
tokio::try_join!(join_b, join_a).expect("joined"); tokio::try_join!(join_b, join_a).expect("joined");
assert!(map.is_empty(), "Must be empty"); assert!(map.is_empty(), "Must be empty");
} }
#[test]
fn camel_to_snake_case_0() {
use utils::string::camel_to_snake_string;
let res = camel_to_snake_string("CamelToSnakeCase");
assert_eq!(res, "camel_to_snake_case");
}
#[test]
fn camel_to_snake_case_1() {
use utils::string::camel_to_snake_string;
let res = camel_to_snake_string("CAmelTOSnakeCase");
assert_eq!(res, "camel_tosnake_case");
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment