File: Publisher.pm

package info (click to toggle)
libipc-pubsub-perl 0.29-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 176 kB
  • sloc: perl: 1,471; makefile: 2
file content (66 lines) | stat: -rw-r--r-- 1,467 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package IPC::PubSub::Publisher;
use strict;
use warnings;
use base qw/Class::Accessor::Fast/;

__PACKAGE__->mk_accessors(qw/expiry/);
__PACKAGE__->mk_ro_accessors(qw/_indice uuid _cache/);

sub new {
    my $class   = shift;
    my $cache   = shift;

    require Data::UUID;

    my $uuid    = Data::UUID->new->create_b64;
    my $self    = bless({
        expiry  => 0,
        _cache  => $cache,
        _indice => { map { $_ => 1 } @_ },
        uuid    => $uuid,
    });
    $cache->add_publisher($_, $uuid) for @_;
    return $self;
}

sub channels {
    my $self = shift;
    wantarray
        ? keys(%{$self->_indice})
        : $self->_indice;
}

sub publish {
    my $self = shift;
    $self->_indice->{$_} ||= do {
        $self->_cache->add_publisher($_, $self->uuid);
        1;
    } for @_;
}

sub unpublish {
    my $self = shift;
    delete($self->_indice->{$_}) and $self->_cache->remove_publisher($_, $self->uuid) for @_;
}

sub msg {
    my $self    = shift;
    my $uuid    = $self->uuid;
    my $indice  = $self->_indice;
    my $expiry  = $self->expiry;
    foreach my $msg (@_) {
        while (my ($channel, $index) = each %$indice) {
            $self->_cache->put($channel, $uuid, $index, $msg, $expiry);
            $indice->{$channel} = $index+1;
        }
    }
}

no warnings 'redefine';
sub DESTROY {
    my $self = shift;
    return unless $self->_cache;
    $self->_cache->remove_publisher($_, $self->uuid) for $self->channels;
}

1;