Skip to content

Commit

Permalink
builtin: fix `assert 'JVM_PUBLIC_ACC'.camel_to_snake() == 'jvm_public…
Browse files Browse the repository at this point in the history
…_acc'` (vlang#21722)
  • Loading branch information
ttytm authored and raw-bin committed Jul 2, 2024
1 parent ec83816 commit c108786
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
28 changes: 20 additions & 8 deletions vlib/builtin/string.v
Original file line number Diff line number Diff line change
Expand Up @@ -2647,34 +2647,46 @@ pub fn (s string) camel_to_snake() string {
if s.len == 0 {
return ''
}
lower_first_char := if s[0] >= `A` && s[0] <= `Z` { s[0] + 32 } else { s[0] }
if s.len == 1 {
return lower_first_char.ascii_str()
return s.to_lower()
}
mut b := unsafe { malloc_noscan(2 * s.len + 1) }
second_char := if s[1] >= `A` && s[1] <= `Z` { `_` } else { s[1] }
mut prev_is_upper := false
first_char, second_char := if s[0] >= `A` && s[0] <= `Z` {
lower_first_c := if s[0] >= `A` && s[0] <= `Z` { s[0] + 32 } else { s[0] }
lower_second_c := if s[1] >= `A` && s[1] <= `Z` {
prev_is_upper = true
s[1] + 32
} else {
s[1]
}
lower_first_c, lower_second_c
} else {
lower_first_c := s[0]
second_c := if s[1] >= `A` && s[1] <= `Z` { u8(`_`) } else { s[1] }
lower_first_c, second_c
}
unsafe {
b[0] = lower_first_char
b[0] = first_char
b[1] = second_char
}
mut pos := 2
mut prev_char := second_char
mut prev_is_upper := false
mut lower_c := `_`
mut c_is_upper := false
mut pos := 1
for i in pos .. s.len {
c := s[i]
c_is_upper = c >= `A` && c <= `Z`
lower_c = if c_is_upper { c + 32 } else { c }
if prev_is_upper == false && c_is_upper {
if !prev_is_upper && c_is_upper {
// aB => a_b, if prev has `_`, then do not add `_`
unsafe {
if b[pos - 1] != `_` {
b[pos] = `_`
pos++
}
}
} else if prev_is_upper && c_is_upper == false && c != `_` {
} else if prev_is_upper && !c_is_upper && c != `_` {
// Ba => _ba, if prev has `_`, then do not add `_`
unsafe {
if b[pos - 2] != `_` {
Expand Down
1 change: 1 addition & 0 deletions vlib/builtin/string_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -1528,6 +1528,7 @@ fn test_camel_to_snake() {
assert 'aaBbCcDD'.camel_to_snake() == 'aa_bb_cc_dd'
assert 'BBaa'.camel_to_snake() == 'b_baa'
assert 'aa_BB'.camel_to_snake() == 'aa_bb'
assert 'JVM_PUBLIC_ACC'.camel_to_snake() == 'jvm_public_acc'
}

fn test_snake_to_camel() {
Expand Down

0 comments on commit c108786

Please sign in to comment.