Class: LazyList::ReadQueue
Overview
ReadQueue is the implementation of an read-only queue that only supports #shift and #empty? methods. It’s used as a wrapper to encapsulate enumerables in lazy lists.
Instance Method Summary collapse
-
#empty? ⇒ Boolean
Returns true if the queue is empty.
-
#initialize(enumerable) ⇒ ReadQueue
constructor
Creates an ReadQueue object from an enumerable.
-
#shift ⇒ Object
(also: #pop)
Extracts the top element from the queue or nil if the queue is empty.
Constructor Details
#initialize(enumerable) ⇒ ReadQueue
Creates an ReadQueue object from an enumerable.
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
# File 'lib/lazylist.rb', line 139 def initialize(enumerable) @data = [] @producer = Thread.new do Thread.stop begin enumerable.each do |value| old, Thread.critical = Thread.critical, true begin @data << value @consumer.wakeup Thread.stop ensure Thread.critical = old end end rescue => e @consumer.raise e ensure @consumer.wakeup end end Thread.pass until @producer.stop? end |
Instance Method Details
#empty? ⇒ Boolean
Returns true if the queue is empty.
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
# File 'lib/lazylist.rb', line 176 def empty? if @data.empty? old, Thread.critical = Thread.critical, true begin @consumer = Thread.current @producer.wakeup Thread.stop rescue ThreadError ; ensure @consumer = nil Thread.critical = old end end @data.empty? end |
#shift ⇒ Object Also known as: pop
Extracts the top element from the queue or nil if the queue is empty.
165 166 167 168 169 170 171 |
# File 'lib/lazylist.rb', line 165 def shift if empty? nil else @data.shift end end |