package ZMQ::FFI::SocketRole;
$ZMQ::FFI::SocketRole::VERSION = '1.07';
use FFI::Platypus;
use FFI::Platypus::Memory qw(malloc);

use ZMQ::FFI::Constants qw(zmq_msg_t_size);

use Moo::Role;

has soname => (
    is       => 'ro',
    required => 1,
);

# context to associate socket instance with.
# reference necessary to guard against premature object destruction
has ctx => (
    is       => 'ro',
    required => 1,
);

# zmq constant socket type, e.g. ZMQ_REQ
has type => (
    is       => 'ro',
    required => 1,
);

# real underlying zmq socket pointer
has _socket => (
    is      => 'rw',
    default => -1,
);

# message struct to reuse when sending/receiving
has _zmq_msg_t => (
    is        => 'ro',
    lazy      => 1,
    builder   => '_build_zmq_msg_t',
);

# used to make sure we handle fork situations correctly
has _pid => (
    is      => 'ro',
    default => sub { $$ },
);

has sockopt_sizes => (
    is      => 'ro',
    lazy    => 1,
    builder => '_build_sockopt_sizes'
);

sub _build_zmq_msg_t {
    my ($self) = @_;

    my $msg_ptr;
    {
        no strict q/refs/;
        my $class = ref $self;
        $msg_ptr = malloc(zmq_msg_t_size);
        &{"$class\::zmq_msg_init"}($msg_ptr);
    }

    return $msg_ptr;
}

sub _build_sockopt_sizes {
    my $ffi = FFI::Platypus->new();

    return {
        int    => $ffi->sizeof('int'),
        sint64 => $ffi->sizeof('sint64'),
        uint64 => $ffi->sizeof('uint64'),
    };
}

requires qw(
    connect
    disconnect
    bind
    unbind
    send
    send_multipart
    recv
    recv_multipart
    get_fd
    get_linger
    set_linger
    get_identity
    set_identity
    subscribe
    unsubscribe
    has_pollin
    has_pollout
    get
    set
    close
);

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

ZMQ::FFI::SocketRole

=head1 VERSION

version 1.07

=head1 AUTHOR

Dylan Cali <calid1984@gmail.com>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by Dylan Cali.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
