Skip to content

Commit ca3d4a3

Browse files
Fix underscore and dash counter in Enum.parse? (#16192)
The algorithm already skips `_` and `-`, but they were counted in the overall string length and thus would trigger the early return condition.
1 parent 6d5ea54 commit ca3d4a3

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

spec/std/enum_spec.cr

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,8 @@ describe Enum do
316316
SpecEnum.parse("TWO").should eq(SpecEnum::Two)
317317
SpecEnum.parse("TwO").should eq(SpecEnum::Two)
318318
SpecEnum2.parse("FORTY_TWO").should eq(SpecEnum2::FortyTwo)
319+
SpecEnum2.parse("FORTY___TWO").should eq(SpecEnum2::FortyTwo)
320+
SpecEnum2.parse("FORTY___TWO_").should eq(SpecEnum2::FortyTwo)
319321

320322
SpecEnum2.parse("FORTY_FOUR").should eq(SpecEnum2::FORTY_FOUR)
321323
SpecEnum2.parse("forty_four").should eq(SpecEnum2::FORTY_FOUR)

src/enum.cr

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -520,9 +520,11 @@ abstract struct Enum
520520
{% max_size = @type.constants.map(&.size).sort.last %}
521521
buffer = uninitialized UInt8[{{ max_size * 4 + 1 }}]
522522
appender = buffer.to_unsafe.appender
523-
string.each_char_with_index do |char, index|
524-
return nil if index > {{max_size}}
523+
char_counter = 0
524+
string.each_char do |char|
525525
next if char == '-' || char == '_'
526+
char_counter += 1
527+
return nil if char_counter > {{max_size}}
526528
char.downcase &.each_byte do |byte|
527529
appender << byte
528530
end

0 commit comments

Comments
 (0)