Skip to content
This repository has been archived by the owner on Oct 6, 2024. It is now read-only.

Commit

Permalink
Merge pull request #23 from thedavidmeister/2020-04-26-camel
Browse files Browse the repository at this point in the history
support camel modifier for snake to camel case
  • Loading branch information
dtolnay authored Apr 26, 2020
2 parents 5feb376 + 643c817 commit 576ba98
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 2 deletions.
20 changes: 20 additions & 0 deletions impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,26 @@ fn paste_segments(span: Span, segments: &[Segment]) -> Result<TokenStream> {
prev = ch;
}
evaluated.push(acc.to_lowercase());
} else if ident == "camel" {
let mut acc = String::new();
let mut prev = '_';
for ch in last.chars() {
if ch != '_' {
if prev == '_' {
for chu in ch.to_uppercase() {
acc.push(chu);
}
} else if prev.is_uppercase() {
for chl in ch.to_lowercase() {
acc.push(chl);
}
} else {
acc.push(ch);
}
}
prev = ch;
}
evaluated.push(acc);
} else {
return Err(Error::new_spanned(span, "unsupported modifier"));
}
Expand Down
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,9 @@
//! example, `[<ld_ $reg:lower _expr>]` would paste to `ld_bc_expr` if invoked
//! with $reg=`Bc`.
//!
//! Use `$var:snake` to convert CamelCase input to snake\_case. These compose,
//! so for example `$var:snake:upper` would give you SCREAMING\_CASE.
//! Use `$var:snake` to convert CamelCase input to snake\_case.
//! Use `$var:camel` to convert snake\_case to CamelCase.
//! These compose, so for example `$var:snake:upper` would give you SCREAMING\_CASE.
//!
//! The precise Unicode conversions are as defined by [`str::to_lowercase`] and
//! [`str::to_uppercase`].
Expand Down
30 changes: 30 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,33 @@ fn test_env_to_snake() {
let _ = LIBPASTE;
}
}

mod test_to_camel {
macro_rules! m {
($id:ident) => {
paste::item! {
const DEFAULT_CAMEL: &str = stringify!([<$id:camel>]);
const LOWER_CAMEL: &str = stringify!([<$id:camel:lower>]);
const UPPER_CAMEL: &str = stringify!([<$id:camel:upper>]);
}
};
}

m!(this_is_but_a_test);

#[test]
fn test_to_snake() {
assert_eq!(DEFAULT_CAMEL, "ThisIsButATest");
assert_eq!(LOWER_CAMEL, "thisisbutatest");
assert_eq!(UPPER_CAMEL, "THISISBUTATEST");
}
}

#[test]
fn test_env_to_camel() {
paste::expr! {
const [<LIB env!("CARGO_PKG_NAME"):camel>]: &str = "libpaste";

let _ = LIBPaste;
}
}

0 comments on commit 576ba98

Please sign in to comment.