PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/generator.rb

http://github.com/FooBarWidget/rubyenterpriseedition
Ruby | 380 lines | 209 code | 75 blank | 96 comment | 22 complexity | d32d7126b3783e0b0de56bca8eff8350 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, LGPL-2.1, AGPL-3.0
  1. #!/usr/bin/env ruby
  2. #--
  3. # $Idaemons: /home/cvs/rb/generator.rb,v 1.8 2001/10/03 08:54:32 knu Exp $
  4. # $RoughId: generator.rb,v 1.10 2003/10/14 19:36:58 knu Exp $
  5. # $Id$
  6. #++
  7. #
  8. # = generator.rb: convert an internal iterator to an external one
  9. #
  10. # Copyright (c) 2001,2003 Akinori MUSHA <knu@iDaemons.org>
  11. #
  12. # All rights reserved. You can redistribute and/or modify it under
  13. # the same terms as Ruby.
  14. #
  15. # == Overview
  16. #
  17. # This library provides the Generator class, which converts an
  18. # internal iterator (i.e. an Enumerable object) to an external
  19. # iterator. In that form, you can roll many iterators independently.
  20. #
  21. # The SyncEnumerator class, which is implemented using Generator,
  22. # makes it easy to roll many Enumerable objects synchronously.
  23. #
  24. # See the respective classes for examples of usage.
  25. #
  26. # Generator converts an internal iterator (i.e. an Enumerable object)
  27. # to an external iterator.
  28. #
  29. # Note that it is not very fast since it is implemented using
  30. # continuations, which are currently slow.
  31. #
  32. # == Example
  33. #
  34. # require 'generator'
  35. #
  36. # # Generator from an Enumerable object
  37. # g = Generator.new(['A', 'B', 'C', 'Z'])
  38. #
  39. # while g.next?
  40. # puts g.next
  41. # end
  42. #
  43. # # Generator from a block
  44. # g = Generator.new { |g|
  45. # for i in 'A'..'C'
  46. # g.yield i
  47. # end
  48. #
  49. # g.yield 'Z'
  50. # }
  51. #
  52. # # The same result as above
  53. # while g.next?
  54. # puts g.next
  55. # end
  56. #
  57. class Generator
  58. include Enumerable
  59. # Creates a new generator either from an Enumerable object or from a
  60. # block.
  61. #
  62. # In the former, block is ignored even if given.
  63. #
  64. # In the latter, the given block is called with the generator
  65. # itself, and expected to call the +yield+ method for each element.
  66. def initialize(enum = nil, &block)
  67. if enum
  68. @block = proc { |g|
  69. enum.each { |x| g.yield x }
  70. }
  71. else
  72. @block = block
  73. end
  74. @index = 0
  75. @queue = []
  76. @cont_next = @cont_yield = @cont_endp = nil
  77. if @cont_next = callcc { |c| c }
  78. @block.call(self)
  79. @cont_endp.call(nil) if @cont_endp
  80. end
  81. self
  82. end
  83. # Yields an element to the generator.
  84. def yield(value)
  85. if @cont_yield = callcc { |c| c }
  86. @queue << value
  87. @cont_next.call(nil)
  88. end
  89. self
  90. end
  91. # Returns true if the generator has reached the end.
  92. def end?()
  93. if @cont_endp = callcc { |c| c }
  94. @cont_yield.nil? && @queue.empty?
  95. else
  96. @queue.empty?
  97. end
  98. end
  99. # Returns true if the generator has not reached the end yet.
  100. def next?()
  101. !end?
  102. end
  103. # Returns the current index (position) counting from zero.
  104. def index()
  105. @index
  106. end
  107. # Returns the current index (position) counting from zero.
  108. def pos()
  109. @index
  110. end
  111. # Returns the element at the current position and moves forward.
  112. def next()
  113. if end?
  114. raise EOFError, "no more elements available"
  115. end
  116. if @cont_next = callcc { |c| c }
  117. @cont_yield.call(nil) if @cont_yield
  118. end
  119. @index += 1
  120. @queue.shift
  121. end
  122. # Returns the element at the current position.
  123. def current()
  124. if @queue.empty?
  125. raise EOFError, "no more elements available"
  126. end
  127. @queue.first
  128. end
  129. # Rewinds the generator.
  130. def rewind()
  131. initialize(nil, &@block) if @index.nonzero?
  132. self
  133. end
  134. # Rewinds the generator and enumerates the elements.
  135. def each
  136. rewind
  137. until end?
  138. yield self.next
  139. end
  140. self
  141. end
  142. end
  143. #
  144. # SyncEnumerator creates an Enumerable object from multiple Enumerable
  145. # objects and enumerates them synchronously.
  146. #
  147. # == Example
  148. #
  149. # require 'generator'
  150. #
  151. # s = SyncEnumerator.new([1,2,3], ['a', 'b', 'c'])
  152. #
  153. # # Yields [1, 'a'], [2, 'b'], and [3,'c']
  154. # s.each { |row| puts row.join(', ') }
  155. #
  156. class SyncEnumerator
  157. include Enumerable
  158. # Creates a new SyncEnumerator which enumerates rows of given
  159. # Enumerable objects.
  160. def initialize(*enums)
  161. @gens = enums.map { |e| Generator.new(e) }
  162. end
  163. # Returns the number of enumerated Enumerable objects, i.e. the size
  164. # of each row.
  165. def size
  166. @gens.size
  167. end
  168. # Returns the number of enumerated Enumerable objects, i.e. the size
  169. # of each row.
  170. def length
  171. @gens.length
  172. end
  173. # Returns true if the given nth Enumerable object has reached the
  174. # end. If no argument is given, returns true if any of the
  175. # Enumerable objects has reached the end.
  176. def end?(i = nil)
  177. if i.nil?
  178. @gens.detect { |g| g.end? } ? true : false
  179. else
  180. @gens[i].end?
  181. end
  182. end
  183. # Enumerates rows of the Enumerable objects.
  184. def each
  185. @gens.each { |g| g.rewind }
  186. loop do
  187. count = 0
  188. ret = @gens.map { |g|
  189. if g.end?
  190. count += 1
  191. nil
  192. else
  193. g.next
  194. end
  195. }
  196. if count == @gens.size
  197. break
  198. end
  199. yield ret
  200. end
  201. self
  202. end
  203. end
  204. if $0 == __FILE__
  205. eval DATA.read, nil, $0, __LINE__+4
  206. end
  207. __END__
  208. require 'test/unit'
  209. class TC_Generator < Test::Unit::TestCase
  210. def test_block1
  211. g = Generator.new { |g|
  212. # no yield's
  213. }
  214. assert_equal(0, g.pos)
  215. assert_raises(EOFError) { g.current }
  216. end
  217. def test_block2
  218. g = Generator.new { |g|
  219. for i in 'A'..'C'
  220. g.yield i
  221. end
  222. g.yield 'Z'
  223. }
  224. assert_equal(0, g.pos)
  225. assert_equal('A', g.current)
  226. assert_equal(true, g.next?)
  227. assert_equal(0, g.pos)
  228. assert_equal('A', g.current)
  229. assert_equal(0, g.pos)
  230. assert_equal('A', g.next)
  231. assert_equal(1, g.pos)
  232. assert_equal(true, g.next?)
  233. assert_equal(1, g.pos)
  234. assert_equal('B', g.current)
  235. assert_equal(1, g.pos)
  236. assert_equal('B', g.next)
  237. assert_equal(g, g.rewind)
  238. assert_equal(0, g.pos)
  239. assert_equal('A', g.current)
  240. assert_equal(true, g.next?)
  241. assert_equal(0, g.pos)
  242. assert_equal('A', g.current)
  243. assert_equal(0, g.pos)
  244. assert_equal('A', g.next)
  245. assert_equal(1, g.pos)
  246. assert_equal(true, g.next?)
  247. assert_equal(1, g.pos)
  248. assert_equal('B', g.current)
  249. assert_equal(1, g.pos)
  250. assert_equal('B', g.next)
  251. assert_equal(2, g.pos)
  252. assert_equal(true, g.next?)
  253. assert_equal(2, g.pos)
  254. assert_equal('C', g.current)
  255. assert_equal(2, g.pos)
  256. assert_equal('C', g.next)
  257. assert_equal(3, g.pos)
  258. assert_equal(true, g.next?)
  259. assert_equal(3, g.pos)
  260. assert_equal('Z', g.current)
  261. assert_equal(3, g.pos)
  262. assert_equal('Z', g.next)
  263. assert_equal(4, g.pos)
  264. assert_equal(false, g.next?)
  265. assert_raises(EOFError) { g.next }
  266. end
  267. def test_each
  268. a = [5, 6, 7, 8, 9]
  269. g = Generator.new(a)
  270. i = 0
  271. g.each { |x|
  272. assert_equal(a[i], x)
  273. i += 1
  274. break if i == 3
  275. }
  276. assert_equal(3, i)
  277. i = 0
  278. g.each { |x|
  279. assert_equal(a[i], x)
  280. i += 1
  281. }
  282. assert_equal(5, i)
  283. end
  284. end
  285. class TC_SyncEnumerator < Test::Unit::TestCase
  286. def test_each
  287. r = ['a'..'f', 1..10, 10..20]
  288. ra = r.map { |x| x.to_a }
  289. a = (0...(ra.map {|x| x.size}.max)).map { |i| ra.map { |x| x[i] } }
  290. s = SyncEnumerator.new(*r)
  291. i = 0
  292. s.each { |x|
  293. assert_equal(a[i], x)
  294. i += 1
  295. break if i == 3
  296. }
  297. assert_equal(3, i)
  298. i = 0
  299. s.each { |x|
  300. assert_equal(a[i], x)
  301. i += 1
  302. }
  303. assert_equal(a.size, i)
  304. end
  305. end