Class: BinData::Buffer::BufferIO

Inherits:
IO::Transform show all
Defined in:
lib/bindata/buffer.rb

Overview

Transforms the IO stream to restrict access inside a buffer of specified length.

Instance Method Summary collapse

Methods inherited from IO::Transform

#offset, #prepend_to_chain, #seekable?, transform_changes_stream_length!

Constructor Details

#initialize(length) ⇒ BufferIO

Returns a new instance of BufferIO.



112
113
114
115
# File 'lib/bindata/buffer.rb', line 112

def initialize(length)
  super()
  @bytes_remaining = length
end

Instance Method Details

#after_read_transformObject



161
162
163
# File 'lib/bindata/buffer.rb', line 161

def after_read_transform
  read(nil)
end

#after_write_transformObject



165
166
167
# File 'lib/bindata/buffer.rb', line 165

def after_write_transform
  write("\x00" * @bytes_remaining)
end

#before_transformObject



117
118
119
120
# File 'lib/bindata/buffer.rb', line 117

def before_transform
  @buf_start = offset
  @buf_end = @buf_start + @bytes_remaining
end

#buffer_limited_n(n) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/bindata/buffer.rb', line 169

def buffer_limited_n(n)
  if n.nil?
    @bytes_remaining
  elsif n.positive?
    limit = @bytes_remaining
    n > limit ? limit : n
# uncomment if we decide to allow backwards skipping
#        elsif n.negative?
#          limit = @bytes_remaining + @buf_start - @buf_end
#          n < limit ? limit : n
  else
    0
  end
end

#num_bytes_remainingObject



122
123
124
125
126
# File 'lib/bindata/buffer.rb', line 122

def num_bytes_remaining
  [@bytes_remaining, super].min
rescue IOError
  @bytes_remaining
end

#read(n) ⇒ Object



144
145
146
147
148
149
# File 'lib/bindata/buffer.rb', line 144

def read(n)
  nbytes = buffer_limited_n(n)
  @bytes_remaining -= nbytes

  chain_read(nbytes)
end

#seek_abs(n) ⇒ Object



135
136
137
138
139
140
141
142
# File 'lib/bindata/buffer.rb', line 135

def seek_abs(n)
  if n < @buf_start || n >= @buf_end
    raise IOError, "can not seek to abs_offset outside of buffer"
  end

  @bytes_remaining -= (n - offset)
  chain_seek_abs(n)
end

#skip(n) ⇒ Object



128
129
130
131
132
133
# File 'lib/bindata/buffer.rb', line 128

def skip(n)
  nbytes = buffer_limited_n(n)
  @bytes_remaining -= nbytes

  chain_skip(nbytes)
end

#write(data) ⇒ Object



151
152
153
154
155
156
157
158
159
# File 'lib/bindata/buffer.rb', line 151

def write(data)
  nbytes = buffer_limited_n(data.size)
  @bytes_remaining -= nbytes
  if nbytes < data.size
    data = data[0, nbytes]
  end

  chain_write(data)
end