Class: BinaryCodec::Hash

Inherits:
ComparableSerializedType show all
Defined in:
lib/binary-codec/types/hash.rb

Direct Known Subclasses

Hash128, Hash160, Hash192, Hash256

Instance Attribute Summary

Attributes inherited from SerializedType

#bytes

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ComparableSerializedType

#eq, #gt, #gte, #lt, #lte

Methods inherited from SerializedType

from_bytes, from_hex, from_json, get_type_by_name, #to_byte_sink, #to_bytes, #to_hex, #to_json, #value_of

Constructor Details

#initialize(bytes = nil) ⇒ Hash

Returns a new instance of Hash.



11
12
13
14
15
16
17
# File 'lib/binary-codec/types/hash.rb', line 11

def initialize(bytes = nil)
  bytes = Array.new(self.class.width, 0) if bytes.nil? || bytes.empty?
  super(bytes)
  if @bytes.length != self.class.width
    raise StandardError, "Invalid Hash length #{@bytes.length}"
  end
end

Class Method Details

.from(value) ⇒ Hash

Creates a new Hash instance from a value.

Parameters:

  • value (Hash, String, Array<Integer>)

    The value to convert.

Returns:

  • (Hash)

    The created instance.

Raises:

  • (StandardError)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/binary-codec/types/hash.rb', line 22

def self.from(value)
  return value if value.is_a?(self)

  if value.is_a?(String)
    return new if value.empty?
    return new(hex_to_bytes(value))
  end

  if value.is_a?(Array)
    return new(value)
  end

  raise StandardError, "Cannot construct #{self} from the value given"
end

.from_parser(parser, hint = nil) ⇒ Hash

Creates a Hash instance from a parser.

Parameters:

  • parser (BinaryParser)

    The parser to read from.

  • hint (Integer, nil) (defaults to: nil)

    Optional width hint.

Returns:

  • (Hash)

    The created instance.



41
42
43
# File 'lib/binary-codec/types/hash.rb', line 41

def self.from_parser(parser, hint = nil)
  new(parser.read(hint || width))
end

.widthInteger

Returns the width of the Hash type in bytes.

Returns:

  • (Integer)

    The width.



7
8
9
# File 'lib/binary-codec/types/hash.rb', line 7

def self.width
  @width
end

Instance Method Details

#compare_to(other) ⇒ Integer

Compares this Hash to another Hash.

Parameters:

  • other (Hash)

    The other Hash to compare to.

Returns:

  • (Integer)

    Comparison result (-1, 0, or 1).



48
49
50
# File 'lib/binary-codec/types/hash.rb', line 48

def compare_to(other)
  @bytes <=> other.bytes
end

#nibblet(depth) ⇒ Integer

Returns four bits at the specified depth within a hash

Parameters:

  • depth (Integer)

    The depth of the four bits

Returns:

  • (Integer)

    The number represented by the four bits



56
57
58
59
60
61
62
63
64
# File 'lib/binary-codec/types/hash.rb', line 56

def nibblet(depth)
  byte_index = depth > 0 ? (depth / 2).floor : 0
  b = bytes[byte_index]
  if depth.even?
    (b & 0xf0) >> 4
  else
    b & 0x0f
  end
end