Class: Bytes

Inherits:
Object
  • Object
show all
Extended by:
BytesHelper, Forwardable
Defined in:
lib/bytes.rb

Constant Summary

Constants included from BytesHelper

BytesHelper::HEX_RE

Class Method Summary collapse

Instance Method Summary collapse

Methods included from BytesHelper

bin_to_hex, hex_to_bin, is_hex?

Constructor Details

#initialize(bin = String.new) ⇒ Bytes

Returns a new instance of Bytes.



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/bytes.rb', line 65

def initialize( bin=String.new )
  ## note: for now will NOT dup(licate) passed in binary array
  ##    you only get a new binary array if no arg passed in e.g. Bytes.new
  @bin  = if bin.encoding != Encoding::ASCII_8BIT
           puts "!! WARN - Bytes.new - BINARY/ASCII-8BIT encoding expected; got: #{bin.encoding} for string:"
           pp bin

           bin.b
          else
             bin
          end
end

Class Method Details

.convert(arg) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/bytes.rb', line 99

def self.convert( arg )
  ## used by Bytes() in global Kernel converter method
    if arg.is_a?( Bytes )
      arg   ## pass-through as is
    elsif arg.is_a?( String )
      ## todo/fix: use coerce to_str if arg is NOT a string - why? why not
      ##
      if arg.encoding == Encoding::ASCII_8BIT
        ## assume it's binary data - use as is (no hexstring conversion)
        Bytes.wrap( arg )   ## todo/check: return str as-is (without new) - why? why not?
      else    ## assume it's a hexstring
        Bytes.from_hex( arg )
      end
    else
     ## check for array or such e.g if arg.is_a? Array
        ## raise TypeError - why? why not?
       raise ArgumentError, "Bytes() expected String; got #{arg.class.name}"
    end
end

.from_hex(hex) ⇒ Object



59
# File 'lib/bytes.rb', line 59

def self.from_hex( hex ) new( hex_to_bin( hex ) );  end

.wrap(bin) ⇒ Object

“semantic” constructor for wrapping (binary) strings e.g. same as Bytes.new(bin)



62
# File 'lib/bytes.rb', line 62

def self.wrap( bin ) new( bin );  end

Instance Method Details

#==(other) ⇒ Object



93
94
95
# File 'lib/bytes.rb', line 93

def ==(other)
  self.class == other.class && @bin == other.b
end

#bObject



88
# File 'lib/bytes.rb', line 88

def b()  @bin; end

#to_hexObject Also known as: to_s



85
# File 'lib/bytes.rb', line 85

def to_hex() Bytes.bin_to_hex( @bin ); end