Guest User

Untitled

a guest
Feb 20th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. class BufferedString
  4.  
  5. class Buffer < String
  6.  
  7. def initialize
  8. @eof = false
  9. super
  10. end
  11.  
  12. def eof?
  13. @eof
  14. end
  15.  
  16. def close!
  17. @eof = true
  18. end
  19.  
  20. end
  21.  
  22. def initialize
  23. @buf = Buffer.new
  24. @pos = 0
  25. end
  26.  
  27. def initialize_copy( from )
  28. @buf = from.instance_eval { @buf }
  29. @pos = 0
  30. end
  31.  
  32. def read
  33. rval = @buf[ @pos..-1 ]
  34. @pos += ( @buf.length - @pos )
  35. return rval
  36. end
  37.  
  38. def close!
  39. @buf.close!
  40. end
  41.  
  42. def eof?
  43. @buf.eof? and @pos >= @buf.length
  44. end
  45.  
  46. def seek(pos) ; @pos = pos ; end
  47.  
  48. def write( string )
  49. @buf.insert(@pos,string)
  50. end
  51.  
  52. def method_missing(name,*args,&block)
  53. @buf.send(name,*args,&block)
  54. end
  55.  
  56. end
  57.  
  58. io = BufferedString.new
  59. ioread = io.dup
  60. writer = Thread.new do
  61. io << "xxx" while ( io.length < 1000 )
  62. io.close!
  63. end
  64. reader = Thread.new do
  65. p ioread.read until ioread.eof?
  66. end
  67. sleep 1 while [ reader, writer ].find { |thread| thread.alive? }
  68.  
  69. io = BufferedString.new
  70. ioread = io.dup
  71. io << "dan"
  72. io.seek(0)
  73. io.write("hello ")
  74. p ioread.read
Add Comment
Please, Sign In to add comment