Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. struct Slice(T)
  2. def []?(start, count)
  3. if start + count >= size
  4. count = -1
  5. end
  6.  
  7. if count < 0
  8. count = size - start + (count + 1)
  9. end
  10.  
  11. self[start, count]
  12. end
  13. end
  14.  
  15. class InjectingIO
  16. include IO
  17.  
  18. getter? closed = false
  19. @remaining_token : Bytes?
  20.  
  21. def initialize(@io : IO, @token : Bytes, @replacement : Bytes)
  22. end
  23.  
  24. def read(slice : Bytes)
  25. check_open
  26.  
  27. @io.read(slice)
  28. end
  29.  
  30. def write(slice : Bytes)
  31. check_open
  32.  
  33. remaining_token = @remaining_token
  34. if remaining_token
  35. if slice[0, remaining_token.size]? == remaining_token
  36. @io.write(@replacement)
  37. @io.write(slice[remaining_token.size, -1]?)
  38. @remaining_token = nil
  39. return
  40. elsif slice.size < remaining_token.size
  41. if slice == remaining_token[0, slice.size]?
  42. @remaining_token = remaining_token[slice.size, -1]?
  43. return
  44. else
  45. @io.write(@token[0, @token.size - remaining_token.size])
  46. @remaining_token = nil
  47. end
  48. else
  49. @io.write(@token[0, @token.size - remaining_token.size])
  50. @remaining_token = nil
  51. end
  52. end
  53.  
  54. first_half = slice
  55. second_half = nil
  56. 0.upto(slice.size - 1) do |i|
  57. candidate = slice[i, @token.size]?
  58. if candidate == @token
  59. first_half = slice[0, i]?
  60. second_half = slice[i + @token.size, -1]?
  61. break
  62. elsif candidate.size < @token.size && candidate == @token[0, candidate.size]?
  63. @remaining_token = @token[candidate.size, -1]?
  64. first_half = slice[0, i]?
  65. break
  66. end
  67. end
  68.  
  69. @io.write(first_half)
  70.  
  71. if second_half
  72. @io.write(@replacement)
  73. @io.write(second_half)
  74. end
  75. end
  76.  
  77. def close
  78. @io.close
  79. @closed = true
  80. end
  81. end
  82.  
  83. io = InjectingIO.new(STDOUT, "foo".to_slice, "bar".to_slice)
  84.  
  85. io.puts "Hello World"
  86. io.puts "Hello foo"
  87. io.print "fo"
  88. io.puts "o is cool"
  89. io.print "f"
  90. io.puts "oo is cooler"
  91. io.print "f"
  92. io.print "o"
  93. io.puts "o is the coolest"
  94. io.print "foo"
  95. io.puts " is okay too"
  96. io.print "fo"
  97. io.puts " stays"
  98. io.close
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement