Class: BlockCipherKit::ReadWindowIO

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io, starting_at_offset, window_size) ⇒ ReadWindowIO

Returns a new instance of ReadWindowIO.



2
3
4
5
6
7
# File 'lib/block_cipher_kit/read_window_io.rb', line 2

def initialize(io, starting_at_offset, window_size)
  @io = io
  @starting_at_offset = starting_at_offset.to_i
  @window_size = window_size.to_i
  @pos = 0
end

Instance Attribute Details

#posObject (readonly)

Returns the value of attribute pos.



13
14
15
# File 'lib/block_cipher_kit/read_window_io.rb', line 13

def pos
  @pos
end

Instance Method Details

#read(n_bytes) ⇒ Object

Raises:

  • (ArgumentError)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/block_cipher_kit/read_window_io.rb', line 15

def read(n_bytes)
  return "" if n_bytes == 0 # As hardcoded for all Ruby IO objects
  raise ArgumentError, "negative length #{n_bytes} given" if n_bytes < 0 # also as per Ruby IO objects

  window_limit = @starting_at_offset + @window_size
  wants_upto = @starting_at_offset + @pos + n_bytes

  read_limit = [window_limit, wants_upto].compact.min
  actual_n = read_limit - (@starting_at_offset + @pos)
  return if actual_n <= 0

  @io.seek(@starting_at_offset + @pos)
  @io.read(actual_n).tap { @pos += actual_n }
end

#seek(to_offset_in_window) ⇒ Object

Raises:

  • (ArgumentError)


30
31
32
33
34
# File 'lib/block_cipher_kit/read_window_io.rb', line 30

def seek(to_offset_in_window)
  raise ArgumentError, "negative seek destination #{to_offset_in_window}" if to_offset_in_window < 0 # also as per Ruby IO objects
  @pos = to_offset_in_window
  0
end

#sizeObject



9
10
11
# File 'lib/block_cipher_kit/read_window_io.rb', line 9

def size
  @window_size
end