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/no_string_ext.rb

Constant Summary collapse

INDEX =
Marshal.load(Gem.gunzip(File.binread(INDEX_FILENAME)))
VERSION =
'1.0.5'
UNICODE_VERSION =
"8.0.0".freeze
DATA_DIRECTORY =
File.expand_path(File.dirname(__FILE__) + '/../../../data/').freeze
INDEX_FILENAME =
(DATA_DIRECTORY + '/display_width.marshal.gz').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
# 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|
    index_or_value = INDEX
    codepoint_depth_offset = codepoint
    [0x10000, 0x1000, 0x100, 0x10].each{ |depth|
      index_or_value         = index_or_value[codepoint_depth_offset / depth]
      codepoint_depth_offset = codepoint_depth_offset % depth
      break unless index_or_value.is_a? Array
    }
    width = index_or_value.is_a?(Array) ? index_or_value[codepoint_depth_offset] : index_or_value
    width = ambiguous if width == :A
    total_width + (overwrite[codepoint] || width || 1)
  }

  res < 0 ? 0 : res
end