Guard-1.022/0000755000000000000000000000000011603464214011257 5ustar rootrootGuard-1.022/t/0000755000000000000000000000000011603464214011522 5ustar rootrootGuard-1.022/t/02_guard.t0000644000000000000000000000066111121004411013275 0ustar rootrootBEGIN { $| = 1; print "1..11\n"; } use Guard; print "ok 1\n"; { my $guard = guard { print "ok 3\n" }; print "ok 2\n"; } print "ok 4\n"; { my $guard = guard { print "not ok 6\n" }; print "ok 5\n"; $guard->cancel; } print "ok 6\n"; { my $guard = guard { print "ok 9\n" }; my $guard2 = $guard; print "ok 7\n"; undef $guard; print "ok 8\n"; undef $guard2; print "ok 10\n"; } print "ok 11\n"; Guard-1.022/t/01_scoped.t0000644000000000000000000000056311121004014013447 0ustar rootrootBEGIN { $| = 1; print "1..10\n"; } use Guard; print "ok 1\n"; our $global = 0; { scope_guard { print "ok 3\n" }; local $global = 1; print "ok 2\n"; } print "ok 4\n"; { scope_guard { print "ok 6\n" }; print "ok 5\n"; last; } print "ok 7\n"; { scope_guard { print "ok 9\n" }; print "ok 8\n"; exit; } END { print "ok 10\n"; } Guard-1.022/t/00_load.t0000644000000000000000000000016311120737516013127 0ustar rootrootBEGIN { $| = 1; print "1..1\n"; } END {print "not ok 1\n" unless $loaded;} use Guard; $loaded = 1; print "ok 1\n"; Guard-1.022/t/03_die.t0000644000000000000000000000144411121010021012727 0ustar rootrootBEGIN { $| = 1; print "1..11\n"; } use Guard; print "ok 1\n"; $Guard::DIED = sub { print $@ =~ /^x1 at / ? "" : "not ", "ok 3 # $@\n"; }; eval { scope_guard { die "x1" }; print "ok 2\n"; }; print $@ ? "not " : "", "ok 4 # $@\n"; $Guard::DIED = sub { print $@ =~ /^x2 at / ? "" : "not ", "ok 6 # $@\n"; }; eval { scope_guard { die "x2" }; print "ok 5\n"; die "x3"; }; print $@ =~ /^x3 at /s ? "" : "not ", "ok 7 # $@\n"; our $x4 = 1; $SIG{__DIE__} = sub { if ($x4) { print "not ok 9\n"; } else { print $_[0] =~ /^x5 at / ? "" : "not ", "ok 11 # $_[0]\n"; } exit 0; }; { $Guard::DIED = sub { print $@ =~ /^x4 at / ? "" : "not ", "ok 9 # $@\n"; }; scope_guard { die "x4" }; print "ok 8\n"; }; $x4 = 0; print "ok 10\n"; die "x5"; Guard-1.022/Guard.pm0000644000000000000000000001441411603464205012663 0ustar rootroot=head1 NAME Guard - safe cleanup blocks =head1 SYNOPSIS use Guard; # temporarily chdir to "/etc" directory, but make sure # to go back to "/" no matter how myfun exits: sub myfun { scope_guard { chdir "/" }; chdir "/etc"; code_that_might_die_or_does_other_fun_stuff; } # create an object that, when the last reference to it is gone, # invokes the given codeblock: my $guard = guard { print "destroyed!\n" }; undef $guard; # probably destroyed here =head1 DESCRIPTION This module implements so-called "guards". A guard is something (usually an object) that "guards" a resource, ensuring that it is cleaned up when expected. Specifically, this module supports two different types of guards: guard objects, which execute a given code block when destroyed, and scoped guards, which are tied to the scope exit. =head1 FUNCTIONS This module currently exports the C and C functions by default. =over 4 =cut package Guard; no warnings; BEGIN { $VERSION = '1.022'; @ISA = qw(Exporter); @EXPORT = qw(guard scope_guard); require Exporter; require XSLoader; XSLoader::load Guard, $VERSION; } our $DIED = sub { warn "$@" }; =item scope_guard BLOCK =item scope_guard ($coderef) Registers a block that is executed when the current scope (block, function, method, eval etc.) is exited. See the EXCEPTIONS section for an explanation of how exceptions (i.e. C) are handled inside guard blocks. The description below sounds a bit complicated, but that's just because C tries to get even corner cases "right": the goal is to provide you with a rock solid clean up tool. The behaviour is similar to this code fragment: eval ... code following scope_guard ... { local $@; eval BLOCK; eval { $Guard::DIED->() } if $@; } die if $@; Except it is much faster, and the whole thing gets executed even when the BLOCK calls C, C, C or escapes via other means. If multiple BLOCKs are registered to the same scope, they will be executed in reverse order. Other scope-related things such as C are managed via the same mechanism, so variables Cised I calling C will be restored when the guard runs. Example: temporarily change the timezone for the current process, ensuring it will be reset when the C scope is exited: use Guard; use POSIX (); if ($need_to_switch_tz) { # make sure we call tzset after $ENV{TZ} has been restored scope_guard { POSIX::tzset }; # localise after the scope_guard, so it gets undone in time local $ENV{TZ} = "Europe/London"; POSIX::tzset; # do something with the new timezone } =item my $guard = guard BLOCK =item my $guard = guard ($coderef) Behaves the same as C, except that instead of executing the block on scope exit, it returns an object whose lifetime determines when the BLOCK gets executed: when the last reference to the object gets destroyed, the BLOCK gets executed as with C. See the EXCEPTIONS section for an explanation of how exceptions (i.e. C) are handled inside guard blocks. Example: acquire a Coro::Semaphore for a second by registering a timer. The timer callback references the guard used to unlock it again. (Please ignore the fact that C has a C method that does this already): use Guard; use Coro::AnyEvent; use Coro::Semaphore; my $sem = new Coro::Semaphore; sub lock_for_a_second { $sem->down; my $guard = guard { $sem->up }; Coro::AnyEvent::sleep 1; # $sem->up gets executed when returning } The advantage of doing this with a guard instead of simply calling C<< $sem->down >> in the callback is that you can opt not to create the timer, or your code can throw an exception before it can create the timer (or the thread gets canceled), or you can create multiple timers or other event watchers and only when the last one gets executed will the lock be unlocked. Using the C, you do not have to worry about catching all the places where you have to unlock the semaphore. =item $guard->cancel Calling this function will "disable" the guard object returned by the C function, i.e. it will free the BLOCK originally passed to Cand will arrange for the BLOCK not to be executed. This can be useful when you use C to create a cleanup handler to be called under fatal conditions and later decide it is no longer needed. =cut 1; =back =head1 EXCEPTIONS Guard blocks should not normally throw exceptions (that is, C). After all, they are usually used to clean up after such exceptions. However, if something truly exceptional is happening, a guard block should of course be allowed to die. Also, programming errors are a large source of exceptions, and the programmer certainly wants to know about those. Since in most cases, the block executing when the guard gets executed does not know or does not care about the guard blocks, it makes little sense to let containing code handle the exception. Therefore, whenever a guard block throws an exception, it will be caught by Guard, followed by calling the code reference stored in C<$Guard::DIED> (with C<$@> set to the actual exception), which is similar to how most event loops handle this case. The default for C<$Guard::DIED> is to call C, i.e. the error is printed as a warning and the program continues. The C<$@> variable will be restored to its value before the guard call in all cases, so guards will not disturb C<$@> in any way. The code reference stored in C<$Guard::DIED> should not die (behaviour is not guaranteed, but right now, the exception will simply be ignored). =head1 AUTHOR Marc Lehmann http://home.schmorp.de/ =head1 THANKS Thanks to Marco Maisenhelder, who reminded me of the C<$Guard::DIED> solution to the problem of exceptions. =head1 SEE ALSO L and L, which actually implement dynamically scoped guards only, not the lexically scoped guards that their documentation promises, and have a lot higher CPU, memory and typing overhead. L, which has apparently never been finished and can corrupt memory when used. L seems to have a big SEE ALSO section for even more modules like it. =cut Guard-1.022/Changes0000644000000000000000000000227111603464202012551 0ustar rootrootRevision history for Perl extension Guard 1.022 Sat Jul 2 02:38:21 CEST 2011 - document how () after the function name overrides the prototype. - improve documentation, fix the examples. 1.021 Sun Jul 19 07:43:17 CEST 2009 - try to provide compatibility to pre-5.8.8. 1.02 Sat Apr 11 06:42:06 CEST 2009 - set NODEBUG on scope_guard, to work around -d: modules causing scope_guard to be called in the wrong context. 1.01 Wed Jan 14 00:30:18 CET 2009 - guard_free didn't return a value. 1.0 Fri Dec 26 14:03:28 CET 2008 - un-support windows process emulation (it didn't work anyways). - discuss similar modules. - tweaked documentation slightly. 0.5 Sat Dec 13 22:46:46 CET 2008 - vastly improve documentation, clarify local/scope_guard ordering and give a niftier examples. - always bless guard objects and convert Guard::cancel to a method, at an 8% runtime cost. - temporarily disable $SIG{__DIE__} when executing guard blocks. - fix testsuite. 0.1 Sat Dec 13 18:49:30 CET 2008 - first release. 0.01 Sat Dec 13 14:57:44 CET 2008 - cloned form Convert-Scalar. Guard-1.022/META.json0000644000000000000000000000106711603464214012704 0ustar rootroot{ "no_index" : { "directory" : [ "t", "inc" ] }, "meta-spec" : { "version" : 1.4, "url" : "http://module-build.sourceforge.net/META-spec-v1.4.html" }, "generated_by" : "ExtUtils::MakeMaker::JSONMETA version 7.000", "distribution_type" : "module", "version" : "1.022", "name" : "Guard", "author" : [], "license" : "unknown", "build_requires" : { "ExtUtils::MakeMaker" : 0 }, "requires" : {}, "abstract" : null, "configure_requires" : { "ExtUtils::MakeMaker" : 0 } } Guard-1.022/README0000644000000000000000000001514711603464215012150 0ustar rootrootNAME Guard - safe cleanup blocks SYNOPSIS use Guard; # temporarily chdir to "/etc" directory, but make sure # to go back to "/" no matter how myfun exits: sub myfun { scope_guard { chdir "/" }; chdir "/etc"; code_that_might_die_or_does_other_fun_stuff; } # create an object that, when the last reference to it is gone, # invokes the given codeblock: my $guard = guard { print "destroyed!\n" }; undef $guard; # probably destroyed here DESCRIPTION This module implements so-called "guards". A guard is something (usually an object) that "guards" a resource, ensuring that it is cleaned up when expected. Specifically, this module supports two different types of guards: guard objects, which execute a given code block when destroyed, and scoped guards, which are tied to the scope exit. FUNCTIONS This module currently exports the "scope_guard" and "guard" functions by default. scope_guard BLOCK scope_guard ($coderef) Registers a block that is executed when the current scope (block, function, method, eval etc.) is exited. See the EXCEPTIONS section for an explanation of how exceptions (i.e. "die") are handled inside guard blocks. The description below sounds a bit complicated, but that's just because "scope_guard" tries to get even corner cases "right": the goal is to provide you with a rock solid clean up tool. The behaviour is similar to this code fragment: eval ... code following scope_guard ... { local $@; eval BLOCK; eval { $Guard::DIED->() } if $@; } die if $@; Except it is much faster, and the whole thing gets executed even when the BLOCK calls "exit", "goto", "last" or escapes via other means. If multiple BLOCKs are registered to the same scope, they will be executed in reverse order. Other scope-related things such as "local" are managed via the same mechanism, so variables "local"ised *after* calling "scope_guard" will be restored when the guard runs. Example: temporarily change the timezone for the current process, ensuring it will be reset when the "if" scope is exited: use Guard; use POSIX (); if ($need_to_switch_tz) { # make sure we call tzset after $ENV{TZ} has been restored scope_guard { POSIX::tzset }; # localise after the scope_guard, so it gets undone in time local $ENV{TZ} = "Europe/London"; POSIX::tzset; # do something with the new timezone } my $guard = guard BLOCK my $guard = guard ($coderef) Behaves the same as "scope_guard", except that instead of executing the block on scope exit, it returns an object whose lifetime determines when the BLOCK gets executed: when the last reference to the object gets destroyed, the BLOCK gets executed as with "scope_guard". See the EXCEPTIONS section for an explanation of how exceptions (i.e. "die") are handled inside guard blocks. Example: acquire a Coro::Semaphore for a second by registering a timer. The timer callback references the guard used to unlock it again. (Please ignore the fact that "Coro::Semaphore" has a "guard" method that does this already): use Guard; use Coro::AnyEvent; use Coro::Semaphore; my $sem = new Coro::Semaphore; sub lock_for_a_second { $sem->down; my $guard = guard { $sem->up }; Coro::AnyEvent::sleep 1; # $sem->up gets executed when returning } The advantage of doing this with a guard instead of simply calling "$sem->down" in the callback is that you can opt not to create the timer, or your code can throw an exception before it can create the timer (or the thread gets canceled), or you can create multiple timers or other event watchers and only when the last one gets executed will the lock be unlocked. Using the "guard", you do not have to worry about catching all the places where you have to unlock the semaphore. $guard->cancel Calling this function will "disable" the guard object returned by the "guard" function, i.e. it will free the BLOCK originally passed to "guard "and will arrange for the BLOCK not to be executed. This can be useful when you use "guard" to create a cleanup handler to be called under fatal conditions and later decide it is no longer needed. EXCEPTIONS Guard blocks should not normally throw exceptions (that is, "die"). After all, they are usually used to clean up after such exceptions. However, if something truly exceptional is happening, a guard block should of course be allowed to die. Also, programming errors are a large source of exceptions, and the programmer certainly wants to know about those. Since in most cases, the block executing when the guard gets executed does not know or does not care about the guard blocks, it makes little sense to let containing code handle the exception. Therefore, whenever a guard block throws an exception, it will be caught by Guard, followed by calling the code reference stored in $Guard::DIED (with $@ set to the actual exception), which is similar to how most event loops handle this case. The default for $Guard::DIED is to call "warn "$@"", i.e. the error is printed as a warning and the program continues. The $@ variable will be restored to its value before the guard call in all cases, so guards will not disturb $@ in any way. The code reference stored in $Guard::DIED should not die (behaviour is not guaranteed, but right now, the exception will simply be ignored). AUTHOR Marc Lehmann http://home.schmorp.de/ THANKS Thanks to Marco Maisenhelder, who reminded me of the $Guard::DIED solution to the problem of exceptions. SEE ALSO Scope::Guard and Sub::ScopeFinalizer, which actually implement dynamically scoped guards only, not the lexically scoped guards that their documentation promises, and have a lot higher CPU, memory and typing overhead. Hook::Scope, which has apparently never been finished and can corrupt memory when used. Scope::Guard seems to have a big SEE ALSO section for even more modules like it. Guard-1.022/Guard.xs0000644000000000000000000000506611230524001012667 0ustar rootroot#define PERL_NO_GET_CONTEXT #include "EXTERN.h" #include "perl.h" #include "XSUB.h" /* apparently < 5.8.8 */ #ifndef SvSTASH_set # define SvSTASH_set(x,a) SvSTASH(x) = (a) #endif #ifndef PERL_MAGIC_ext # define PERL_MAGIC_ext '~' #endif static HV *guard_stash; static SV * guard_get_cv (pTHX_ SV *cb_sv) { HV *st; GV *gvp; CV *cv = sv_2cv (cb_sv, &st, &gvp, 0); if (!cv) croak ("expected a CODE reference for guard"); return (SV *)cv; } static void exec_guard_cb (pTHX_ SV *cb) { dSP; SV *saveerr = SvOK (ERRSV) ? sv_mortalcopy (ERRSV) : 0; SV *savedie = PL_diehook; PL_diehook = 0; PUSHSTACKi (PERLSI_DESTROY); PUSHMARK (SP); PUTBACK; call_sv (cb, G_VOID | G_DISCARD | G_EVAL); if (SvTRUE (ERRSV)) { SPAGAIN; PUSHMARK (SP); PUTBACK; call_sv (get_sv ("Guard::DIED", 1), G_VOID | G_DISCARD | G_EVAL | G_KEEPERR); sv_setpvn (ERRSV, "", 0); } if (saveerr) sv_setsv (ERRSV, saveerr); { SV *oldhook = PL_diehook; PL_diehook = savedie; SvREFCNT_dec (oldhook); } POPSTACK; } static void scope_guard_cb (pTHX_ void *cv) { exec_guard_cb (aTHX_ sv_2mortal ((SV *)cv)); } static int guard_free (pTHX_ SV *cv, MAGIC *mg) { exec_guard_cb (aTHX_ mg->mg_obj); return 0; } static MGVTBL guard_vtbl = { 0, 0, 0, 0, guard_free }; MODULE = Guard PACKAGE = Guard BOOT: guard_stash = gv_stashpv ("Guard", 1); CvNODEBUG_on (get_cv ("Guard::scope_guard", 0)); /* otherwise calling scope can be the debugger */ void scope_guard (SV *block) PROTOTYPE: & CODE: LEAVE; /* unfortunately, perl sandwiches XS calls into ENTER/LEAVE */ SAVEDESTRUCTOR_X (scope_guard_cb, (void *)SvREFCNT_inc (guard_get_cv (aTHX_ block))); ENTER; /* unfortunately, perl sandwiches XS calls into ENTER/LEAVE */ SV * guard (SV *block) PROTOTYPE: & CODE: { SV *cv = guard_get_cv (aTHX_ block); SV *guard = NEWSV (0, 0); SvUPGRADE (guard, SVt_PVMG); sv_magicext (guard, cv, PERL_MAGIC_ext, &guard_vtbl, 0, 0); RETVAL = newRV_noinc (guard); SvOBJECT_on (guard); ++PL_sv_objcount; SvSTASH_set (guard, (HV*)SvREFCNT_inc ((SV *)guard_stash)); } OUTPUT: RETVAL void cancel (SV *guard) PROTOTYPE: $ CODE: { MAGIC *mg; if (!SvROK (guard) || !(mg = mg_find (SvRV (guard), PERL_MAGIC_ext)) || mg->mg_virtual != &guard_vtbl) croak ("Guard::cancel called on a non-guard object"); SvREFCNT_dec (mg->mg_obj); mg->mg_obj = 0; mg->mg_virtual = 0; } Guard-1.022/Makefile.PL0000644000000000000000000000046511231735756013247 0ustar rootrootuse ExtUtils::MakeMaker; use 5.008; WriteMakefile( dist => { PREOP => 'pod2text Guard.pm | tee README >$(DISTVNAME)/README; chmod -R u=rwX,go=rX . ;', COMPRESS => 'gzip -9v', SUFFIX => '.gz', }, NAME => "Guard", VERSION_FROM => "Guard.pm", ); Guard-1.022/COPYING0000644000000000000000000000007611120737516012317 0ustar rootrootThis module is licensed under the same terms as perl itself. Guard-1.022/MANIFEST0000644000000000000000000000027711603464214012416 0ustar rootrootREADME Changes MANIFEST COPYING Makefile.PL Guard.pm Guard.xs t/00_load.t t/01_scoped.t t/02_guard.t t/03_die.t META.json Module meta-data (added by MakeMaker)