blib/lib/IO/Async/Stream.pm

filter: Statementstmt 94.7% 358 / 378 Branchbran 78.7% 167 / 212 Conditioncond 68.8% 86 / 125 MC/DCmcdc 46.4% 33 / 71 Subroutinesub 93.3% 56 / 60 Podpod 100% 24 / 24 totaltotal 83.2% 724 / 870 CC 150 SCAR 28.3
CC
150
Cov
85%
_flush_one_write
42.8
configure
31.3
_do_read
25.2
CRAP 17.0
« blib/lib/IO/Async/Resolver.pm ↑ Summary blib/lib/IO/Async/Process.pm »
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2006-2024 -- leonerd@leonerd.org.uk
5  
6 package IO::Async::Stream 0.805;
7  
8 55 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 55 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 55 ▶use base qw( IO::Async::Handle );
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 55 ▶use Errno qw( EAGAIN EWOULDBLOCK EINTR EPIPE );
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 55 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 55 ▶use Encode 2.11 qw( find_encoding STOP_AT_PARTIAL );
Subroutine BEGIN: called CC=1 SCAR=0.0
18 55 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 55 ▶use Future 0.44; # ->result
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 55 ▶use IO::Async::Debug;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 55 ▶use IO::Async::Metrics '$METRICS';
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 # Tuneable from outside
26 # Not yet documented
27 55 our $READLEN = 8192;
28 55 our $WRITELEN = 8192;
29  
30 55 ▶use Struct::Dumb;
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 # Element of the writequeue
33 55 struct Writer => [qw( data writelen on_write on_flush on_error watching )];
34  
35 # Element of the readqueue
36 55 struct Reader => [qw( on_read future )];
37  
38 # Bitfields in the want flags
39 55 ▶use constant WANT_READ_FOR_READ => 0x01;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 55 ▶use constant WANT_READ_FOR_WRITE => 0x02;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 55 ▶use constant WANT_WRITE_FOR_READ => 0x04;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 55 ▶use constant WANT_WRITE_FOR_WRITE => 0x08;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 55 ▶use constant WANT_ANY_READ => WANT_READ_FOR_READ |WANT_READ_FOR_WRITE;
Subroutine BEGIN: called CC=1 SCAR=0.0
44 55 ▶use constant WANT_ANY_WRITE => WANT_WRITE_FOR_READ|WANT_WRITE_FOR_WRITE;
Subroutine BEGIN: called CC=1 SCAR=0.0
45  
46 =head1 NAME
47  
48 C<IO::Async::Stream> - event callbacks and write bufering for a stream
49 filehandle
50  
51 =head1 SYNOPSIS
52  
53 =for highlighter language=perl
54  
55 use IO::Async::Stream;
56  
57 use IO::Async::Loop;
58 my $loop = IO::Async::Loop->new;
59  
60 my $stream = IO::Async::Stream->new(
61 read_handle => \*STDIN,
62 write_handle => \*STDOUT,
63  
64 on_read => sub {
65 my ( $self, $buffref, $eof ) = @_;
66  
67 while( $$buffref =~ s/^(.*\n)// ) {
68 print "Received a line $1";
69 }
70  
71 if( $eof ) {
72 print "EOF; last partial line is $$buffref\n";
73 }
74  
75 return 0;
76 }
77 );
78  
79 $loop->add( $stream );
80  
81 $stream->write( "An initial line here\n" );
82  
83 =head1 DESCRIPTION
84  
85 This subclass of L<IO::Async::Handle> contains a filehandle that represents
86 a byte-stream. It provides buffering for both incoming and outgoing data. It
87 invokes the C<on_read> handler when new data is read from the filehandle. Data
88 may be written to the filehandle by calling the C<write> method.
89  
90 This class is suitable for any kind of filehandle that provides a
91 possibly-bidirectional reliable byte stream, such as a pipe, TTY, or
92 C<SOCK_STREAM> socket (such as TCP or a byte-oriented UNIX local socket). For
93 datagram or raw message-based sockets (such as UDP) see instead
94 L<IO::Async::Socket>.
95  
96 =cut
97  
98 =head1 EVENTS
99  
100 The following events are invoked, either using subclass methods or CODE
101 references in parameters:
102  
103 =head2 $ret = on_read \$buffer, $eof
104  
105 Invoked when more data is available in the internal receiving buffer.
106  
107 The first argument is a reference to a plain perl string. The code should
108 inspect and remove any data it likes, but is not required to remove all, or
109 indeed any of the data. Any data remaining in the buffer will be preserved for
110 the next call, the next time more data is received from the handle.
111  
112 In this way, it is easy to implement code that reads records of some form when
113 completed, but ignores partially-received records, until all the data is
114 present. If the handler wishes to be immediately invoke a second time, to have
115 another attempt at consuming more content, it should return C<1>. Otherwise,
116 it should return C<0>, and the handler will next be invoked when more data has
117 arrived from the underlying read handle and appended to the buffer. This makes
118 it easy to implement code that handles multiple incoming records at the same
119 time. Alternatively, if the handler function already attempts to consume as
120 much as possible from the buffer, it will have no need to return C<1> at all.
121 See the examples at the end of this documentation for more detail.
122  
123 The second argument is a scalar indicating whether the stream has reported an
124 end-of-file (EOF) condition. A reference to the buffer is passed to the
125 handler in the usual way, so it may inspect data contained in it. Once the
126 handler returns a false value, it will not be called again, as the handle is
127 now at EOF and no more data can arrive.
128  
129 The C<on_read> code may also dynamically replace itself with a new callback
130 by returning a CODE reference instead of C<0> or C<1>. The original callback
131 or method that the object first started with may be restored by returning
132 C<undef>. Whenever the callback is changed in this way, the new code is called
133 again; even if the read buffer is currently empty. See the examples at the end
134 of this documentation for more detail.
135  
136 The C<push_on_read> method can be used to insert new, temporary handlers that
137 take precedence over the global C<on_read> handler. This event is only used if
138 there are no further pending handlers created by C<push_on_read>.
139  
140 =head2 on_read_eof
141  
142 Optional. Invoked when the read handle indicates an end-of-file (EOF)
143 condition. If there is any data in the buffer still to be processed, the
144 C<on_read> event will be invoked first, before this one.
145  
146 =head2 on_write_eof
147  
148 Optional. Invoked when the write handle indicates an end-of-file (EOF)
149 condition. Note that this condition can only be detected after a C<write>
150 syscall returns the C<EPIPE> error. If there is no data pending to be written
151 then it will not be detected yet.
152  
153 =head2 on_read_error $errno
154  
155 Optional. Invoked when the C<sysread> method on the read handle fails.
156  
157 =head2 on_write_error $errno
158  
159 Optional. Invoked when the C<syswrite> method on the write handle fails.
160  
161 The C<on_read_error> and C<on_write_error> handlers are passed the value of
162 C<$!> at the time the error occurred. (The C<$!> variable itself, by its
163 nature, may have changed from the original error by the time this handler
164 runs so it should always use the value passed in).
165  
166 If an error occurs when the corresponding error callback is not supplied, and
167 there is not a handler for it, then the C<close> method is called instead.
168  
169 =head2 on_read_high_watermark $length
170  
171 =head2 on_read_low_watermark $length
172  
173 Optional. Invoked when the read buffer grows larger than the high watermark
174 or smaller than the low watermark respectively. These are edge-triggered
175 events; they will only be triggered once per crossing, not continuously while
176 the buffer remains above or below the given limit.
177  
178 If these event handlers are not defined, the default behaviour is to disable
179 read-ready notifications if the read buffer grows larger than the high
180 watermark (so as to avoid it growing arbitrarily if nothing is consuming it),
181 and re-enable notifications again once something has read enough to cause it to
182 drop. If these events are overridden, the overriding code will have to perform
183 this behaviour if required, by using
184  
185 $self->want_readready_for_read(...);
186  
187 =head2 on_outgoing_empty
188  
189 Optional. Invoked when the writing data buffer becomes empty.
190  
191 =head2 on_writeable_start
192  
193 =head2 on_writeable_stop
194  
195 Optional. These two events inform when the filehandle becomes writeable, and
196 when it stops being writeable. C<on_writeable_start> is invoked by the
197 C<on_write_ready> event if previously it was known to be not writeable.
198 C<on_writeable_stop> is invoked after a C<syswrite> operation fails with
199 C<EAGAIN> or C<EWOULDBLOCK>. These two events track the writeability state,
200 and ensure that only state change cause events to be invoked. A stream starts
201 off being presumed writeable, so the first of these events to be observed will
202 be C<on_writeable_stop>.
203  
204 =cut
205  
206 sub _init
207 {
208 706 ▶ my $self = shift;
Subroutine _init: called CC=1 SCAR=0.0
209  
210 706 $self->{writequeue} = []; # Queue of Writers
211 706 $self->{readqueue} = []; # Queue of Readers
212 706 $self->{writeable} = 1; # "innocent until proven guilty" (by means of EAGAIN)
213 706 $self->{readbuff} = "";
214  
215 706 $self->{reader} = "_sysread";
216 706 $self->{writer} = "_syswrite";
217  
218 706 $self->{read_len} = $READLEN;
219 706 $self->{write_len} = $WRITELEN;
220  
221 706 $self->{want} = WANT_READ_FOR_READ;
222  
223 706 $self->{close_on_read_eof} = 1;
224 }
225  
226 =head1 PARAMETERS
227  
228 The following named parameters may be passed to C<new> or C<configure>:
229  
230 =head2 read_handle => IO
231  
232 The IO handle to read from. Must implement C<fileno> and C<sysread> methods.
233  
234 =head2 write_handle => IO
235  
236 The IO handle to write to. Must implement C<fileno> and C<syswrite> methods.
237  
238 =head2 handle => IO
239  
240 Shortcut to specifying the same IO handle for both of the above.
241  
242 =head2 on_read => CODE
243  
244 =head2 on_read_error => CODE
245  
246 =head2 on_outgoing_empty => CODE
247  
248 =head2 on_write_error => CODE
249  
250 =head2 on_writeable_start => CODE
251  
252 =head2 on_writeable_stop => CODE
253  
254 CODE references for event handlers.
255  
256 =head2 autoflush => BOOL
257  
258 Optional. If true, the C<write> method will attempt to write data to the
259 operating system immediately, without waiting for the loop to indicate the
260 filehandle is write-ready. This is useful, for example, on streams that should
261 contain up-to-date logging or console information.
262  
263 It currently defaults to false for any file handle, but future versions of
264 L<IO::Async> may enable this by default on STDOUT and STDERR.
265  
266 =head2 read_len => INT
267  
268 Optional. Sets the buffer size for C<read> calls. Defaults to 8 KiBytes.
269  
270 =head2 read_all => BOOL
271  
272 Optional. If true, attempt to read as much data from the kernel as possible
273 when the handle becomes readable. By default this is turned off, meaning at
274 most one fixed-size buffer is read. If there is still more data in the
275 kernel's buffer, the handle will still be readable, and will be read from
276 again.
277  
278 This behaviour allows multiple streams and sockets to be multiplexed
279 simultaneously, meaning that a large bulk transfer on one cannot starve other
280 filehandles of processing time. Turning this option on may improve bulk data
281 transfer rate, at the risk of delaying or stalling processing on other
282 filehandles.
283  
284 =head2 write_len => INT
285  
286 Optional. Sets the buffer size for C<write> calls. Defaults to 8 KiBytes.
287  
288 =head2 write_all => BOOL
289  
290 Optional. Analogous to the C<read_all> option, but for writing. When
291 C<autoflush> is enabled, this option only affects deferred writing if the
292 initial attempt failed due to buffer space.
293  
294 =head2 read_high_watermark => INT
295  
296 =head2 read_low_watermark => INT
297  
298 Optional. If defined, gives a way to implement flow control or other
299 behaviours that depend on the size of Stream's read buffer.
300  
301 If after more data is read from the underlying filehandle the read buffer is
302 now larger than the high watermark, the C<on_read_high_watermark> event is
303 triggered (which, by default, will disable read-ready notifications and pause
304 reading from the filehandle).
305  
306 If after data is consumed by an C<on_read> handler the read buffer is now
307 smaller than the low watermark, the C<on_read_low_watermark> event is
308 triggered (which, by default, will re-enable read-ready notifications and
309 resume reading from the filehandle). For to be possible, the read handler
310 would have to be one added by the C<push_on_read> method or one of the
311 Future-returning C<read_*> methods.
312  
313 By default these options are not defined, so this behaviour will not happen.
314 C<read_low_watermark> may not be set to a larger value than
315 C<read_high_watermark>, but it may be set to a smaller value, creating a
316 hysteresis region. If either option is defined then both must be.
317  
318 If these options are used with the default event handlers, be careful not to
319 cause deadlocks by having a high watermark sufficiently low that a single
320 C<on_read> invocation might not consider it finished yet.
321  
322 =head2 reader => STRING|CODE
323  
324 =head2 writer => STRING|CODE
325  
326 Optional. If defined, gives the name of a method or a CODE reference to use
327 to implement the actual reading from or writing to the filehandle. These will
328 be invoked as
329  
330 $stream->reader( $read_handle, $buffer, $len );
331 $stream->writer( $write_handle, $buffer, $len );
332  
333 Each is expected to modify the passed buffer; C<reader> by appending to it,
334 C<writer> by removing a prefix from it. Each is expected to return a true
335 value on success, zero on EOF, or C<undef> with C<$!> set for errors. If not
336 provided, they will be substituted by implenentations using C<sysread> and
337 C<syswrite> on the underlying handle, respectively.
338  
339 =head2 close_on_read_eof => BOOL
340  
341 Optional. Usually true, but if set to a false value then the stream will not
342 be C<close>d when an EOF condition occurs on read. This is normally not useful
343 as at that point the underlying stream filehandle is no longer useable, but it
344 may be useful for reading regular files, or interacting with TTY devices.
345  
346 =head2 encoding => STRING
347  
348 If supplied, sets the name of encoding of the underlying stream. If an
349 encoding is set, then the C<write> method will expect to receive Unicode
350 strings and encodes them into bytes, and incoming bytes will be decoded into
351 Unicode strings for the C<on_read> event.
352  
353 If an encoding is not supplied then C<write> and C<on_read> will work in byte
354 strings.
355  
356 I<IMPORTANT NOTE:> in order to handle reads of UTF-8 content or other
357 multibyte encodings, the code implementing the C<on_read> event uses a feature
358 of L<Encode>; the C<STOP_AT_PARTIAL> flag. While this flag has existed for a
359 while and is used by the C<:encoding> PerlIO layer itself for similar
360 purposes, the flag is not officially documented by the C<Encode> module. In
361 principle this undocumented feature could be subject to change, in practice I
362 believe it to be reasonably stable.
363  
364 This note applies only to the C<on_read> event; data written using the
365 C<write> method does not rely on any undocumented features of C<Encode>.
366  
367 If a read handle is given, it is required that either an C<on_read> callback
368 reference is configured, or that the object provides an C<on_read> method. It
369 is optional whether either is true for C<on_outgoing_empty>; if neither is
370 supplied then no action will be taken when the writing buffer becomes empty.
371  
372 An C<on_read> handler may be supplied even if no read handle is yet given, to
373 be used when a read handle is eventually provided by the C<set_handles>
374 method.
375  
376 This condition is checked at the time the object is added to a Loop; it is
377 allowed to create a C<IO::Async::Stream> object with a read handle but without
378 a C<on_read> handler, provided that one is later given using C<configure>
379 before the stream is added to its containing Loop, either directly or by being
380 a child of another Notifier already in a Loop, or added to one.
381  
382 =cut
383  
384 sub configure
385 {
386 985 ▶ my $self = shift;
Subroutine configure: called CC=22 SCAR=34.4
Pod documented
387 985 my %params = @_;
388  
389 985 for (qw( on_read on_outgoing_empty on_read_eof on_write_eof on_read_error
390 on_write_error on_writeable_start on_writeable_stop autoflush
391 read_len read_all write_len write_all on_read_high_watermark
392 on_read_low_watermark reader writer close_on_read_eof )) {
393 17730 ▶ $self->{$_} = delete $params{$_} if exists $params{$_};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{$_} 820 16910 17730
394 }
395  
396 985 ▶ if( exists $params{read_high_watermark} or exists $params{read_low_watermark} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"read_high_watermark"} or exists $params{"read_low_watermark"}) 1 984 985
Condition66%2/3
exists $params{"read_high_watermark"} or exists $params{"read_low_watermark"}
l!l&&r!l&&!r
10984
MC/DC50%1/2
exists $params{"read_high_watermark"} or exists $params{"read_low_watermark"}
exists $params{"read_high_watermark"} exists $params{"read_low_watermark"}
Truth table66%2/3
A or B
A= exists $params{"read_high_watermark"}B= exists $params{"read_low_watermark"}
ABresult
1X1
011
000
397 1 ▶ my $high = delete $params{read_high_watermark} // $self->{read_high_watermark};
Condition33%1/3
delete $params{"read_high_watermark"} // $self->{"read_high_watermark"}
l!l&&r!l&&!r
100
MC/DC0%0/2
delete $params{"read_high_watermark"} // $self->{"read_high_watermark"}
delete $params{"read_high_watermark"} $self->{"read_high_watermark"}
Truth table33%1/3
A // B
A= delete $params{"read_high_watermark"}B= $self->{"read_high_watermark"}
ABresult
1X1
011
000
398 1 ▶ my $low = delete $params{read_low_watermark} // $self->{read_low_watermark};
Condition33%1/3
delete $params{"read_low_watermark"} // $self->{"read_low_watermark"}
l!l&&r!l&&!r
100
MC/DC0%0/2
delete $params{"read_low_watermark"} // $self->{"read_low_watermark"}
delete $params{"read_low_watermark"} $self->{"read_low_watermark"}
Truth table33%1/3
A // B
A= delete $params{"read_low_watermark"}B= $self->{"read_low_watermark"}
ABresult
1X1
011
000
399  
400 1 ▶ croak "Cannot set read_low_watermark without read_high_watermark" if defined $low and !defined $high;
Branch: 1 branch
BranchTrueFalseTotal
if defined $low and not defined $high 0 1 1
Condition33%1/3
defined $low and not defined $high
!ll&&!rl&&r
010
MC/DC0%0/2
defined $low and not defined $high
defined $low not defined $high
Truth table33%1/3
A and not(B)
A= defined $lowB= not defined $high
ABresult
0X0
100
111
401 1 ▶ croak "Cannot set read_high_watermark without read_low_watermark" if defined $high and !defined $low;
Branch: 1 branch
BranchTrueFalseTotal
if defined $high and not defined $low 0 1 1
Condition33%1/3
defined $high and not defined $low
!ll&&!rl&&r
010
MC/DC0%0/2
defined $high and not defined $low
defined $high not defined $low
Truth table33%1/3
A and not(B)
A= defined $highB= not defined $low
ABresult
0X0
100
111
402  
403 1 ▶ croak "Cannot set read_low_watermark higher than read_high_watermark" if defined $low and defined $high and $low > $high;
Branch: 1 branch
BranchTrueFalseTotal
if defined $low and defined $high and $low > $high 0 1 1
Condition33%2/6
defined $low and defined $high and $low > $high
!ll&&!rl&&r
010
defined $low and defined $high
!ll&&!rl&&r
001
MC/DC0%0/3
defined $low and defined $high and $low > $high
defined $low defined $high $low > $high
Truth table25%1/4
A and B and C
A= defined $lowB= defined $highC= $low > $high
ABCresult
0XX0
10X0
1100
1111
404  
405 1 $self->{read_high_watermark} = $high;
406 1 $self->{read_low_watermark} = $low;
407  
408 # TODO: reassert levels if we've moved them
409 }
410  
411 985 ▶ if( exists $params{encoding} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"encoding"}) 2 983 985
412 2 my $encoding = delete $params{encoding};
413 2 my $obj = find_encoding( $encoding );
414 2 ▶ defined $obj or croak "Cannot handle an encoding of '$encoding'";
Branch: 1 branch
BranchTrueFalseTotal
defined $obj or croak("Cannot handle an encoding of '${encoding}'") 0 2 2
415 2 $self->{encoding} = $obj;
416 }
417  
418 985 $self->SUPER::configure( %params );
419  
420 985 ▶ if( $self->loop and $self->read_handle ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->loop and $self->read_handle) 5 980 985
Condition100%3/3
$self->loop and $self->read_handle
!ll&&!rl&&r
97555
MC/DC100%2/2
$self->loop and $self->read_handle
$self->loop $self->read_handle
Truth table100%3/3
A and B
A= $self->loopB= $self->read_handle
ABresult
0X0
100
111
421 5 ▶ $self->can_event( "on_read" ) or
Branch: 1 branch
BranchTrueFalseTotal
$self->can_event("on_read") or croak("Expected either an on_read callback or to be able to ->on_read") 0 5 5
422 croak 'Expected either an on_read callback or to be able to ->on_read';
423 }
424  
425 985 ▶ if( $self->{autoflush} and my $write_handle = $self->write_handle ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"autoflush"} and my $write_handle = $self->write_handle) 62 923 985
Condition100%3/3
$self->{"autoflush"} and my $write_handle = $self->write_handle
!ll&&!rl&&r
8556862
MC/DC100%2/2
$self->{"autoflush"} and my $write_handle = $self->write_handle
$self->{"autoflush"} my $write_handle = $self->write_handle
Truth table100%3/3
A and B
A= $self->{"autoflush"}B= my $write_handle = $self->write_handle
ABresult
0X0
100
111
426 62 ▶ carp "An IO::Async::Stream with autoflush needs an O_NONBLOCK write handle"
Branch: 1 branch
BranchTrueFalseTotal
if $write_handle->blocking 0 62 62
427 if $write_handle->blocking;
428 }
429 }
430  
431 sub _add_to_loop
432 {
433 697 ▶ my $self = shift;
Subroutine _add_to_loop: called CC=4 SCAR=13.9
434  
435 697 ▶ if( defined $self->read_handle ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->read_handle) 586 111 697
436 586 ▶ $self->can_event( "on_read" ) or
Branch: 1 branch
BranchTrueFalseTotal
$self->can_event("on_read") or croak("Expected either an on_read callback or to be able to ->on_read") 1 585 586
437 croak 'Expected either an on_read callback or to be able to ->on_read';
438 }
439  
440 696 $self->SUPER::_add_to_loop( @_ );
441  
442 696 ▶ if( !$self->_is_empty ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->_is_empty) 39 657 696
443 39 $self->want_writeready_for_write( 1 );
444 }
445 }
446  
447 =head1 METHODS
448  
449 The following methods documented in C<await> expressions return L<Future>
450 instances.
451  
452 =cut
453  
454 =head2 want_readready_for_read
455  
456 =head2 want_readready_for_write
457  
458 $stream->want_readready_for_read( $set );
459  
460 $stream->want_readready_for_write( $set );
461  
462 Mutators for the C<want_readready> property on L<IO::Async::Handle>, which
463 control whether the C<read> or C<write> behaviour should be continued once the
464 filehandle becomes ready for read.
465  
466 Normally, C<want_readready_for_read> is always true (though the read watermark
467 behaviour can modify it), and C<want_readready_for_write> is not used.
468 However, if a custom C<writer> function is provided, it may find this useful
469 for being invoked again if it cannot proceed with a write operation until the
470 filehandle becomes readable (such as during transport negotiation or SSL key
471 management, for example).
472  
473 =cut
474  
475 sub want_readready_for_read
476 {
477 0 ▶ my $self = shift;
Subroutine want_readready_for_read: not called CC=3 SCAR=24.8
Pod documented
478 0 my ( $set ) = @_;
479 0 ▶ $set ? ( $self->{want} |= WANT_READ_FOR_READ ) : ( $self->{want} &= ~WANT_READ_FOR_READ );
Branch: 1 branch
BranchTrueFalseTotal
$set ? : 0 0 0
480  
481 0 ▶ $self->want_readready( $self->{want} & WANT_ANY_READ ) if $self->read_handle;
Branch: 1 branch
BranchTrueFalseTotal
if $self->read_handle 0 0 0
482 }
483  
484 sub want_readready_for_write
485 {
486 1 ▶ my $self = shift;
Subroutine want_readready_for_write: called CC=3 SCAR=11.4
Pod documented
487 1 my ( $set ) = @_;
488 1 ▶ $set ? ( $self->{want} |= WANT_READ_FOR_WRITE ) : ( $self->{want} &= ~WANT_READ_FOR_WRITE );
Branch: 1 branch
BranchTrueFalseTotal
$set ? : 1 0 1
489  
490 1 ▶ $self->want_readready( $self->{want} & WANT_ANY_READ ) if $self->read_handle;
Branch: 1 branch
BranchTrueFalseTotal
if $self->read_handle 1 0 1
491 }
492  
493 =head2 want_writeready_for_read
494  
495 =head2 want_writeready_for_write
496  
497 $stream->want_writeready_for_write( $set );
498  
499 $stream->want_writeready_for_read( $set );
500  
501 Mutators for the C<want_writeready> property on L<IO::Async::Handle>, which
502 control whether the C<write> or C<read> behaviour should be continued once the
503 filehandle becomes ready for write.
504  
505 Normally, C<want_writeready_for_write> is managed by the C<write> method and
506 associated flushing, and C<want_writeready_for_read> is not used. However, if
507 a custom C<reader> function is provided, it may find this useful for being
508 invoked again if it cannot proceed with a read operation until the filehandle
509 becomes writable (such as during transport negotiation or SSL key management,
510 for example).
511  
512 =cut
513  
514 sub want_writeready_for_write
515 {
516 221 ▶ my $self = shift;
Subroutine want_writeready_for_write: called CC=3 SCAR=11.0
Pod documented
517 221 my ( $set ) = @_;
518 221 ▶ $set ? ( $self->{want} |= WANT_WRITE_FOR_WRITE ) : ( $self->{want} &= ~WANT_WRITE_FOR_WRITE );
Branch: 1 branch
BranchTrueFalseTotal
$set ? : 67 154 221
519  
520 221 ▶ $self->want_writeready( $self->{want} & WANT_ANY_WRITE ) if $self->write_handle;
Branch: 1 branch
BranchTrueFalseTotal
if $self->write_handle 201 20 221
521 }
522  
523 sub want_writeready_for_read
524 {
525 1 ▶ my $self = shift;
Subroutine want_writeready_for_read: called CC=3 SCAR=11.4
Pod documented
526 1 my ( $set ) = @_;
527 1 ▶ $set ? ( $self->{want} |= WANT_WRITE_FOR_READ ) : ( $self->{want} &= ~WANT_WRITE_FOR_READ );
Branch: 1 branch
BranchTrueFalseTotal
$set ? : 1 0 1
528  
529 1 ▶ $self->want_writeready( $self->{want} & WANT_ANY_WRITE ) if $self->write_handle;
Branch: 1 branch
BranchTrueFalseTotal
if $self->write_handle 1 0 1
530 }
531  
532 # FUNCTION not method
533 sub _nonfatal_error
534 {
535 9 ▶ my ( $errno ) = @_;
Subroutine _nonfatal_error: called CC=3 SCAR=11.4
536  
537 9 ▶ return $errno == EAGAIN ||
Condition66%4/6
$errno == 11 || $errno == 11 || $errno == 4
l!l&&r!l&&!r
306
$errno == 11 or $errno == 11
l!l&&r!l&&!r
306
MC/DC33%1/3
$errno == 11 || $errno == 11 || $errno == 4
$errno == 11 $errno == 11 $errno == 4
Truth table50%2/4
A or B || C
A= $errno == 11B= $errno == 11C= $errno == 4
ABCresult
1XX1
01X1
0011
0000
538 $errno == EWOULDBLOCK ||
539 $errno == EINTR;
540 }
541  
542 sub _is_empty
543 {
544 1315 ▶ my $self = shift;
Subroutine _is_empty: called CC=1 SCAR=0.0
545 1315 return !@{ $self->{writequeue} };
546 }
547  
548 =head2 close
549  
550 $stream->close;
551  
552 A synonym for C<close_when_empty>. This should not be used when the deferred
553 wait behaviour is required, as the behaviour of C<close> may change in a
554 future version of L<IO::Async>. Instead, call C<close_when_empty> directly.
555  
556 =cut
557  
558 sub close
559 {
560 8 ▶ my $self = shift;
Subroutine close: called CC=1 SCAR=0.0
Pod documented
561 8 $self->close_when_empty;
562 }
563  
564 =head2 close_when_empty
565  
566 $stream->close_when_empty;
567  
568 If the write buffer is empty, this method calls C<close> on the underlying IO
569 handles, and removes the stream from its containing loop. If the write buffer
570 still contains data, then this is deferred until the buffer is empty. This is
571 intended for "write-then-close" one-shot streams.
572  
573 $stream->write( "Here is my final data\n" );
574 $stream->close_when_empty;
575  
576 Because of this deferred nature, it may not be suitable for error handling.
577 See instead the C<close_now> method.
578  
579 =cut
580  
581 sub close_when_empty
582 {
583 173 ▶ my $self = shift;
Subroutine close_when_empty: called CC=2 SCAR=6.9
Pod documented
584  
585 173 ▶ return $self->SUPER::close if $self->_is_empty;
Branch: 1 branch
BranchTrueFalseTotal
if $self->_is_empty 165 8 173
586  
587 8 $self->{stream_closing} = 1;
588 }
589  
590 =head2 close_now
591  
592 $stream->close_now;
593  
594 This method immediately closes the underlying IO handles and removes the
595 stream from the containing loop. It will not wait to flush the remaining data
596 in the write buffer.
597  
598 =cut
599  
600 sub close_now
601 {
602 472 ▶ my $self = shift;
Subroutine close_now: called CC=3 SCAR=11.0
Pod documented
603  
604 472 foreach ( @{ $self->{writequeue} } ) {
605 2 ▶ $_->on_error->( $self, "stream closing" ) if $_->on_error;
Branch: 1 branch
BranchTrueFalseTotal
if $_->on_error 1 1 2
606 }
607  
608 472 undef @{ $self->{writequeue} };
609 472 undef $self->{stream_closing};
610  
611 472 $self->SUPER::close;
612 }
613  
614 =head2 is_read_eof
615  
616 =head2 is_write_eof
617  
618 $eof = $stream->is_read_eof;
619  
620 $eof = $stream->is_write_eof;
621  
622 Returns true after an EOF condition is reported on either the read or the
623 write handle, respectively.
624  
625 =cut
626  
627 sub is_read_eof
628 {
629 2 ▶ my $self = shift;
Subroutine is_read_eof: called CC=1 SCAR=0.0
Pod documented
630 2 return $self->{read_eof};
631 }
632  
633 sub is_write_eof
634 {
635 2 ▶ my $self = shift;
Subroutine is_write_eof: called CC=1 SCAR=0.0
Pod documented
636 2 return $self->{write_eof};
637 }
638  
639 =head2 write
640  
641 $stream->write( $data, %params );
642  
643 This method adds data to the outgoing data queue, or writes it immediately,
644 according to the C<autoflush> parameter.
645  
646 If the C<autoflush> option is set, this method will try immediately to write
647 the data to the underlying filehandle. If this completes successfully then it
648 will have been written by the time this method returns. If it fails to write
649 completely, then the data is queued as if C<autoflush> were not set, and will
650 be flushed as normal.
651  
652 C<$data> can either be a plain string, a L<Future>, or a CODE reference. If it
653 is a plain string it is written immediately. If it is not, its value will be
654 used to generate more C<$data> values, eventually leading to strings to be
655 written.
656  
657 If C<$data> is a C<Future>, the Stream will wait until it is ready, and take
658 the single value it yields.
659  
660 If C<$data> is a CODE reference, it will be repeatedly invoked to generate new
661 values. Each time the filehandle is ready to write more data to it, the
662 function is invoked. Once the function has finished generating data it should
663 return undef. The function is passed the Stream object as its first argument.
664  
665 It is allowed that C<Future>s yield CODE references, or CODE references return
666 C<Future>s, as well as plain strings.
667  
668 For example, to stream the contents of an existing opened filehandle:
669  
670 open my $fileh, "<", $path or die "Cannot open $path - $!";
671  
672 $stream->write( sub {
673 my ( $stream ) = @_;
674  
675 sysread $fileh, my $buffer, 8192 or return;
676 return $buffer;
677 } );
678  
679 Takes the following optional named parameters in C<%params>:
680  
681 =over 8
682  
683 =item write_len => INT
684  
685 Overrides the C<write_len> parameter for the data written by this call.
686  
687 =item on_write => CODE
688  
689 A CODE reference which will be invoked after every successful C<syswrite>
690 operation on the underlying filehandle. It will be passed the number of bytes
691 that were written by this call, which may not be the entire length of the
692 buffer - if it takes more than one C<syscall> operation to empty the buffer
693 then this callback will be invoked multiple times.
694  
695 $on_write->( $stream, $len );
696  
697 =item on_flush => CODE
698  
699 A CODE reference which will be invoked once the data queued by this C<write>
700 call has been flushed. This will be invoked even if the buffer itself is not
701 yet empty; if more data has been queued since the call.
702  
703 $on_flush->( $stream );
704  
705 =item on_error => CODE
706  
707 A CODE reference which will be invoked if a C<syswrite> error happens while
708 performing this write. Invoked as for the C<Stream>'s C<on_write_error> event.
709  
710 $on_error->( $stream, $errno );
711  
712 =back
713  
714 If the object is not yet a member of a loop and doesn't yet have a
715 C<write_handle>, then calls to the C<write> method will simply queue the data
716 and return. It will be flushed when the object is added to the loop.
717  
718 If C<$data> is a defined but empty string, the write is still queued, and the
719 C<on_flush> continuation will be invoked, if supplied. This can be used to
720 obtain a marker, to invoke some code once the output queue has been flushed up
721 to this point.
722  
723 =head2 write (scalar)
724  
725 await $stream->write( ... );
726  
727 If called in non-void context, this method returns a L<Future> which will
728 complete (with no value) when the write operation has been flushed. This may
729 be used as an alternative to, or combined with, the C<on_flush> callback.
730  
731 =cut
732  
733 sub _syswrite
734 {
735 164 ▶ my $self = shift;
Subroutine _syswrite: called CC=2 SCAR=6.9
736 164 my ( $handle, undef, $len ) = @_;
737  
738 164 my $written = $handle->syswrite( $_[1], $len );
739 164 ▶ return $written if !$written; # zero or undef
Branch: 1 branch
BranchTrueFalseTotal
unless $written 8 156 164
740  
741 156 substr( $_[1], 0, $written ) = "";
742 156 return $written;
743 }
744  
745 sub _flush_one_write
746 {
747 175 ▶ my $self = shift;
Subroutine _flush_one_write: called CC=37 SCAR=37.6
748  
749 175 my $writequeue = $self->{writequeue};
750  
751 175 my $head;
752 175 ▶ while( $head = $writequeue->[0] and ref $head->data ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($head = $writequeue->[0] and ref $head->data) 18 168 186
Condition66%2/3
$head = $writequeue->[0] and ref $head->data
!ll&&!rl&&r
016818
MC/DC50%1/2
$head = $writequeue->[0] and ref $head->data
$head = $writequeue->[0] ref $head->data
Truth table66%2/3
A and B
A= $head = $writequeue->[0]B= ref $head->data
ABresult
0X0
100
111
753 18 ▶ if( ref $head->data eq "CODE" ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $head->data eq 'CODE') { } 12 6 18
elsif (builtin::blessed($head->data) and $head->data->isa('Future')) { } 6 0 6
754 12 my $data = $head->data->( $self );
755 12 ▶ if( !defined $data ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 5 7 12
756 5 ▶ $head->on_flush->( $self ) if $head->on_flush;
Branch: 1 branch
BranchTrueFalseTotal
if $head->on_flush 5 0 5
757 5 shift @$writequeue;
758 5 return 1;
759 }
760 7 ▶ if( !ref $data and my $encoding = $self->{encoding} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $data and my $encoding = $self->{"encoding"}) 1 6 7
Condition100%3/3
not ref $data and my $encoding = $self->{"encoding"}
!ll&&!rl&&r
151
MC/DC100%2/2
not ref $data and my $encoding = $self->{"encoding"}
not ref $data my $encoding = $self->{"encoding"}
Truth table100%3/3
not(A) and B
A= not ref $dataB= my $encoding = $self->{"encoding"}
ABresult
0X0
100
111
761 1 $data = $encoding->encode( $data );
762 }
763 7 unshift @$writequeue, my $new = Writer(
764 $data, $head->writelen, $head->on_write, undef, undef, 0
765 );
766 7 next;
767 }
768 ▶ elsif( blessed $head->data and $head->data->isa( "Future" ) ) {
Condition33%1/3
builtin::blessed($head->data) and $head->data->isa("Future")
!ll&&!rl&&r
006
MC/DC0%0/2
builtin::blessed($head->data) and $head->data->isa("Future")
builtin::blessed($head->data) $head->data->isa("Future")
Truth table33%1/3
A and B
A= builtin::blessed($head->data)B= $head->data->isa("Future")
ABresult
0X0
100
111
769 6 my $f = $head->data;
770 6 ▶ if( !$f->is_ready ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($f->is_ready) 2 4 6
771 2 ▶ return 0 if $head->watching;
Branch: 1 branch
BranchTrueFalseTotal
if $head->watching 0 2 2
772 2 ▶ $f->on_ready( sub { $self->_flush_one_write } );
Subroutine __ANON__: called CC=1 SCAR=0.0
773 2 $head->watching++;
774 2 return 0;
775 }
776 4 my $data = $f->result;
777 4 ▶ if( !ref $data and my $encoding = $self->{encoding} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $data and my $encoding = $self->{"encoding"}) 1 3 4
Condition100%3/3
not ref $data and my $encoding = $self->{"encoding"}
!ll&&!rl&&r
121
MC/DC100%2/2
not ref $data and my $encoding = $self->{"encoding"}
not ref $data my $encoding = $self->{"encoding"}
Truth table100%3/3
not(A) and B
A= not ref $dataB= my $encoding = $self->{"encoding"}
ABresult
0X0
100
111
778 1 $data = $encoding->encode( $data );
779 }
780 4 $head->data = $data;
781 4 next;
782 }
783 else {
784 0 die "Unsure what to do with reference ".ref($head->data)." in write queue";
785 }
786 }
787  
788 168 my $second;
789 168 ▶ while( $second = $writequeue->[1] and
Branch: 1 branch
BranchTrueFalseTotal
if ($second = $writequeue->[1] and not ref $second->data and $head->writelen == $second->writelen and not $head->on_write and not $second->on_write and not $head->on_flush) 1 168 169
Condition73%11/15
$second = $writequeue->[1] and not ref $second->data and $head->writelen == $second->writelen and not $head->on_write and not $second->on_write and not $head->on_flush
!ll&&!rl&&r
16801
$second = $writequeue->[1] and not ref $second->data and $head->writelen == $second->writelen and not $head->on_write and not $second->on_write
!ll&&!rl&&r
16801
$second = $writequeue->[1] and not ref $second->data and $head->writelen == $second->writelen and not $head->on_write
!ll&&!rl&&r
16801
$second = $writequeue->[1] and not ref $second->data and $head->writelen == $second->writelen
!ll&&!rl&&r
16801
$second = $writequeue->[1] and not ref $second->data
!ll&&!rl&&r
16081
MC/DC33%2/6
$second = $writequeue->[1] and not ref $second->data and $head->writelen == $second->writelen and not $head->on_write and not $second->on_write and not $head->on_flush
$second = $writequeue->[1] not ref $second->data $head->writelen == $second->writelen not $head->on_write not $second->on_write not $head->on_flush
Truth table42%3/7
A and not(B) and C and not(D) and not(E) and not(F)
A= $second = $writequeue->[1]B= not ref $second->dataC= $head->writelen == $second->writelenD= not $head->on_writeE= not $second->on_writeF= not $head->on_flush
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
790 !ref $second->data and
791 $head->writelen == $second->writelen and
792 !$head->on_write and !$second->on_write and
793 !$head->on_flush ) {
794 1 $head->data .= $second->data;
795 1 $head->on_write = $second->on_write;
796 1 $head->on_flush = $second->on_flush;
797 1 splice @$writequeue, 1, 1, ();
798 }
799  
800 168 ▶ die "TODO: head data does not contain a plain string" if ref $head->data;
Branch: 1 branch
BranchTrueFalseTotal
if ref $head->data 0 168 168
801  
802 168 ▶ if( $IO::Async::Debug::DEBUG > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($IO::Async::Debug::DEBUG > 1) 0 168 168
803 0 my $data = substr $head->data, 0, $head->writelen;
804 0 $self->debug_printf( "WRITE len=%d", length $data );
805 0 ▶ IO::Async::Debug::log_hexdump( $data ) if $IO::Async::Debug::DEBUG_FLAGS{Sw};
Branch: 1 branch
BranchTrueFalseTotal
if $IO::Async::Debug::DEBUG_FLAGS{"Sw"} 0 0 0
806 }
807  
808 168 my $writer = $self->{writer};
809 168 my $len = $self->$writer( $self->write_handle, $head->data, $head->writelen );
810  
811 168 ▶ if( !defined $len ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $len) 3 165 168
812 3 my $errno = $!;
813  
814 3 ▶ if( $errno == EAGAIN or $errno == EWOULDBLOCK ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($errno == 11 or $errno == 11) 1 2 3
Condition66%2/3
$errno == 11 or $errno == 11
l!l&&r!l&&!r
102
MC/DC50%1/2
$errno == 11 or $errno == 11
$errno == 11 $errno == 11
Truth table66%2/3
A or B
A= $errno == 11B= $errno == 11
ABresult
1X1
011
000
815 1 ▶ $self->maybe_invoke_event( on_writeable_stop => ) if $self->{writeable};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"writeable"} 1 0 1
816 1 $self->{writeable} = 0;
817 }
818  
819 3 ▶ return 0 if _nonfatal_error( $errno );
Branch: 1 branch
BranchTrueFalseTotal
if _nonfatal_error($errno) 1 2 3
820  
821 2 ▶ $self->debug_printf( "WRITE err=%d/%s", $errno, $errno ) if $IO::Async::Debug::DEBUG > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $IO::Async::Debug::DEBUG > 1 0 2 2
822  
823 2 ▶ if( $errno == EPIPE ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($errno == 32) 1 1 2
824 1 $self->debug_printf( "WRITE-EOF" );
825 1 $self->{write_eof} = 1;
826 1 $self->maybe_invoke_event( on_write_eof => );
827 }
828  
829 2 ▶ $head->on_error->( $self, $errno ) if $head->on_error;
Branch: 1 branch
BranchTrueFalseTotal
if $head->on_error 2 0 2
830 2 ▶ $self->maybe_invoke_event( on_write_error => $errno )
Branch: 1 branch
BranchTrueFalseTotal
$self->maybe_invoke_event("on_write_error", $errno) or $self->close_now 1 1 2
831 or $self->close_now;
832  
833 2 return 0;
834 }
835  
836 165 ▶ $METRICS and $METRICS->inc_counter_by( stream_written => $len ) if $len;
Branch: 1 branch
BranchTrueFalseTotal
if $len 159 6 165
Condition66%4/6
$len && ($IO::Async::Stream::METRICS && $IO::Async::Stream::METRICS->inc_counter_by('stream_written', $len))
!ll&&!rl&&r
61590
$IO::Async::Stream::METRICS and $IO::Async::Stream::METRICS->inc_counter_by("stream_written", $len)
!ll&&!rl&&r
122370
MC/DC0%0/3
$len && ($IO::Async::Stream::METRICS && $IO::Async::Stream::METRICS->inc_counter_by('stream_written', $len))
$len $IO::Async::Stream::METRICS $IO::Async::Stream::METRICS->inc_counter_by("stream_written", $len)
Truth table0%0/4
A && B and C
A= $lenB= $IO::Async::Stream::METRICSC= $IO::Async::Stream::METRICS->inc_counter_by("stream_written", $len)
ABCresult
0XX0
10X0
1100
1111
837  
838 165 ▶ if( my $on_write = $head->on_write ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $on_write = $head->on_write) 3 162 165
839 3 $on_write->( $self, $len );
840 }
841  
842 165 ▶ if( !length $head->data ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $head->data) 155 10 165
843 155 ▶ $head->on_flush->( $self ) if $head->on_flush;
Branch: 1 branch
BranchTrueFalseTotal
if $head->on_flush 34 121 155
844 155 shift @{ $self->{writequeue} };
845 }
846  
847 165 return 1;
848 }
849  
850 sub write
851 {
852 167 ▶ my $self = shift;
Subroutine write: called CC=16 SCAR=28.4
Pod documented
853 167 my ( $data, %params ) = @_;
854  
855 167 ▶ carp "Cannot write data to a Stream that is closing" and return if $self->{stream_closing};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stream_closing"} 0 167 167
Condition20%1/5
$self->{'stream_closing'} && (carp('Cannot write data to a Stream that is closing') && (return))
!ll&&!rl&&r
16700
carp("Cannot write data to a Stream that is closing") and return
!ll
00
MC/DC0%0/2
$self->{'stream_closing'} && (carp('Cannot write data to a Stream that is closing') && (return))
$self->{'stream_closing'} carp("Cannot write data to a Stream that is closing")
Truth table33%1/3
A && B
A= $self->{'stream_closing'}B= carp("Cannot write data to a Stream that is closing")
ABresult
0X0
100
111
856  
857 # Allow writes without a filehandle if we're not yet in a Loop, just don't
858 # try to flush them
859 167 my $handle = $self->write_handle;
860  
861 167 ▶ croak "Cannot write data to a Stream with no write_handle" if !$handle and $self->loop;
Branch: 1 branch
BranchTrueFalseTotal
if not $handle and $self->loop 1 166 167
Condition100%3/3
not $handle and $self->loop
!ll&&!rl&&r
130361
MC/DC100%2/2
not $handle and $self->loop
not $handle $self->loop
Truth table100%3/3
not(A) and B
A= not $handleB= $self->loop
ABresult
0X0
100
111
862  
863 166 ▶ if( !ref $data and my $encoding = $self->{encoding} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $data and my $encoding = $self->{"encoding"}) 2 164 166
Condition100%3/3
not ref $data and my $encoding = $self->{"encoding"}
!ll&&!rl&&r
71572
MC/DC100%2/2
not ref $data and my $encoding = $self->{"encoding"}
not ref $data my $encoding = $self->{"encoding"}
Truth table100%3/3
not(A) and B
A= not ref $dataB= my $encoding = $self->{"encoding"}
ABresult
0X0
100
111
864 2 $data = $encoding->encode( $data );
865 }
866  
867 166 my $on_write = delete $params{on_write};
868 166 my $on_flush = delete $params{on_flush};
869 166 my $on_error = delete $params{on_error};
870  
871 166 my $f;
872 166 ▶ if( defined wantarray ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined wantarray) 3 163 166
873 3 my $orig_on_flush = $on_flush;
874 3 my $orig_on_error = $on_error;
875  
876 3 ▶ my $loop = $self->loop or
Branch: 1 branch
BranchTrueFalseTotal
my $loop = $self->loop or croak("Cannot ->write data returning a Future to a Stream not in a Loop") 0 3 3
877 croak "Cannot ->write data returning a Future to a Stream not in a Loop";
878 3 $f = $loop->new_future;
879 $on_flush = sub {
880 1 ▶ $f->done;
Subroutine __ANON__: called CC=2 SCAR=7.2
881 1 ▶ $orig_on_flush->( @_ ) if $orig_on_flush;
Branch: 1 branch
BranchTrueFalseTotal
if $orig_on_flush 1 0 1
882 3 };
883 $on_error = sub {
884 3 ▶ my $self = shift;
Subroutine __ANON__: called CC=3 SCAR=11.0
885 3 my ( $errno ) = @_;
886  
887 3 ▶ $f->fail( "write failed: $errno", syswrite => $errno ) unless $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $f->is_ready 2 1 3
888  
889 3 ▶ $orig_on_error->( $self, @_ ) if $orig_on_error;
Branch: 1 branch
BranchTrueFalseTotal
if $orig_on_error 0 3 3
890 3 };
891 }
892  
893 166 ▶ my $write_len = $params{write_len} // $self->{write_len};
Condition33%1/3
$params{"write_len"} // $self->{"write_len"}
l!l&&r!l&&!r
01660
MC/DC0%0/2
$params{"write_len"} // $self->{"write_len"}
$params{"write_len"} $self->{"write_len"}
Truth table33%1/3
A // B
A= $params{"write_len"}B= $self->{"write_len"}
ABresult
1X1
011
000
894  
895 166 push @{ $self->{writequeue} }, Writer(
896 $data, $write_len, $on_write, $on_flush, $on_error, 0
897 );
898  
899 166 ▶ keys %params and croak "Unrecognised keys for ->write - " . join( ", ", keys %params );
Branch: 1 branch
BranchTrueFalseTotal
keys %params and croak('Unrecognised keys for ->write - ' . join(", ", keys %params)) 0 166 166
900  
901 166 ▶ return $f unless $handle;
Branch: 1 branch
BranchTrueFalseTotal
unless $handle 36 130 166
902  
903 130 ▶ if( $self->{autoflush} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"autoflush"}) 102 28 130
904 102 ▶ 1 while !$self->_is_empty and $self->_flush_one_write;
Branch: 1 branch
BranchTrueFalseTotal
not $self->_is_empty and $self->_flush_one_write and do { '???' } 102 102 204
Condition66%2/3
not $self->_is_empty and $self->_flush_one_write
!ll&&!rl&&r
1020102
MC/DC50%1/2
not $self->_is_empty and $self->_flush_one_write
not $self->_is_empty $self->_flush_one_write
Truth table66%2/3
not(A) and B
A= not $self->_is_emptyB= $self->_flush_one_write
ABresult
0X0
100
111
905  
906 102 ▶ if( $self->_is_empty ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_empty) 102 0 102
907 102 $self->want_writeready_for_write( 0 );
908 102 return $f;
909 }
910 }
911  
912 28 $self->want_writeready_for_write( 1 );
913 28 return $f;
914 }
915  
916 sub on_write_ready
917 {
918 68 ▶ my $self = shift;
Subroutine on_write_ready: called CC=4 SCAR=13.9
Pod documented
919  
920 68 ▶ if( !$self->{writeable} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"writeable"}) 1 67 68
921 1 $self->maybe_invoke_event( on_writeable_start => );
922 1 $self->{writeable} = 1;
923 }
924  
925 68 ▶ $self->_do_write if $self->{want} & WANT_WRITE_FOR_WRITE;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"want"} & 8 67 1 68
926 68 ▶ $self->_do_read if $self->{want} & WANT_WRITE_FOR_READ;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"want"} & 4 1 67 68
927 }
928  
929 sub _do_write
930 {
931 68 ▶ my $self = shift;
Subroutine _do_write: called CC=6 SCAR=17.9
932  
933 68 ▶ 1 while !$self->_is_empty and $self->_flush_one_write and $self->{write_all};
Branch: 1 branch
BranchTrueFalseTotal
not $self->_is_empty and $self->_flush_one_write and $self->{"write_all"} and do { '???' } 4 68 72
Condition100%6/6
not $self->_is_empty and $self->_flush_one_write and $self->{"write_all"}
!ll&&!rl&&r
6624
not $self->_is_empty and $self->_flush_one_write
!ll&&!rl&&r
1566
MC/DC100%3/3
not $self->_is_empty and $self->_flush_one_write and $self->{"write_all"}
not $self->_is_empty $self->_flush_one_write $self->{"write_all"}
Truth table100%4/4
not(A) and B and C
A= not $self->_is_emptyB= $self->_flush_one_writeC= $self->{"write_all"}
ABCresult
0XX0
10X0
1100
1111
934  
935 # All data successfully flushed
936 68 ▶ if( $self->_is_empty ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_empty) 51 17 68
937 51 $self->want_writeready_for_write( 0 );
938  
939 51 $self->maybe_invoke_event( on_outgoing_empty => );
940  
941 51 ▶ $self->close_now if $self->{stream_closing};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stream_closing"} 8 43 51
942 }
943 }
944  
945 sub _flush_one_read
946 {
947 1135 ▶ my $self = shift;
Subroutine _flush_one_read: called CC=11 SCAR=24.0
948 1135 my ( $eof ) = @_;
949  
950 1135 local $self->{flushing_read} = 1;
951  
952 1135 my $readqueue = $self->{readqueue};
953  
954 1135 my $ret;
955 1135 ▶ if( $readqueue->[0] and my $on_read = $readqueue->[0]->on_read ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($readqueue->[0] and my $on_read = $readqueue->[0]->on_read) { } 17 1118 1135
Condition66%2/3
$readqueue->[0] and my $on_read = $readqueue->[0]->on_read
!ll&&!rl&&r
1118017
MC/DC50%1/2
$readqueue->[0] and my $on_read = $readqueue->[0]->on_read
$readqueue->[0] my $on_read = $readqueue->[0]->on_read
Truth table66%2/3
A and B
A= $readqueue->[0]B= my $on_read = $readqueue->[0]->on_read
ABresult
0X0
100
111
956 17 $ret = $on_read->( $self, \$self->{readbuff}, $eof );
957 }
958 else {
959 1118 $ret = $self->invoke_event( on_read => \$self->{readbuff}, $eof );
960 }
961  
962 1135 ▶ if( defined $self->{read_low_watermark} and $self->{at_read_high_watermark} and
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"read_low_watermark"} and $self->{"at_read_high_watermark"} and length $self->{"readbuff"} < $self->{"read_low_watermark"}) 1 1134 1135
Condition83%5/6
defined $self->{"read_low_watermark"} and $self->{"at_read_high_watermark"} and length $self->{"readbuff"} < $self->{"read_low_watermark"}
!ll&&!rl&&r
113401
defined $self->{"read_low_watermark"} and $self->{"at_read_high_watermark"}
!ll&&!rl&&r
113221
MC/DC66%2/3
defined $self->{"read_low_watermark"} and $self->{"at_read_high_watermark"} and length $self->{"readbuff"} < $self->{"read_low_watermark"}
defined $self->{"read_low_watermark"} $self->{"at_read_high_watermark"} length $self->{"readbuff"} < $self->{"read_low_watermark"}
Truth table75%3/4
A and B and C
A= defined $self->{"read_low_watermark"}B= $self->{"at_read_high_watermark"}C= length $self->{"readbuff"} < $self->{"read_low_watermark"}
ABCresult
0XX0
10X0
1100
1111
963 length $self->{readbuff} < $self->{read_low_watermark} ) {
964 1 undef $self->{at_read_high_watermark};
965 1 $self->invoke_event( on_read_low_watermark => length $self->{readbuff} );
966 }
967  
968 1135 ▶ if( ref $ret eq "CODE" ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $ret eq 'CODE') { } 1 1134 1135
elsif (@$readqueue and not defined $ret) { } 13 1121 1134
969 # Replace the top CODE, or add it if there was none
970 1 $readqueue->[0] = Reader( $ret, undef );
971 1 return 1;
972 }
973 ▶ elsif( @$readqueue and !defined $ret ) {
Condition100%3/3
@$readqueue and not defined $ret
!ll&&!rl&&r
1117413
MC/DC100%2/2
@$readqueue and not defined $ret
@$readqueue not defined $ret
Truth table100%3/3
A and not(B)
A= @$readqueueB= not defined $ret
ABresult
0X0
100
111
974 13 shift @$readqueue;
975 13 return 1;
976 }
977 else {
978 1121 ▶ return $ret && ( length( $self->{readbuff} ) > 0 || $eof );
Condition100%6/6
$ret && (length $self->{'readbuff'} > 0 || $eof)
!ll&&!rl&&r
630300191
length $self->{"readbuff"} > 0 or $eof
l!l&&r!l&&!r
20171300
MC/DC100%3/3
$ret && (length $self->{'readbuff'} > 0 || $eof)
$ret length $self->{"readbuff"} > 0 $eof
Truth table100%4/4
A && B or C
A= $retB= length $self->{"readbuff"} > 0C= $eof
ABCresult
0XX0
1000
11X1
1011
979 }
980 }
981  
982 sub _sysread
983 {
984 930 ▶ my $self = shift;
Subroutine _sysread: called CC=1 SCAR=0.0
985 930 my ( $handle, undef, $len ) = @_;
986 930 return $handle->sysread( $_[1], $len );
987 }
988  
989 sub on_read_ready
990 {
991 929 ▶ my $self = shift;
Subroutine on_read_ready: called CC=3 SCAR=11.1
Pod documented
992  
993 929 ▶ $self->_do_read if $self->{want} & WANT_READ_FOR_READ;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"want"} & 1 929 0 929
994 929 ▶ $self->_do_write if $self->{want} & WANT_READ_FOR_WRITE;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"want"} & 2 1 928 929
995 }
996  
997 sub _do_read
998 {
999 930 ▶ my $self = shift;
Subroutine _do_read: called CC=23 SCAR=32.3
1000  
1001 930 my $handle = $self->read_handle;
1002 930 my $reader = $self->{reader};
1003  
1004 930 while(1) {
1005 934 my $data;
1006 934 my $len = $self->$reader( $handle, $data, $self->{read_len} );
1007  
1008 934 ▶ if( !defined $len ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $len) 6 928 934
1009 6 my $errno = $!;
1010  
1011 6 ▶ return if _nonfatal_error( $errno );
Branch: 1 branch
BranchTrueFalseTotal
if _nonfatal_error($errno) 2 4 6
1012  
1013 4 ▶ $self->debug_printf( "READ err=%d/%s", $errno, $errno ) if $IO::Async::Debug::DEBUG > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $IO::Async::Debug::DEBUG > 1 0 4 4
1014  
1015 4 ▶ $self->maybe_invoke_event( on_read_error => $errno )
Branch: 1 branch
BranchTrueFalseTotal
$self->maybe_invoke_event("on_read_error", $errno) or $self->close_now 2 2 4
1016 or $self->close_now;
1017  
1018 4 foreach ( @{ $self->{readqueue} } ) {
1019 1 ▶ $_->future->fail( "read failed: $errno", sysread => $errno ) if $_->future;
Branch: 1 branch
BranchTrueFalseTotal
if $_->future 1 0 1
1020 }
1021 4 undef @{ $self->{readqueue} };
1022  
1023 4 return;
1024 }
1025  
1026 928 ▶ if( $IO::Async::Debug::DEBUG > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($IO::Async::Debug::DEBUG > 1) 0 928 928
1027 0 $self->debug_printf( "READ len=%d", $len );
1028 0 ▶ IO::Async::Debug::log_hexdump( $data ) if $IO::Async::Debug::DEBUG_FLAGS{Sr};
Branch: 1 branch
BranchTrueFalseTotal
if $IO::Async::Debug::DEBUG_FLAGS{"Sr"} 0 0 0
1029 }
1030  
1031 928 ▶ $METRICS and $METRICS->inc_counter_by( stream_read => $len ) if $len;
Branch: 1 branch
BranchTrueFalseTotal
if $len 458 470 928
Condition66%4/6
$len && ($IO::Async::Stream::METRICS && $IO::Async::Stream::METRICS->inc_counter_by('stream_read', $len))
!ll&&!rl&&r
4704580
$IO::Async::Stream::METRICS and $IO::Async::Stream::METRICS->inc_counter_by("stream_read", $len)
!ll&&!rl&&r
415430
MC/DC0%0/3
$len && ($IO::Async::Stream::METRICS && $IO::Async::Stream::METRICS->inc_counter_by('stream_read', $len))
$len $IO::Async::Stream::METRICS $IO::Async::Stream::METRICS->inc_counter_by("stream_read", $len)
Truth table0%0/4
A && B and C
A= $lenB= $IO::Async::Stream::METRICSC= $IO::Async::Stream::METRICS->inc_counter_by("stream_read", $len)
ABCresult
0XX0
10X0
1100
1111
1032  
1033 928 my $eof = $self->{read_eof} = ( $len == 0 );
1034  
1035 928 ▶ if( my $encoding = $self->{encoding} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $encoding = $self->{"encoding"}) 4 924 928
1036 4 ▶ my $bytes = defined $self->{bytes_remaining} ? $self->{bytes_remaining} . $data : $data;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'bytes_remaining'} ? : 3 1 4
1037 4 $data = $encoding->decode( $bytes, STOP_AT_PARTIAL );
1038 4 $self->{bytes_remaining} = $bytes;
1039 }
1040  
1041 928 ▶ $self->{readbuff} .= $data if !$eof;
Branch: 1 branch
BranchTrueFalseTotal
unless $eof 458 470 928
1042  
1043 928 ▶ 1 while $self->_flush_one_read( $eof );
Branch: 1 branch
BranchTrueFalseTotal
$self->_flush_one_read($eof) and do { '???' } 203 928 1131
1044  
1045 928 ▶ if( $eof ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eof) 470 458 928
1046 470 $self->debug_printf( "READ-EOF" );
1047 470 $self->maybe_invoke_event( on_read_eof => );
1048 470 ▶ $self->close_now if $self->{close_on_read_eof};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"close_on_read_eof"} 461 9 470
1049 470 foreach ( @{ $self->{readqueue} } ) {
1050 0 ▶ $_->future->done( undef ) if $_->future;
Branch: 1 branch
BranchTrueFalseTotal
if $_->future 0 0 0
1051 }
1052 470 undef @{ $self->{readqueue} };
1053 470 return;
1054 }
1055  
1056 458 ▶ last unless $self->{read_all};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"read_all"} 454 4 458
1057 }
1058  
1059 454 ▶ if( defined $self->{read_high_watermark} and length $self->{readbuff} >= $self->{read_high_watermark} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"read_high_watermark"} and length $self->{"readbuff"} >= $self->{"read_high_watermark"}) 1 453 454
Condition66%2/3
defined $self->{"read_high_watermark"} and length $self->{"readbuff"} >= $self->{"read_high_watermark"}
!ll&&!rl&&r
45301
MC/DC50%1/2
defined $self->{"read_high_watermark"} and length $self->{"readbuff"} >= $self->{"read_high_watermark"}
defined $self->{"read_high_watermark"} length $self->{"readbuff"} >= $self->{"read_high_watermark"}
Truth table66%2/3
A and B
A= defined $self->{"read_high_watermark"}B= length $self->{"readbuff"} >= $self->{"read_high_watermark"}
ABresult
0X0
100
111
1060 $self->{at_read_high_watermark} or
1061 1 ▶ $self->invoke_event( on_read_high_watermark => length $self->{readbuff} );
Branch: 1 branch
BranchTrueFalseTotal
$self->{"at_read_high_watermark"} or $self->invoke_event("on_read_high_watermark", length $self->{"readbuff"}) 1 0 1
1062  
1063 1 $self->{at_read_high_watermark} = 1;
1064 }
1065 }
1066  
1067 sub on_read_high_watermark
1068 {
1069 0 ▶ my $self = shift;
Subroutine on_read_high_watermark: not called CC=1 SCAR=6.9
Pod documented
1070 0 $self->want_readready_for_read( 0 );
1071 }
1072  
1073 sub on_read_low_watermark
1074 {
1075 0 ▶ my $self = shift;
Subroutine on_read_low_watermark: not called CC=1 SCAR=6.9
Pod documented
1076 0 $self->want_readready_for_read( 1 );
1077 }
1078  
1079 =head2 push_on_read
1080  
1081 $stream->push_on_read( $on_read );
1082  
1083 Pushes a new temporary C<on_read> handler to the end of the queue. This queue,
1084 if non-empty, is used to provide C<on_read> event handling code in preference
1085 to using the object's main event handler or method. New handlers can be
1086 supplied at any time, and they will be used in first-in first-out (FIFO)
1087 order.
1088  
1089 As with the main C<on_read> event handler, each can return a (defined) boolean
1090 to indicate if they wish to be invoked again or not, another C<CODE> reference
1091 to replace themself with, or C<undef> to indicate it is now complete and
1092 should be removed. When a temporary handler returns C<undef> it is shifted
1093 from the queue and the next one, if present, is invoked instead. If there are
1094 no more then the object's main handler is invoked instead.
1095  
1096 =cut
1097  
1098 sub push_on_read
1099 {
1100 13 ▶ my $self = shift;
Subroutine push_on_read: called CC=4 SCAR=13.9
Pod documented
1101 13 my ( $on_read, %args ) = @_;
1102 # %args undocumented for internal use
1103  
1104 13 push @{ $self->{readqueue} }, Reader( $on_read, $args{future} );
1105  
1106 # TODO: Should this always defer?
1107 13 ▶ return if $self->{flushing_read};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"flushing_read"} 1 12 13
1108 12 ▶ 1 while length $self->{readbuff} and $self->_flush_one_read( 0 );
Branch: 1 branch
BranchTrueFalseTotal
length $self->{"readbuff"} and $self->_flush_one_read(0) and do { 1 } 1 12 13
Condition100%3/3
length $self->{"readbuff"} and $self->_flush_one_read(0)
!ll&&!rl&&r
1111
MC/DC100%2/2
length $self->{"readbuff"} and $self->_flush_one_read(0)
length $self->{"readbuff"} $self->_flush_one_read(0)
Truth table100%3/3
A and B
A= length $self->{"readbuff"}B= $self->_flush_one_read(0)
ABresult
0X0
100
111
1109 }
1110  
1111 =head1 FUTURE-RETURNING READ METHODS
1112  
1113 The following methods all return a L<Future> which will become ready when
1114 enough data has been read by the Stream into its buffer. At this point, the
1115 data is removed from the buffer and given to the C<Future> object to complete
1116 it.
1117  
1118 my $string = await $stream->read_...
1119  
1120 Unlike the C<on_read> event handlers, these methods don't allow for access to
1121 "partial" results; they only provide the final result once it is ready.
1122  
1123 If a C<Future> is cancelled before it completes it is removed from the read
1124 queue without consuming any data; i.e. each C<Future> atomically either
1125 completes or is cancelled.
1126  
1127 Since it is possible to use a readable C<Stream> entirely using these
1128 C<Future>-returning methods instead of the C<on_read> event, it may be useful
1129 to configure a trivial return-false event handler to keep it from consuming
1130 any input, and to allow it to be added to a C<Loop> in the first place.
1131  
1132 my $stream = IO::Async::Stream->new( on_read => sub { 0 }, ... );
1133 $loop->add( $stream );
1134  
1135 my $f = $stream->read_...
1136  
1137 If a read EOF or error condition happens while there are read C<Future>s
1138 pending, they are all completed. In the case of a read EOF, they are done with
1139 C<undef>; in the case of a read error they are failed using the C<$!> error
1140 value as the failure.
1141  
1142 $f->fail( $message, sysread => $! )
1143  
1144 If a read EOF condition happens to the currently-processing read C<Future>, it
1145 will return a partial result. The calling code can detect this by the fact
1146 that the returned data is not complete according to the specification (too
1147 short in C<read_exactly>'s case, or lacking the ending pattern in
1148 C<read_until>'s case). Additionally, each C<Future> will yield the C<$eof>
1149 value in its results.
1150  
1151 my ( $string, $eof ) = await ...;
1152  
1153 =cut
1154  
1155 sub _read_future
1156 {
1157 11 ▶ my $self = shift;
Subroutine _read_future: called CC=1 SCAR=0.0
1158 11 my $f = $self->loop->new_future;
1159 $f->on_cancel( $self->_capture_weakself( sub {
1160 1 ▶ my $self = shift or return;
Subroutine __ANON__: called CC=3 SCAR=11.1
Branch: 1 branch
BranchTrueFalseTotal
my $self = shift() or return 0 1 1
1161 1 ▶ 1 while $self->_flush_one_read;
Branch: 1 branch
BranchTrueFalseTotal
$self->_flush_one_read and do { 1 } 1 1 2
1162 11 }));
1163 11 return $f;
1164 }
1165  
1166 =head2 read_atmost
1167  
1168 =head2 read_exactly
1169  
1170 ( $string, $eof ) = await $stream->read_atmost( $len );
1171  
1172 ( $string, $eof ) = await $stream->read_exactly( $len );
1173  
1174 Completes the C<Future> when the read buffer contains C<$len> or more
1175 characters of input. C<read_atmost> will also complete after the first
1176 invocation of C<on_read>, even if fewer characters are available, whereas
1177 C<read_exactly> will wait until at least C<$len> are available.
1178  
1179 =cut
1180  
1181 sub read_atmost
1182 {
1183 2 ▶ my $self = shift;
Subroutine read_atmost: called CC=1 SCAR=0.0
Pod documented
1184 2 my ( $len ) = @_;
1185  
1186 2 my $f = $self->_read_future;
1187 $self->push_on_read( sub {
1188 1 ▶ my ( undef, $buffref, $eof ) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.0
1189 1 ▶ return undef if $f->is_cancelled;
Branch: 1 branch
BranchTrueFalseTotal
if $f->is_cancelled 0 1 1
1190 1 $f->done( substr( $$buffref, 0, $len, "" ), $eof );
1191 1 return undef;
1192 2 }, future => $f );
1193 2 return $f;
1194 }
1195  
1196 sub read_exactly
1197 {
1198 4 ▶ my $self = shift;
Subroutine read_exactly: called CC=1 SCAR=0.1
Pod documented
1199 4 my ( $len ) = @_;
1200  
1201 4 my $f = $self->_read_future;
1202 $self->push_on_read( sub {
1203 4 ▶ my ( undef, $buffref, $eof ) = @_;
Subroutine __ANON__: called CC=4 SCAR=15.2
1204 4 ▶ return undef if $f->is_cancelled;
Branch: 1 branch
BranchTrueFalseTotal
if $f->is_cancelled 0 4 4
1205 4 ▶ return 0 unless $eof or length $$buffref >= $len;
Branch: 1 branch
BranchTrueFalseTotal
unless $eof or length $$buffref >= $len 0 4 4
Condition33%1/3
$eof or length $$buffref >= $len
l!l&&r!l&&!r
040
MC/DC0%0/2
$eof or length $$buffref >= $len
$eof length $$buffref >= $len
Truth table33%1/3
A or B
A= $eofB= length $$buffref >= $len
ABresult
1X1
011
000
1206 4 $f->done( substr( $$buffref, 0, $len, "" ), $eof );
1207 4 return undef;
1208 4 }, future => $f );
1209 4 return $f;
1210 }
1211  
1212 =head2 read_until
1213  
1214 ( $string, $eof ) = await $stream->read_until( $end );
1215  
1216 Completes the C<Future> when the read buffer contains a match for C<$end>,
1217 which may either be a plain string or a compiled C<Regexp> reference. Yields
1218 the prefix of the buffer up to and including this match.
1219  
1220 =cut
1221  
1222 sub read_until
1223 {
1224 4 ▶ my $self = shift;
Subroutine read_until: called CC=2 SCAR=7.0
Pod documented
1225 4 my ( $until ) = @_;
1226  
1227 4 ▶ ref $until or $until = qr/\Q$until\E/;
Branch: 1 branch
BranchTrueFalseTotal
ref $until or $until = qr/\Q$until\E/u 3 1 4
1228  
1229 4 my $f = $self->_read_future;
1230 $self->push_on_read( sub {
1231 5 ▶ my ( undef, $buffref, $eof ) = @_;
Subroutine __ANON__: called CC=4 SCAR=14.6
1232 5 ▶ return undef if $f->is_cancelled;
Branch: 1 branch
BranchTrueFalseTotal
if $f->is_cancelled 1 4 5
1233 4 ▶ if( $$buffref =~ $until ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$buffref =~ /$until/u) { } 3 1 4
elsif ($eof) { } 0 1 1
1234 3 $f->done( substr( $$buffref, 0, $+[0], "" ), $eof );
1235 3 return undef;
1236 }
1237 elsif( $eof ) {
1238 0 $f->done( $$buffref, $eof ); $$buffref = "";
1239 0 return undef;
1240 }
1241 else {
1242 1 return 0;
1243 }
1244 4 }, future => $f );
1245 4 return $f;
1246 }
1247  
1248 =head2 read_until_eof
1249  
1250 ( $string, $eof ) = await $stream->read_until_eof;
1251  
1252 Completes the C<Future> when the stream is eventually closed at EOF, and
1253 yields all of the data that was available.
1254  
1255 =cut
1256  
1257 sub read_until_eof
1258 {
1259 1 ▶ my $self = shift;
Subroutine read_until_eof: called CC=1 SCAR=0.0
Pod documented
1260  
1261 1 my $f = $self->_read_future;
1262 $self->push_on_read( sub {
1263 2 ▶ my ( undef, $buffref, $eof ) = @_;
Subroutine __ANON__: called CC=3 SCAR=11.0
1264 2 ▶ return undef if $f->is_cancelled;
Branch: 1 branch
BranchTrueFalseTotal
if $f->is_cancelled 0 2 2
1265 2 ▶ return 0 unless $eof;
Branch: 1 branch
BranchTrueFalseTotal
unless $eof 1 1 2
1266 1 $f->done( $$buffref, $eof ); $$buffref = "";
1267 1 return undef;
1268 1 }, future => $f );
1269 1 return $f;
1270 }
1271  
1272 =head1 UTILITY CONSTRUCTORS
1273  
1274 =cut
1275  
1276 =head2 new_for_stdin
1277  
1278 =head2 new_for_stdout
1279  
1280 =head2 new_for_stdio
1281  
1282 $stream = IO::Async::Stream->new_for_stdin;
1283  
1284 $stream = IO::Async::Stream->new_for_stdout;
1285  
1286 $stream = IO::Async::Stream->new_for_stdio;
1287  
1288 Return a C<IO::Async::Stream> object preconfigured with the correct
1289 C<read_handle>, C<write_handle> or both.
1290  
1291 =cut
1292  
1293 1 ▶sub new_for_stdin { shift->new( read_handle => \*STDIN, @_ ) }
Subroutine new_for_stdin: called CC=1 SCAR=0.0
Pod documented
1294 1 ▶sub new_for_stdout { shift->new( write_handle => \*STDOUT, @_ ) }
Subroutine new_for_stdout: called CC=1 SCAR=0.0
Pod documented
1295  
1296 1 ▶sub new_for_stdio { shift->new( read_handle => \*STDIN, write_handle => \*STDOUT, @_ ) }
Subroutine new_for_stdio: called CC=1 SCAR=0.0
Pod documented
1297  
1298 =head2 connect
1299  
1300 $future = $stream->connect( %args );
1301  
1302 A convenient wrapper for calling the C<connect> method on the underlying
1303 L<IO::Async::Loop> object, passing the C<socktype> hint as C<stream> if not
1304 otherwise supplied.
1305  
1306 =cut
1307  
1308 sub connect
1309 {
1310 0 ▶ my $self = shift;
Subroutine connect: not called CC=1 SCAR=6.9
Pod documented
1311 0 return $self->SUPER::connect( socktype => "stream", @_ );
1312 }
1313  
1314 =head1 DEBUGGING FLAGS
1315  
1316 The following flags in C<IO_ASYNC_DEBUG_FLAGS> enable extra logging:
1317  
1318 =over 4
1319  
1320 =item C<Sr>
1321  
1322 Log byte buffers as data is read from a Stream
1323  
1324 =item C<Sw>
1325  
1326 Log byte buffers as data is written to a Stream
1327  
1328 =back
1329  
1330 =cut
1331  
1332 =head1 EXAMPLES
1333  
1334 =head2 A line-based C<on_read> method
1335  
1336 The following C<on_read> method accepts incoming C<\n>-terminated lines and
1337 prints them to the program's C<STDOUT> stream.
1338  
1339 sub on_read
1340 {
1341 my $self = shift;
1342 my ( $buffref, $eof ) = @_;
1343  
1344 while( $$buffref =~ s/^(.*\n)// ) {
1345 print "Received a line: $1";
1346 }
1347  
1348 return 0;
1349 }
1350  
1351 Because a reference to the buffer itself is passed, it is simple to use a
1352 C<s///> regular expression on the scalar it points at, to both check if data
1353 is ready (i.e. a whole line), and to remove it from the buffer. Since it
1354 always removes as many complete lines as possible, it doesn't need invoking
1355 again when it has finished, so it can return a constant C<0>.
1356  
1357 =head2 Reading binary data
1358  
1359 This C<on_read> method accepts incoming records in 16-byte chunks, printing
1360 each one.
1361  
1362 sub on_read
1363 {
1364 my ( $self, $buffref, $eof ) = @_;
1365  
1366 if( length $$buffref >= 16 ) {
1367 my $record = substr( $$buffref, 0, 16, "" );
1368 print "Received a 16-byte record: $record\n";
1369  
1370 return 1;
1371 }
1372  
1373 if( $eof and length $$buffref ) {
1374 print "EOF: a partial record still exists\n";
1375 }
1376  
1377 return 0;
1378 }
1379  
1380 This time, rather than a C<while()> loop we have decided to have the handler
1381 just process one record, and use the C<return 1> mechanism to ask that the
1382 handler be invoked again if there still remains data that might contain
1383 another record; only stopping with C<return 0> when we know we can't find one.
1384  
1385 The 4-argument form of C<substr()> extracts the 16-byte record from the buffer
1386 and assigns it to the C<$record> variable, if there was enough data in the
1387 buffer to extract it.
1388  
1389 A lot of protocols use a fixed-size header, followed by a variable-sized body
1390 of data, whose size is given by one of the fields of the header. The following
1391 C<on_read> method extracts messages in such a protocol.
1392  
1393 sub on_read
1394 {
1395 my ( $self, $buffref, $eof ) = @_;
1396  
1397 return 0 unless length $$buffref >= 8; # "N n n" consumes 8 bytes
1398  
1399 my ( $len, $x, $y ) = unpack "N n n", $$buffref;
1400  
1401 return 0 unless length $$buffref >= 8 + $len;
1402  
1403 substr( $$buffref, 0, 8, "" );
1404 my $data = substr( $$buffref, 0, $len, "" );
1405  
1406 print "A record with values x=$x y=$y\n";
1407  
1408 return 1;
1409 }
1410  
1411 In this example, the header is C<unpack()>ed first, to extract the body
1412 length, and then the body is extracted. If the buffer does not have enough
1413 data yet for a complete message then C<0> is returned, and the buffer is left
1414 unmodified for next time. Only when there are enough bytes in total does it
1415 use C<substr()> to remove them.
1416  
1417 =head2 Dynamic replacement of C<on_read>
1418  
1419 Consider the following protocol (inspired by IMAP), which consists of
1420 C<\n>-terminated lines that may have an optional data block attached. The
1421 presence of such a data block, as well as its size, is indicated by the line
1422 prefix.
1423  
1424 sub on_read
1425 {
1426 my $self = shift;
1427 my ( $buffref, $eof ) = @_;
1428  
1429 if( $$buffref =~ s/^DATA (\d+):(.*)\n// ) {
1430 my $length = $1;
1431 my $line = $2;
1432  
1433 return sub {
1434 my $self = shift;
1435 my ( $buffref, $eof ) = @_;
1436  
1437 return 0 unless length $$buffref >= $length;
1438  
1439 # Take and remove the data from the buffer
1440 my $data = substr( $$buffref, 0, $length, "" );
1441  
1442 print "Received a line $line with some data ($data)\n";
1443  
1444 return undef; # Restore the original method
1445 }
1446 }
1447 elsif( $$buffref =~ s/^LINE:(.*)\n// ) {
1448 my $line = $1;
1449  
1450 print "Received a line $line with no data\n";
1451  
1452 return 1;
1453 }
1454 else {
1455 print STDERR "Unrecognised input\n";
1456 # Handle it somehow
1457 }
1458 }
1459  
1460 In the case where trailing data is supplied, a new temporary C<on_read>
1461 callback is provided in a closure. This closure captures the C<$length>
1462 variable so it knows how much data to expect. It also captures the C<$line>
1463 variable so it can use it in the event report. When this method has finished
1464 reading the data, it reports the event, then restores the original method by
1465 returning C<undef>.
1466  
1467 =head1 SEE ALSO
1468  
1469 =over 4
1470  
1471 =item *
1472  
1473 L<IO::Handle> - Supply object methods for I/O handles
1474  
1475 =back
1476  
1477 =head1 AUTHOR
1478  
1479 Paul Evans <leonerd@leonerd.org.uk>
1480  
1481 =cut
1482  
1483 55 0x55AA;
« blib/lib/IO/Async/Resolver.pm ↑ Summary blib/lib/IO/Async/Process.pm »