| 1 | package JE::Destroyer; | ||
| 2 | |||
| 3 | our $VERSION = '0.066'; | ||
| 4 | |||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | |||
| 8 | # We cannot use JE::_FieldHash, because we end up triggering bugs in weak | ||
| 9 | # references in 5.8. (JE::_FieldHash uses Tie::RefHash::Weak in 5.8.) | ||
| 10 | # (Those bugs were fixed between 5.10.1 and 5.12.4, but by which commit | ||
| 11 | # I wot not.) | ||
| 12 | #use JE::_FieldHash; | ||
| 13 | BEGIN { | ||
| 14 | require constant; | ||
| 15 | # unsafe_helem means that $h{$foo} will stringify $foo. | ||
| 16 | # Hash::Util::FieldHash doesn’t stringify a ref key. | ||
| 17 | import constant unsafe_helem => | ||
| 18 | not my $hufh = eval { require Hash::Util::FieldHash }; | ||
| 19 | if ($hufh) { | ||
| 20 | import Hash::Util::FieldHash 'fieldhash'; | ||
| 21 | } | ||
| 22 | else { *fieldhash = sub {$_[0]} } | ||
| 23 | } | ||
| 24 | |||
| 25 | use Scalar'Util qw 'refaddr weaken'; | ||
| 26 | |||
| 27 | fieldhash my %js_envs; | ||
| 28 | |||
| 29 | $JE::Destroyer = 1; | ||
| 30 | |||
| 31 | sub register { | ||
| 32 | my $global = $_[0]->global; | ||
| 33 | # if (ref ($global) eq 'JE::Scope') { use Carp; Carp::cluck; warn "-"x70, "\n" } | ||
| 34 | my $globaddr = refaddr $global; | ||
| 35 | if ($globaddr == refaddr $_[0]) { return } | ||
| 36 | ($js_envs{unsafe_helem ? $globaddr : $global} ||= &fieldhash({})) | ||
| 37 | ->{unsafe_helem ? refaddr $_[0] : $_[0]} = \(my $entry = $_[0]); | ||
| 38 | weaken $entry; | ||
| 39 | return # nothing; | ||
| 40 | } | ||
| 41 | |||
| 42 | sub destroy { | ||
| 43 | exists $js_envs{$_[0]} or return; | ||
| 44 | # We can’t just iterate over the values, because $$_->destroy might | ||
| 45 | # actually free some of the things we are iterating over. So put them in | ||
| 46 | # an array first. | ||
| 47 | my @objs = values %{ $js_envs{$_[0]} }; | ||
| 48 | # And still, since the values are themselves weak references to the | ||
| 49 | # objects, we have to check for definition. | ||
| 50 | defined $$_ and $$_->destroy for @objs; | ||
| 51 | delete $js_envs{$_[0]}; | ||
| 52 | $_[0]->destroy; | ||
| 53 | return # nothing; | ||
| 54 | } | ||
| 55 | |||
| 56 | __END__ |