package Evo::Io::Handle::Role;
use Evo '-Role *; -Loop *; Symbol gensym';

use Fcntl qw(F_SETFL F_GETFL O_NONBLOCK);

sub _fopt ($flag, $debug, $s, $val = undef) {
  my $flags = fcntl($s, F_GETFL, 0) or die "$debug: $!";
  return !!($flags & $flag) + 0 if @_ == 3;

  $flags = $val ? $flags | $flag : $flags & ~$flag or die "$debug: $!";
  fcntl($s, F_SETFL, $flags) or _die $debug;
  $s;
}

sub io_non_blocking : Role { _fopt(O_NONBLOCK, "nb", @_) }

sub DESTROY($self) : Role {
  return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
  my $fd = fileno $self or return;
  loop_io_remove_fd $fd;
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Evo::Io::Handle::Role

=head1 VERSION

version 0.0209

=head1 AUTHOR

alexbyk.com

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2016 by alexbyk.

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
