Jesús Gabriel y Galán
11/22/2007 10:33:00 AM
On Nov 22, 2007 9:59 AM, Martin Durai <martin@angleritech.com> wrote:
> Actually i need to create a ring buffer class, with read, write, seek
> methods.
>
> Read should take number as an argument(number of bytes to read) and
> should return a string. when you read, you need to read either the
> request number of bytes or the availlable number of bytes, whichever is
> smaller. when you read you advance forward the read_position.
>
> similarly write method should take string as a argument. now advance
> forward the write position.
>
> seek should take number as a argument and return nothing. it should do
> range checking. seek changes the read position.
I think you are doing too much work. I would wrap a StringIO which is basically
what you want:
$ cat ringbuffer.rb && ruby ringbuffer.rb
require 'stringio'
class RingBuffer
def initialize string = ""
@string_io = StringIO.new string
end
def read bytes = nil
@string_io.read bytes
end
def write string
cur_pos = @string_io.pos
@string_io.seek(0, IO::SEEK_END)
@string_io.write string
@string_io.seek(cur_pos, IO::SEEK_SET)
string.length
end
def seek bytes
@string_io.seek bytes
end
end
b = RingBuffer.new
b.write "abcde"
puts b.read
b.write "fghij"
puts b.read(2)
puts b.read(1)
b.write "12345"
puts b.read(5)
abcde
fg
h
ij123
Of course you might need to add some checks to fulfill your error
handling requirements but this might get you started.
Jesus.