Move QUIT command out of the common case
[perl-Redis.git] / lib / Redis.pm
index 3be91ff..ca065b9 100644 (file)
@@ -60,6 +60,8 @@ sub new {
 # we don't want DESTROY to fallback into AUTOLOAD
 sub DESTROY {}
 
+
+### Deal with common, general case, Redis commands
 our $AUTOLOAD;
 sub AUTOLOAD {
        my $self = shift;
@@ -69,22 +71,8 @@ sub AUTOLOAD {
 
        my $command = $AUTOLOAD;
        $command =~ s/.*://;
-       warn "[SEND] $command ",Dumper([@_]) if $deb;
-
-       my $n_elems = scalar(@_)+1;
-       my $send = "\*$n_elems\r\n";
-       for my $str (uc($command), @_) {
-         my $bin = $enc? encode($enc, $str) : $str;
-         $send .= defined($bin)? '$'.length($bin)."\r\n$bin\r\n" : "\$-1\r\n";
-       }
 
-       warn "[SEND RAW] $send" if $deb;
-       print $sock $send;
-
-       if ( $command eq 'quit' ) {
-               close( $sock ) || confess("Can't close socket: $!");
-               return 1;
-       }
+       $self->__send_command($command, @_);
 
        my $result = <$sock> || confess("Can't read socket: $!");
        my $type = substr($result,0,1);
@@ -123,6 +111,50 @@ sub AUTOLOAD {
        }
 }
 
+
+### Commands with extra logic
+
+sub quit {
+  my ($self) = @_;
+
+  $self->__send_command('QUIT');
+
+  close(delete $self->{sock}) || confess("Can't close socket: $!");
+  return 1;
+}
+
+
+### Socket operations
+
+sub __send_command {
+  my $self = shift;
+  my $cmd  = uc(shift);
+  my $enc  = $self->{encoding};
+  my $deb  = $self->{debug};
+
+  warn "[SEND] $cmd ", Dumper([@_]) if $deb;
+
+  ## Encode command using multi-bulk format
+  my $n_elems = scalar(@_) + 1;
+  my $buf     = "\*$n_elems\r\n";
+  for my $elem ($cmd, @_) {
+    my $bin = $enc ? encode($enc, $elem) : $elem;
+    $buf .= defined($bin) ? '$' . length($bin) . "\r\n$bin\r\n" : "\$-1\r\n";
+  }
+
+  ## Send command, take care for partial writes
+  warn "[SEND RAW] $buf" if $deb;
+  my $sock = $self->{sock} || confess("Not connected to any server");
+  while ($buf) {
+    my $len = syswrite $sock, $buf, length $buf;
+    confess("Could not write to Redis server: $!")
+      unless $len;
+    substr $buf, 0, $len, "";
+  }
+
+  return;
+}
+
 sub __read_bulk {
        my ($self,$len) = @_;
        return if $len < 0;