Future-IO-0.16000755001750001750 014672062243 11746 5ustar00leoleo000000000000Future-IO-0.16/.editorconfig000444001750001750 5314672062243 14516 0ustar00leoleo000000000000root = true [*.{pm,pl,t}] indent_size = 3 Future-IO-0.16/Build.PL000444001750001750 105614672062243 13401 0ustar00leoleo000000000000use v5; use strict; use warnings; use Module::Build; my $build = Module::Build->new( module_name => 'Future::IO', requires => { 'Future' => 0, 'Struct::Dumb' => 0, 'Time::HiRes' => 0, 'perl' => '5.014', }, test_requires => { 'Test::ExpectAndCheck' => '0.06', 'Test::Future::IO::Impl' => 0, 'Test2::V0' => 0, }, configure_requires => { 'Module::Build' => '0.4004', # test_requires }, license => 'perl', create_license => 1, create_readme => 1, ); $build->create_build_script; Future-IO-0.16/Changes000444001750001750 705214672062243 13402 0ustar00leoleo000000000000Revision history for Future-IO 0.16 2024-09-16 [CHANGES] * Added `Future::IO->load_impl` convenience method for toplevel applications 0.15 2023-10-18 [BUGFIXES] * Avoid creating a long `->then` chain of Futures when handling EAGAIN (RT150117) * Temporarily enable blocking mode on filehandles when the default event loop is not using `select()`, to avoid a CPU spin (RT150117) 0.14 2023-04-25 [CHANGES] * Moved `Test::Future::IO::Impl` into its own distribution, so that downstream packages don't have to runtime-depend on `Test2` 0.13 2023-02-19 [CHANGES] * Swap all unit tests from `Test::More` to `Test2::V0` * Reomved test-time dependency on `Test::Identity` [BUGFIXES] * t/30system.t should check that the impl actually provides a `->waitpid` method before using it * Insert a hacky "sleep 1" into the connect tests on MSWin32 in case that helps fix the test failures 0.12 2023-01-31 [CHANGES] * Added `Future::IO::System`, containing a system()-like and a qx()-like method * Added `->sysread_until_eof` method * Update to perl v5.14 `package NAME VERSION` syntax * Use `await` notation in method minisynopsis lines [BUGFIXES] * Need to work harder to set LocalAddr during socket tests 0.11 2022-01-07 [CHANGES] * Added ->connect and ->accept for socket-based code * Provide ->HAVE_MULTIPLE_FILEHANDLES for user code to check if a real impl has been loaded * Simplify the default implementation so it can reuse most of the ImplBase class * Wording fix in docs for ->alarm 0.10 2021-08-26 [BUGFIXES] * Skip the unit test about filling pipes with ->syswrite on MSWin32 because the test just hangs there (RT138985) 0.09 2021-08-24 [CHANGES] * Added ->waitpid that real event loop implementations can provide (though built-in default implementation does not provide it) * Extracted impl tests to shareable Test::Future::IO::Impl module * Add links to existing CPAN implementations and test modules 0.08 2020-12-31 [CHANGES] * Added Future::IO->alarm [BUGFIXES] * Avoid CPU-spin in the single-filehandle case on nonblocking filehandles 0.07 2020-03-24 [CHANGES] * Make the ->await method wait until the future instance is ready * Document ->await 0.06 2019-06-26 18:11:54 [CHANGES] * Added Future::IO::ImplBase to assist implementation authors 0.05 2019-05-07 01:00:19 [CHANGES] * Misc small docs fixes [BUGFIXES] * Expect EINVAL on MSWin32 for pipe close write test, rather than EPIPE 0.04 2019-04-27 19:08:40 [CHANGES] * Added ->syswrite and ->syswrite_exactly [BUGFIXES] * Implement ->sysread_exactly test a better way that shouldn't break on Windows due to select() on pipes 0.03 2019-04-25 22:39:55 [CHANGES] * Add ->sysread_exactly 0.02 2019-04-10 14:01:17 [CHANGES] * Provide and document the $IMPL package variable mechanism [BUGFIXES] * Skip t/10sleep+sysread.t on MSWin32 because Windows doesn't support select() on pipes (RT129108) 0.01 2019-04-10 01:44:18 First version, released on an unsuspecting world. Future-IO-0.16/LICENSE000444001750001750 4653414672062243 13144 0ustar00leoleo000000000000This software is copyright (c) 2024 by Paul Evans . This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2024 by Paul Evans . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Perl Artistic License 1.0 --- This software is Copyright (c) 2024 by Paul Evans . This is free software, licensed under: The Perl Artistic License 1.0 The "Artistic License" Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder as specified below. "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as uunet.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) give non-standard executables non-standard names, and clearly document the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. You may embed this Package's interpreter within an executable of yours (by linking); this shall be construed as a mere form of aggregation, provided that the complete Standard Version of the interpreter is so embedded. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whoever generated them, and may be sold commercially, and may be aggregated with this Package. If such scripts or library files are aggregated with this Package via the so-called "undump" or "unexec" methods of producing a binary executable image, then distribution of such an image shall neither be construed as a distribution of this Package nor shall it fall under the restrictions of Paragraphs 3 and 4, provided that you do not represent such an executable image as a Standard Version of this Package. 7. C subroutines (or comparably compiled subroutines in other languages) supplied by you and linked into this Package in order to emulate subroutines and variables of the language defined by this Package shall not be considered part of this Package, but are the equivalent of input as in Paragraph 6, provided these subroutines do not change the language in any way that would cause it to fail the regression tests for the language. 8. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. 9. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Future-IO-0.16/MANIFEST000444001750001750 63214672062243 13215 0ustar00leoleo000000000000.editorconfig Build.PL Changes lib/Future/IO.pm lib/Future/IO/ImplBase.pm lib/Future/IO/System.pm LICENSE MANIFEST This list of files META.json META.yml README t/00use.t t/01sleep.t t/02sysread.t t/03sysread_exactly.t t/03sysread_until_eof.t t/04syswrite.t t/05syswrite_exactly.t t/06connect.t t/07accept.t t/10sleep+sysread.t t/20impl-override.t t/21impl-before-load.t t/30system.t t/90rt150117.t t/99pod.t Future-IO-0.16/META.json000444001750001750 261114672062243 13524 0ustar00leoleo000000000000{ "abstract" : "Future-returning IO methods", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4234", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Future-IO", "prereqs" : { "configure" : { "requires" : { "Module::Build" : "0.4004" } }, "runtime" : { "requires" : { "Future" : "0", "Struct::Dumb" : "0", "Time::HiRes" : "0", "perl" : "5.014" } }, "test" : { "requires" : { "Test2::V0" : "0", "Test::ExpectAndCheck" : "0.06", "Test::Future::IO::Impl" : "0" } } }, "provides" : { "Future::IO" : { "file" : "lib/Future/IO.pm", "version" : "0.16" }, "Future::IO::ImplBase" : { "file" : "lib/Future/IO/ImplBase.pm", "version" : "0.16" }, "Future::IO::System" : { "file" : "lib/Future/IO/System.pm", "version" : "0.16" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ] }, "version" : "0.16", "x_serialization_backend" : "JSON::PP version 4.16" } Future-IO-0.16/META.yml000444001750001750 157214672062243 13361 0ustar00leoleo000000000000--- abstract: 'Future-returning IO methods' author: - 'Paul Evans ' build_requires: Test2::V0: '0' Test::ExpectAndCheck: '0.06' Test::Future::IO::Impl: '0' configure_requires: Module::Build: '0.4004' dynamic_config: 1 generated_by: 'Module::Build version 0.4234, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Future-IO provides: Future::IO: file: lib/Future/IO.pm version: '0.16' Future::IO::ImplBase: file: lib/Future/IO/ImplBase.pm version: '0.16' Future::IO::System: file: lib/Future/IO/System.pm version: '0.16' requires: Future: '0' Struct::Dumb: '0' Time::HiRes: '0' perl: '5.014' resources: license: http://dev.perl.org/licenses/ version: '0.16' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Future-IO-0.16/README000444001750001750 2360614672062243 13012 0ustar00leoleo000000000000NAME Future::IO - Future-returning IO methods SYNOPSIS use Future::IO; my $delay = Future::IO->sleep( 5 ); # $delay will become done in 5 seconds time my $input = Future::IO->sysread( \*STDIN, 4096 ); # $input will yield some input from the STDIN IO handle DESCRIPTION This package provides a few basic methods that behave similarly to the same-named core perl functions relating to IO operations, but yield their results asynchronously via Future instances. This is provided primarily as a decoupling mechanism, to allow modules to be written that perform IO in an asynchronous manner to depend directly on this, while allowing asynchronous event systems to provide an implementation of these operations. Default Implementation If the override_impl method is not invoked, a default implementation of these operations is provided. This implementation allows a single queue of sysread or syswrite calls on a single filehandle only, combined with sleep calls. It does not support waitpid. It is provided for the simple cases where modules only need one filehandle (most likely a single network socket or hardware device handle), allowing such modules to work without needing a better event system. If there are both read/write and sleep futures pending, the implementation will use select() to wait for either. This may be problematic on MSWin32, depending on what type of filehandle is involved. If select() is not being used then the default implementation will temporarily set filehandles into blocking mode (by switching off the O_NONBLOCK flag) while performing IO on them. For cases where multiple filehandles are required, or for doing more involved IO operations, a real implementation based on an actual event loop should be provided. The following are known to exist; CPAN may provide others: * Future::IO::Impl::Glib * Future::IO::Impl::IOAsync * Future::IO::Impl::UV Unit Testing The replaceable implementation is also useful for writing unit test scripts. If the implementation is set to an instance of some sort of test fixture or mocking object, a unit test can check that the appropriate IO operations happen as part of the test. A testing module which does this is provided by Test::Future::IO. METHODS accept $socketfh = await Future::IO->accept( $fh ); Since version 0.11. Returns a Future that will become done when a new connection has been accepted on the given filehandle, which should represent a listen-mode socket. The returned future will yield the newly-accepted client socket filehandle. alarm await Future::IO->alarm( $epoch ); Since version 0.08. Returns a Future that will become done at a fixed point in the future, given as an epoch timestamp (such as returned by time()). This value may be fractional. connect await Future::IO->connect( $fh, $name ); Since version 0.11. Returns a Future that will become done when a connect() has succeeded on the given filehandle to the given sockname address. sleep await Future::IO->sleep( $secs ); Returns a Future that will become done a fixed delay from now, given in seconds. This value may be fractional. sysread $bytes = await Future::IO->sysread( $fh, $length ); Returns a Future that will become done when at least one byte can be read from the given filehandle. It may return up to $length bytes. On EOF, the returned future will yield an empty list (or undef in scalar context). On any error (other than EAGAIN / EWOULDBLOCK which are ignored), the future fails with a suitable error message. Note specifically this may perform only a single sysread() call, and thus is not guaranteed to actually return the full length. sysread_exactly $bytes = await Future::IO->sysread_exactly( $fh, $length ); Since version 0.03. Returns a Future that will become done when exactly the given number of bytes have been read from the given filehandle. It returns exactly $length bytes. On EOF, the returned future will yield an empty list (or undef in scalar context), even if fewer bytes have already been obtained. These bytes will be lost. On any error (other than EAGAIN / EWOULDBLOCK which are ignored), the future fails with a suitable error message. This may make more than one sysread() call. sysread_until_eof $f = Future::IO->sysread_until_eof( $fh ); Since version 0.12. Returns a Future that will become done when the given filehandle reaches the EOF condition. The returned future will yield all of the bytes read up until that point. syswrite $written_len = await Future::IO->syswrite( $fh, $bytes ); Since version 0.04. Returns a Future that will become done when at least one byte has been written to the given filehandle. It may write up to all of the bytes. On any error (other than EAGAIN / EWOULDBLOCK which are ignored) the future fails with a suitable error message. Note specifically this may perform only a single syswrite() call, and thus is not guaranteed to actually return the full length. syswrite_exactly $written_len = await Future::IO->syswrite_exactly( $fh, $bytes ); Since version 0.04. Returns a Future that will become done when exactly the given bytes have been written to the given filehandle. On any error (other than EAGAIN / EWOULDBLOCK which are ignored) the future fails with a suitable error message. This may make more than one syswrite() call. waitpid $wstatus = await Future::IO->waitpid( $pid ); Since version 0.09. Returns a Future that will become done when the given child process terminates. The future will yield the wait status of the child process. This can be inspected by the usual bitshifting operations as per $?: if( my $termsig = ($wstatus & 0x7f) ) { say "Terminated with signal $termsig"; } else { my $exitcode = ($wstatus >> 8); say "Terminated with exit code $exitcode"; } override_impl Future::IO->override_impl( $impl ); Sets a new implementation for Future::IO, replacing the minimal default internal implementation. This can either be a package name or an object instance reference, but must provide the methods named above. This method is intended to be called by event loops and other similar places, to provide a better integration. Another way, which doesn't involve directly depending on Future::IO or loading it, is to use the $IMPL variable; see below. Can only be called once, and only if the default implementation is not in use, therefore a module that wishes to override this ought to invoke it as soon as possible on program startup, before any of the main Future::IO methods may have been called. load_impl Future::IO->load_impl( @names ); Since version 0.16. Given a list of possible implementation module names, iterates through them attempting to load each one until a suitable module is found. Any errors encountered while loading each are ignored. If no module is found to be suitable, an exception is thrown that likely aborts the program. @names should contain a list of Perl module names (which likely live in the Future::IO::Impl::* prefix). If any name does not contain a :: separator, it will have that prefix applied to it. This allows a conveniently short list; e.g. Future::IO->load_impl( qw( UV Glib IOAsync ) ); This method is intended to be called once, at startup, by the main containing program. Since it sets the implementation, it would generally be considered inappropriate to invoke this method from some additional module that might be loaded by a containing program. HAVE_MULTIPLE_FILEHANDLES $has = Future::IO->HAVE_MULTIPLE_FILEHANDLES; Since version 0.11. Returns true if the underlying IO implementation actually supports multiple filehandles. Most real support modules will return true here, but this returns false for the internal minimal implementation. await $f = $f->await; Since version 0.07. Blocks until this future is ready (either by success or failure). Does not throw an exception if failed. THE $IMPL VARIABLE Since version 0.02. As an alternative to setting an implementation by using override_impl, a package variable is also available that allows modules such as event systems to opportunistically provide an implementation without needing to depend on the module, or loading it require. Simply directly set that package variable to the name of an implementing package or an object instance. Additionally, implementors may use a name within the Future::IO::Impl:: namespace, suffixed by the name of their event system. For example, something like the following code arrangement is recommended. package Future::IO::Impl::BananaLoop; { no warnings 'once'; ( $Future::IO::IMPL //= __PACKAGE__ ) eq __PACKAGE__ or warn "Unable to set Future::IO implementation to " . __PACKAGE__ . " as it is already $Future::IO::IMPL\n"; } sub sleep { ... } sub sysread { ... } sub syswrite { ... } sub waitpid { ... } Optionally, you can also implement "sysread_exactly" and "syswrite_exactly": sub sysread_exactly { ... } sub syswrite_exactly { ... } If not, they will be emulated by Future::IO itself, making multiple calls to the non-_exactly versions. AUTHOR Paul Evans Future-IO-0.16/lib000755001750001750 014672062243 12514 5ustar00leoleo000000000000Future-IO-0.16/lib/Future000755001750001750 014672062243 13766 5ustar00leoleo000000000000Future-IO-0.16/lib/Future/IO.pm000444001750001750 4203214672062243 15011 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2019-2023 -- leonerd@leonerd.org.uk package Future::IO 0.16; use v5.14; use warnings; use Carp; # These need to be visible to sub override_impl my @alarms; my @readers; my @writers; our $IMPL; our $MAX_READLEN = 8192; our $MAX_WRITELEN = 8192; =head1 NAME C - Future-returning IO methods =head1 SYNOPSIS =for highlighter language=perl use Future::IO; my $delay = Future::IO->sleep( 5 ); # $delay will become done in 5 seconds time my $input = Future::IO->sysread( \*STDIN, 4096 ); # $input will yield some input from the STDIN IO handle =head1 DESCRIPTION This package provides a few basic methods that behave similarly to the same-named core perl functions relating to IO operations, but yield their results asynchronously via L instances. This is provided primarily as a decoupling mechanism, to allow modules to be written that perform IO in an asynchronous manner to depend directly on this, while allowing asynchronous event systems to provide an implementation of these operations. =head2 Default Implementation If the C method is not invoked, a default implementation of these operations is provided. This implementation allows a single queue of C or C calls on a single filehandle only, combined with C calls. It does not support C. It is provided for the simple cases where modules only need one filehandle (most likely a single network socket or hardware device handle), allowing such modules to work without needing a better event system. If there are both read/write and C futures pending, the implementation will use C to wait for either. This may be problematic on MSWin32, depending on what type of filehandle is involved. If C is not being used then the default implementation will temporarily set filehandles into blocking mode (by switching off the C flag) while performing IO on them. For cases where multiple filehandles are required, or for doing more involved IO operations, a real implementation based on an actual event loop should be provided. The following are known to exist; CPAN may provide others: =over 4 =item * L =item * L =item * L =back =head2 Unit Testing The replaceable implementation is also useful for writing unit test scripts. If the implementation is set to an instance of some sort of test fixture or mocking object, a unit test can check that the appropriate IO operations happen as part of the test. A testing module which does this is provided by L. =cut =head1 METHODS =cut =head2 accept $socketfh = await Future::IO->accept( $fh ); I Returns a L that will become done when a new connection has been accepted on the given filehandle, which should represent a listen-mode socket. The returned future will yield the newly-accepted client socket filehandle. =cut sub accept { shift; my ( $fh ) = @_; return ( $IMPL //= "Future::IO::_DefaultImpl" )->accept( $fh ); } =head2 alarm await Future::IO->alarm( $epoch ); I Returns a L that will become done at a fixed point in the future, given as an epoch timestamp (such as returned by C). This value may be fractional. =cut sub alarm { shift; my ( $epoch ) = @_; $IMPL //= "Future::IO::_DefaultImpl"; if( $IMPL->can( "alarm" ) ) { return $IMPL->alarm( $epoch ); } else { return $IMPL->sleep( $epoch - Time::HiRes::time() ); } } =head2 connect await Future::IO->connect( $fh, $name ); I Returns a L that will become done when a C has succeeded on the given filehandle to the given sockname address. =cut sub connect { shift; my ( $fh, $name ) = @_; return ( $IMPL //= "Future::IO::_DefaultImpl" )->connect( $fh, $name ); } =head2 sleep await Future::IO->sleep( $secs ); Returns a L that will become done a fixed delay from now, given in seconds. This value may be fractional. =cut sub sleep { shift; my ( $secs ) = @_; return ( $IMPL //= "Future::IO::_DefaultImpl" )->sleep( $secs ); } =head2 sysread $bytes = await Future::IO->sysread( $fh, $length ); Returns a L that will become done when at least one byte can be read from the given filehandle. It may return up to C<$length> bytes. On EOF, the returned future will yield an empty list (or C in scalar context). On any error (other than C / C which are ignored), the future fails with a suitable error message. Note specifically this may perform only a single C call, and thus is not guaranteed to actually return the full length. =cut sub sysread { shift; my ( $fh, $length ) = @_; return ( $IMPL //= "Future::IO::_DefaultImpl" )->sysread( $fh, $length ); } =head2 sysread_exactly $bytes = await Future::IO->sysread_exactly( $fh, $length ); I Returns a L that will become done when exactly the given number of bytes have been read from the given filehandle. It returns exactly C<$length> bytes. On EOF, the returned future will yield an empty list (or C in scalar context), even if fewer bytes have already been obtained. These bytes will be lost. On any error (other than C / C which are ignored), the future fails with a suitable error message. This may make more than one C call. =cut sub sysread_exactly { shift; my ( $fh, $length ) = @_; $IMPL //= "Future::IO::_DefaultImpl"; if( my $code = $IMPL->can( "sysread_exactly" ) ) { return $IMPL->$code( $fh, $length ); } return _sysread_into_buffer( $IMPL, $fh, $length, \(my $buffer = '') ); } sub _sysread_into_buffer { my ( $IMPL, $fh, $length, $bufref ) = @_; $IMPL->sysread( $fh, $length - length $$bufref )->then( sub { my ( $more ) = @_; return Future->done() if !defined $more; # EOF $$bufref .= $more; return Future->done( $$bufref ) if length $$bufref >= $length; return _sysread_into_buffer( $IMPL, $fh, $length, $bufref ); }); } =head2 sysread_until_eof $f = Future::IO->sysread_until_eof( $fh ); I Returns a L that will become done when the given filehandle reaches the EOF condition. The returned future will yield all of the bytes read up until that point. =cut sub sysread_until_eof { shift; my ( $fh ) = @_; $IMPL //= "Future::IO::_DefaultImpl"; return _sysread_until_eof( $IMPL, $fh, \(my $buffer = '') ); } sub _sysread_until_eof { my ( $IMPL, $fh, $bufref ) = @_; $IMPL->sysread( $fh, $MAX_READLEN )->then( sub { my ( $more ) = @_; return Future->done( $$bufref ) if !defined $more; $$bufref .= $more; return _sysread_until_eof( $IMPL, $fh, $bufref ); }); } =head2 syswrite $written_len = await Future::IO->syswrite( $fh, $bytes ); I Returns a L that will become done when at least one byte has been written to the given filehandle. It may write up to all of the bytes. On any error (other than C / C which are ignored) the future fails with a suitable error message. Note specifically this may perform only a single C call, and thus is not guaranteed to actually return the full length. =cut sub syswrite { shift; my ( $fh, $bytes ) = @_; return ( $IMPL //= "Future::IO::_DefaultImpl" )->syswrite( $fh, $bytes ); } =head2 syswrite_exactly $written_len = await Future::IO->syswrite_exactly( $fh, $bytes ); I Returns a L that will become done when exactly the given bytes have been written to the given filehandle. On any error (other than C / C which are ignored) the future fails with a suitable error message. This may make more than one C call. =cut sub syswrite_exactly { shift; my ( $fh, $bytes ) = @_; $IMPL //= "Future::IO::_DefaultImpl"; if( my $code = $IMPL->can( "syswrite_exactly" ) ) { return $IMPL->$code( $fh, $bytes ); } return _syswrite_from_buffer( $IMPL, $fh, \$bytes, length $bytes ); } sub _syswrite_from_buffer { my ( $IMPL, $fh, $bufref, $len ) = @_; $IMPL->syswrite( $fh, substr $$bufref, 0, $MAX_WRITELEN )->then( sub { my ( $written_len ) = @_; substr $$bufref, 0, $written_len, ""; return Future->done( $len ) if !length $$bufref; return _syswrite_from_buffer( $IMPL, $fh, $bufref, $len ); }); } =head2 waitpid $wstatus = await Future::IO->waitpid( $pid ); I Returns a L that will become done when the given child process terminates. The future will yield the wait status of the child process. This can be inspected by the usual bitshifting operations as per C<$?>: if( my $termsig = ($wstatus & 0x7f) ) { say "Terminated with signal $termsig"; } else { my $exitcode = ($wstatus >> 8); say "Terminated with exit code $exitcode"; } =cut sub waitpid { shift; my ( $pid ) = @_; return ( $IMPL //= "Future::IO::_DefaultImpl" )->waitpid( $pid ); } =head2 override_impl Future::IO->override_impl( $impl ); Sets a new implementation for C, replacing the minimal default internal implementation. This can either be a package name or an object instance reference, but must provide the methods named above. This method is intended to be called by event loops and other similar places, to provide a better integration. Another way, which doesn't involve directly depending on C or loading it, is to use the C<$IMPL> variable; see below. Can only be called once, and only if the default implementation is not in use, therefore a module that wishes to override this ought to invoke it as soon as possible on program startup, before any of the main C methods may have been called. =cut my $overridden; sub override_impl { shift; croak "Future::IO implementation is already overridden" if defined $IMPL; croak "Future::IO implementation cannot be set once default is already in use" if @alarms or @readers; ( $IMPL ) = @_; } =head2 load_impl Future::IO->load_impl( @names ); I Given a list of possible implementation module names, iterates through them attempting to load each one until a suitable module is found. Any errors encountered while loading each are ignored. If no module is found to be suitable, an exception is thrown that likely aborts the program. C<@names> should contain a list of Perl module names (which likely live in the C prefix). If any name does not contain a C<::> separator, it will have that prefix applied to it. This allows a conveniently short list; e.g. Future::IO->load_impl( qw( UV Glib IOAsync ) ); This method is intended to be called once, at startup, by the main containing program. Since it sets the implementation, it would generally be considered inappropriate to invoke this method from some additional module that might be loaded by a containing program. =cut sub load_impl { shift; my $loaded; foreach ( @_ ) { my $name = $_; $name =~ m/::/ or $name = "Future::IO::Impl::$name"; my $module = "$name.pm" =~ s{::}{/}gr; eval { require $module } or next; $loaded = 1; last; } $loaded or die "Unable to find a usable Future::IO::Impl subclass\n"; } =head2 HAVE_MULTIPLE_FILEHANDLES $has = Future::IO->HAVE_MULTIPLE_FILEHANDLES; I Returns true if the underlying IO implementation actually supports multiple filehandles. Most real support modules will return true here, but this returns false for the internal minimal implementation. =cut sub HAVE_MULTIPLE_FILEHANDLES { return ( $IMPL //= "Future::IO::_DefaultImpl" )->HAVE_MULTIPLE_FILEHANDLES; } package Future::IO::_DefaultImpl; use base qw( Future::IO::ImplBase ); use Carp; use Struct::Dumb qw( readonly_struct ); use Time::HiRes qw( time ); readonly_struct Alarm => [qw( time f )]; readonly_struct Reader => [qw( fh f )]; readonly_struct Writer => [qw( fh f )]; use constant HAVE_MULTIPLE_FILEHANDLES => 0; sub alarm { my $class = shift; return $class->_done_at( shift ); } sub sleep { my $class = shift; return $class->_done_at( time() + shift ); } sub ready_for_read { my $class = shift; my ( $fh ) = @_; croak "This implementation can only cope with a single pending filehandle in ->syread" if @readers and $readers[-1]->fh != $fh; my $f = Future::IO::_DefaultImpl::F->new; push @readers, Reader( $fh, $f ); $f->on_cancel( sub { my $f = shift; my $idx = 0; $idx++ while $idx < @readers and $readers[$idx]->f != $f; splice @readers, $idx, 1, (); }); return $f; } sub ready_for_write { my $class = shift; my ( $fh ) = @_; croak "This implementation can only cope with a single pending filehandle in ->syswrite" if @writers and $writers[-1]->fh != $fh; my $f = Future::IO::_DefaultImpl::F->new; push @writers, Writer( $fh, $f ); $f->on_cancel( sub { my $f = shift; my $idx = 0; $idx++ while $idx < @writers and $writers[$idx]->f != $f; splice @writers, $idx, 1, (); }); return $f; } sub waitpid { croak "This implementation cannot handle waitpid"; } sub _done_at { shift; my ( $time ) = @_; my $f = Future::IO::_DefaultImpl::F->new; # TODO: Binary search my $idx = 0; $idx++ while $idx < @alarms and $alarms[$idx]->time < $time; splice @alarms, $idx, 0, Alarm( $time, $f ); $f->on_cancel( sub { my $self = shift; my $idx = 0; $idx++ while $idx < @alarms and $alarms[$idx]->f != $f; splice @alarms, $idx, 1, (); } ); return $f; } package # hide Future::IO::_DefaultImpl::F; use base qw( Future ); use Time::HiRes qw( time ); sub _await_once { die "Cowardly refusing to sit idle and do nothing" unless @alarms || @readers || @writers; # If we always select() then problematic platforms like MSWin32 would # always break. Instead, we'll only select() if we're waiting on more than # one of alarm, reader, writer. If not we'll just presume the one operation # we're waiting for is definitely ready right now. my $do_select = @alarms || ( @readers && @writers ); my $rready; my $wready; redo_select: if( $do_select ) { my $rvec = ''; vec( $rvec, $readers[0]->fh->fileno, 1 ) = 1 if @readers; my $wvec = ''; vec( $wvec, $writers[0]->fh->fileno, 1 ) = 1 if @writers; my $maxwait; $maxwait = $alarms[0]->time - time() if @alarms; my $ret = select( $rvec, $wvec, undef, $maxwait ); $rready = $ret && @readers && vec( $rvec, $readers[0]->fh->fileno, 1 ); $wready = $ret && @writers && vec( $wvec, $writers[0]->fh->fileno, 1 ); } else { $rready = !!@readers; $wready = !!@writers; } my $was_blocking; if( $rready ) { my $rd = shift @readers; $was_blocking = $rd->fh->blocking(1) if !$do_select; $rd->f->done; $rd->fh->blocking(0) if !$do_select and !$was_blocking; } if( $wready ) { my $wr = shift @writers; $was_blocking = $wr->fh->blocking(1) if !$do_select; $wr->f->done; $wr->fh->blocking(0) if !$do_select and !$was_blocking; } my $now = time(); while( @alarms and $alarms[0]->time <= $now ) { ( shift @alarms )->f->done; } } =head2 await $f = $f->await; I Blocks until this future is ready (either by success or failure). Does not throw an exception if failed. =cut sub await { my $self = shift; _await_once until $self->is_ready; return $self; } =head1 THE C<$IMPL> VARIABLE I As an alternative to setting an implementation by using L, a package variable is also available that allows modules such as event systems to opportunistically provide an implementation without needing to depend on the module, or loading it C. Simply directly set that package variable to the name of an implementing package or an object instance. Additionally, implementors may use a name within the C namespace, suffixed by the name of their event system. For example, something like the following code arrangement is recommended. package Future::IO::Impl::BananaLoop; { no warnings 'once'; ( $Future::IO::IMPL //= __PACKAGE__ ) eq __PACKAGE__ or warn "Unable to set Future::IO implementation to " . __PACKAGE__ . " as it is already $Future::IO::IMPL\n"; } sub sleep { ... } sub sysread { ... } sub syswrite { ... } sub waitpid { ... } Optionally, you can also implement L and L: sub sysread_exactly { ... } sub syswrite_exactly { ... } If not, they will be emulated by C itself, making multiple calls to the non-C<_exactly> versions. =head1 AUTHOR Paul Evans =cut 0x55AA; Future-IO-0.16/lib/Future/IO000755001750001750 014672062243 14275 5ustar00leoleo000000000000Future-IO-0.16/lib/Future/IO/ImplBase.pm000444001750001750 1051314672062243 16504 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2019-2021 -- leonerd@leonerd.org.uk package Future::IO::ImplBase 0.16; use v5.14; use warnings; use Errno qw( EAGAIN EWOULDBLOCK EINPROGRESS ); use Socket qw( SOL_SOCKET SO_ERROR ); # connect() yields EWOULDBLOCK on MSWin32 use constant CONNECT_EWOULDBLOCK => ( $^O eq "MSWin32" ); use constant HAVE_MULTIPLE_FILEHANDLES => 1; =head1 NAME C - base class for C implementations =head1 DESCRIPTION This package provides a few utility methods that may help writing actual L implementation classes. It is entirely optional; implementations are not required to use it. =cut =head1 CLASS METHODS =cut =head2 APPLY __PACKAGE__->APPLY; Attempts to set the value of the C<$Future::IO::IMPL> variable to the name of the calling package. =cut sub APPLY { my $pkg = shift; no warnings 'once'; ( $Future::IO::IMPL //= $pkg ) eq $pkg or warn "Unable to set Future::IO implementation to $pkg". " as it is already $Future::IO::IMPL\n"; } =head1 DEFAULT METHODS These methods are provided based on lower-level functionallity that the implementing class should provide. =cut =head2 accept Implemented by wrapping C, as L uses. =cut sub accept { my $self = shift; my ( $fh ) = @_; return $self->ready_for_read( $fh )->then( sub { my $accepted = $fh->accept; if( $accepted ) { return Future->done( $accepted ); } else { return Future->fail( "accept: $!\n", accept => $fh, $! ); } } ); } =head2 alarm Implemented by wrapping C. =cut sub alarm { my $self = shift; my ( $time ) = @_; return $self->sleep( $time - Time::HiRes::time() ); } =head2 connect Implemented by wrapping C, as L uses. =cut sub connect { my $self = shift; my ( $fh, $name ) = @_; # We can't use IO::Socket->connect here because # https://github.com/Perl/perl5/issues/19326 my $ret = CORE::connect( $fh, $name ); my $errno = $!; if( $ret ) { return Future->done; } elsif( $errno != EINPROGRESS and !CONNECT_EWOULDBLOCK || $errno != EWOULDBLOCK ) { return Future->fail( "connect: $errno\n", connect => $fh, $errno ); } # not synchronous result return $self->ready_for_write( $fh )->then( sub { $errno = $fh->getsockopt( SOL_SOCKET, SO_ERROR ); if( $errno ) { $! = $errno; return Future->fail( "connect: $!\n", connect => $fh, $! ); } return Future->done; } ); } =head2 sysread Requires a lower-level method $f = $class->ready_for_read( $fh ); which should return a Future that completes when the given filehandle may be ready for reading. =cut sub _sysread1 { my $self = shift; my ( $f, $fh, $length ) = @_; my $waitf = $self->ready_for_read( $fh )->on_done( sub { my $ret = $fh->sysread( my $buf, $length ); if( $ret ) { $f->done( $buf ); } elsif( defined $ret ) { # EOF $f->done(); } elsif( $! == EAGAIN or $! == EWOULDBLOCK ) { # Try again $self->_sysread1( $f, $fh, $length ); } else { $f->fail( "sysread: $!\n", sysread => $fh, $! ); } }); $f //= $waitf->new; $f->on_cancel( $waitf ); return $f; } sub sysread { my $self = shift; return $self->_sysread1( undef, @_ ); } =head2 syswrite Requires a lower-level method $f = $class->ready_for_write( $fh ); which should return a Future that completes when the given filehandle may be ready for writing. =cut sub _syswrite1 { my $self = shift; my ( $f, $fh, $data ) = @_; my $waitf = $self->ready_for_write( $fh )->on_done( sub { my $len = $fh->syswrite( $data ); if( defined $len ) { $f->done( $len ); } elsif( $! == EAGAIN or $! == EWOULDBLOCK ) { # Try again $self->_syswrite1( $f, $fh, $data ); } else { $f->fail( "syswrite: $!\n", syswrite => $fh, $! ); } }); $f //= $waitf->new; $f->on_cancel( $waitf ); return $f; } sub syswrite { my $self = shift; return $self->_syswrite1( undef, @_ ); } =head1 AUTHOR Paul Evans =cut 0x55AA; Future-IO-0.16/lib/Future/IO/System.pm000444001750001750 1270114672062243 16275 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2023 -- leonerd@leonerd.org.uk package Future::IO::System 0.16; use v5.14; use warnings; use Carp; use Future::IO; =head1 NAME C - C-like methods for L =head1 SYNOPSIS =for highlighter language=perl use Future::IO; use Future::IO::System; my $f = Future::IO::System->system( "cmd", "args go", "here" ); # $f will become done when the command completes my $f = Future::IO::System->system_out( "cmd", "-v" ); my ( $status, $out ) = $f->get; # $status will contain the exit code and $out will contain what it wrote # to STDOUT =head1 DESCRIPTION This package contains a selection of methods that behave like the core C and related functions, running asynchronously via L. In particular, the L behaves somewhat like C and L behaves somewhat like L. =head2 Portability In order for this module to work at all, the underlying C implementation must support the L method. The default minimal implementation included with the module does not, but most of the additional implementations from CPAN will. In addition, the operation of this module uses techniques that only really work on full POSIX systems (such as Linux, Mac OS X, the various BSDs, etc). It is unlikely to work in places like MSWin32. =cut # TODO: Print at least some sort of warning if loaded on one of the weird # non-POSIX OSes =head1 METHODS =cut =head2 run ( $exitcode, ... ) = await Future::IO::System->run( argv => [ $path, @args ], ... ); I Runs the given C<$path> with the given C<@args> as a sub-process, optionally with some additional filehandles set up as determined by the other arguments. The returned L will yield the C exit code from the process when it terminates, and optionally the bytes read from the other filehandles that were set up. Takes the following named arguments =over 4 =item argv => ARRAY An array reference containing the path and arguments to pass to C in the child process. =item in => STRING If defined, create a pipe and assign the reading end to the child process's STDIN filehandle. The given string will then be written to the pipe, after which the pipe will be closed. =item want_out => BOOL If true, create a pipe and assign the writing end to the child process's STDOUT filehandle. The returned future will additionally contain all the bytes read from it until EOF. =item want_err => BOOL If true, create a pipe and assign the writing end to the child process's STDERR filehandle. The returned future will additionally contain all the bytes read from it until EOF. =back The remaining methods in this class are simplified wrappers of this one. =cut sub run { shift; my %params = @_; my $argv = $params{argv}; my $want_in = defined $params{in}; my $want_out = $params{want_out}; my $want_err = $params{want_err}; my @infh; pipe( $infh[0], $infh[1] ) or croak "Cannot pipe() - $!" if $want_in; my @outfh; pipe( $outfh[0], $outfh[1] ) or croak "Cannot pipe() - $!" if $want_out; my @errfh; pipe( $errfh[0], $errfh[1] ) or croak "Cannot pipe() - $!" if $want_err; defined( my $pid = fork() ) or croak "Cannot fork() - $!"; if( $pid ) { # parent my @f; push @f, Future::IO->waitpid( $pid ); if( $want_in ) { close $infh[0]; push @f, Future::IO->syswrite_exactly( $infh[1], $params{in} ) ->then( sub { close $infh[1]; Future->done() } ); } if( $want_out ) { close $outfh[1]; push @f, Future::IO->sysread_until_eof( $outfh[0] ); } if( $want_err ) { close $errfh[1]; push @f, Future::IO->sysread_until_eof( $errfh[0] ); } return Future->needs_all( @f ); } else { # child if( $want_in ) { close $infh[1]; POSIX::dup2( $infh[0]->fileno, 0 ); } if( $want_out ) { close $outfh[0]; POSIX::dup2( $outfh[1]->fileno, 1 ); } if( $want_err ) { close $errfh[0]; POSIX::dup2( $errfh[1]->fileno, 2 ); } exec( @$argv ) or POSIX::_exit( -1 ); } } =head2 system $exitcode = await Future::IO::System->system( $path, @args ); I Runs the given C<$path> with the given C<@args> as a sub-process with no extra filehandles. =cut sub system { my $self = shift; my @argv = @_; return $self->run( argv => \@argv ); } =head2 system_out ( $exitcode, $out ) = await Future::IO::System->system_out( $path, @args ); I Runs the given C<$path> with the given C<@args> as a sub-process with a new pipe as its STDOUT filehandle. The returned L will additionally yield the bytes read from the STDOUT pipe. =cut sub system_out { my $self = shift; my @argv = @_; return $self->run( argv => \@argv, want_out => 1 ); } =head1 TODO =over 4 =item * Add some OS portability guard warnings when loading the module on platforms not known to support it. =item * Consider what other features of modules like L or L to support here. Try not to go overboard. =back =cut =head1 AUTHOR Paul Evans =cut 0x55AA; Future-IO-0.16/t000755001750001750 014672062243 12211 5ustar00leoleo000000000000Future-IO-0.16/t/00use.t000444001750001750 22314672062243 13444 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; require Future::IO; require Future::IO::ImplBase; pass "Modules loaded"; done_testing; Future-IO-0.16/t/01sleep.t000444001750001750 21214672062243 13757 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Test::Future::IO::Impl; use Future::IO; run_tests 'sleep'; done_testing; Future-IO-0.16/t/02sysread.t000444001750001750 21414672062243 14324 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Test::Future::IO::Impl; use Future::IO; run_tests 'sysread'; done_testing; Future-IO-0.16/t/03sysread_exactly.t000444001750001750 170014672062243 16077 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use IO::Handle; use Future::IO; # ->sysread_exactly yielding bytes { pipe my ( $rd, $wr ) or die "Cannot pipe() - $!"; $wr->autoflush(); $wr->print( "BYTES" ); my $f = Future::IO->sysread_exactly( $rd, 5 ); my @read; no warnings 'redefine'; local *IO::Handle::sysread = sub { my ( $fh, undef, $len ) = @_; push @read, $len; return CORE::sysread( $fh, $_[1], 1 ); }; is( scalar $f->get, "BYTES", 'Future::IO->sysread_exactly eventually yields all the bytes' ); is( \@read, [ 5, 4, 3, 2, 1 ], 'IO::Handle->sysread override worked' ); } # ->sysread_exactly yielding EOF { pipe my ( $rd, $wr ) or die "Cannot pipe() - $!"; $wr->autoflush(); my $f = Future::IO->sysread_exactly( $rd, 5 ); $wr->print( "BY" ); $wr->close; undef $wr; is( [ $f->get ], [], 'Future::IO->sysread_exactly yields nothing on EOF' ); } done_testing; Future-IO-0.16/t/03sysread_until_eof.t000444001750001750 66014672062243 16376 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use IO::Handle; use Future::IO; # ->sysread_until_eof { pipe my ( $rd, $wr ) or die "Cannot pipe() - $!"; $wr->autoflush(); $wr->print( "BYTES" ); my $f = Future::IO->sysread_until_eof( $rd ); $wr->print( " HERE" ); $wr->close; is( scalar $f->get, "BYTES HERE", 'Future::IO->sysread_until_eof eventually yields all the bytes' ); } done_testing; Future-IO-0.16/t/04syswrite.t000444001750001750 21514672062243 14546 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Test::Future::IO::Impl; use Future::IO; run_tests 'syswrite'; done_testing; Future-IO-0.16/t/05syswrite_exactly.t000444001750001750 133114672062243 16320 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use IO::Handle; use Future::IO; # ->syswrite_exactly writing bytes { pipe my ( $rd, $wr ) or die "Cannot pipe() - $!"; my $f = Future::IO->syswrite_exactly( $wr, "ABC" ); my @written; no warnings 'redefine'; local *IO::Handle::syswrite = sub { my ( $fh, $bytes ) = @_; push @written, $bytes; return CORE::syswrite( $fh, substr $bytes, 0, 1 ); }; is( scalar $f->get, 3, 'Future::IO->syswrite_exactly eventually writes all bytes' ); is( \@written, [ "ABC", "BC", "C" ], 'IO::Handle->syswrite override worked' ); $rd->read( my $buf, 3 ); is( $buf, "ABC", 'Future::IO->syswrite_exactly wrote bytes' ); } done_testing; Future-IO-0.16/t/06connect.t000444001750001750 21414672062243 14307 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Test::Future::IO::Impl; use Future::IO; run_tests 'connect'; done_testing; Future-IO-0.16/t/07accept.t000444001750001750 21314672062243 14115 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Test::Future::IO::Impl; use Future::IO; run_tests 'accept'; done_testing; Future-IO-0.16/t/10sleep+sysread.t000444001750001750 147114672062243 15455 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use IO::Handle; use Future::IO; plan skip_all => "Cannot select() on pipes on Windows" if $^O eq "MSWin32"; # sleep + sysread IO ready { pipe my ( $rd, $wr ) or die "Cannot pipe() - $!"; $wr->autoflush(); $wr->print( "BYTES" ); my $f = Future->needs_any( Future::IO->sysread( $rd, 5 ), Future::IO->sleep( 2 ), ); is( scalar $f->get, "BYTES", 'Future::IO ->sleep ->sysread concurrently yields bytes' ); } # sleep + sysread timeout { pipe my ( $rd, $wr ) or die "Cannot pipe() - $!"; my $f = Future->needs_any( Future::IO->sysread( $rd, 5 ), Future::IO->sleep( 0.2 )->then_done( "timeout" ), ); is( scalar $f->get, "timeout", 'Future::IO ->sleep ->sysread concurrently yields timeout' ); } done_testing; Future-IO-0.16/t/20impl-override.t000444001750001750 135714672062243 15461 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Future::IO; my @impl_args; my $impl_f; { package TestImplementation; sub sleep { shift; @impl_args = @_; return $impl_f; } sub sysread { shift; @impl_args = @_; return $impl_f; } } Future::IO->override_impl( "TestImplementation" ); # sleep { $impl_f = Future->new; my $f = Future::IO->sleep( 5 ); is( \@impl_args, [ 5 ], '->sleep args' ); ref_is( $f, $impl_f, '->sleep return' ); $f->cancel; } # sysread { $impl_f = Future->new; my $f = Future::IO->sysread( "FH", 1024 ); is( \@impl_args, [ "FH", 1024 ], '->sysread args' ); ref_is( $f, $impl_f, '->sysread return' ); $f->cancel; } done_testing; Future-IO-0.16/t/21impl-before-load.t000444001750001750 47114672062243 15776 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; no warnings 'once'; $Future::IO::IMPL = "TestImplementation"; require Future::IO; { package TestImplementation; sub sleep { return "TestFuture" } } is( Future::IO->sleep(123), "TestFuture", 'override before require still works' ); done_testing; Future-IO-0.16/t/30system.t000444001750001750 344614672062243 14231 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use IO::Handle; use Future::IO; use Future::IO::System; sub load_impl_supporting_waitpid { # We need a Future::IO impl that can ->waitpid foreach my $impl (qw( Future::IO::Impl::UV Future::IO::Impl::Glib Future::IO::Impl::IOAsync )) { eval { require "$impl.pm" =~ s{::}{/}gr; 1 } or next; $impl->can( "waitpid" ) and return; # Clear that impl before trying again undef $Future::IO::IMPL; } plan skip_all => "Unable to find a Future::IO impl that supports ->waitpid"; } load_impl_supporting_waitpid(); # system { my $f = Future::IO::System->system( $^X, "-e", "exit 5" ); is( scalar $f->get, 5<<8, 'Future::IO::System->system future yields exit status' ); } # system_out { my $f = Future::IO::System->system_out( $^X, "-e", "print qq(Hello, world\\n)" ); my ( $exitcode, $out ) = $f->get; is( $exitcode, 0, 'exitcode from ->system_out Future' ); is( $out, "Hello, world\n", 'out from ->system_out Future' ); } # run with in+out { my $f = Future::IO::System->run( argv => [ $^X, "-e", "print uc( scalar );" ], in => "hello, world", want_out => 1, ); my ( $exitcode, $out ) = $f->get; is( $exitcode, 0, 'exitcode from ->run+in+out Future' ); is( $out, "HELLO, WORLD", 'out from ->run+in+out Future' ); } # run with out+err { my $f = Future::IO::System->run( argv => [ $^X, "-e", "print qq(OUT\\n); print STDERR qq(ERR\\n);" ], want_out => 1, want_err => 1, ); my ( $exitcode, $out, $err ) = $f->get; is( $exitcode, 0, 'exitcode from ->run+out+err Future' ); is( $out, "OUT\n", 'out from ->run+out+err Future' ); is( $err, "ERR\n", 'err from ->run+out+err Future' ); } done_testing; Future-IO-0.16/t/90rt150117.t000444001750001750 351114672062243 14010 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Test::ExpectAndCheck 0.06; # ->will_return_using can modify caller args use Errno qw( EAGAIN ); # We need to ensure we have a pureperl Future implementation for the following # helper function to work properly BEGIN { $ENV{PERL_FUTURE_NO_XS} = 1; } use Future; use Future::IO; BEGIN { Future->isa( "Future::PP" ) or plan skip_all => "Unable to ensure that Future uses the pure-perl implementation"; } sub get_future_oncancel { my ( $f ) = @_; # gut-wrenching into Future my $on_cancel = $f->{on_cancel} or return; return grep { defined } @$on_cancel; } sub count_future_dependents { my ( $f ) = @_; my $count = 0; my @queue = ( $f ); while( @queue ) { my $f = shift @queue; $count++; push @queue, get_future_oncancel $f; } return $count; } my ( $controller, $puppet ) = Test::ExpectAndCheck->create; # ->sysread does not build long future chains on EAGAIN { my $read_f; my $dep_count; # 100 times yield undef/EAGAIN for( 1 .. 100 ) { $controller->expect( blocking => 1 ) ->will_return( 1 ); $controller->expect( sysread => Test::Deep::ignore(), 128 ) ->will_return_using( sub { $! = EAGAIN; return undef } ); } $controller->expect( blocking => 1 ) ->will_return( 1 ); $controller->expect( sysread => Test::Deep::ignore(), 128 ) ->will_return_using( sub { my ( $args ) = @_; $args->[0] = "result"; $dep_count = count_future_dependents $read_f; return length $args->[0]; }); $read_f = Future::IO->sysread( $puppet, 128 ); is( $read_f->get, "result", '->sysread yields result' ); is( $dep_count, 1, '->sysread future did not build a big dependent chain' ); $controller->check_and_clear( '->sysread' ); } done_testing; Future-IO-0.16/t/99pod.t000444001750001750 25514672062243 13461 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok();