Module BSV::Primitives::Hex ¶
Strict hex encoding/decoding utilities.
Ruby's +Array#pack('H*')+ silently drops non-hex characters and truncates odd-length strings. This module rejects both, raising ArgumentError on invalid input so consumer-facing parse paths fail loudly rather than producing garbage.
Internal paths that serialise/deserialise trusted hex (e.g. round-tripping our own +unpack1('H')+ output) can continue using +pack('H')+ directly — the validation overhead isn't warranted when the hex is known-good.
@example
BSV::Primitives::Hex.decode('deadbeef') #=> "\xDE\xAD\xBE\xEF"
BSV::Primitives::Hex.decode('nope') #=> ArgumentError
BSV::Primitives::Hex.decode('abc') #=> ArgumentError (odd length)
BSV::Primitives::Hex.encode("\xDE\xAD") #=> "dead"
Constants¶
HEX_RE ¶
Matches an even number of hex characters (case-insensitive). Empty string is valid (decodes to empty bytes).
Public Class Methods¶
decode(str, name: = 'hex value') ¶
Decode a hex string to binary bytes. - @param str [String] hex string (must be even-length, hex-only) - @param name [String] label for the error message - @raise [ArgumentError] if +str+ is not valid hex - @return [String] binary string (ASCII-8BIT encoding)
encode(bytes) ¶
Encode binary bytes as lowercase hex. - @param bytes [String] binary data - @return [String] lowercase hex string (UTF-8 encoding)
valid?(str) ¶
Test whether str is valid hex (even-length, hex-only). - @param str [String] - @return [Boolean]
validate!(str, name: = 'hex value') ¶
Validate str as hex, raising on failure. - @param str [String] - @param name [String] label for the error message (e.g. +'txid'+) - @raise [ArgumentError] if +str+ is not valid hex - @return [String] the input string (pass-through for chaining)