class Buffer

Fixed size buffer.

Constants

NUL

Public Class Methods

from_string(str) click to toggle source
# File lib/buffer.rb, line 10
def self.from_string(str)
  new(str)
end
new(content) click to toggle source
# File lib/buffer.rb, line 19
def initialize(content)
  @size = content.size
  @content = content
  @position = 0
end
of_size(size) click to toggle source
# File lib/buffer.rb, line 14
def self.of_size(size)
  raise ArgumentError if size < 0
  new('#' * size)
end

Public Instance Methods

at_end?() click to toggle source
# File lib/buffer.rb, line 38
def at_end?
  @position == @size
end
content() click to toggle source
# File lib/buffer.rb, line 42
def content
  @content
end
copy_from_stream(stream, n) click to toggle source
# File lib/buffer.rb, line 61
def copy_from_stream(stream, n)
  raise ArgumentError if n < 0
  while n > 0
    str = stream.read(n) 
    write(str)
    n -= str.size
  end
  raise if n < 0 
end
position() click to toggle source
# File lib/buffer.rb, line 29
def position
  @position
end
position=(new_pos) click to toggle source
# File lib/buffer.rb, line 33
def position=(new_pos)
  raise ArgumentError if new_pos < 0 or new_pos > @size
  @position = new_pos
end
read(n) click to toggle source
# File lib/buffer.rb, line 46
def read(n)
  raise EOF, 'cannot read beyond the end of buffer' if @position + n > @size
  str = @content[@position, n]
  @position += n
  str
end
read_cstring() click to toggle source

returns a Ruby string without the trailing NUL character

# File lib/buffer.rb, line 80
def read_cstring
  nul_pos = @content.index(NUL, @position)
  raise Error, "no cstring found!" unless nul_pos

  sz = nul_pos - @position
  str = @content[@position, sz]
  @position += sz + 1
  return str
end
read_rest() click to toggle source

read till the end of the buffer

# File lib/buffer.rb, line 91
def read_rest
  read(self.size-@position)
end
size() click to toggle source
# File lib/buffer.rb, line 25
def size
  @size
end
write(str) click to toggle source
# File lib/buffer.rb, line 53
def write(str)
  sz = str.size
  raise EOF, 'cannot write beyond the end of buffer' if @position + sz > @size
  @content[@position, sz] = str
  @position += sz
  self
end
write_cstring(cstr) click to toggle source
# File lib/buffer.rb, line 73
def write_cstring(cstr)
  raise ArgumentError, "Invalid Ruby/cstring" if cstr.include?(NUL)
  write(cstr)
  write(NUL)
end