Future/Utils.pm

filter: Statementstmt 97.6% 164 / 168 Branchbran 93.9% 62 / 66 Conditioncond 65.3% 32 / 49 MC/DCmcdc 20.0% 6 / 30 Subroutinesub 96.8% 31 / 32 Podpod 77.7% 7 / 9 totaltotal 85.3% 302 / 354 CC 54 SCAR 18.7
CC
54
Cov
91%
_fmap_slot
14.0
repeat
11.0
_repeat
10.1
CRAP 6.5
« Future/PP.pm ↑ Summary Future.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, 2013-2024 -- leonerd@leonerd.org.uk
5  
6 package Future::Utils 0.54;
7  
8 8 ▶use v5.20;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 # Don't use feature 'signatures' in this module yet, because until perl 5.28
12 # it's awkward to use both signatures and (&...)-style prototypes at the same
13 # time.
14  
15 8 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
16 # Can't import the one from Exporter as it relies on package inheritance
17 sub export_to_level
18 0 ▶{
Subroutine export_to_level: not called CC=1 SCAR=6.9
Pod undocumented
19 0 my $pkg = shift; local $Exporter::ExportLevel = 1 + shift; $pkg->import(@_);
20 }
21  
22 8 our @EXPORT_OK = qw(
23 call
24 call_with_escape
25  
26 repeat
27 try_repeat try_repeat_until_success
28 repeat_until_success
29  
30 fmap fmap_concat
31 fmap1 fmap_scalar
32 fmap0 fmap_void
33 );
34  
35 8 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 8 our @CARP_NOT = qw( Future );
37  
38 8 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
39  
40 =head1 NAME
41  
42 C<Future::Utils> - utility functions for working with C<Future> objects
43  
44 =head1 SYNOPSIS
45  
46 =for highlighter language=perl
47  
48 use Future::Utils qw( call_with_escape );
49  
50 my $result_f = call_with_escape {
51 my $escape_f = shift;
52 my $f = ...
53 $escape_f->done( "immediate result" );
54 ...
55 };
56  
57 Z<>
58  
59 use Future::Utils qw( repeat try_repeat try_repeat_until_success );
60  
61 my $eventual_f = repeat {
62 my $trial_f = ...
63 return $trial_f;
64 } while => sub { my $f = shift; return want_more($f) };
65  
66 my $eventual_f = repeat {
67 ...
68 return $trial_f;
69 } until => sub { my $f = shift; return acceptable($f) };
70  
71 my $eventual_f = repeat {
72 my $item = shift;
73 ...
74 return $trial_f;
75 } foreach => \@items;
76  
77 my $eventual_f = try_repeat {
78 my $trial_f = ...
79 return $trial_f;
80 } while => sub { ... };
81  
82 my $eventual_f = try_repeat_until_success {
83 ...
84 return $trial_f;
85 };
86  
87 my $eventual_f = try_repeat_until_success {
88 my $item = shift;
89 ...
90 return $trial_f;
91 } foreach => \@items;
92  
93 Z<>
94  
95 use Future::Utils qw( fmap_concat fmap_scalar fmap_void );
96  
97 my $result_f = fmap_concat {
98 my $item = shift;
99 ...
100 return $item_f;
101 } foreach => \@items, concurrent => 4;
102  
103 my $result_f = fmap_scalar {
104 my $item = shift;
105 ...
106 return $item_f;
107 } foreach => \@items, concurrent => 8;
108  
109 my $done_f = fmap_void {
110 my $item = shift;
111 ...
112 return $item_f;
113 } foreach => \@items, concurrent => 10;
114  
115 =head1 DESCRIPTION
116  
117 This module provides a number of utility functions for working with L<Future>
118 instances, that cannot generally be provided as methods on the C<Future> class
119 itself (mostly as they are prototyped to take a block of code as the first
120 argument).
121  
122 Unless otherwise noted, the following functions require at least version
123 I<0.08>.
124  
125 =cut
126  
127 =head1 INVOKING A BLOCK OF CODE
128  
129 =head2 call
130  
131 $f = call { CODE };
132  
133 I<Since version 0.22.>
134  
135 The C<call> function invokes a block of code that returns a future, and simply
136 returns the future it returned. The code is wrapped in an C<eval {}> block, so
137 that if it throws an exception this is turned into an immediate failed
138 C<Future>. If the code does not return a C<Future>, then an immediate failed
139 C<Future> instead.
140  
141 (This is equivalent to using C<< Future->call >>, but is duplicated here for
142 completeness).
143  
144 =cut
145  
146 sub call(&)
147 3 ▶{
Subroutine call: called CC=1 SCAR=0.0
Pod documented
148 3 my ( $code ) = @_;
149 3 return Future->call( $code );
150 }
151  
152 =head2 call_with_escape
153  
154 $f = call_with_escape { CODE };
155  
156 I<Since version 0.22.>
157  
158 The C<call_with_escape> function invokes a block of code that returns a
159 future, and passes in a separate future (called here an "escape future").
160 Normally this is equivalent to the simple C<call> function. However, if the
161 code captures this future and completes it by calling C<done> or C<fail> on
162 it, the future returned by C<call_with_escape> immediately completes with this
163 result, and the future returned by the code itself is cancelled.
164  
165 This can be used to implement short-circuit return from an iterating loop or
166 complex sequence of code, or immediate fail that bypasses failure handling
167 logic in the code itself, or several other code patterns.
168  
169 $f = $code->( $escape_f );
170  
171 (This can be considered similar to C<call-with-escape-continuation> as found
172 in some Scheme implementations).
173  
174 =cut
175  
176 sub call_with_escape(&)
177 4 ▶{
Subroutine call_with_escape: called CC=1 SCAR=0.0
Pod documented
178 4 my ( $code ) = @_;
179  
180 4 my $escape_f = Future->new;
181  
182 4 return Future->wait_any(
183 Future->call( $code, $escape_f ),
184 $escape_f,
185 );
186 }
187  
188 =head1 REPEATING A BLOCK OF CODE
189  
190 The C<repeat> function provides a way to repeatedly call a block of code that
191 returns a L<Future> (called here a "trial future") until some ending condition
192 is satisfied. The C<repeat> function itself returns a C<Future> to represent
193 running the repeating loop until that end condition (called here the "eventual
194 future"). The first time the code block is called, it is passed no arguments,
195 and each subsequent invocation is passed the previous trial future.
196  
197 The result of the eventual future is the result of the last trial future.
198  
199 If the eventual future is cancelled, the latest trial future will be
200 cancelled.
201  
202 If some specific subclass or instance of C<Future> is required as the return
203 value, it can be passed as the C<return> argument. Otherwise the return value
204 will be constructed by cloning the first non-immediate trial C<Future>.
205  
206 =head2 repeat+while
207  
208 $future = repeat { CODE } while => CODE;
209  
210 Repeatedly calls the C<CODE> block while the C<while> condition returns a true
211 value. Each time the trial future completes, the C<while> condition is passed
212 the trial future.
213  
214 $trial_f = $code->( $previous_trial_f );
215 $again = $while->( $trial_f );
216  
217 If the C<$code> block dies entirely and throws an exception, this will be
218 caught and considered as an immediately-failed C<Future> with the exception as
219 the future's failure. The exception will not be propagated to the caller.
220  
221 =head2 repeat+until
222  
223 $future = repeat { CODE } until => CODE;
224  
225 Repeatedly calls the C<CODE> block until the C<until> condition returns a true
226 value. Each time the trial future completes, the C<until> condition is passed
227 the trial future.
228  
229 $trial_f = $code->( $previous_trial_f );
230 $accept = $until->( $trial_f );
231  
232 =head2 repeat+foreach
233  
234 $future = repeat { CODE } foreach => ARRAY, otherwise => CODE;
235  
236 I<Since version 0.13.>
237  
238 Calls the C<CODE> block once for each value obtained from the array, passing
239 in the value as the first argument (before the previous trial future). When
240 there are no more items left in the array, the C<otherwise> code is invoked
241 once and passed the last trial future, if there was one, or C<undef> if the
242 list was originally empty. The result of the eventual future will be the
243 result of the future returned from C<otherwise>.
244  
245 The referenced array may be modified by this operation.
246  
247 $trial_f = $code->( $item, $previous_trial_f );
248 $final_f = $otherwise->( $last_trial_f );
249  
250 The C<otherwise> code is optional; if not supplied then the result of the
251 eventual future will simply be that of the last trial. If there was no trial,
252 because the C<foreach> list was already empty, then an immediate successful
253 future with an empty result is returned.
254  
255 =head2 repeat+foreach+while
256  
257 $future = repeat { CODE } foreach => ARRAY, while => CODE, ...;
258  
259 I<Since version 0.13.>
260  
261 =head2 repeat+foreach+until
262  
263 $future = repeat { CODE } foreach => ARRAY, until => CODE, ...;
264  
265 I<Since version 0.13.>
266  
267 Combines the effects of C<foreach> with C<while> or C<until>. Calls the
268 C<CODE> block once for each value obtained from the array, until the array is
269 exhausted or the given ending condition is satisfied.
270  
271 If a C<while> or C<until> condition is combined with C<otherwise>, the
272 C<otherwise> code will only be run if the array was entirely exhausted. If the
273 operation is terminated early due to the C<while> or C<until> condition being
274 satisfied, the eventual result will simply be that of the last trial that was
275 executed.
276  
277 =head2 repeat+generate
278  
279 $future = repeat { CODE } generate => CODE, otherwise => CODE;
280  
281 I<Since version 0.13.>
282  
283 Calls the C<CODE> block once for each value obtained from the generator code,
284 passing in the value as the first argument (before the previous trial future).
285 When the generator returns an empty list, the C<otherwise> code is invoked and
286 passed the last trial future, if there was one, otherwise C<undef> if the
287 generator never returned a value. The result of the eventual future will be
288 the result of the future returned from C<otherwise>.
289  
290 $trial_f = $code->( $item, $previous_trial_f );
291 $final_f = $otherwise->( $last_trial_f );
292  
293 ( $item ) = $generate->();
294  
295 The generator is called in list context but should return only one item per
296 call. Subsequent values will be ignored. When it has no more items to return
297 it should return an empty list.
298  
299 For backward compatibility this function will allow a C<while> or C<until>
300 condition that requests a failure be repeated, but it will print a warning if
301 it has to do that. To apply repeating behaviour that can catch and retry
302 failures, use C<try_repeat> instead. This old behaviour is now deprecated and
303 will be removed in the next version.
304  
305 =cut
306  
307 sub _repeat
308 36 ▶{
Subroutine _repeat: called CC=10 SCAR=23.1
309 36 my ( $code, $return, $trialp, $cond, $sense, $is_try ) = @_;
310  
311 36 my $prev = $$trialp;
312  
313 36 while(1) {
314 64 ▶ my $trial = $$trialp ||= Future->call( $code, $prev );
Condition66%2/3
$$trialp ||= "Future"->call($code, $prev)
l!l&&r!l&&!r
11530
MC/DC0%0/2
$$trialp ||= "Future"->call($code, $prev)
$$trialp "Future"->call($code, $prev)
Truth table66%2/3
A ||= B
A= $$trialpB= "Future"->call($code, $prev)
ABresult
1X1
011
000
315 64 $prev = $trial;
316  
317 64 ▶ if( !$trial->is_ready ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($trial->is_ready) 13 51 64
318 # defer
319 13 ▶ $return ||= $trial->new;
Condition66%2/3
$return ||= $trial->new
l!l&&r!l&&!r
850
MC/DC0%0/2
$return ||= $trial->new
$return $trial->new
Truth table66%2/3
A ||= B
A= $returnB= $trial->new
ABresult
1X1
011
000
320 12 ▶ $trial->on_ready( sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
321 12 ▶ return if $$trialp->is_cancelled;
Branch: 1 branch
BranchTrueFalseTotal
if $$trialp->is_cancelled 1 11 12
322 11 _repeat( $code, $return, $trialp, $cond, $sense, $is_try );
323 13 });
324 13 return $return;
325 }
326  
327 51 my $stop;
328 51 ▶ if( not eval { $stop = !$cond->( $trial ) ^ $sense; 1 } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $stop = !&$cond($trial) ^ $sense; 1 } }) 1 50 51
329 1 ▶ $return ||= $trial->new;
Condition33%1/3
$return ||= $trial->new
l!l&&r!l&&!r
010
MC/DC0%0/2
$return ||= $trial->new
$return $trial->new
Truth table33%1/3
A ||= B
A= $returnB= $trial->new
ABresult
1X1
011
000
330 1 $return->fail( $@ );
331 1 return $return;
332 }
333  
334 50 ▶ if( $stop ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stop) 22 28 50
335 # Return result
336 22 ▶ $return ||= $trial->new;
Condition66%2/3
$return ||= $trial->new
l!l&&r!l&&!r
4180
MC/DC0%0/2
$return ||= $trial->new
$return $trial->new
Truth table66%2/3
A ||= B
A= $returnB= $trial->new
ABresult
1X1
011
000
337 22 $trial->on_done( $return );
338 22 $trial->on_fail( $return );
339 22 return $return;
340 }
341  
342 28 ▶ if( !$is_try and $trial->failure ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $is_try and $trial->failure) 2 26 28
Condition100%3/3
not $is_try and $trial->failure
!ll&&!rl&&r
10162
MC/DC100%2/2
not $is_try and $trial->failure
not $is_try $trial->failure
Truth table100%3/3
not(A) and B
A= not $is_tryB= $trial->failure
ABresult
0X0
100
111
343 2 carp "Using Future::Utils::repeat to retry a failure is deprecated; use try_repeat instead";
344 }
345  
346 # redo
347 28 undef $$trialp;
348 }
349 }
350  
351 sub repeat(&@)
352 25 ▶{
Subroutine repeat: called CC=11 SCAR=24.0
Pod undocumented
353 25 my $code = shift;
354 25 my %args = @_;
355  
356 # This makes it easier to account for other conditions
357 defined($args{while}) + defined($args{until}) == 1
358 or defined($args{foreach})
359 or defined($args{generate})
360 25 ▶ or croak "Expected one of 'while', 'until', 'foreach' or 'generate'";
Branch: 1 branch
BranchTrueFalseTotal
defined($args{"while"}) + defined($args{"until"}) == 1 or defined $args{"foreach"} or defined $args{"generate"} or croak("Expected one of 'while', 'until', 'foreach' or 'generate'") 25 0 25
Condition83%5/6
defined($args{"while"}) + defined($args{"until"}) == 1 or defined $args{"foreach"} or defined $args{"generate"}
l!l&&r!l&&!r
2230
defined($args{"while"}) + defined($args{"until"}) == 1 or defined $args{"foreach"}
l!l&&r!l&&!r
1573
MC/DC0%0/3
defined($args{"while"}) + defined($args{"until"}) == 1 or defined $args{"foreach"} or defined $args{"generate"}
defined($args{"while"}) + defined($args{"until"}) == 1 defined $args{"foreach"} defined $args{"generate"}
Truth table75%3/4
A or B or C
A= defined($args{"while"}) + defined($args{"until"}) == 1B= defined $args{"foreach"}C= defined $args{"generate"}
ABCresult
1XX1
01X1
0011
0000
361  
362 25 ▶ if( $args{foreach} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"foreach"}) 11 14 25
363 11 ▶ $args{generate} and croak "Cannot use both 'foreach' and 'generate'";
Branch: 1 branch
BranchTrueFalseTotal
$args{"generate"} and croak("Cannot use both 'foreach' and 'generate'") 0 11 11
364  
365 11 my $array = delete $args{foreach};
366 24 ▶ $args{generate} = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
367 24 ▶ @$array ? shift @$array : ();
Branch: 1 branch
BranchTrueFalseTotal
@$array ? : 17 7 24
368 11 };
369 }
370  
371 25 ▶ if( $args{generate} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"generate"}) 14 11 25
372 14 my $generator = delete $args{generate};
373 14 my $otherwise = delete $args{otherwise};
374  
375 # TODO: This is slightly messy as this lexical is captured by both
376 # blocks of code. Can we do better somehow?
377 14 my $done;
378  
379 14 my $orig_code = $code;
380 33 ▶ $code = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
381 33 my ( $last_trial_f ) = @_;
382 33 my $again = my ( $value ) = $generator->( $last_trial_f );
383  
384 33 ▶ if( $again ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($again) 23 10 33
385 23 unshift @_, $value; goto &$orig_code;
386 }
387  
388 10 $done++;
389 10 ▶ if( $otherwise ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($otherwise) { } 6 4 10
390 6 goto &$otherwise;
391 }
392 else {
393 4 ▶ return $last_trial_f || Future->done;
Condition66%2/3
$last_trial_f || 'Future'->done
l!l&&r!l&&!r
310
MC/DC0%0/2
$last_trial_f || 'Future'->done
$last_trial_f 'Future'->done
Truth table66%2/3
A || B
A= $last_trial_fB= 'Future'->done
ABresult
1X1
011
000
394 }
395 14 };
396  
397 14 ▶ if( my $orig_while = delete $args{while} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $orig_while = delete $args{'while'}) { } 3 11 14
elsif (my $orig_until = delete $args{'until'}) { } 1 10 11
398 6 ▶ $args{while} = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
399 6 ▶ $orig_while->( $_[0] ) and !$done;
Branch: 1 branch
BranchTrueFalseTotal
&$orig_while($_[0]) and not $done 3 3 6
400 3 };
401 }
402 elsif( my $orig_until = delete $args{until} ) {
403 2 ▶ $args{while} = sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
404 2 ▶ !$orig_until->( $_[0] ) and !$done;
Condition66%2/3
&$orig_until($_[0]) || $done
l!l&&r!l&&!r
101
MC/DC50%1/2
&$orig_until($_[0]) || $done
&$orig_until($_[0]) $done
Truth table66%2/3
A || B
A= &$orig_until($_[0])B= $done
ABresult
1X1
011
000
405 1 };
406 }
407 else {
408 10 ▶ $args{while} = sub { !$done };
Subroutine __ANON__: called CC=1 SCAR=0.0
409 }
410 }
411  
412 25 my $future = $args{return};
413  
414 25 my $trial;
415 25 ▶ $args{while} and $future = _repeat( $code, $future, \$trial, $args{while}, 0, $args{try} );
Branch: 1 branch
BranchTrueFalseTotal
$args{"while"} and $future = _repeat($code, $future, \$trial, $args{"while"}, 0, $args{"try"}) 23 2 25
416 25 ▶ $args{until} and $future = _repeat( $code, $future, \$trial, $args{until}, 1, $args{try} );
Branch: 1 branch
BranchTrueFalseTotal
$args{"until"} and $future = _repeat($code, $future, \$trial, $args{"until"}, 1, $args{"try"}) 2 23 25
417  
418 25 ▶ $future->on_cancel( sub { $trial->cancel } );
Subroutine __ANON__: called CC=1 SCAR=0.0
419  
420 25 return $future;
421 }
422  
423 =head2 try_repeat
424  
425 $future = try_repeat { CODE } ...;
426  
427 I<Since version 0.18.>
428  
429 A variant of C<repeat> that doesn't warn when the trial fails and the
430 condition code asks for it to be repeated.
431  
432 In some later version the C<repeat> function will be changed so that if a
433 trial future fails, then the eventual future will immediately fail as well,
434 making its semantics a little closer to that of a C<while {}> loop in Perl.
435 Code that specifically wishes to catch failures in trial futures and retry
436 the block should use C<try_repeat> specifically.
437  
438 =cut
439  
440 sub try_repeat(&@)
441 6 ▶{
Subroutine try_repeat: called CC=1 SCAR=0.0
Pod documented
442 # defeat prototype
443 6 &repeat( @_, try => 1 );
444 }
445  
446 =head2 try_repeat_until_success
447  
448 $future = try_repeat_until_success { CODE } ...;
449  
450 I<Since version 0.18.>
451  
452 A shortcut to calling C<try_repeat> with an ending condition that simply tests
453 for a successful result from a future. May be combined with C<foreach> or
454 C<generate>.
455  
456 This function used to be called C<repeat_until_success>, and is currently
457 aliased as this name as well.
458  
459 =cut
460  
461 sub try_repeat_until_success(&@)
462 2 ▶{
Subroutine try_repeat_until_success: called CC=3 SCAR=12.0
Pod documented
463 2 my $code = shift;
464 2 my %args = @_;
465  
466 # TODO: maybe merge while/until conditions one day...
467 defined($args{while}) or defined($args{until})
468 2 ▶ and croak "Cannot pass 'while' or 'until' to try_repeat_until_success";
Branch: 1 branch
BranchTrueFalseTotal
defined $args{"while"} or defined $args{"until"} and croak("Cannot pass 'while' or 'until' to try_repeat_until_success") 0 2 2
Condition40%2/5
defined $args{'while'} || defined $args{'until'} && croak(q[Cannot pass 'while' or 'until' to try_repeat_until_success])
l!l&&r!l&&!r
020
defined $args{"until"} and croak("Cannot pass 'while' or 'until' to try_repeat_until_success")
!ll
20
MC/DC0%0/2
defined $args{'while'} || defined $args{'until'} && croak(q[Cannot pass 'while' or 'until' to try_repeat_until_success])
defined $args{'while'} defined $args{"until"}
Truth table0%0/3
A || B
A= defined $args{'while'}B= defined $args{"until"}
ABresult
1X1
011
000
469  
470 # defeat prototype
471 2 ▶ &try_repeat( $code, while => sub { shift->failure }, %args );
Subroutine __ANON__: called CC=1 SCAR=0.0
472 }
473  
474 # Legacy name
475 8 *repeat_until_success = \&try_repeat_until_success;
476  
477 =head1 APPLYING A FUNCTION TO A LIST
478  
479 The C<fmap> family of functions provide a way to call a block of code that
480 returns a L<Future> (called here an "item future") once per item in a given
481 list, or returned by a generator function. The C<fmap*> functions themselves
482 return a C<Future> to represent the ongoing operation, which completes when
483 every item's future has completed.
484  
485 While this behaviour can also be implemented using C<repeat>, the main reason
486 to use an C<fmap> function is that the individual item operations are
487 considered as independent, and thus more than one can be outstanding
488 concurrently. An argument can be passed to the function to indicate how many
489 items to start initially, and thereafter it will keep that many of them
490 running concurrently until all of the items are done, or until any of them
491 fail. If an individual item future fails, the overall result future will be
492 marked as failing with the same failure, and any other pending item futures
493 that are outstanding at the time will be cancelled.
494  
495 The following named arguments are common to each C<fmap*> function:
496  
497 =over 8
498  
499 =item foreach => ARRAY
500  
501 Provides the list of items to iterate over, as an C<ARRAY> reference.
502  
503 The referenced array will be modified by this operation, C<shift>ing one item
504 from it each time. The can C<push> more items to this array as it runs, and
505 they will be included in the iteration.
506  
507 =item generate => CODE
508  
509 Provides the list of items to iterate over, by calling the generator function
510 once for each required item. The function should return a single item, or an
511 empty list to indicate it has no more items.
512  
513 ( $item ) = $generate->();
514  
515 This function will be invoked each time any previous item future has completed
516 and may be called again even after it has returned empty.
517  
518 =item concurrent => INT
519  
520 Gives the number of item futures to keep outstanding. By default this value
521 will be 1 (i.e. no concurrency); larger values indicate that multiple item
522 futures will be started at once.
523  
524 =item return => Future
525  
526 Normally, a new instance is returned by cloning the first non-immediate future
527 returned as an item future. By passing a new instance as the C<return>
528 argument, the result will be put into the given instance. This can be used to
529 return subclasses, or specific instances.
530  
531 =back
532  
533 In each case, the main code block will be called once for each item in the
534 list, passing in the item as the only argument:
535  
536 $item_f = $code->( $item );
537  
538 The expected return value from each item's future, and the value returned from
539 the result future will differ in each function's case; they are documented
540 below.
541  
542 For similarity with perl's core C<map> function, the item is also available
543 aliased as C<$_>.
544  
545 =cut
546  
547 # This function is invoked in two circumstances:
548 # a) to create an item Future in a slot,
549 # b) once a non-immediate item Future is complete, to check its results
550 # It can tell which circumstance by whether the slot itself is defined or not
551 sub _fmap_slot
552 60 ▶{
Subroutine _fmap_slot: called CC=14 SCAR=26.4
553 60 my ( $slots, undef, $code, $generator, $collect, $results, $return ) = @_;
554  
555 60 SLOT: while(1) {
556 # Capture args each call because we mutate them
557 99 my ( undef, $idx ) = my @args = @_;
558  
559 99 ▶ unless( $slots->[$idx] ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($slots->[$idx]) 69 30 99
560 # No item Future yet (case a), so create one
561 69 my $item;
562 69 ▶ unless( ( $item ) = $generator->() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (($item) = &$generator()) 26 43 69
563 # All out of items, so now just wait for the slots to be finished
564 26 undef $slots->[$idx];
565 26 ▶ defined and return $return for @$slots;
Branch: 1 branch
BranchTrueFalseTotal
defined $_ and return $return 15 33 48
566  
567 # All the slots are done
568 11 ▶ $return ||= Future->new;
Condition66%2/3
$return ||= "Future"->new
l!l&&r!l&&!r
1010
MC/DC0%0/2
$return ||= "Future"->new
$return "Future"->new
Truth table66%2/3
A ||= B
A= $returnB= "Future"->new
ABresult
1X1
011
000
569  
570 11 $return->done( @$results );
571 11 return $return;
572 }
573  
574 43 my $f = $slots->[$idx] = Future->call( $code, local $_ = $item );
575  
576 43 ▶ if( $collect eq "array" ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($collect eq 'array') { } 10 33 43
elsif ($collect eq 'scalar') { } 3 30 33
577 10 push @$results, my $r = [];
578 10 ▶ $f->on_done( sub { @$r = @_ });
Subroutine __ANON__: called CC=1 SCAR=0.0
579 }
580 elsif( $collect eq "scalar" ) {
581 3 push @$results, undef;
582 3 my $r = \$results->[-1];
583 3 ▶ $f->on_done( sub { $$r = $_[0] });
Subroutine __ANON__: called CC=1 SCAR=0.0
584 }
585 }
586  
587 73 my $f = $slots->[$idx];
588  
589 # Slot is non-immediate; arrange for us to be invoked again later when it's ready
590 73 ▶ if( !$f->is_ready ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($f->is_ready) 36 37 73
591 36 ▶ $args[-1] = ( $return ||= $f->new );
Condition66%2/3
$return ||= $f->new
l!l&&r!l&&!r
23130
MC/DC0%0/2
$return ||= $f->new
$return $f->new
Truth table66%2/3
A ||= B
A= $returnB= $f->new
ABresult
1X1
011
000
592 36 ▶ $f->on_done( sub { _fmap_slot( @args ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
593 36 $f->on_fail( $return );
594  
595 # Try looking for more that might be ready
596 36 my $i = $idx + 1;
597 36 ▶ while( $i != $idx ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i != $idx) 40 33 73
598 40 $i++;
599 40 $i %= @$slots;
600 40 ▶ next if defined $slots->[$i];
Branch: 1 branch
BranchTrueFalseTotal
if defined $slots->[$i] 37 3 40
601  
602 3 $_[1] = $i;
603 3 redo SLOT;
604 }
605 33 return $return;
606 }
607  
608 # Either we've been invoked again (case b), or the immediate Future was
609 # already ready.
610 37 ▶ if( $f->failure ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f->failure) 1 36 37
611 1 ▶ $return ||= $f->new;
Condition33%1/3
$return ||= $f->new
l!l&&r!l&&!r
100
MC/DC0%0/2
$return ||= $f->new
$return $f->new
Truth table33%1/3
A ||= B
A= $returnB= $f->new
ABresult
1X1
011
000
612 1 $return->fail( $f->failure );
613 1 return $return;
614 }
615  
616 36 undef $slots->[$idx];
617 # next
618 }
619 }
620  
621 sub _fmap
622 15 ▶{
Subroutine _fmap: called CC=6 SCAR=18.0
623 15 my $code = shift;
624 15 my %args = @_;
625  
626 15 ▶ my $concurrent = $args{concurrent} || 1;
Condition100%2/2
$args{'concurrent'} || 1
l!l
96
MC/DC100%1/1
$args{'concurrent'} || 1
$args{'concurrent'}
Truth table100%2/2
A
A= $args{'concurrent'}
Aresult
11
00
627 15 my @slots;
628  
629 15 my $results = [];
630 15 my $future = $args{return};
631  
632 15 my $generator;
633 15 ▶ if( $generator = $args{generate} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($generator = $args{'generate'}) { } 1 14 15
elsif (my $array = $args{'foreach'}) { } 14 0 14
634 # OK
635 }
636 elsif( my $array = $args{foreach} ) {
637 14 ▶ $generator = sub { return unless @$array; shift @$array };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless @$array 25 40 65
638 }
639 else {
640 0 croak "Expected either 'generate' or 'foreach'";
641 }
642  
643 # If any of these immediately fail, don't bother continuing
644 15 foreach my $idx ( 0 .. $concurrent-1 ) {
645 30 $future = _fmap_slot( \@slots, $idx, $code, $generator, $args{collect}, $results, $future );
646 30 ▶ last if $future->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $future->is_ready 3 27 30
647 }
648  
649 2 ▶ $future->on_fail( sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
650 2 ▶ !defined $_ or $_->is_ready or $_->cancel for @slots;
Branch: 1 branch
BranchTrueFalseTotal
not defined $_ or $_->is_ready or $_->cancel 2 2 4
Condition66%2/3
not defined $_ or $_->is_ready
l!l&&r!l&&!r
022
MC/DC50%1/2
not defined $_ or $_->is_ready
not defined $_ $_->is_ready
Truth table66%2/3
not(A) or B
A= not defined $_B= $_->is_ready
ABresult
1X1
011
000
651 15 });
652 2 ▶ $future->on_cancel( sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
653 2 ▶ !defined $_ or $_->is_ready or $_->cancel for @slots;
Branch: 1 branch
BranchTrueFalseTotal
not defined $_ or $_->is_ready or $_->cancel 1 3 4
Condition66%2/3
not defined $_ or $_->is_ready
l!l&&r!l&&!r
103
MC/DC50%1/2
not defined $_ or $_->is_ready
not defined $_ $_->is_ready
Truth table66%2/3
not(A) or B
A= not defined $_B= $_->is_ready
ABresult
1X1
011
000
654 15 });
655  
656 15 return $future;
657 }
658  
659 =head2 fmap_concat
660  
661 $future = fmap_concat { CODE } ...;
662  
663 I<Since version 0.14.>
664  
665 This version of C<fmap> expects each item future to return a list of zero or
666 more values, and the overall result will be the concatenation of all these
667 results. It acts like a future-based equivalent to Perl's C<map> operator.
668  
669 The results are returned in the order of the original input values, not in the
670 order their futures complete in. Because of the intermediate storage of
671 C<ARRAY> references and final flattening operation used to implement this
672 behaviour, this function is slightly less efficient than C<fmap_scalar> or
673 C<fmap_void> in cases where item futures are expected only ever to return one,
674 or zero values, respectively.
675  
676 This function is also available under the name of simply C<fmap> to emphasise
677 its similarity to perl's C<map> keyword.
678  
679 =cut
680  
681 sub fmap_concat(&@)
682 4 ▶{
Subroutine fmap_concat: called CC=1 SCAR=0.0
Pod documented
683 4 my $code = shift;
684 4 my %args = @_;
685  
686 3 ▶ _fmap( $code, %args, collect => "array" )->then( sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
687 3 return Future->done( map { @$_ } @_ );
688 4 });
689 }
690 8 *fmap = \&fmap_concat;
691  
692 =head2 fmap_scalar
693  
694 $future = fmap_scalar { CODE } ...;
695  
696 I<Since version 0.14.>
697  
698 This version of C<fmap> acts more like the C<map> functions found in Scheme or
699 Haskell; it expects that each item future returns only one value, and the
700 overall result will be a list containing these, in order of the original input
701 items. If an item future returns more than one value the others will be
702 discarded. If it returns no value, then C<undef> will be substituted in its
703 place so that the result list remains in correspondence with the input list.
704  
705 This function is also available under the shorter name of C<fmap1>.
706  
707 =cut
708  
709 sub fmap_scalar(&@)
710 1 ▶{
Subroutine fmap_scalar: called CC=1 SCAR=0.0
Pod documented
711 1 my $code = shift;
712 1 my %args = @_;
713  
714 1 _fmap( $code, %args, collect => "scalar" )
715 }
716 8 *fmap1 = \&fmap_scalar;
717  
718 =head2 fmap_void
719  
720 $future = fmap_void { CODE } ...;
721  
722 I<Since version 0.14.>
723  
724 This version of C<fmap> does not collect any results from its item futures, it
725 simply waits for them all to complete. Its result future will provide no
726 values.
727  
728 While not a map in the strictest sense, this variant is still useful as a way
729 to control concurrency of a function call iterating over a list of items,
730 obtaining its results by some other means (such as side-effects on captured
731 variables, or some external system).
732  
733 This function is also available under the shorter name of C<fmap0>.
734  
735 =cut
736  
737 sub fmap_void(&@)
738 10 ▶{
Subroutine fmap_void: called CC=1 SCAR=0.0
Pod documented
739 10 my $code = shift;
740 10 my %args = @_;
741  
742 10 _fmap( $code, %args, collect => "void" )
743 }
744 8 *fmap0 = \&fmap_void;
745  
746 =head1 AUTHOR
747  
748 Paul Evans <leonerd@leonerd.org.uk>
749  
750 =cut
751  
752 8 0x55AA;
« Future/PP.pm ↑ Summary Future.pm »