class Async::List::Iterator

def self.each(list, &block)

def self.each(list, &block)
	return if list.empty?
	
	iterator = Iterator.new(list)
	
	iterator.each(&block)
ensure
	iterator&.remove!
end

def each

def each
	while current = move_current
		yield current
		
		if current.equal?(@tail)
			move_next
		end
	end
end

def initialize(list)

def initialize(list)
	@list = list
	
	# Insert the iterator as the first item in the list:
	@tail = list.tail
	@tail.head = self
	list.tail = self
	@head = list
end

def move_current

def move_current
	while true
		# Are we at the end of the list?
		if @tail.equal?(@list)
			return nil
		end
		
		if @tail.is_a?(Iterator)
			move_next
		else
			return @tail
		end
	end
end

def move_next

def move_next
	# Move to the next item (which could be an iterator or the end):
	@tail.head = @head
	@head.tail = @tail
	@head = @tail
	@tail = @tail.tail
	@head.tail = self
	@tail.head = self
end

def remove!

def remove!
	@head.tail = @tail
	@tail.head = @head
	@head = nil
	@tail = nil
	@list = nil
end