ZMQ/Socket.pm untested

filter: Statementstmt 0.0% 0 / 61 Branchbran 0.0% 0 / 18 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 92 CC 9 SCAR 29.6
CC
9
Cov
0%
configure
42.0
_zmq_get_io_handle
20.0
socket
2.0
CRAP 19.3
1 package Net::Async::ZMQ::Socket;
2 # ABSTRACT: Use a ZMQ socket asynchronously using IO::Async
3 $Net::Async::ZMQ::Socket::VERSION = '0.002';
4 use strict;
5 use warnings;
6  
7 use Package::Stash;
8  
9 use Module::Load;
10 use Fcntl qw(O_RDONLY);
11 use if $^O eq 'MSWin32', 'Win32API::File' => qw(OsFHandleOpenFd);
12  
13 use base qw( IO::Async::Handle );
14  
15 sub configure {
16 my ($self, %params) = @_;
17  
18 for (qw(socket)) {
19 $self->{$_} = delete $params{$_} if exists $params{$_};
20 }
21  
22  
23 if( exists $self->{socket} ) {
24 my $zmq_class;
25 my $zmq_fd;
26  
27 my $socket = $self->{socket};
28 if( $socket->isa('ZMQ::LibZMQ3::Socket') ) {
29 $self->{_zmq_class} = 'ZMQ::LibZMQ3';
30 load 'ZMQ::Constants', qw(ZMQ_FD);
31 $zmq_fd = ZMQ::Constants::ZMQ_FD();
32 } elsif( $socket->isa('ZMQ::LibZMQ4::Socket') ) {
33 $self->{_zmq_class} = 'ZMQ::LibZMQ4';
34 load 'ZMQ::Constants', qw(ZMQ_FD);
35 $zmq_fd = ZMQ::Constants::ZMQ_FD();
36 } elsif( $socket->DOES('ZMQ::FFI::SocketRole') ) {
37 $self->{_zmq_class} = 'ZMQ::FFI';
38 load 'ZMQ::FFI::Constants', qw(ZMQ_FD);
39 $zmq_fd = ZMQ::FFI::Constants::ZMQ_FD();
40 } else {
41 die "Unknown ZMQ socket: $socket";
42 }
43  
44 $self->{_stash} = Package::Stash->new($self->{_zmq_class});
45  
46 $params{read_handle} = $self->_zmq_get_io_handle($self->{socket}, $zmq_fd);
47 }
48  
49 $self->SUPER::configure(%params);
50 }
51  
52 sub socket {
53 my ($self) = @_;
54 $self->{socket};
55 }
56  
57 sub _zmq_get_io_handle {
58 my ($self, $socket, $zmq_fd) = @_;
59  
60 my $zmq_getsockopt =
61 $self->{_zmq_class} eq 'ZMQ::FFI'
62 ? sub { my ($socket, $opt) = @_; $socket->get( $opt, 'int' ) }
63 : $self->{_stash}->get_symbol('&zmq_getsockopt');
64 my $zmq_getsockopt_uint64 =
65 $self->{_zmq_class} eq 'ZMQ::FFI'
66 ? sub { my ($socket, $opt) = @_; $socket->get( $opt, 'uint64_t' ) }
67 : $self->{_stash}->get_symbol('&zmq_getsockopt_uint64');
68  
69 my $fd;
70  
71 if( $^O eq 'MSWin32' ) {
72 # `SOCKET` data type is a `uint64` on Windows x64.
73 my $socket_handle = $zmq_getsockopt_uint64->( $socket, $zmq_fd );
74 # Converts OS socket handle to a C runtime file descriptor.
75 $fd = OsFHandleOpenFd($socket_handle, O_RDONLY);
76 } else {
77 $fd = $zmq_getsockopt->( $socket, $zmq_fd );
78 }
79  
80 # Use dup() on the ZMQ file descriptor so that Perl can close the
81 # handle without closing the ZMQ handle.
82 #
83 # Also, avoid using IO::Handle here due to how it closes the file
84 # handle automatically.
85 open(my $io_handle, "<&", $fd);
86  
87 $io_handle;
88 }
89  
90 1;
91  
92 __END__