Class: ByteArray

Inherits:
Object
  • Object
show all
Defined in:
lib/byte_array/byte_array.rb

Constant Summary collapse

VERSION =
"0.9.0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size = 0, obj = 0) ⇒ ByteArray

Returns a new instance of ByteArray.



5
6
7
8
# File 'lib/byte_array/byte_array.rb', line 5

def initialize size = 0, obj = 0
  @bytes = []
  size.times do @bytes << Byte[obj] end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *a, &b) ⇒ Object



68
69
70
71
# File 'lib/byte_array/byte_array.rb', line 68

def method_missing m, *a, &b
  #puts "Method #{m} called with", *a
  @bytes.send m, *a, &b
end

Instance Attribute Details

#bytesObject (readonly)

Returns the value of attribute bytes.



4
5
6
# File 'lib/byte_array/byte_array.rb', line 4

def bytes
  @bytes
end

Class Method Details

.[](array = []) ⇒ Object



10
11
12
13
14
15
# File 'lib/byte_array/byte_array.rb', line 10

def self.[] array = []
  return array if array.is_a? ByteArray
  b = new
  b.insert 0, *array
  b
end

Instance Method Details

#==(other) ⇒ Object



51
52
53
54
# File 'lib/byte_array/byte_array.rb', line 51

def == other
  return false if other.length != @bytes.length
  ByteArray[other].zip(@bytes).all?{|a,b| a == b}
end

#[](slice) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/byte_array/byte_array.rb', line 17

def [] slice
  case slice
  when Range
    ByteArray[@bytes[slice]]
  when Integer
    @bytes[slice]
  end
end

#[]=(slice, *input) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/byte_array/byte_array.rb', line 26

def []= slice, *input
  input = input.flat_map(&method(:to_bytes))
  case slice
  when Range
    @bytes[slice] = *input 
  when Integer
    insert slice, *input
  end unless input.empty?
end

#coerce(other) ⇒ Object



56
57
58
# File 'lib/byte_array/byte_array.rb', line 56

def coerce other
  [ByteArray[other], self]
end

#insert(position, *what) ⇒ Object



44
45
46
47
48
49
# File 'lib/byte_array/byte_array.rb', line 44

def insert position, *what
  assert_in_range position

  what = what.flat_map(&method(:to_bytes))
  @bytes[position..position+what.length-1] = what unless what.empty?
end

#inspectObject



40
41
42
# File 'lib/byte_array/byte_array.rb', line 40

def inspect
  "ByteArray#{@bytes}"
end

#lengthObject



36
37
38
# File 'lib/byte_array/byte_array.rb', line 36

def length
  @bytes.length
end

#to_aObject



64
65
66
# File 'lib/byte_array/byte_array.rb', line 64

def to_a
  @bytes
end

#to_aryObject



60
61
62
# File 'lib/byte_array/byte_array.rb', line 60

def to_ary
  @bytes
end