Module: Unicode::DisplayWidth

Defined in:
lib/unicode/display_width.rb,
lib/unicode/display_width/index.rb,
lib/unicode/display_width/constants.rb,
lib/unicode/display_width/index_builder.rb,
lib/unicode/display_width/no_string_ext.rb

Defined Under Namespace

Modules: IndexBuilder

Constant Summary collapse

INDEX =
Marshal.load(File.binread(INDEX_FILENAME))
VERSION =
'1.0.1'.freeze
DATA_DIRECTORY =
File.join(File.dirname(__FILE__), '../../../data/').freeze
INDEX_FILENAME =
(DATA_DIRECTORY + 'unicode-width.index').freeze
NO_STRING_EXT =
true

Class Method Summary collapse

Class Method Details

.of(string, ambiguous = 1, overwrite = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/unicode/display_width.rb', line 5

def self.of(string, ambiguous = 1, overwrite = {})
  require_relative 'display_width/index' unless defined? ::Unicode::DisplayWidth::INDEX

  res = string.unpack('U*').inject(0){ |total_width, codepoint|
    total_width + (
      overwrite[codepoint] || case width = INDEX[codepoint]
                              when Integer
                                width
                              when :F, :W
                                2
                              when :A
                                ambiguous
                              else # including :N, :Na, :H
                                1
                              end
    )
  }

  res < 0 ? 0 : res
end