Module: ABI::Helpers
- Included in:
- Utils
- Defined in:
- lib/abicoder/utils.rb
Instance Method Summary collapse
- #big_endian_to_int(s) ⇒ Object
- #ceil32(x) ⇒ Object
- #decode_hex(str) ⇒ Object
- #encode_hex(b) ⇒ Object
- #encode_int(n) ⇒ Object
- #int_to_big_endian(n) ⇒ Object
-
#lpad(x, symbol, l) ⇒ Object
encoding / decoding helpers.
- #rpad(x, symbol, l) ⇒ Object
- #zpad(x, l) ⇒ Object
- #zpad_hex(s, l = 32) ⇒ Object
- #zpad_int(n, l = 32) ⇒ Object
Instance Method Details
#big_endian_to_int(s) ⇒ Object
31 32 33 34 35 36 37 |
# File 'lib/abicoder/utils.rb', line 31 def big_endian_to_int(s) s = s.sub( /\A(\x00)+/, '' ) ## keep "performance" shortcut - why? why not? ### todo/check - allow nil - why? why not? ## raise DeserializationError, "Invalid serialization (not minimal length)" if !@size && serial.size > 0 && serial[0] == BYTE_ZERO s = s || BYTE_ZERO s.unpack("H*").first.to_i(16) end |
#ceil32(x) ⇒ Object
69 70 71 |
# File 'lib/abicoder/utils.rb', line 69 def ceil32(x) x % 32 == 0 ? x : (x + 32 - x%32) end |
#decode_hex(str) ⇒ Object
63 64 65 66 67 |
# File 'lib/abicoder/utils.rb', line 63 def decode_hex(str) raise TypeError, "Value must be an instance of string" unless str.instance_of?(String) raise TypeError, 'Non-hexadecimal digit found' unless str =~ /\A[0-9a-fA-F]*\z/ [str].pack("H*") end |
#encode_hex(b) ⇒ Object
58 59 60 61 |
# File 'lib/abicoder/utils.rb', line 58 def encode_hex(b) raise TypeError, "Value must be an instance of String" unless b.instance_of?(String) b.unpack("H*").first end |
#encode_int(n) ⇒ Object
52 53 54 55 |
# File 'lib/abicoder/utils.rb', line 52 def encode_int(n) raise ArgumentError, "Integer invalid or out of range: #{n}" unless n.is_a?(Integer) && n >= 0 && n <= UINT_MAX int_to_big_endian( n ) end |
#int_to_big_endian(n) ⇒ Object
40 41 42 43 44 45 46 47 48 49 |
# File 'lib/abicoder/utils.rb', line 40 def int_to_big_endian(n) if n == 0 BYTE_EMPTY else hex = n.to_s(16) hex = "0#{hex}" if hex.size.odd? [hex].pack("H*") ## note Util.hex_to_bin() "inline" shortcut end end |
#lpad(x, symbol, l) ⇒ Object
encoding / decoding helpers
7 8 9 10 |
# File 'lib/abicoder/utils.rb', line 7 def lpad(x, symbol, l) return x if x.size >= l symbol * (l - x.size) + x end |
#rpad(x, symbol, l) ⇒ Object
12 13 14 15 |
# File 'lib/abicoder/utils.rb', line 12 def rpad(x, symbol, l) return x if x.size >= l x + symbol * (l - x.size) end |
#zpad(x, l) ⇒ Object
17 18 19 |
# File 'lib/abicoder/utils.rb', line 17 def zpad(x, l) lpad( x, BYTE_ZERO, l ) end |
#zpad_hex(s, l = 32) ⇒ Object
25 26 27 |
# File 'lib/abicoder/utils.rb', line 25 def zpad_hex(s, l=32) zpad( decode_hex(s), l ) end |
#zpad_int(n, l = 32) ⇒ Object
21 22 23 |
# File 'lib/abicoder/utils.rb', line 21 def zpad_int(n, l=32) zpad( encode_int(n), l ) end |