From 1be2c16a88dede90bbc8520498a5bf884538a9a3 Mon Sep 17 00:00:00 2001 From: Ian Katz Date: Mon, 28 Jun 2021 23:14:15 -0400 Subject: [PATCH] change pattern for ::IO.pipe --- lib/piperator.rb | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/lib/piperator.rb b/lib/piperator.rb index fe331bc..2b0276a 100644 --- a/lib/piperator.rb +++ b/lib/piperator.rb @@ -60,24 +60,23 @@ def self.wrap(value) # @yieldparam io_r [IO] readable IO def self.infinite_io(enumerator) stop = false - io_r, io_w = ::IO.pipe # not the IO from this library + ::IO.pipe do |io_r, io_w| # not the IO from this library - # a thread writes all the data to the pipe. the pipe automatically buffers everything for us - thr = Thread.new do - enumerator.each do |chunk| - break if stop - io_w.write(chunk) + # a thread writes all the data to the pipe. the pipe automatically buffers everything for us + thr = Thread.new do + enumerator.each do |chunk| + break if stop + io_w.write(chunk) + end + ensure + io_w.close # otherwise a read will hang end + + yield io_r ensure - io_w.close + stop = true + thr.join end - - yield io_r - ensure - stop = true - io_r.read until io_r.eof? # must drain, or risk closing before writes finish -- broken pipe - io_r.close # must close ??? - thr.join # must ensure that all data desired to be written is actually written end end