Class: Primate::Readable

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(typed_array, content_type = nil) ⇒ Readable

Returns a new instance of Readable.



7
8
9
10
11
12
# File 'lib/primate/readable.rb', line 7

def initialize(typed_array, content_type = nil)
  @ta = typed_array
  @content_type = content_type
  @pos = 0
  @size = @ta[:length].to_i
end

Instance Attribute Details

#content_typeObject (readonly)

Returns the value of attribute content_type.



5
6
7
# File 'lib/primate/readable.rb', line 5

def content_type
  @content_type
end

Instance Method Details

#bytes(n = nil) ⇒ Object

return an array of bytes (integers), advance position



28
29
30
31
32
33
34
# File 'lib/primate/readable.rb', line 28

def bytes(n = nil)
  return [] if eof?
  n = n ? [n, @size - @pos].min : (@size - @pos)
  arr = Array.new(n) { |i| @ta[@pos + i].to_i }
  @pos += n
  arr
end

#each_chunk(chunk = 64 * 1024) ⇒ Object

enumerate binary string chunks starting at current position (no rewind)



49
50
51
52
53
54
55
56
57
58
# File 'lib/primate/readable.rb', line 49

def each_chunk(chunk = 64 * 1024)
  return enum_for(:each_chunk, chunk) unless block_given?
  off = @pos
  while off < @size
    n = [chunk, @size - off].min
    yield pack_range(off, n)
    off += n
  end
  self
end

#eof?Boolean

Returns:

  • (Boolean)


15
# File 'lib/primate/readable.rb', line 15

def eof? = @pos >= @size

#head(n = 4) ⇒ Object

first n bytes from the beginning (integers), does not affect position



43
44
45
46
# File 'lib/primate/readable.rb', line 43

def head(n = 4)
  n = [n, @size].min
  Array.new(n) { |i| @ta[i].to_i }
end

#peek(n) ⇒ Object

look ahead without advancing position (integers)



37
38
39
40
# File 'lib/primate/readable.rb', line 37

def peek(n)
  n = [n, @size - @pos].min
  Array.new(n) { |i| @ta[@pos + i].to_i }
end

#read(n = nil) ⇒ Object

return a binary string (ASCII-8BIT), advance position



19
20
21
22
23
24
25
# File 'lib/primate/readable.rb', line 19

def read(n = nil)
  return ''.b if eof?
  n = n ? [n, @size - @pos].min : (@size - @pos)
  str = pack_range(@pos, n)
  @pos += n
  str
end

#rewindObject



16
# File 'lib/primate/readable.rb', line 16

def rewind; @pos = 0; self; end

#sizeObject



14
# File 'lib/primate/readable.rb', line 14

def size = @size