Created
October 10, 2008 03:00
-
-
Save dyoder/15973 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class BufferedString | |
class Buffer < String | |
def initialize | |
@eof = false | |
super | |
end | |
def eof? | |
@eof | |
end | |
def close! | |
@eof = true | |
end | |
end | |
def initialize | |
@buf = Buffer.new | |
@pos = 0 | |
end | |
def initialize_copy( from ) | |
@buf = from.instance_eval { @buf } | |
@pos = 0 | |
end | |
def read | |
rval = @buf[ @pos..-1 ] | |
@pos += ( @buf.length - @pos ) | |
return rval | |
end | |
def close! | |
@buf.close! | |
end | |
def eof? | |
@buf.eof? and @pos >= @buf.length | |
end | |
def seek(pos) ; @pos = pos ; end | |
def write( string ) | |
@buf.insert(@pos,string) | |
end | |
def method_missing(name,*args,&block) | |
@buf.send(name,*args,&block) | |
end | |
end | |
io = BufferedString.new | |
ioread = io.dup | |
writer = Thread.new do | |
io << "xxx" while ( io.length < 1000 ) | |
io.close! | |
end | |
reader = Thread.new do | |
p ioread.read until ioread.eof? | |
end | |
sleep 1 while [ reader, writer ].find { |thread| thread.alive? } | |
io = BufferedString.new | |
ioread = io.dup | |
io << "dan" | |
io.seek(0) | |
io.write("hello ") | |
p ioread.read |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment