Skip to content

Commit

Permalink
Further improve performance for ASCII-only strings
Browse files Browse the repository at this point in the history
  • Loading branch information
janlelis committed Jan 3, 2023
1 parent 26a939f commit 919c98b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# CHANGELOG

## Next (unreleased)

- Further improve performance for ASCII-only strings

## 2.4.0
- Improve performance for ASCII-only strings, by @fatkodima
- Require Ruby 2.4
Expand Down
11 changes: 8 additions & 3 deletions lib/unicode/display_width.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@ class DisplayWidth
ASCII_NON_ZERO_REGEX = /[\0\x05\a\b\n\v\f\r\x0E\x0F]/

def self.of(string, ambiguous = 1, overwrite = {}, options = {})
# Optimization for ASCII-only strings without control symbols.
if overwrite.empty? && string.ascii_only? && !string.match?(ASCII_NON_ZERO_REGEX)
return string.size
# Optimization for ASCII-only strings without certain control symbols
if overwrite.empty? && string.ascii_only?
if string.match?(ASCII_NON_ZERO_REGEX)
res = string.gsub(ASCII_NON_ZERO_REGEX, "").size - string.count("\b")
return res < 0 ? 0 : res
else
return string.size
end
end

# Add width of each char
Expand Down

0 comments on commit 919c98b

Please sign in to comment.