Class: MoreCoreExtensions::StringHexDump::HexDumper

Inherits:
Object
  • Object
show all
Defined in:
lib/more_core_extensions/core_ext/string/hex_dump.rb

Overview

This class is a private implementation and not part of the public API.

Constant Summary collapse

DEFAULT_OPTIONS =
{
  :grouping  => 16,
  :newline   => true,
  :start_pos => 0
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target, options) ⇒ HexDumper

Returns a new instance of HexDumper.



26
27
28
29
30
31
32
33
# File 'lib/more_core_extensions/core_ext/string/hex_dump.rb', line 26

def initialize(target, options)
  @target  = target
  @options = DEFAULT_OPTIONS.merge(options)

  if !!options[:obj] ^ !!options[:meth] # rubocop:disable Style/DoubleNegation
    raise ArgumentError, "obj and meth must both be set, or both not set"
  end
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



18
19
20
# File 'lib/more_core_extensions/core_ext/string/hex_dump.rb', line 18

def options
  @options
end

#targetObject (readonly)

Returns the value of attribute target.



18
19
20
# File 'lib/more_core_extensions/core_ext/string/hex_dump.rb', line 18

def target
  @target
end

Instance Method Details

#dumpObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/more_core_extensions/core_ext/string/hex_dump.rb', line 35

def dump
  obj, meth, grouping, pos = options.values_at(:obj, :meth, :grouping, :start_pos)

  ret = ""

  target.each_byte.each_slice(grouping) do |bytes|
    row = format_row(pos, bytes)
    ret << row

    if obj
      obj.send(meth, row)
      ret = ""
    end

    pos += grouping
  end

  ret
end

#format_row(pos, bytes) ⇒ Object



55
56
57
58
59
60
# File 'lib/more_core_extensions/core_ext/string/hex_dump.rb', line 55

def format_row(pos, bytes)
  padding    = "   " * (options[:grouping] - bytes.size)
  byte_chars = bytes.collect { |byte| row_char(byte) }.join
  newline    = "\n" if options[:newline]
  "0x%08x  #{"%02x " * bytes.size}#{padding} " % [pos, *bytes] << "#{byte_chars}#{newline}"
end

#row_char(byte) ⇒ Object



62
63
64
# File 'lib/more_core_extensions/core_ext/string/hex_dump.rb', line 62

def row_char(byte)
  byte < 0x20 || (byte >= 0x7F && byte < 0xA0) ? '.' : byte.chr
end