Class: Mobi::StreamSlicer

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stream, start = 0, stop = nil) ⇒ StreamSlicer

Returns a new instance of StreamSlicer.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/mobi/stream_slicer.rb', line 7

def initialize(stream, start = 0, stop = nil)
  @stream = stream
  @start  = start

  if stop.nil?
    stream.seek(0, 2)
    stop = stream.tell
  end

  @stop    = stop
  @length  = stop - start
end

Instance Attribute Details

#lengthObject (readonly)

Returns the value of attribute length.



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

def length
  @length
end

#startObject

Returns the value of attribute start.



5
6
7
# File 'lib/mobi/stream_slicer.rb', line 5

def start
  @start
end

#stopObject

Returns the value of attribute stop.



5
6
7
# File 'lib/mobi/stream_slicer.rb', line 5

def stop
  @stop
end

#streamObject (readonly)

Returns the value of attribute stream.



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

def stream
  @stream
end

Instance Method Details

#[](offset, bytes = 1) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/mobi/stream_slicer.rb', line 20

def [](offset, bytes=1)
  stream = @stream
  base   = @start

  if bytes == 1
    stream.seek(base + offset)
    return stream.read(1)
  end

  start = offset
  stop  = offset + bytes

  # Reverse if you want to pass in negative bytes
  start, stop = stop, start if bytes < 0

  # I can't find a use case where it will ever get here
  size = stop - start
  return nil if size <= 0

  stream.seek(base + start)
  data = stream.read(size)
  return data
end