+ while (1) {
+ ## Read NN bytes, strip \r\n at the end
+ if (defined $len) {
+ if (length($$rbuf) >= $len + 2) {
+ $data = substr(substr($$rbuf, 0, $len + 2, ''), 0, -2);
+ last;
+ }
+ }
+ ## No len, means line more, read until \r\n
+ elsif ($$rbuf =~ s/^(.)([^\015\012]*)\015\012//) {
+ ($type, $data) = ($1, $2);
+ last;
+ }
+
+ my $bytes = sysread $sock, $$rbuf, $read_size, length $$rbuf;
+ confess("Error while reading from Redis server: $!")
+ unless defined $bytes;
+ confess("Redis server closed connection") unless $bytes;
+ }
+
+ $data = decode($enc, $data) if $enc;
+ warn "[RECV] '$type$data'" if $self->{debug};
+
+ return ($type, $data) if $type;
+ return $data;
+}
+
+sub __can_read_sock {
+ my ($self) = @_;
+ my $sock = $self->{sock};
+ my $rbuf = \($self->{rbuf});
+
+ return 1 if $$rbuf;
+ __fh_nonblocking($sock, 1);
+ my $bytes = sysread $sock, $$rbuf, $self->{read_size}, length $$rbuf;
+ __fh_nonblocking($sock, 0);
+ return 1 if $bytes;
+ return 0;
+}
+
+
+### Copied from AnyEvent::Util
+BEGIN {
+ *__fh_nonblocking = ($^O eq 'MSWin32')
+ ? sub($$) { ioctl $_[0], 0x8004667e, pack "L", $_[1]; } # FIONBIO
+ : sub($$) { fcntl $_[0], F_SETFL, $_[1] ? O_NONBLOCK : 0; };
+}
+
+
+1;
+
+__END__