Future-XS-0.12000755001750001750 014543104252 11757 5ustar00leoleo000000000000Future-XS-0.12/.editorconfig000444001750001750 5314543104252 14527 0ustar00leoleo000000000000root = true [*.{pm,pl,t}] indent_size = 3 Future-XS-0.12/Build.PL000444001750001750 207514543104252 13414 0ustar00leoleo000000000000use v5; use strict; use warnings; use Module::Build; my @extra_compiler_flags = qw( -Iinclude -Ihax -ggdb ); # Perl 5.36 made -std=c99 standard; before then we'll have to request it specially push @extra_compiler_flags, qw( -std=c99 ) if $^V lt v5.36.0; push @extra_compiler_flags, qw( -DDEBUGGING=-g ) if $^X =~ m|/debugperl|; my $build = Module::Build->new( module_name => 'Future::XS', requires => { 'perl' => '5.024', # RT145597 'Future' => '0.48_001', # for Future::_base }, test_requires => { 'Test2::V0' => 0, }, configure_requires => { 'Module::Build' => '0.4004', # test_requires }, license => 'perl', create_license => 1, create_readme => 1, extra_compiler_flags => \@extra_compiler_flags, c_source => [ "src/" ], ); if( eval { require Devel::MAT::Dumper::Helper and Devel::MAT::Dumper::Helper->VERSION( '0.44' ) } ) { Devel::MAT::Dumper::Helper->extend_module_build( $build ); } # cheating $build->add_property( 'optimize' ); $build->config( optimize => '' ); $build->create_build_script; Future-XS-0.12/Changes000444001750001750 676314543104252 13423 0ustar00leoleo000000000000Revision history for Future-XS 0.12 2023-12-27 [BUGFIXES] * Ensure the "not yet ready ..." exception is thrown from the correct caller * Include the current state name in exception message for forbidden state changes 0.11 2023-10-26 [CHANGES] * Module style updates: + Swap unit tests from `Test::More` to `Test2::V0` * Removed the now-redundant `sub import` [BUGFIXES] * Avoid memory leak with combined `->followed_by` + `->then` (RT150198) 0.10 2023-03-28 [BUGFIXES] * Remember to destroy the `catches` HV after immediate `->thencatch` (RT145699) * Many other small refcount-related bugfixes * Provide MAGIC with an `svt_dup` function on threaded perls, so as not to break objects on destruction of sidecar threads * Don't SEGV when DESTROY is run during global destruction and some SVs have already been reclaimed 0.09 2023-03-17 [CHANGES] * Improved rethrow of failures to set a more accurate thrower location file+line number (related to RT145249) 0.08 2022-12-11 [CHANGES] * Now requires perl v5.24 or later This is due to a bugfix for RT145597 which does not work on earlier perls https://rt.cpan.org/Ticket/Display.html?id=145597 [BUGFIXES] * Remember to PUTBACK after POPx'ing after a call_method/call_sv * Throw an exception if instance methods are not called on an instance, rather than segfaulting 0.07 2022-12-06 [BUGFIXES] * Ensure that `$f->retain` on a completed Future::XS returns the future and not undef (RT145168) * Include the real stringified future SV in croak messages rather than the placeholder `(SELF)` text 0.06 2022-09-27 [BUGFIXES] * Bugfixes for convergent constructors on pre-cancelled futures (RT144459) 0.05 2022-09-23 [BUGFIXES] * Always invoke the real ->new method for prototype cloning * Only inflate real Future::Exception instances, not any object * Implement compaction logic for on_cancel AVs * Don't crash on attempts to revoke cancellation from lost futures 0.04 2022-09-13 [CHANGES] * Implement remaining bits of API and behaviour in order to make the full set of Future dist tests pass [BUGFIXES] * Many many (many) bugfixes to refcounting and reference tracking, especially around the on_cancel revocation list * getenv() needs aTHX when running on Windows 0.03 2022-08-16 [CHANGES] * Added many new methods: + the new udata API + the timing capture methods + ->get and ->await + the `_with_f` variant methods * Implement proper subclassing support * Upgrade non-future results from sequencing methods into future instances [BUGFIXES] * Declare test-time dependency of Test::Fatal 0.02 2022-08-11 [BUGFIXES] * Declare test-time dependencies of Test::Identity and Test::Refcount * Before perl 5.36 we'll have to add -std=c99 to the compiler flags * Fix weird typo of `RETVAL` in .xs file * Use `XS_INTERNAL()` rather than `static XS()` because cygwin 0.01 2022-08-10 First version, released on an unsuspecting world. Future-XS-0.12/LICENSE000444001750001750 4375514543104252 13157 0ustar00leoleo000000000000This software is copyright (c) 2023 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) 2023 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 Artistic License 1.0 --- This software is Copyright (c) 2023 by Paul Evans . This is free software, licensed under: The 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. - "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 ftp.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) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting 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. 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 whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. 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-XS-0.12/MANIFEST000444001750001750 46614543104252 13233 0ustar00leoleo000000000000.editorconfig Build.PL Changes hax/av-utils.c.inc hax/croak_from_caller.c.inc hax/cv_set_anysv_refcounted.c.inc hax/perl-backcompat.c.inc include/future.h lib/Future/XS.pm lib/Future/XS.xs LICENSE MANIFEST This list of files META.json META.yml README src/future.c t/00use.t t/50thread.t t/90leak.t t/99pod.t Future-XS-0.12/META.json000444001750001750 220314543104252 13532 0ustar00leoleo000000000000{ "abstract" : "experimental XS implementation of C", "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-XS", "prereqs" : { "build" : { "requires" : { "ExtUtils::CBuilder" : "0" } }, "configure" : { "requires" : { "Module::Build" : "0.4004" } }, "runtime" : { "requires" : { "Future" : "0.48_001", "perl" : "5.024" } }, "test" : { "requires" : { "Test2::V0" : "0" } } }, "provides" : { "Future::XS" : { "file" : "lib/Future/XS.pm", "version" : "0.12" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ] }, "version" : "0.12", "x_serialization_backend" : "JSON::PP version 4.07" } Future-XS-0.12/META.yml000444001750001750 125114543104252 13364 0ustar00leoleo000000000000--- abstract: 'experimental XS implementation of C' author: - 'Paul Evans ' build_requires: ExtUtils::CBuilder: '0' Test2::V0: '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-XS provides: Future::XS: file: lib/Future/XS.pm version: '0.12' requires: Future: 0.48_001 perl: '5.024' resources: license: http://dev.perl.org/licenses/ version: '0.12' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Future-XS-0.12/README000444001750001750 417214543104252 13000 0ustar00leoleo000000000000NAME Future::XS - experimental XS implementation of Future SYNOPSIS my $future = Future::XS->new; perform_some_operation( on_complete => sub { $future->done( @_ ); } ); $future->on_ready( sub { say "The operation is complete"; } ); DESCRIPTION This module provides an XS-based implementation of the Future class. It is currently experimental and shipped in its own distribution for testing purposes, though once it seems stable the plan is to move it into the main Future distribution and load it automatically in favour of the pureperl implementation on supported systems. Future::XS and threads In a program not involving multiple threads, this module behaves entirely as expected, following the behaviour of the regular pure-perl Future implementation (regardless of whether or not the perl interpreter is actually built to support threads). When multiple threads are created, previous versions of this module would most likely crash. The current version (0.10) fixes enough of the logic, that future instances that are only ever accessed from one thread (either the initial main thread, or any additional sidecar threads) will work fine. However, future instances cannot currently cross the boundary between threads. Any instances that were created before a new thread is made will no longer be accessible within that thread, and instances may not be returned as the result of the thread exit value. Some of these restrictions may be relaxed in later versions. Attempts to access a future instance created in one thread from another thread will raise an exception: Future::XS instance IO::Async::Future=SCALAR(0x...) is not available in this thread at ... As a special case for process cleanup activities, the ->cancel method does not throw this exception, but simply returns silently. This is because cleanup code such as DESTROY methods or defer blocks often attempt to call this on existing instances. AUTHOR Paul Evans Future-XS-0.12/hax000755001750001750 014543104252 12537 5ustar00leoleo000000000000Future-XS-0.12/hax/av-utils.c.inc000444001750001750 131414543104252 15353 0ustar00leoleo000000000000/* vi: set ft=c : */ // TODO: move av_push_from_av() from perl-additions.c.inc to here #define XPUSHs_from_AV(av) \ do { \ EXTEND(SP, AvFILL(av)+1); \ size_t i; \ for(i = 0; i < AvFILL(av)+1; i++) \ PUSHs(AvARRAY(av)[i]); \ } while(0) #define av_push_svn(av, svp, n) S_av_push_svn(aTHX_ av, svp, n) static void S_av_push_svn(pTHX_ AV *av, SV **svp, size_t n) { while(n) { av_push(av, newSVsv(*svp)); svp++; n--; } } #define newAV_svn_dup(svp, n) S_newAV_svn_dup(aTHX_ svp, n) static AV *S_newAV_svn_dup(pTHX_ SV **svp, size_t n) { AV *av = newAV(); av_push_svn(av, svp, n); return av; } Future-XS-0.12/hax/croak_from_caller.c.inc000444001750001750 154614543104252 17262 0ustar00leoleo000000000000/* vi: set ft=c : */ static void S_croaksv_from_caller(pTHX_ SV *msg_sv) __attribute__noreturn__; static void S_croaksv_from_caller(pTHX_ SV *msg_sv) { I32 count = 0; const PERL_CONTEXT *cx; while((cx = caller_cx(count, NULL))) { count++; /* TODO: Skip internal call frames? */ /* warn("TODO: maybe croak from caller where caller stash is %s\n", * HvNAME(CopSTASH(cx->blk_oldcop))); */ PL_curcop = cx->blk_oldcop; break; } croak_sv(msg_sv); } #define croak_from_caller(fmt, ...) S_croak_from_caller(aTHX_ fmt, __VA_ARGS__) static void S_croak_from_caller(pTHX_ const char *fmt, ...) __attribute__noreturn__; static void S_croak_from_caller(pTHX_ const char *fmt, ...) { va_list args; va_start(args, fmt); SV *msg_sv = sv_2mortal(vnewSVpvf(fmt, &args)); va_end(args); S_croaksv_from_caller(aTHX_ msg_sv); } Future-XS-0.12/hax/cv_set_anysv_refcounted.c.inc000444001750001750 215014543104252 20527 0ustar00leoleo000000000000/* vi: set ft=c : */ #if HAVE_PERL_VERSION(5, 26, 0) # define XSANY_sv XSANY.any_sv # define CvXSUBANY_sv(cv) CvXSUBANY(cv).any_sv # define CvXSUBANY_sv_set(cv, sv) (CvXSUBANY(cv).any_sv = (sv)) #else /* Older perls did not have a .any_sv; we'll just cast the .any_ptr pointer */ # define XSANY_sv ((SV *)XSANY.any_ptr) # define CvXSUBANY_sv(cv) ((SV *)CvXSUBANY(cv).any_ptr) # define CvXSUBANY_sv_set(cv, sv) (CvXSUBANY(cv).any_ptr = (sv)) #endif #ifdef CvREFCOUNTED_ANYSV # define HAVE_CVREFCOUNTED_ANYSV #endif #ifndef HAVE_CVREFCOUNTED_ANYSV static int free_anysv_refcounted(pTHX_ SV *sv, MAGIC *mg) { SvREFCNT_dec(CvXSUBANY_sv((CV *)sv)); return 0; } static MGVTBL vtbl_anysv_refcounted = { .svt_free = &free_anysv_refcounted, }; #endif #define cv_set_anysv_refcounted(cv, sv) S_cv_set_anysv_refcounted(aTHX_ cv, sv) static void S_cv_set_anysv_refcounted(pTHX_ CV *cv, SV *sv) { CvXSUBANY_sv_set(cv, sv); #ifdef HAVE_CVREFCOUNTED_ANYSV CvREFCOUNTED_ANYSV_on(cv); #else sv_magicext((SV *)cv, NULL, PERL_MAGIC_ext, &vtbl_anysv_refcounted, NULL, 0); #endif } Future-XS-0.12/hax/perl-backcompat.c.inc000444001750001750 1410114543104252 16671 0ustar00leoleo000000000000/* vi: set ft=c : */ #define HAVE_PERL_VERSION(R, V, S) \ (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S)))))) #ifndef NOT_REACHED # define NOT_REACHED assert(0) #endif #ifndef SvTRUE_NN # define SvTRUE_NN(sv) SvTRUE(sv) #endif #ifndef G_LIST # define G_LIST G_ARRAY #endif #if !HAVE_PERL_VERSION(5, 18, 0) typedef AV PADNAMELIST; # define PadlistARRAY(pl) ((PAD **)AvARRAY(pl)) # define PadlistNAMES(pl) (*PadlistARRAY(pl)) typedef SV PADNAME; # define PadnamePV(pn) (SvPOKp(pn) ? SvPVX(pn) : NULL) # define PadnameLEN(pn) SvCUR(pn) # define PadnameIsSTATE(pn) (!!SvPAD_STATE(pn)) # define PadnameOUTER(pn) (SvFAKE(pn) && !SvPAD_STATE(pn)) # define PadnamelistARRAY(pnl) AvARRAY(pnl) # define PadnamelistMAX(pnl) AvFILLp(pnl) # define PadARRAY(p) AvARRAY(p) # define PadMAX(pad) AvFILLp(pad) #endif #if !HAVE_PERL_VERSION(5, 22, 0) # define CvPADLIST_set(cv, padlist) (CvPADLIST(cv) = padlist) # define newPADNAMEpvn(p,n) S_newPADNAMEpvn(aTHX_ p,n) static PADNAME *S_newPADNAMEpvn(pTHX_ const char *pv, STRLEN n) { PADNAME *pn = newSVpvn(pv, n); /* PADNAMEs need to be at least SVt_PVNV in order to store the COP_SEQ_* * fields */ sv_upgrade(pn, SVt_PVNV); return pn; } # define PadnameREFCNT_dec(pn) SvREFCNT_dec(pn) #endif #ifndef av_count # define av_count(av) (AvFILL(av) + 1) #endif #ifndef av_fetch_simple # define av_fetch_simple(av, idx, lval) av_fetch(av, idx, lval) #endif #ifndef av_push_simple # define av_push_simple(av, sv) av_push(av, sv) #endif #ifndef av_top_index # define av_top_index(av) AvFILL(av) #endif #ifndef block_end # define block_end(a,b) Perl_block_end(aTHX_ a,b) #endif #ifndef block_start # define block_start(a) Perl_block_start(aTHX_ a) #endif #ifndef cophh_exists_pvs # define cophh_exists_pvs(a,b,c) cBOOL(cophh_fetch_pvs(a,b,c)) #endif #ifndef cv_clone # define cv_clone(a) Perl_cv_clone(aTHX_ a) #endif #ifndef intro_my # define intro_my() Perl_intro_my(aTHX) #endif #ifndef pad_alloc # define pad_alloc(a,b) Perl_pad_alloc(aTHX_ a,b) #endif #ifndef CX_CUR # define CX_CUR() (&cxstack[cxstack_ix]) #endif #if HAVE_PERL_VERSION(5, 24, 0) # define OLDSAVEIX(cx) (cx->blk_oldsaveix) #else # define OLDSAVEIX(cx) (PL_scopestack[cx->blk_oldscopesp-1]) #endif #ifndef OpSIBLING # define OpSIBLING(op) ((op)->op_sibling) #endif #ifndef OpHAS_SIBLING # define OpHAS_SIBLING(op) (cBOOL(OpSIBLING(op))) #endif #ifndef OpMORESIB_set # define OpMORESIB_set(op,sib) ((op)->op_sibling = (sib)) #endif #ifndef OpLASTSIB_set /* older perls don't need to store this at all */ # define OpLASTSIB_set(op,parent) #endif #ifndef op_convert_list # define op_convert_list(type, flags, o) S_op_convert_list(aTHX_ type, flags, o) static OP *S_op_convert_list(pTHX_ I32 type, I32 flags, OP *o) { /* A minimal recreation just for our purposes */ assert( /* A hardcoded list of the optypes we know this will work for */ type == OP_ENTERSUB || type == OP_JOIN || type == OP_PUSH || 0); o->op_type = type; o->op_flags |= flags; o->op_ppaddr = PL_ppaddr[type]; o = PL_check[type](aTHX_ o); /* op_std_init() */ if(PL_opargs[type] & OA_RETSCALAR) o = op_contextualize(o, G_SCALAR); if(PL_opargs[type] & OA_TARGET && !o->op_targ) o->op_targ = pad_alloc(type, SVs_PADTMP); return o; } #endif #ifndef newMETHOP_named # define newMETHOP_named(type, flags, name) newSVOP(type, flags, name) #endif #ifndef PARENT_PAD_INDEX_set # if HAVE_PERL_VERSION(5, 22, 0) # define PARENT_PAD_INDEX_set(pn,val) (PARENT_PAD_INDEX(pn) = val) # else /* stolen from perl-5.20.0's pad.c */ # define PARENT_PAD_INDEX_set(sv,val) \ STMT_START { ((XPVNV*)SvANY(sv))->xnv_u.xpad_cop_seq.xlow = (val); } STMT_END # endif #endif /* On Perl 5.14 this had a different name */ #ifndef pad_add_name_pvn #define pad_add_name_pvn(name, len, flags, typestash, ourstash) MY_pad_add_name(aTHX_ name, len, flags, typestash, ourstash) static PADOFFSET MY_pad_add_name(pTHX_ const char *name, STRLEN len, U32 flags, HV *typestash, HV *ourstash) { /* perl 5.14's Perl_pad_add_name requires a NUL-terminated name */ SV *namesv = sv_2mortal(newSVpvn(name, len)); return Perl_pad_add_name(aTHX_ SvPV_nolen(namesv), SvCUR(namesv), flags, typestash, ourstash); } #endif #if !HAVE_PERL_VERSION(5, 26, 0) # define isIDFIRST_utf8_safe(s, e) (PERL_UNUSED_ARG(e), isIDFIRST_utf8(s)) # define isIDCONT_utf8_safe(s, e) (PERL_UNUSED_ARG(e), isIDCONT_utf8(s)) #endif #ifndef CXp_EVALBLOCK /* before perl 5.34 this was called CXp_TRYBLOCK */ # define CXp_EVALBLOCK CXp_TRYBLOCK #endif #if !HAVE_PERL_VERSION(5, 26, 0) # define sv_set_undef(sv) sv_setsv(sv, &PL_sv_undef) #endif #ifndef newAVav # define newAVav(av) S_newAVav(aTHX_ av) static AV *S_newAVav(pTHX_ AV *av) { AV *ret = newAV(); U32 count = av_count(av); U32 i; for(i = 0; i < count; i++) av_push(ret, newSVsv(AvARRAY(av)[i])); return ret; } #endif #if !defined(sv_derived_from_hv) && HAVE_PERL_VERSION(5, 16, 0) # define sv_derived_from_hv(sv, hv) MY_sv_derived_from_hv(aTHX_ sv, hv) static bool MY_sv_derived_from_hv(pTHX_ SV *sv, HV *hv) { char *hvname = HvNAME(hv); if(!hvname) return FALSE; return sv_derived_from_pvn(sv, hvname, HvNAMELEN(hv), HvNAMEUTF8(hv) ? SVf_UTF8 : 0); } #endif #ifndef xV_FROM_REF # ifdef PERL_USE_GCC_BRACE_GROUPS # define xV_FROM_REF(XV, ref) \ ({ SV *_ref = ref; assert(SvROK(_ref)); assert(SvTYPE(SvRV(_ref)) == SVt_PV ## XV); (XV *)(SvRV(_ref)); }) # else # define xV_FROM_REF(XV, ref) ((XV *)SvRV(ref)) # endif # define AV_FROM_REF(ref) xV_FROM_REF(AV, ref) # define CV_FROM_REF(ref) xV_FROM_REF(CV, ref) # define HV_FROM_REF(ref) xV_FROM_REF(HV, ref) #endif #ifndef newPADxVOP # define newPADxVOP(type, flags, padix) S_newPADxVOP(aTHX_ type, flags, padix) static OP *S_newPADxVOP(pTHX_ I32 type, I32 flags, PADOFFSET padix) { OP *op = newOP(type, flags); op->op_targ = padix; return op; } #endif Future-XS-0.12/include000755001750001750 014543104252 13402 5ustar00leoleo000000000000Future-XS-0.12/include/future.h000444001750001750 1003114543104252 15235 0ustar00leoleo000000000000#ifndef __FUTURE_H__ #define __FUTURE_H__ #define future_boot() Future_boot(aTHX) void Future_boot(pTHX); #define future_new(cls) Future_new(aTHX_ cls) SV *Future_new(pTHX_ const char *cls); #define future_destroy(f) Future_destroy(aTHX_ f) void Future_destroy(pTHX_ SV *f); #define sv_is_future(sv) Future_sv_is_future(aTHX_ sv) bool Future_sv_is_future(pTHX_ SV *sv); #define future_is_ready(f) Future_is_ready(aTHX_ f) bool Future_is_ready(pTHX_ SV *f); #define future_is_done(f) Future_is_done(aTHX_ f) bool Future_is_done(pTHX_ SV *f); #define future_is_failed(f) Future_is_failed(aTHX_ f) bool Future_is_failed(pTHX_ SV *f); #define future_is_cancelled(f) Future_is_cancelled(aTHX_ f) bool Future_is_cancelled(pTHX_ SV *f); #define future_donev(f, svp, n) Future_donev(aTHX_ f, svp, n) void Future_donev(pTHX_ SV *f, SV **svp, size_t n); #define future_failv(f, svp, n) Future_failv(aTHX_ f, svp, n) void Future_failv(pTHX_ SV *f, SV **svp, size_t n); #define future_failp(f, s) Future_failp(aTHX_ f, s) void Future_failp(pTHX_ SV *f, const char *s); #define future_on_cancel(f, code) Future_on_cancel(aTHX_ f, code) void Future_on_cancel(pTHX_ SV *f, SV *code); #define future_on_ready(f, code) Future_on_ready(aTHX_ f, code) void Future_on_ready(pTHX_ SV *f, SV *code); #define future_on_done(f, code) Future_on_done(aTHX_ f, code) void Future_on_done(pTHX_ SV *f, SV *code); #define future_on_fail(f, code) Future_on_fail(aTHX_ f, code) void Future_on_fail(pTHX_ SV *f, SV *code); #define future_get_result_av(f, await) Future_get_result_av(aTHX_ f, await) AV *Future_get_result_av(pTHX_ SV *f, bool await); #define future_get_failure_av(f) Future_get_failure_av(aTHX_ f) AV *Future_get_failure_av(pTHX_ SV *f); #define future_cancel(f) Future_cancel(aTHX_ f) void Future_cancel(pTHX_ SV *f); #define future_without_cancel(f) Future_without_cancel(aTHX_ f) SV *Future_without_cancel(pTHX_ SV *f); enum { FUTURE_THEN_WITH_F = (1<<0), }; #define future_then(f, flags, thencode, elsecode) Future_then(aTHX_ f, flags, thencode, elsecode) SV *Future_then(pTHX_ SV *f, U32 flags, SV *thencode, SV *elsecode); #define future_thencatch(f, flags, thencode, catches, elsecode) Future_thencatch(aTHX_ f, flags, thencode, catches, elsecode) SV *Future_thencatch(pTHX_ SV *f, U32 flags, SV *thencode, HV *catches, SV *elsecode); #define future_followed_by(f, code) Future_followed_by(aTHX_ f, code) SV *Future_followed_by(pTHX_ SV *f, SV *code); /* convergent constructors */ #define future_new_waitallv(cls, subs, n) Future_new_waitallv(aTHX_ cls, subs, n) SV *Future_new_waitallv(pTHX_ const char *cls, SV **subs, size_t n); #define future_new_waitanyv(cls, subs, n) Future_new_waitanyv(aTHX_ cls, subs, n) SV *Future_new_waitanyv(pTHX_ const char *cls, SV **subs, size_t n); #define future_new_needsallv(cls, subs, n) Future_new_needsallv(aTHX_ cls, subs, n) SV *Future_new_needsallv(pTHX_ const char *cls, SV **subs, size_t n); #define future_new_needsanyv(cls, subs, n) Future_new_needsanyv(aTHX_ cls, subs, n) SV *Future_new_needsanyv(pTHX_ const char *cls, SV **subs, size_t n); enum FutureSubFilter { FUTURE_SUBS_PENDING, FUTURE_SUBS_READY, FUTURE_SUBS_DONE, FUTURE_SUBS_FAILED, FUTURE_SUBS_CANCELLED, }; #define future_mPUSH_subs(f, filter) Future_mPUSH_subs(aTHX_ f, filter) Size_t Future_mPUSH_subs(pTHX_ SV *f, enum FutureSubFilter filter); #define future_get_btime(f) Future_get_btime(aTHX_ f) struct timeval Future_get_btime(pTHX_ SV *f); #define future_get_rtime(f) Future_get_rtime(aTHX_ f) struct timeval Future_get_rtime(pTHX_ SV *f); #define future_set_label(f, label) Future_set_label(aTHX_ f, label) void Future_set_label(pTHX_ SV *f, SV *label); #define future_get_label(f) Future_get_label(aTHX_ f) SV *Future_get_label(pTHX_ SV *f); #define future_set_udata(f, key, value) Future_set_udata(aTHX_ f, key, value) void Future_set_udata(pTHX_ SV *f, SV *key, SV *value); #define future_get_udata(f, key) Future_get_udata(aTHX_ f, key) SV *Future_get_udata(pTHX_ SV *f, SV *key); void Future_reread_environment(pTHX); #endif Future-XS-0.12/lib000755001750001750 014543104252 12525 5ustar00leoleo000000000000Future-XS-0.12/lib/Future000755001750001750 014543104252 13777 5ustar00leoleo000000000000Future-XS-0.12/lib/Future/XS.pm000444001750001750 507414543104252 15032 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, 2022 -- leonerd@leonerd.org.uk package Future::XS 0.12; use v5.14; use warnings; use Carp; require XSLoader; XSLoader::load( __PACKAGE__, our $VERSION ); use Time::HiRes qw( tv_interval ); # Future::_base is provided in Future.pm itself require Future; our @ISA = qw( Future::_base ); our @CARP_NOT = qw( Future Future::_base ); require Future::Exception; =head1 NAME C - experimental XS implementation of C =head1 SYNOPSIS my $future = Future::XS->new; perform_some_operation( on_complete => sub { $future->done( @_ ); } ); $future->on_ready( sub { say "The operation is complete"; } ); =head1 DESCRIPTION This module provides an XS-based implementation of the L class. It is currently experimental and shipped in its own distribution for testing purposes, though once it seems stable the plan is to move it into the main C distribution and load it automatically in favour of the pureperl implementation on supported systems. =head2 Future::XS and threads In a program not involving multiple threads, this module behaves entirely as expected, following the behaviour of the regular pure-perl C implementation (regardless of whether or not the perl interpreter is actually built to support threads). When multiple threads are created, previous versions of this module would most likely crash. The current version (0.10) fixes enough of the logic, that future instances that are only ever accessed from one thread (either the initial main thread, or any additional sidecar threads) will work fine. However, future instances cannot currently cross the boundary between threads. Any instances that were created before a new thread is made will no longer be accessible within that thread, and instances may not be returned as the result of the thread exit value. Some of these restrictions may be relaxed in later versions. Attempts to access a future instance created in one thread from another thread will raise an exception: Future::XS instance IO::Async::Future=SCALAR(0x...) is not available in this thread at ... As a special case for process cleanup activities, the C<< ->cancel >> method does not throw this exception, but simply returns silently. This is because cleanup code such as C methods or C blocks often attempt to call this on existing instances. =cut =head1 AUTHOR Paul Evans =cut 0x55AA; Future-XS-0.12/lib/Future/XS.xs000444001750001750 2211514543104252 15063 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, 2022 -- leonerd@leonerd.org.uk */ #define PERL_NO_GET_CONTEXT #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "future.h" #include "perl-backcompat.c.inc" #include "av-utils.c.inc" #include "croak_from_caller.c.inc" #define warn_void_context(func) S_warn_void_context(aTHX_ func) static void S_warn_void_context(pTHX_ const char *func) { if(GIMME_V == G_VOID) warn("Calling ->%s in void context", func); } #define CHECK_INSTANCE(self) \ if(!SvROK(self) || !SvOBJECT(SvRV(self)) || \ !sv_derived_from(self, "Future::XS")) { \ GV *gv = CvGV(cv); HV *stash = GvSTASH(gv); \ croak("Expected a Future instance for %s::%s", \ HvNAME(stash), GvNAME(gv)); \ } MODULE = Future::XS PACKAGE = Future::XS SV * new(SV *proto) CODE: if(SvROK(proto) && SvOBJECT(SvRV(proto))) { HV *protostash = SvSTASH(SvRV(proto)); RETVAL = future_new(HvNAME(protostash)); } else RETVAL = future_new(SvPV_nolen(proto)); OUTPUT: RETVAL void DESTROY(SV *self) CODE: future_destroy(self); bool is_ready(SV *self) CODE: CHECK_INSTANCE(self); RETVAL = future_is_ready(self); OUTPUT: RETVAL bool is_done(SV *self) CODE: CHECK_INSTANCE(self); RETVAL = future_is_done(self); OUTPUT: RETVAL bool is_failed(SV *self) CODE: CHECK_INSTANCE(self); RETVAL = future_is_failed(self); OUTPUT: RETVAL bool is_cancelled(SV *self) CODE: CHECK_INSTANCE(self); RETVAL = future_is_cancelled(self); OUTPUT: RETVAL char * state(SV *self) CODE: CHECK_INSTANCE(self); // TODO: We can do this more efficiently sometime if(!future_is_ready(self)) RETVAL = "pending"; else if(future_is_failed(self)) RETVAL = "failed"; else if(future_is_cancelled(self)) RETVAL = "cancelled"; else RETVAL = "done"; OUTPUT: RETVAL SV * done(SV *self, ...) CODE: if(sv_is_future(self)) RETVAL = SvREFCNT_inc(ST(0)); else RETVAL = future_new(SvPV_nolen(ST(0))); future_donev(RETVAL, &ST(1), items - 1); OUTPUT: RETVAL SV * fail(SV *self, ...) ALIAS: fail = 0 die = 1 CODE: SV *exception = ST(1); if(ix == 1 && /* ->die */ !SvROK(exception) && SvPV_nolen(exception)[SvCUR(exception)-1] != '\n') { ST(1) = exception = newSVsv(exception); sv_catpvf(exception, " at %s line %d\n", CopFILE(PL_curcop), CopLINE(PL_curcop)); } // TODO: mess about with Future::Exception if(sv_is_future(self)) RETVAL = SvREFCNT_inc(ST(0)); else RETVAL = future_new(SvPV_nolen(ST(0))); future_failv(RETVAL, &ST(1), items - 1); OUTPUT: RETVAL SV * on_cancel(SV *self, SV *code) CODE: CHECK_INSTANCE(self); RETVAL = newSVsv(self); future_on_cancel(self, code); OUTPUT: RETVAL SV * on_ready(SV *self, SV *code) CODE: CHECK_INSTANCE(self); /* Need to copy the return value first in case on_ready destroys it * RT145168 */ RETVAL = newSVsv(self); future_on_ready(self, code); OUTPUT: RETVAL SV * await(SV *self) CODE: CHECK_INSTANCE(self); if(future_is_ready(self)) { RETVAL = newSVsv(ST(0)); XSRETURN(1); } croak_from_caller("%" SVf " is not yet complete and does not provide an ->await method", SVfARG(self)); OUTPUT: RETVAL void result(SV *self) ALIAS: result = FALSE get = TRUE PPCODE: CHECK_INSTANCE(self); /* This PUTBACK + SPAGAIN pair is required in case future_get_result_av() * causes the arguments stack to be reällocated. It works fine on perls * 5.24+ but causes older perls to crash. For now we just depend on 5.24 * https://rt.cpan.org/Ticket/Display.html?id=145597 */ PUTBACK; AV *result = future_get_result_av(self, ix); SPAGAIN; if(GIMME_V == G_LIST) { XPUSHs_from_AV(result); XSRETURN(av_count(result)); } else { if(av_count(result)) XPUSHs(AvARRAY(result)[0]); else XPUSHs(&PL_sv_undef); XSRETURN(1); } SV * on_done(SV *self, SV *code) CODE: CHECK_INSTANCE(self); RETVAL = newSVsv(self); future_on_done(self, code); OUTPUT: RETVAL void failure(SV *self) PPCODE: CHECK_INSTANCE(self); PUTBACK; AV *failure = future_get_failure_av(self); SPAGAIN; if(!failure) XSRETURN(0); if(GIMME_V == G_LIST) { XPUSHs_from_AV(failure); XSRETURN(av_count(failure)); } else { if(av_count(failure)) XPUSHs(AvARRAY(failure)[0]); else XPUSHs(&PL_sv_undef); XSRETURN(1); } SV * on_fail(SV *self, SV *code) CODE: CHECK_INSTANCE(self); RETVAL = newSVsv(self); future_on_fail(self, code); OUTPUT: RETVAL SV * cancel(SV *self) CODE: CHECK_INSTANCE(self); future_cancel(self); RETVAL = SvREFCNT_inc(self); OUTPUT: RETVAL SV * without_cancel(SV *self) CODE: RETVAL = future_without_cancel(self); OUTPUT: RETVAL SV * then(SV *self, ...) ALIAS: then = 0 then_with_f = FUTURE_THEN_WITH_F CODE: CHECK_INSTANCE(self); if(GIMME_V == G_VOID) { // Need to ensure we print the ->transform message right const PERL_CONTEXT *cx = caller_cx(0, NULL); if(CxTYPE(cx) == CXt_SUB && strEQ(GvNAME(CvGV(cx->blk_sub.cv)), "transform")) { warn_void_context("transform"); } else { warn_void_context(ix ? "then_with_f" : "then"); } } items--; /* account for self */ SV *thencode = &PL_sv_undef; if(items) { thencode = newSVsv(ST(1)); items--; } SV *elsecode = &PL_sv_undef; if(items % 2) { elsecode = newSVsv(ST(1 + items)); items--; } if(items) { HV *catches = newHV(); for(int i = 0; i < items/2; i++) hv_store_ent(catches, ST(2 + i*2), newSVsv(ST(2 + i*2 + 1)), 0); RETVAL = future_thencatch(self, ix, thencode, catches, elsecode); } else { RETVAL = future_then(self, ix, thencode, elsecode); } OUTPUT: RETVAL SV * else(SV *self, SV *code) ALIAS: else = 0 else_with_f = FUTURE_THEN_WITH_F CODE: CHECK_INSTANCE(self); warn_void_context(ix ? "else_with_f" : "else"); RETVAL = future_then(self, ix, NULL, newSVsv(code)); OUTPUT: RETVAL SV * catch(SV *self, ...) ALIAS: catch = 0 catch_with_f = FUTURE_THEN_WITH_F CODE: CHECK_INSTANCE(self); warn_void_context(ix ? "catch_with_f" : "catch"); items--; /* account for self */ SV *elsecode = &PL_sv_undef; if(items % 2) { elsecode = newSVsv(ST(items)); items--; } HV *catches = newHV(); for(int i = 0; i < items/2; i++) hv_store_ent(catches, ST(1 + i*2), newSVsv(ST(1 + i*2 + 1)), 0); RETVAL = future_thencatch(self, ix, NULL, catches, elsecode); OUTPUT: RETVAL SV * followed_by(SV *self, SV *code) CODE: CHECK_INSTANCE(self); warn_void_context("followed_by"); RETVAL = future_followed_by(self, newSVsv(code)); OUTPUT: RETVAL SV * wait_all(SV *cls, ...) CODE: RETVAL = future_new_waitallv(SvPV_nolen(cls), &ST(1), items - 1); OUTPUT: RETVAL SV * wait_any(SV *cls, ...) CODE: RETVAL = future_new_waitanyv(SvPV_nolen(cls), &ST(1), items - 1); OUTPUT: RETVAL SV * needs_all(SV *cls, ...) CODE: RETVAL = future_new_needsallv(SvPV_nolen(cls), &ST(1), items - 1); OUTPUT: RETVAL SV * needs_any(SV *cls, ...) CODE: RETVAL = future_new_needsanyv(SvPV_nolen(cls), &ST(1), items - 1); OUTPUT: RETVAL void pending_futures(SV *self) ALIAS: pending_futures = FUTURE_SUBS_PENDING ready_futures = FUTURE_SUBS_READY done_futures = FUTURE_SUBS_DONE failed_futures = FUTURE_SUBS_FAILED cancelled_futures = FUTURE_SUBS_CANCELLED PPCODE: CHECK_INSTANCE(self); PUTBACK; Size_t count = future_mPUSH_subs(self, ix); SPAGAIN; XSRETURN(count); SV * btime(SV *self) ALIAS: btime = 0 rtime = 1 CODE: { struct timeval t; switch(ix) { case 0: t = future_get_btime(self); break; case 1: t = future_get_rtime(self); break; } RETVAL = &PL_sv_undef; if(t.tv_sec) { AV *retav = newAV(); av_push(retav, newSViv(t.tv_sec)); av_push(retav, newSViv(t.tv_usec)); RETVAL = newRV_noinc((SV *)retav); } } OUTPUT: RETVAL SV * set_label(SV *self, SV *label) CODE: future_set_label(self, label); RETVAL = SvREFCNT_inc(self); OUTPUT: RETVAL SV * label(SV *self) CODE: SV *label = future_get_label(self); RETVAL = label ? newSVsv(label) : &PL_sv_undef; OUTPUT: RETVAL SV * set_udata(SV *self, SV *name, SV *value) CODE: future_set_udata(self, name, value); RETVAL = SvREFCNT_inc(self); OUTPUT: RETVAL SV * udata(SV *self, SV *name) CODE: RETVAL = newSVsv(future_get_udata(self, name)); OUTPUT: RETVAL void reread_environment() CODE: Future_reread_environment(aTHX); BOOT: future_boot(); Future-XS-0.12/src000755001750001750 014543104252 12546 5ustar00leoleo000000000000Future-XS-0.12/src/future.c000444001750001750 12133214543104252 14423 0ustar00leoleo000000000000#define PERL_NO_GET_CONTEXT #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "future.h" #include "perl-backcompat.c.inc" #include "av-utils.c.inc" #include "cv_set_anysv_refcounted.c.inc" #if !HAVE_PERL_VERSION(5, 16, 0) # define false FALSE # define true TRUE #endif #ifdef HAVE_DMD_HELPER # define WANT_DMD_API_044 # include "DMD_helper.h" #endif #if !HAVE_PERL_VERSION(5, 16, 0) # define XS_INTERNAL(name) static XS(name) #endif #define mPUSHpvs(s) mPUSHp("" s "", sizeof(s)-1) static bool future_debug; static bool capture_times; /* There's no reason these have to match those in Future.pm but for now we * might as well just copy the same values */ enum { CB_DONE = (1<<0), CB_FAIL = (1<<1), CB_CANCEL = (1<<2), CB_ALWAYS = CB_DONE|CB_FAIL|CB_CANCEL, CB_SELF = (1<<3), CB_RESULT = (1<<4), CB_SEQ_READY = (1<<5), CB_SEQ_CANCEL = (1<<6), CB_SEQ_ANY = CB_SEQ_READY|CB_SEQ_CANCEL, CB_SEQ_IMDONE = (1<<7), CB_SEQ_IMFAIL = (1<<8), CB_SEQ_STRICT = (1<<9), CB_IS_FUTURE = (1<<10), }; // TODO: Consider using different struct types to save memory? Or maybe it's // so small a difference it doesn't matter struct FutureXSCallback { unsigned int flags; union { SV *code; /* if !(flags & CB_SEQ_ANY) */ struct { /* if (flags & CB_SEQ_ANY) */ SV *thencode; SV *elsecode; HV *catches; SV *f; } seq; }; }; struct FutureXSRevocation { SV *precedent_f; SV *toclear_sv_at; }; #define CB_NONSEQ_CODE(cb) \ ({ if((cb)->flags & CB_SEQ_ANY) croak("ARGH: CB_NONSEQ_CODE on SEQ"); (cb)->code;}) struct FutureXS { unsigned int ready : 1; unsigned int cancelled : 1; unsigned int reported : 1; SV *label; AV *result; // implies done AV *failure; // implies fail AV *callbacks; // values are struct FutureXSCallback ptrs directly. TODO: custom ptr/fill/max AV *on_cancel; // values are CVs directly AV *revoke_when_ready; // values are struct FutureXSRevocation ptrs directly. int empty_revocation_slots; HV *udata; struct timeval btime, rtime; SV *constructed_at; /* For convergents * TODO: consider making this an optional extra part of the body, only * allocated when required */ AV *subs; Size_t pending_subs; /* For without_cancel, purely to keep a strongref */ SV *precedent_f; }; #ifdef USE_ITHREADS static int future_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param); static MGVTBL vtbl = { .svt_dup = &future_dup, }; #endif bool Future_sv_is_future(pTHX_ SV *sv) { if(!SvROK(sv) || !SvOBJECT(SvRV(sv))) return false; if(sv_derived_from(sv, "Future") || sv_derived_from(sv, "Future::XS")) return true; return false; } #define get_future(sv) S_get_future(aTHX_ sv, FALSE) #define maybe_get_future(sv) S_get_future(aTHX_ sv, TRUE) static struct FutureXS *S_get_future(pTHX_ SV *sv, bool nullok) { assert(sv); assert(SvROK(sv) && SvOBJECT(SvRV(sv))); // TODO: Add some safety checking about class struct FutureXS *self = INT2PTR(struct FutureXS *, SvIV(SvRV(sv))); if(self || nullok) return self; croak("Future::XS instance %" SVf " is not available in this thread", SVfARG(sv)); } SV *Future_new(pTHX_ const char *cls) { if(!cls) cls = "Future::XS"; struct FutureXS *self; Newx(self, 1, struct FutureXS); self->ready = false; self->cancelled = false; self->reported = false; self->label = NULL; if(capture_times) gettimeofday(&self->btime, NULL); else self->btime = (struct timeval){ 0 }; self->rtime = (struct timeval){ 0 }; if(future_debug) self->constructed_at = newSVpvf("constructed at %s line %d", CopFILE(PL_curcop), CopLINE(PL_curcop)); else self->constructed_at = NULL; self->result = NULL; self->failure = NULL; self->callbacks = NULL; self->on_cancel = NULL; self->revoke_when_ready = NULL; self->empty_revocation_slots = 0; self->udata = NULL; self->subs = NULL; self->precedent_f = NULL; SV *ret = newSV(0); sv_setref_pv(ret, cls, self); #ifdef USE_ITHREADS MAGIC *mg = sv_magicext(SvRV(ret), SvRV(ret), PERL_MAGIC_ext, &vtbl, NULL, 0); mg->mg_flags |= MGf_DUP; #endif return ret; } #define future_new_proto(f1) Future_new_proto(aTHX_ f1) SV *Future_new_proto(pTHX_ SV *f1) { assert(f1 && SvROK(f1) && SvRV(f1)); // TODO Shortcircuit in the common case that f1 is a Future instance // return future_new(HvNAME(SvSTASH(SvRV(f1)))); dSP; ENTER; SAVETMPS; EXTEND(SP, 1); PUSHMARK(SP); PUSHs(sv_mortalcopy(f1)); PUTBACK; call_method("new", G_SCALAR); SPAGAIN; SV *ret = SvREFCNT_inc(POPs); PUTBACK; FREETMPS; LEAVE; return ret; } #ifdef USE_ITHREADS static int future_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param) { /* We don't currently support duplicating a Future instance across thread * creation/return. For now just zero out the pointer and complain if anyone * tries to access it. * This at least means that incidental Future instances that happen to exist * in main thread memory won't be disturbed when sidecar threads are joined. */ sv_setiv(mg->mg_obj, 0); } #endif #define clear_callback(cb) S_clear_callback(aTHX_ cb) static void S_clear_callback(pTHX_ struct FutureXSCallback *cb) { int flags = cb->flags; if(flags & CB_SEQ_ANY) { SvREFCNT_dec(cb->seq.thencode); SvREFCNT_dec(cb->seq.elsecode); SvREFCNT_dec(cb->seq.catches); SvREFCNT_dec(cb->seq.f); } else { SvREFCNT_dec(CB_NONSEQ_CODE(cb)); } } #define destroy_callbacks(self) S_destroy_callbacks(aTHX_ self) static void S_destroy_callbacks(pTHX_ struct FutureXS *self) { AV *callbacksav = self->callbacks; while(callbacksav && AvFILLp(callbacksav) > -1) { struct FutureXSCallback *cb = (struct FutureXSCallback *)AvARRAY(self->callbacks)[AvFILLp(callbacksav)--]; clear_callback(cb); Safefree(cb); } } void Future_destroy(pTHX_ SV *f) { #ifdef DEBUGGING // Every pointer in this function ought to have been uniquely held # define UNREF(p) \ do { \ if(p) assert(SvREFCNT(p) == 1); \ SvREFCNT_dec((SV *)p); \ (p) = (void *)0xAA55AA55; \ } while(0) #else # define UNREF(p) SvREFCNT_dec((SV *)p) #endif /* Defend against being run during global destruction */ if(!f || !SvROK(f)) return; struct FutureXS *self = maybe_get_future(f); if(!self) return; if(future_debug && (!self->ready || (self->failure && !self->reported))) { if(!self->ready) warn("%" SVf " was %" SVf " and was lost near %s line %d before it was ready\n", SVfARG(f), SVfARG(self->constructed_at), CopFILE(PL_curcop), CopLINE(PL_curcop)); else { SV *failure = AvARRAY(self->failure)[0]; warn("%" SVf " was %" SVf " and was lost near %s line %d with an unreported failure of: %" SVf "\n", SVfARG(f), SVfARG(self->constructed_at), CopFILE(PL_curcop), CopLINE(PL_curcop), SVfARG(failure)); } } UNREF(self->label); UNREF(self->result); UNREF(self->failure); destroy_callbacks(self); UNREF(self->callbacks); UNREF(self->on_cancel); AV *revocationsav = self->revoke_when_ready; while(revocationsav && AvFILLp(revocationsav) > -1) { struct FutureXSRevocation *rev = (struct FutureXSRevocation *)AvARRAY(revocationsav)[AvFILLp(revocationsav)--]; UNREF(rev->precedent_f); UNREF(rev->toclear_sv_at); Safefree(rev); } UNREF(self->revoke_when_ready); UNREF(self->udata); UNREF(self->constructed_at); UNREF(self->subs); UNREF(self->precedent_f); Safefree(self); #undef UNREF } bool Future_is_ready(pTHX_ SV *f) { struct FutureXS *self = get_future(f); return self->ready; } bool Future_is_done(pTHX_ SV *f) { struct FutureXS *self = get_future(f); return self->ready && !self->failure && !self->cancelled; } bool Future_is_failed(pTHX_ SV *f) { struct FutureXS *self = get_future(f); return self->ready && self->failure; } bool Future_is_cancelled(pTHX_ SV *f) { struct FutureXS *self = get_future(f); return self->cancelled; } #define clear_on_cancel(self) S_clear_on_cancel(aTHX_ self) static void S_clear_on_cancel(pTHX_ struct FutureXS *self) { if(!self->on_cancel) return; AV *on_cancel = self->on_cancel; self->on_cancel = NULL; SvREFCNT_dec(on_cancel); } #define push_callback(self, cb) S_push_callback(aTHX_ self, cb) static void S_push_callback(pTHX_ struct FutureXS *self, struct FutureXSCallback *cb) { struct FutureXSCallback *new; Newx(new, 1, struct FutureXSCallback); new->flags = cb->flags; if(cb->flags & CB_SEQ_ANY) { new->seq.thencode = cb->seq.thencode; new->seq.elsecode = cb->seq.elsecode; new->seq.catches = cb->seq.catches; new->seq.f = cb->seq.f; } else { new->code = CB_NONSEQ_CODE(cb); } if(!self->callbacks) self->callbacks = newAV(); av_push(self->callbacks, (SV *)new); } #define wrap_cb(f, name, cv) S_wrap_cb(aTHX_ f, name, cv) static SV *S_wrap_cb(pTHX_ SV *f, const char *name, SV *cv) { // TODO: This is quite the speed bump having to do this, in the common case // that it isn't overridden dSP; ENTER; SAVETMPS; EXTEND(SP, 3); PUSHMARK(SP); PUSHs(sv_mortalcopy(f)); mPUSHp(name, strlen(name)); PUSHs(sv_mortalcopy(cv)); PUTBACK; call_method("wrap_cb", G_SCALAR); SPAGAIN; SV *ret = newSVsv(POPs); PUTBACK; FREETMPS; LEAVE; return ret; } #define invoke_seq_callback(self, selfsv, cb) S_invoke_seq_callback(aTHX_ self, selfsv, cb) static SV *S_invoke_seq_callback(pTHX_ struct FutureXS *self, SV *selfsv, struct FutureXSCallback *cb) { int flags = cb->flags; bool is_fail = cBOOL(self->failure); bool is_done = !self->cancelled && !is_fail; AV *result = (is_done) ? self->result : (is_fail) ? self->failure : NULL; SV *code = (is_done) ? cb->seq.thencode : (is_fail) ? cb->seq.elsecode : NULL; if(is_fail && result && av_count(result) > 1 && cb->seq.catches) { SV *category = AvARRAY(result)[1]; if(SvOK(category)) { HE *he = hv_fetch_ent(cb->seq.catches, category, 0, 0); if(he && HeVAL(he)) code = HeVAL(he); } } if(!code || !SvOK(code)) return newSVsv(selfsv); dSP; ENTER; SAVETMPS; PUSHMARK(SP); if(flags & CB_SELF) XPUSHs(selfsv); if(flags & CB_RESULT) XPUSHs_from_AV(result); PUTBACK; assert(SvOK(code)); call_sv(code, G_SCALAR|G_EVAL); SPAGAIN; if(SvROK(ERRSV) || SvTRUE(ERRSV)) { POPs; SV *fseq = cb->seq.f; if(!fseq) fseq = future_new_proto(selfsv); future_failv(fseq, &ERRSV, 1); FREETMPS; LEAVE; return fseq; } SV *f2 = POPs; SvREFCNT_inc(f2); PUTBACK; FREETMPS; LEAVE; if(!sv_is_future(f2)) { SV *result = f2; // TODO: strictness check f2 = future_new_proto(selfsv); future_donev(f2, &result, 1); } return f2; } #define invoke_callback(self, selfsv, cb) S_invoke_callback(aTHX_ self, selfsv, cb) static void S_invoke_callback(pTHX_ struct FutureXS *self, SV *selfsv, struct FutureXSCallback *cb) { int flags = cb->flags; bool is_cancelled = self->cancelled; bool is_fail = cBOOL(self->failure); bool is_done = !is_cancelled && !is_fail; AV *result = (is_done) ? self->result : (is_fail) ? self->failure : NULL; if(is_done && !(flags & CB_DONE)) return; if(is_fail && !(flags & CB_FAIL)) return; if(is_cancelled && !(flags & CB_CANCEL)) return; if(flags & CB_IS_FUTURE) { dSP; ENTER; SAVETMPS; PUSHMARK(SP); XPUSHs(CB_NONSEQ_CODE(cb)); // really a Future RV if(result) XPUSHs_from_AV(result); PUTBACK; if(is_done) call_method("done", G_VOID); else if(is_fail) call_method("fail", G_VOID); else call_method("cancel", G_VOID); FREETMPS; LEAVE; } else if(flags & CB_SEQ_ANY) { SV *fseq = cb->seq.f; if(!SvOK(fseq)) { if(self->constructed_at) warn("%" SVf " (%" SVf ") lost a sequence Future", SVfARG(selfsv), SVfARG(self->constructed_at)); else warn("%" SVf " lost a sequence Future", SVfARG(selfsv)); return; } SV *f2 = invoke_seq_callback(self, selfsv, cb); if(f2 == fseq) /* immediate fail */ return; future_on_cancel(fseq, f2); if(future_is_ready(f2)) { if(!future_is_cancelled(f2)) future_on_ready(f2, fseq); else if(flags & CB_CANCEL) future_cancel(fseq); } else { struct FutureXS *f2self = get_future(f2); struct FutureXSCallback cb2 = { .flags = CB_DONE|CB_FAIL|CB_IS_FUTURE, .code = sv_rvweaken(newSVsv(fseq)), }; push_callback(f2self, &cb2); } assert(SvREFCNT(f2) == 1); SvREFCNT_dec(f2); } else { SV *code = CB_NONSEQ_CODE(cb); dSP; ENTER; SAVETMPS; PUSHMARK(SP); if(flags & CB_SELF) XPUSHs(selfsv); if((flags & CB_RESULT) && result) XPUSHs_from_AV(result); PUTBACK; assert(SvOK(code)); call_sv(code, G_VOID); FREETMPS; LEAVE; } } #define revoke_on_cancel(rev) S_revoke_on_cancel(aTHX_ rev) static void S_revoke_on_cancel(pTHX_ struct FutureXSRevocation *rev) { if(rev->toclear_sv_at && SvROK(rev->toclear_sv_at)) { assert(SvTYPE(rev->toclear_sv_at) <= SVt_PVMG); assert(SvROK(rev->toclear_sv_at)); sv_set_undef(SvRV(rev->toclear_sv_at)); SvREFCNT_dec(rev->toclear_sv_at); rev->toclear_sv_at = NULL; } if(!SvOK(rev->precedent_f)) return; struct FutureXS *self = get_future(rev->precedent_f); self->empty_revocation_slots++; AV *on_cancel = self->on_cancel; if(self->empty_revocation_slots >= 8 && on_cancel && self->empty_revocation_slots >= AvFILL(on_cancel)/2) { // Squash up the array to contain only defined values SV **wrsv = AvARRAY(on_cancel), **rdsv = AvARRAY(on_cancel), **end = AvARRAY(on_cancel) + AvFILL(on_cancel); while(rdsv <= end) { if(SvOK(*rdsv)) // Keep this one *(wrsv++) = *rdsv; else // Free this one SvREFCNT_dec(*rdsv); rdsv++; } AvFILLp(on_cancel) = wrsv - AvARRAY(on_cancel) - 1; self->empty_revocation_slots = 0; } } #define mark_ready(self, selfsv, state) S_mark_ready(aTHX_ self, selfsv, state) static void S_mark_ready(pTHX_ struct FutureXS *self, SV *selfsv, const char *state) { self->ready = true; // TODO: self->ready_at if(capture_times) gettimeofday(&self->rtime, NULL); /* Make sure self doesn't disappear during this function */ SvREFCNT_inc(SvRV(selfsv)); SAVEFREESV(SvRV(selfsv)); if(self->precedent_f) { SvREFCNT_dec(self->precedent_f); self->precedent_f = NULL; } clear_on_cancel(self); if(self->revoke_when_ready) { AV *revocations = self->revoke_when_ready; for(size_t i = 0; i < av_count(revocations); i++) { struct FutureXSRevocation *rev = (struct FutureXSRevocation *)AvARRAY(revocations)[i]; revoke_on_cancel(rev); SvREFCNT_dec(rev->precedent_f); Safefree(rev); } AvFILLp(revocations) = -1; SvREFCNT_dec(revocations); self->revoke_when_ready = NULL; } if(!self->callbacks) return; AV *callbacks = self->callbacks; struct FutureXSCallback **cbs = (struct FutureXSCallback **)AvARRAY(callbacks); size_t i, n = av_count(callbacks); for(i = 0; i < n; i++) { struct FutureXSCallback *cb = cbs[i]; invoke_callback(self, selfsv, cb); } destroy_callbacks(self); } #define make_sequence(f1, cb) S_make_sequence(aTHX_ f1, cb) static SV *S_make_sequence(pTHX_ SV *f1, struct FutureXSCallback *cb) { struct FutureXS *self = get_future(f1); int flags = cb->flags; if(self->ready) { // TODO: CB_SEQ_IM* SV *f2 = invoke_seq_callback(self, f1, cb); clear_callback(cb); return f2; } SV *fseq = future_new_proto(f1); if(cb->flags & CB_SEQ_CANCEL) future_on_cancel(fseq, f1); cb->flags |= CB_DONE|CB_FAIL; if(cb->seq.thencode) cb->seq.thencode = wrap_cb(f1, "sequence", sv_2mortal(cb->seq.thencode)); if(cb->seq.elsecode) cb->seq.elsecode = wrap_cb(f1, "sequence", sv_2mortal(cb->seq.elsecode)); cb->seq.f = sv_rvweaken(newSVsv(fseq)); push_callback(self, cb); return fseq; } // TODO: move to a hax/ file #define CvNAME_FILE_LINE(cv) S_CvNAME_FILE_LINE(aTHX_ cv) static SV *S_CvNAME_FILE_LINE(pTHX_ CV *cv) { if(!CvANON(cv)) { SV *ret = newSVpvf("HvNAME::GvNAME"); return ret; } OP *cop = CvSTART(cv); while(cop && OP_CLASS(cop) != OA_COP) cop = cop->op_next; if(!cop) return newSVpvs("__ANON__"); return newSVpvf("__ANON__(%s line %d)", CopFILE((COP *)cop), CopLINE((COP *)cop)); } static const char *statestr(struct FutureXS *self) { if(!self->ready) return "pending"; if(self->cancelled) return "cancelled"; if(self->failure) return "failed"; return "done"; } void Future_donev(pTHX_ SV *f, SV **svp, size_t n) { struct FutureXS *self = get_future(f); if(self->cancelled) return; if(self->ready) croak("%" SVf " is already %s and cannot be ->done", SVfARG(f), statestr(self)); // TODO: test subs self->result = newAV_svn_dup(svp, n); mark_ready(self, f, "done"); } void Future_failv(pTHX_ SV *f, SV **svp, size_t n) { struct FutureXS *self = get_future(f); if(self->cancelled) return; if(self->ready) croak("%" SVf " is already %s and cannot be ->fail'ed", SVfARG(f), statestr(self)); if(n == 1 && SvROK(svp[0]) && SvOBJECT(SvRV(svp[0])) && sv_derived_from(svp[0], "Future::Exception")) { SV *exception = svp[0]; AV *failure = self->failure = newAV(); dSP; { ENTER; SAVETMPS; EXTEND(SP, 1); PUSHMARK(SP); PUSHs(sv_mortalcopy(exception)); PUTBACK; call_method("message", G_SCALAR); SPAGAIN; av_push(failure, SvREFCNT_inc(POPs)); PUTBACK; FREETMPS; LEAVE; } { ENTER; SAVETMPS; EXTEND(SP, 1); PUSHMARK(SP); PUSHs(sv_mortalcopy(exception)); PUTBACK; call_method("category", G_SCALAR); SPAGAIN; av_push(failure, SvREFCNT_inc(POPs)); PUTBACK; FREETMPS; LEAVE; } { ENTER; SAVETMPS; EXTEND(SP, 1); PUSHMARK(SP); PUSHs(sv_mortalcopy(exception)); PUTBACK; SSize_t count = call_method("details", G_LIST); SPAGAIN; SV **retp = SP - count + 1; for(SSize_t i = 0; i < count; i++) av_push(failure, SvREFCNT_inc(retp[i])); SP -= count; PUTBACK; FREETMPS; LEAVE; } } else { self->failure = newAV_svn_dup(svp, n); } mark_ready(self, f, "failed"); } #define future_failp(f, s) Future_failp(aTHX_ f, s) void Future_failp(pTHX_ SV *f, const char *s) { struct FutureXS *self = get_future(f); if(self->cancelled) return; if(self->ready) croak("%" SVf " is already %s and cannot be ->fail'ed", SVfARG(f), statestr(self)); self->failure = newAV(); av_push(self->failure, newSVpv(s, strlen(s))); mark_ready(self, f, "failed"); } void Future_on_cancel(pTHX_ SV *f, SV *code) { struct FutureXS *self = get_future(f); if(self->ready) return; bool is_future = sv_is_future(code); // TODO: is_future or callable(code) or croak if(!self->on_cancel) self->on_cancel = newAV(); SV *rv = newSVsv((SV *)code); av_push(self->on_cancel, rv); if(is_future) { struct FutureXSRevocation *rev; Newx(rev, 1, struct FutureXSRevocation); rev->precedent_f = sv_rvweaken(newSVsv(f)); rev->toclear_sv_at = sv_rvweaken(newRV_inc(rv)); struct FutureXS *codeself = get_future(code); if(!codeself->revoke_when_ready) codeself->revoke_when_ready = newAV(); av_push(codeself->revoke_when_ready, (SV *)rev); } } void Future_on_ready(pTHX_ SV *f, SV *code) { struct FutureXS *self = get_future(f); bool is_future = sv_is_future(code); // TODO: is_future or callable(code) or croak int flags = CB_ALWAYS|CB_SELF; if(is_future) flags |= CB_IS_FUTURE; struct FutureXSCallback cb = { .flags = flags, .code = code, }; if(self->ready) invoke_callback(self, f, &cb); else { cb.code = wrap_cb(f, "on_ready", cb.code); push_callback(self, &cb); } } void Future_on_done(pTHX_ SV *f, SV *code) { struct FutureXS *self = get_future(f); bool is_future = sv_is_future(code); // TODO: is_future or callable(code) or croak int flags = CB_DONE|CB_RESULT; if(is_future) flags |= CB_IS_FUTURE; struct FutureXSCallback cb = { .flags = flags, .code = code, }; if(self->ready) invoke_callback(self, f, &cb); else { cb.code = wrap_cb(f, "on_done", cb.code); push_callback(self, &cb); } } void Future_on_fail(pTHX_ SV *f, SV *code) { struct FutureXS *self = get_future(f); bool is_future = sv_is_future(code); // TODO: is_future or callable(code) or croak int flags = CB_FAIL|CB_RESULT; if(is_future) flags |= CB_IS_FUTURE; struct FutureXSCallback cb = { .flags = flags, .code = code, }; if(self->ready) invoke_callback(self, f, &cb); else { cb.code = wrap_cb(f, "on_fail", cb.code); push_callback(self, &cb); } } #define future_await(f) Future_await(aTHX_ f) static void Future_await(pTHX_ SV *f) { dSP; ENTER; SAVETMPS; PUSHMARK(SP); mXPUSHs(newSVsv(f)); PUTBACK; call_method("await", G_VOID); FREETMPS; LEAVE; } AV *Future_get_result_av(pTHX_ SV *f, bool await) { struct FutureXS *self = get_future(f); if(await && !self->ready) future_await(f); if(!self->ready) croak("%" SVf " is not yet ready", SVfARG(f)); if(self->failure) { self->reported = true; SV *exception = AvARRAY(self->failure)[0]; if(av_count(self->failure) > 1) { dSP; ENTER; SAVETMPS; PUSHMARK(SP); EXTEND(SP, 1 + av_count(self->failure)); mPUSHpvs("Future::Exception"); for(SSize_t i = 0; i < av_count(self->failure); i++) PUSHs(sv_mortalcopy(AvARRAY(self->failure)[i])); PUTBACK; call_method("new", G_SCALAR); SPAGAIN; exception = SvREFCNT_inc(POPs); PUTBACK; FREETMPS; LEAVE; } if(SvROK(exception) || SvPV_nolen(exception)[SvCUR(exception)-1] == '\n') die_sv(exception); else { /* We'd like to call Carp::croak to do the @CARP_NOT logic, but it gets * confused about a missing callframe first because this is XS. We'll * reïmplement the logic here */ I32 cxix; for(cxix = cxstack_ix; cxix; cxix--) { if(CxTYPE(&cxstack[cxix]) != CXt_SUB) continue; const CV *cv = cxstack[cxix].blk_sub.cv; if(!cv) continue; const char *stashname = HvNAME(CvSTASH(cv)); if(!stashname) continue; // The essence of the @CARP_NOT logic if(strEQ(stashname, "Future::_base")) continue; const COP *cop = cxix < cxstack_ix ? cxstack[cxix+1].blk_oldcop : PL_curcop; sv_catpvf(exception, " at %s line %d.\n", CopFILE(cop), CopLINE(cop)); break; } die_sv(exception); } } if(self->cancelled) croak("%" SVf " was cancelled", SVfARG(f)); if(!self->result) self->result = newAV(); return self->result; } AV *Future_get_failure_av(pTHX_ SV *f) { struct FutureXS *self = get_future(f); if(!self->ready) future_await(f); if(!self->failure) return NULL; return self->failure; } void Future_cancel(pTHX_ SV *f) { /* Specifically don't make it an error to ->cancel a future instance not * available in this thread; as it often appears in defer / DESTROY / etc */ struct FutureXS *self = maybe_get_future(f); if(!self) return; if(self->ready) return; self->cancelled = true; AV *on_cancel = self->on_cancel; if(self->subs) { for(Size_t i = 0; i < av_count(self->subs); i++) future_cancel(AvARRAY(self->subs)[i]); } // TODO: maybe we need to clear these out from self before we do this, in // case of recursion? for(int i = on_cancel ? AvFILL(on_cancel) : -1; i >= 0; i--) { SV *code = AvARRAY(on_cancel)[i]; if(!SvOK(code)) continue; if(sv_is_future(code)) { dSP; ENTER; SAVETMPS; PUSHMARK(SP); PUSHs(code); PUTBACK; call_method("cancel", G_VOID); FREETMPS; LEAVE; } else { dSP; ENTER; SAVETMPS; PUSHMARK(SP); PUSHs(f); PUTBACK; assert(SvOK(code)); call_sv(code, G_VOID); FREETMPS; LEAVE; } } mark_ready(self, f, "cancel"); } SV *Future_without_cancel(pTHX_ SV *f) { struct FutureXSCallback cb = { .flags = CB_SEQ_READY|CB_CANCEL, /* without CB_SEQ_CANCEL */ /* no code */ }; SV *ret = make_sequence(f, &cb); struct FutureXS *self = get_future(ret); self->precedent_f = newSVsv(f); return ret; } SV *Future_then(pTHX_ SV *f, U32 flags, SV *thencode, SV *elsecode) { struct FutureXSCallback cb = { .flags = CB_SEQ_ANY|CB_RESULT, .seq.thencode = thencode, .seq.elsecode = elsecode, }; if(flags & FUTURE_THEN_WITH_F) cb.flags |= CB_SELF; return make_sequence(f, &cb); } SV *Future_followed_by(pTHX_ SV *f, SV *code) { struct FutureXSCallback cb = { .flags = CB_SEQ_ANY|CB_SELF, .seq.thencode = code, .seq.elsecode = SvREFCNT_inc(code), }; return make_sequence(f, &cb); } SV *Future_thencatch(pTHX_ SV *f, U32 flags, SV *thencode, HV *catches, SV *elsecode) { struct FutureXSCallback cb = { .flags = CB_SEQ_ANY|CB_RESULT, .seq.thencode = thencode, .seq.elsecode = elsecode, .seq.catches = catches, }; if(flags & FUTURE_THEN_WITH_F) cb.flags |= CB_SELF; return make_sequence(f, &cb); } #define future_new_subsv(cls, subs, n) S_future_new_subsv(aTHX_ cls, subs, n) static SV *S_future_new_subsv(pTHX_ const char *cls, SV **subs, size_t n) { HV *future_stash = get_hv("Future::", 0); assert(future_stash); /* Find the best prototype; pick the first derived instance if there is * one */ SV *proto = NULL; for(Size_t i = 0; i < n; i++) { if(!SvROK(subs[i]) || !SvOBJECT(SvRV(subs[i]))) croak("Expected a Future, got %" SVf, SVfARG(subs[i])); if(SvSTASH(SvRV(subs[i])) != future_stash) { proto = subs[i]; break; } } SV *f = proto ? future_new_proto(proto) : future_new(cls); struct FutureXS *self = get_future(f); if(!self->subs) self->subs = newAV(); for(Size_t i = 0; i < n; i++) av_push(self->subs, newSVsv(subs[i])); return f; } #define copy_result(self, src) S_copy_result(aTHX_ self, src) static void S_copy_result(pTHX_ struct FutureXS *self, SV *src) { /* TODO: Handle non-Future::XS instances too */ struct FutureXS *srcself = get_future(src); assert(srcself->ready); assert(!srcself->cancelled); if(srcself->failure) { self->failure = newAV_svn_dup(AvARRAY(srcself->failure), av_count(srcself->failure)); } else { assert(srcself->result); self->result = newAV_svn_dup(AvARRAY(srcself->result), av_count(srcself->result)); } } #define cancel_pending_subs(self) S_cancel_pending_subs(aTHX_ self) static void S_cancel_pending_subs(pTHX_ struct FutureXS *self) { if(!self->subs) return; for(Size_t i = 0; i < av_count(self->subs); i++) { SV *sub = AvARRAY(self->subs)[i]; if(!future_is_ready(sub)) future_cancel(sub); } } XS_INTERNAL(sub_on_ready_waitall) { dXSARGS; SV *f = XSANY_sv; if(!SvOK(f)) return; /* Make sure self doesn't disappear during this function */ SvREFCNT_inc(SvRV(f)); SAVEFREESV(SvRV(f)); struct FutureXS *self = get_future(f); self->pending_subs--; if(self->pending_subs) XSRETURN(0); /* TODO: This is really just newAVav() */ self->result = newAV_svn_dup(AvARRAY(self->subs), av_count(self->subs)); mark_ready(self, f, "wait_all"); } SV *Future_new_waitallv(pTHX_ const char *cls, SV **subs, size_t n) { SV *f = future_new_subsv(cls, subs, n); struct FutureXS *self = get_future(f); self->pending_subs = 0; for(Size_t i = 0; i < n; i++) { /* TODO: This should probably use some API function to make it transparent */ if(!future_is_ready(subs[i])) self->pending_subs++; } if(!self->pending_subs) { self->result = newAV_svn_dup(subs, n); mark_ready(self, f, "wait_all"); return f; } CV *sub_on_ready = newXS(NULL, sub_on_ready_waitall, __FILE__); cv_set_anysv_refcounted(sub_on_ready, newSVsv(f)); sv_rvweaken(CvXSUBANY_sv(sub_on_ready)); GV *gv = gv_fetchpvs("Future::XS::(wait_all callback)", GV_ADDMULTI, SVt_PVCV); CvGV_set(sub_on_ready, gv); CvANON_off(sub_on_ready); for(Size_t i = 0; i < n; i++) { if(!future_is_ready(subs[i])) future_on_ready(subs[i], sv_2mortal(newRV_inc((SV *)sub_on_ready))); } SvREFCNT_dec(sub_on_ready); return f; } XS_INTERNAL(sub_on_ready_waitany) { dXSARGS; SV *thissub = ST(0); SV *f = XSANY_sv; if(!SvOK(f)) return; /* Make sure self doesn't disappear during this function */ SvREFCNT_inc(SvRV(f)); SAVEFREESV(SvRV(f)); struct FutureXS *self = get_future(f); if(self->result || self->failure) return; self->pending_subs--; bool this_cancelled = future_is_cancelled(thissub); if(self->pending_subs && this_cancelled) return; if(this_cancelled) { future_failp(f, "All component futures were cancelled"); return; } else copy_result(self, thissub); cancel_pending_subs(self); mark_ready(self, f, "wait_any"); } SV *Future_new_waitanyv(pTHX_ const char *cls, SV **subs, size_t n) { SV *f = future_new_subsv(cls, subs, n); struct FutureXS *self = get_future(f); if(!n) { future_failp(f, "Cannot ->wait_any with no subfutures"); return f; } SV *immediate_ready = NULL; for(Size_t i = 0; i < n; i++) { /* TODO: This should probably use some API function to make it transparent */ if(future_is_ready(subs[i]) && !future_is_cancelled(subs[i])) { immediate_ready = subs[i]; break; } } if(immediate_ready) { copy_result(self, immediate_ready); cancel_pending_subs(self); mark_ready(self, f, "wait_any"); return f; } self->pending_subs = 0; CV *sub_on_ready = newXS(NULL, sub_on_ready_waitany, __FILE__); cv_set_anysv_refcounted(sub_on_ready, newSVsv(f)); sv_rvweaken(CvXSUBANY_sv(sub_on_ready)); GV *gv = gv_fetchpvs("Future::XS::(wait_any callback)", GV_ADDMULTI, SVt_PVCV); CvGV_set(sub_on_ready, gv); CvANON_off(sub_on_ready); for(Size_t i = 0; i < n; i++) { if(future_is_cancelled(subs[i])) continue; future_on_ready(subs[i], sv_2mortal(newRV_inc((SV *)sub_on_ready))); self->pending_subs++; } SvREFCNT_dec(sub_on_ready); return f; } #define compose_needsall_result(self) S_compose_needsall_result(aTHX_ self) static void S_compose_needsall_result(pTHX_ struct FutureXS *self) { AV *result = self->result = newAV(); for(Size_t i = 0; i < av_count(self->subs); i++) { SV *sub = AvARRAY(self->subs)[i]; struct FutureXS *subself = get_future(sub); assert(subself->result); av_push_svn(result, AvARRAY(subself->result), av_count(subself->result)); } } XS_INTERNAL(sub_on_ready_needsall) { dXSARGS; SV *thissub = ST(0); SV *f = XSANY_sv; if(!SvOK(f)) return; /* Make sure self doesn't disappear during this function */ SvREFCNT_inc(SvRV(f)); SAVEFREESV(SvRV(f)); struct FutureXS *self = get_future(f); if(self->result || self->failure) return; if(future_is_cancelled(thissub)) { future_failp(f, "A component future was cancelled"); cancel_pending_subs(self); return; } else if(future_is_failed(thissub)) { copy_result(self, thissub); cancel_pending_subs(self); mark_ready(self, f, "needs_all"); } else { self->pending_subs--; if(self->pending_subs) return; compose_needsall_result(self); mark_ready(self, f, "needs_all"); } } SV *Future_new_needsallv(pTHX_ const char *cls, SV **subs, size_t n) { SV *f = future_new_subsv(cls, subs, n); struct FutureXS *self = get_future(f); if(!n) { future_donev(f, NULL, 0); return f; } SV *immediate_fail = NULL; for(Size_t i = 0; i < n; i++) { if(future_is_cancelled(subs[i])) { future_failp(f, "A component future was cancelled"); cancel_pending_subs(self); return f; } if(future_is_failed(subs[i])) { immediate_fail = subs[i]; break; } } if(immediate_fail) { copy_result(self, immediate_fail); cancel_pending_subs(self); mark_ready(self, f, "needs_all"); return f; } self->pending_subs = 0; CV *sub_on_ready = newXS(NULL, sub_on_ready_needsall, __FILE__); cv_set_anysv_refcounted(sub_on_ready, newSVsv(f)); sv_rvweaken(CvXSUBANY_sv(sub_on_ready)); GV *gv = gv_fetchpvs("Future::XS::(needs_all callback)", GV_ADDMULTI, SVt_PVCV); CvGV_set(sub_on_ready, gv); CvANON_off(sub_on_ready); for(Size_t i = 0; i < n; i++) { if(future_is_ready(subs[i])) continue; future_on_ready(subs[i], sv_2mortal(newRV_inc((SV *)sub_on_ready))); self->pending_subs++; } if(!self->pending_subs) { compose_needsall_result(self); mark_ready(self, f, "needs_all"); } SvREFCNT_dec(sub_on_ready); return f; } XS_INTERNAL(sub_on_ready_needsany) { dXSARGS; SV *thissub = ST(0); SV *f = XSANY_sv; if(!SvOK(f)) return; /* Make sure self doesn't disappear during this function */ SvREFCNT_inc(SvRV(f)); SAVEFREESV(SvRV(f)); struct FutureXS *self = get_future(f); if(self->result || self->failure) return; self->pending_subs--; bool this_cancelled = future_is_cancelled(thissub); if(self->pending_subs && this_cancelled) return; if(this_cancelled) { future_failp(f, "All component futures were cancelled"); } else if(future_is_failed(thissub)) { if(self->pending_subs) return; copy_result(self, thissub); mark_ready(self, f, "needs_any"); } else { copy_result(self, thissub); cancel_pending_subs(self); mark_ready(self, f, "needs_any"); } } SV *Future_new_needsanyv(pTHX_ const char *cls, SV **subs, size_t n) { SV *f = future_new_subsv(cls, subs, n); struct FutureXS *self = get_future(f); if(!n) { future_failp(f, "Cannot ->needs_any with no subfutures"); return f; } SV *immediate_done = NULL; for(Size_t i = 0; i < n; i++) { if(future_is_done(subs[i])) { immediate_done = subs[i]; break; } } if(immediate_done) { copy_result(self, immediate_done); cancel_pending_subs(self); mark_ready(self, f, "needs_any"); return f; } self->pending_subs = 0; CV *sub_on_ready = newXS(NULL, sub_on_ready_needsany, __FILE__); cv_set_anysv_refcounted(sub_on_ready, newSVsv(f)); sv_rvweaken(CvXSUBANY_sv(sub_on_ready)); GV *gv = gv_fetchpvs("Future::XS::(needs_any callback)", GV_ADDMULTI, SVt_PVCV); CvGV_set(sub_on_ready, gv); CvANON_off(sub_on_ready); for(Size_t i = 0; i < n; i++) { if(future_is_ready(subs[i])) continue; future_on_ready(subs[i], sv_2mortal(newRV_inc((SV *)sub_on_ready))); self->pending_subs++; } if(!self->pending_subs) { copy_result(self, subs[n-1]); mark_ready(self, f, "needs_any"); } SvREFCNT_dec(sub_on_ready); return f; } Size_t Future_mPUSH_subs(pTHX_ SV *f, enum FutureSubFilter filter) { dSP; struct FutureXS *self = get_future(f); Size_t ret = 0; for(Size_t i = 0; self->subs && i < av_count(self->subs); i++) { SV *sub = AvARRAY(self->subs)[i]; bool want; switch(filter) { case FUTURE_SUBS_PENDING: want = !future_is_ready(sub); break; case FUTURE_SUBS_READY: want = future_is_ready(sub); break; case FUTURE_SUBS_DONE: want = future_is_done(sub); break; case FUTURE_SUBS_FAILED: want = future_is_failed(sub); break; case FUTURE_SUBS_CANCELLED: want = future_is_cancelled(sub); break; } if(want) { XPUSHs(sv_mortalcopy(sub)); ret++; } } PUTBACK; return ret; } struct timeval Future_get_btime(pTHX_ SV *f) { struct FutureXS *self = get_future(f); return self->btime; } struct timeval Future_get_rtime(pTHX_ SV *f) { struct FutureXS *self = get_future(f); return self->rtime; } void Future_set_label(pTHX_ SV *f, SV *label) { struct FutureXS *self = get_future(f); if(self->label) SvREFCNT_dec(label); self->label = newSVsv(label); } SV *Future_get_label(pTHX_ SV *f) { struct FutureXS *self = get_future(f); return self->label; } void Future_set_udata(pTHX_ SV *f, SV *key, SV *value) { struct FutureXS *self = get_future(f); if(!self->udata) self->udata = newHV(); hv_store_ent(self->udata, key, newSVsv(value), 0); } SV *Future_get_udata(pTHX_ SV *f, SV *key) { struct FutureXS *self = get_future(f); if(!self->udata) return &PL_sv_undef; HE *he = hv_fetch_ent(self->udata, key, 0, 0); return he ? HeVAL(he) : &PL_sv_undef; } /* DMD_HELPER assistants */ #ifdef HAVE_DMD_HELPER static int dumpstruct_callback(pTHX_ DMDContext *ctx, struct FutureXSCallback *cb) { if(!(cb->flags & CB_SEQ_ANY)) DMD_DUMP_STRUCT(ctx, "Future::XS/FutureXSCallback", cb, sizeof(struct FutureXSCallback), /* Some cheating here, to claim the "code" is either a CV or a Future, * depending on the CB_IS_FUTURE flag */ 3, ((const DMDNamedField []){ {"flags", DMD_FIELD_UINT, .n = cb->flags}, {"the code CV", DMD_FIELD_PTR, .ptr = (cb->flags & CB_IS_FUTURE) ? NULL : cb->code}, {"the Future SV", DMD_FIELD_PTR, .ptr = (cb->flags & CB_IS_FUTURE) ? cb->code : NULL }, }) ); else DMD_DUMP_STRUCT(ctx, "Future::XS/FutureXSCallback(CB_SEQ)", cb, sizeof(struct FutureXSCallback), 4, ((const DMDNamedField []){ {"flags", DMD_FIELD_UINT, .n = cb->flags}, {"the then code CV", DMD_FIELD_PTR, .ptr = cb->seq.thencode}, {"the else code CV", DMD_FIELD_PTR, .ptr = cb->seq.elsecode}, {"the sequence future SV", DMD_FIELD_PTR, .ptr = cb->seq.f}, }) ); return 0; } static int dumpstruct_revocation(pTHX_ DMDContext *ctx, struct FutureXSRevocation *rev) { DMD_DUMP_STRUCT(ctx, "Future::XS/FutureXSRevocation", rev, sizeof(struct FutureXSRevocation), 2, ((const DMDNamedField []){ {"the precedent future SV", DMD_FIELD_PTR, .ptr = rev->precedent_f}, {"the SV to clear RV", DMD_FIELD_PTR, .ptr = rev->toclear_sv_at}, }) ); return 0; } static int dumpstruct(pTHX_ DMDContext *ctx, const SV *sv) { int ret = 0; // TODO: Add some safety checking struct FutureXS *self = INT2PTR(struct FutureXS *, SvIV((SV *)sv)); DMD_DUMP_STRUCT(ctx, "Future::XS/FutureXS", self, sizeof(struct FutureXS), 12, ((const DMDNamedField []){ {"ready", DMD_FIELD_BOOL, .b = self->ready}, {"cancelled", DMD_FIELD_BOOL, .b = self->cancelled}, {"the label SV", DMD_FIELD_PTR, .ptr = self->label}, {"the result AV", DMD_FIELD_PTR, .ptr = self->result}, {"the failure AV", DMD_FIELD_PTR, .ptr = self->failure}, {"the callbacks AV", DMD_FIELD_PTR, .ptr = self->callbacks}, {"the on_cancel AV", DMD_FIELD_PTR, .ptr = self->on_cancel}, {"the revoke_when_ready AV", DMD_FIELD_PTR, .ptr = self->revoke_when_ready}, {"the udata HV", DMD_FIELD_PTR, .ptr = self->udata}, {"the constructed-at SV", DMD_FIELD_PTR, .ptr = self->constructed_at}, {"the subs AV", DMD_FIELD_PTR, .ptr = self->subs}, {"the pending sub count", DMD_FIELD_UINT, .n = self->pending_subs}, }) ); for(size_t i = 0; self->callbacks && i < av_count(self->callbacks); i++) { struct FutureXSCallback *cb = (struct FutureXSCallback *)AvARRAY(self->callbacks)[i]; ret += dumpstruct_callback(aTHX_ ctx, cb); } for(size_t i = 0; self->revoke_when_ready && i < av_count(self->revoke_when_ready); i++) { struct FutureXSRevocation *rev = (struct FutureXSRevocation *)AvARRAY(self->revoke_when_ready)[i]; ret += dumpstruct_revocation(aTHX_ ctx, rev); } ret += DMD_ANNOTATE_SV(sv, (SV *)self, "the FutureXS structure"); return ret; } #endif #define getenv_bool(key) S_getenv_bool(aTHX_ key) static bool S_getenv_bool(pTHX_ const char *key) { const char *val = getenv(key); if(!val || !val[0]) return false; if(val[0] == '0' && strlen(val) == 1) return false; return true; } #ifndef newSVbool # define newSVbool(b) newSVsv(b ? &PL_sv_yes : &PL_sv_no) #endif void Future_reread_environment(pTHX) { future_debug = getenv_bool("PERL_FUTURE_DEBUG"); capture_times = future_debug || getenv_bool("PERL_FUTURE_TIMES"); sv_setsv(get_sv("Future::TIMES", GV_ADDMULTI), capture_times ? &PL_sv_yes : &PL_sv_no); } void Future_boot(pTHX) { #ifdef HAVE_DMD_HELPER DMD_SET_PACKAGE_HELPER("Future::XS", dumpstruct); #endif Future_reread_environment(aTHX); // We can only do this once newCONSTSUB(gv_stashpvn("Future::XS", 10, TRUE), "DEBUG", newSVbool(future_debug)); } Future-XS-0.12/t000755001750001750 014543104252 12222 5ustar00leoleo000000000000Future-XS-0.12/t/00use.t000444001750001750 17014543104252 13456 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; require Future::XS; pass( 'Modules loaded' ); done_testing; Future-XS-0.12/t/50thread.t000444001750001750 203314543104252 14156 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Test2::IPC; # to quiet the warning use Future::XS; eval { require Config && $Config::Config{useithreads} } or plan skip_all => "This perl does not support threads"; require threads; # Just to keep the in-dist unit tests happy; when loaded via Future.pm the # one provided there takes precedence sub Future::XS::wrap_cb { my $self = shift; my ( $name, $cb ) = @_; return $cb; } # future outside of thread { my $f1 = Future::XS->new; my $f2 = $f1->then( sub { Future::XS->done( "result" ) } ); threads->create(sub { return "dummy"; })->join; $f1->done; is( $f2->get, "result", 'Result of Future::XS entirely ouside of sidecar thread' ); } # future inside thread { my $ret = threads->create(sub { my $f1 = Future::XS->new; my $f2 = $f1->then( sub { Future::XS->done( "result" ) } ); $f1->done; return $f2->get; })->join; is( $ret, "result", 'Result of Future::XS entirely within thread' ); } done_testing; Future-XS-0.12/t/90leak.t000444001750001750 724414543104252 13640 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Future::XS; BEGIN { plan skip_all => "Test::MemoryGrowth is not available" unless defined eval { require Test::MemoryGrowth }; Test::MemoryGrowth->import; } # Just to keep the in-dist unit tests happy; when loaded via Future.pm the # one provided there takes precedence sub Future::XS::wrap_cb { my $self = shift; my ( $name, $cb ) = @_; return $cb; } no_growth { my $f = Future::XS->new; $f->done( 123 ); $f->result; } 'Future::XS->new->done does not leak'; no_growth { my $f = Future::XS->new; $f->fail( "Oopsie\n" ); $f->failure; } 'Future::XS->new->fail does not leak'; no_growth { my $f = Future::XS->new; $f->cancel; } 'Future::XS->new->cancel does not leak'; no_growth { my $fret = ( my $f1 = Future::XS->new ) ->then( sub { Future::XS->done } ); $f1->done; $fret->result; } 'Future::XS->then does not leak'; no_growth { my $fret = ( my $f1 = Future::XS->done ) ->then( sub { Future::XS->done } ); $fret->result; } 'Future::XS->then immediate does not leak'; no_growth { my $fret = ( my $f1 = Future::XS->new ) ->else( sub { Future::XS->done } ); $f1->done; $fret->result; } 'Future::XS->else does not leak'; no_growth { my $fret = ( my $f1 = Future::XS->fail( "oopsie" ) ) ->else( sub { Future::XS->done } ); $fret->result; } 'Future::XS->else does not leak'; no_growth { my $fret = ( my $f1 = Future::XS->new ) ->followed_by( sub { Future::XS->done } ); $f1->done; $fret->result; } 'Future::XS->followed_by does not leak'; no_growth { my $fret = ( my $f1 = Future::XS->done ) ->followed_by( sub { Future::XS->done } ); $fret->result; } 'Future::XS->followed_by immediate does not leak'; # RT150198 no_growth { my ( $f1, $f2 ); my $fret = ( $f1 = Future::XS->new->set_label( '$f1' ) ) ->followed_by( sub { my $f = shift; $f2 = Future->new->set_label( '$f2' ); return $f2->then( sub { $f }, sub { $f } )->set_label( '->then' ); } ); $f1->done; $f2->done; $fret->result; } 'Future::XS->followed_by + ->then does not leak (RT150198)'; no_growth { my $fret = ( my $f1 = Future::XS->new ) ->catch( fail => sub { Future::XS->done } ); $f1->done; $fret->result; } 'Future::XS->catch does not leak'; no_growth { my $fret = ( my $f1 = Future::XS->done ) ->catch( fail => sub { Future::XS->done } ); $fret->result; } 'Future::XS->catch immediate does not leak'; no_growth { Future::XS->wait_all( Future::XS->new, Future::XS->new, Future::XS->new, )->cancel; } 'Future::XS->wait_all on three subfutures does not leak'; no_growth { Future::XS->wait_any( Future::XS->new, Future::XS->new, Future::XS->new, )->cancel; } 'Future::XS->wait_any on three subfutures does not leak'; no_growth { Future::XS->needs_all( Future::XS->new, Future::XS->new, Future::XS->new, )->cancel; } 'Future::XS->needs_all on three subfutures does not leak'; no_growth { Future::XS->needs_any( Future::XS->new, Future::XS->new, Future::XS->new, )->cancel; } 'Future::XS->needs_any on three subfutures does not leak'; no_growth { my $f = Future::XS->new; $f->set_label( "A string label here" ); $f->cancel; } 'Future::XS->set_label does not leak'; no_growth { my $f = Future::XS->new; $f->set_udata( datum => [] ); $f->cancel; } 'Future::XS->set_label does not leak'; # Test the compaction logic on revocation list { my $f1 = Future::XS->new; no_growth { my $f2 = Future::XS->new; $f1->on_cancel( $f2 ); $f2->cancel; } 'Future::XS on_cancel chaining does not grow'; } done_testing; Future-XS-0.12/t/99pod.t000444001750001750 25514543104252 13472 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();