Class: Rjq::JSON::InputBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/rjq/json/input_buffer.rb

Constant Summary collapse

DEFAULT_CHUNK_SIZE =
16_384

Instance Method Summary collapse

Constructor Details

#initialize(io_or_string, chunk_size: DEFAULT_CHUNK_SIZE) ⇒ InputBuffer

Returns a new instance of InputBuffer.



8
9
10
11
12
13
14
15
# File 'lib/rjq/json/input_buffer.rb', line 8

def initialize(io_or_string, chunk_size: DEFAULT_CHUNK_SIZE)
  @io = io_or_string if io_or_string.respond_to?(:read)
  @chunk_size = chunk_size
  @offset = 0
  @eof = !@io
  @buffer = @io ? +''.b : io_or_string.to_s.dup
  normalize_encoding!
end

Instance Method Details

#[](index, length = nil) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rjq/json/input_buffer.rb', line 17

def [](index, length = nil)
  if index.is_a?(Range)
    range_end = index.end
    range_end -= 1 if index.exclude_end?
    ensure_index(range_end)
    return @buffer[local_index(index.begin)..local_index(index.end)] unless index.exclude_end?

    return @buffer[local_index(index.begin)...local_index(index.end)]
  end

  ensure_index(index + length - 1) if length
  ensure_index(index) unless length
  length ? @buffer[local_index(index), length] : @buffer[local_index(index)]
end

#discard_before(index) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/rjq/json/input_buffer.rb', line 32

def discard_before(index)
  return if index <= @offset

  local = [index - @offset, @buffer.length].min
  @buffer = @buffer[local..].to_s
  @offset += local
end