Skip to content

Commit

Permalink
custom to_pascal_case
Browse files Browse the repository at this point in the history
  • Loading branch information
burrbull committed Feb 14, 2024
1 parent 735c5a2 commit 6c7f925
Showing 1 changed file with 48 additions and 27 deletions.
75 changes: 48 additions & 27 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,40 +24,52 @@ pub const BITS_PER_BYTE: u32 = 8;
/// that are not valid in Rust ident
const BLACKLIST_CHARS: &[char] = &['(', ')', '[', ']', '/', ' ', '-'];

fn to_pascal_case(s: &str) -> String {
if !s.contains('_') {
s.to_pascal_case()
} else {
let mut string = String::new();
let mut parts = s.split('_').peekable();
if let Some(&"") = parts.peek() {
string.push('_');
}
loop {
if let Some(p) = parts.next() {
if p.is_empty() {
continue;
}
string.push_str(&p.to_pascal_case());
match parts.peek() {
Some(nxt)
if p.ends_with(|s: char| s.is_numeric())
&& nxt.starts_with(|s: char| s.is_numeric()) =>
{
string.push('_');
}
Some(&"") => {
string.push('_');
}
_ => {}
}
} else {
break;
}
}
string
}
}

impl Case {
pub fn cow_to_case<'a>(&self, cow: Cow<'a, str>) -> Cow<'a, str> {
match self {
Self::Constant => match cow {
Cow::Borrowed(s) if s.is_constant_case() => cow,
_ => cow.to_constant_case().into(),
},
Self::Pascal => {
if let Some((first, _)) = cow
.char_indices()
.find(|(_, c)| c != &'_' && !c.is_ascii_digit())
{
if first != 0 {
let (prefix, s) = cow.split_at(first);
// Keep trailing "_"
if let Some(s) = s.strip_suffix('_') {
format!("{prefix}{}_", s.to_pascal_case()).into()
} else {
format!("{prefix}{}", s.to_pascal_case()).into()
}
} else {
if let Some(s) = cow.strip_suffix('_') {
format!("{}_", s.to_pascal_case()).into()
} else {
match cow {
Cow::Borrowed(s) if s.is_pascal_case() => cow,
_ => cow.to_pascal_case().into(),
}
}
}
} else {
cow
}
}
Self::Pascal => match cow {
Cow::Borrowed(s) if s.is_pascal_case() => cow,
_ => to_pascal_case(&cow).into(),
},
Self::Snake => match cow {
Cow::Borrowed(s) if s.is_snake_case() => cow,
_ => cow.to_snake_case().into(),
Expand Down Expand Up @@ -475,3 +487,12 @@ pub fn peripheral_names(d: &Device, feature_format: &IdentFormat) -> Vec<String>
v.sort();
v
}

#[test]
fn pascalcase() {
assert_eq!(to_pascal_case("_FOO_BAR_"), "_FooBar_");
assert_eq!(to_pascal_case("FOO_BAR1"), "FooBar1");
assert_eq!(to_pascal_case("FOO_BAR_1"), "FooBar1");
assert_eq!(to_pascal_case("FOO_BAR_1_2"), "FooBar1_2");
assert_eq!(to_pascal_case("FOO_BAR_1_2_"), "FooBar1_2_");
}

0 comments on commit 6c7f925

Please sign in to comment.