Class: BinaryCodec::Hash
- Inherits:
-
ComparableSerializedType
- Object
- SerializedType
- ComparableSerializedType
- BinaryCodec::Hash
- Defined in:
- lib/binary-codec/types/hash.rb
Instance Attribute Summary
Attributes inherited from SerializedType
Class Method Summary collapse
-
.from(value) ⇒ Hash
Creates a new Hash instance from a value.
-
.from_parser(parser, hint = nil) ⇒ Hash
Creates a Hash instance from a parser.
-
.width ⇒ Integer
Returns the width of the Hash type in bytes.
Instance Method Summary collapse
-
#compare_to(other) ⇒ Integer
Compares this Hash to another Hash.
-
#initialize(bytes = nil) ⇒ Hash
constructor
A new instance of Hash.
-
#nibblet(depth) ⇒ Integer
Returns four bits at the specified depth within a hash.
Methods inherited from ComparableSerializedType
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.
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.
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 |
.width ⇒ Integer
Returns the width of the Hash type in bytes.
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.
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
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 |