Skip to content

Commit

Permalink
Auto-implement ConnectionLike for Deref + DerefMut
Browse files Browse the repository at this point in the history
This provides an implementation of `ConnectionLike` for any type that
can be mutably and immutably dereferenced to an implementation of
`ConnectionLike` through `Deref` and `DerefMut`. The primary motivation
is being able to use `r2d2::PoolConnection`s directly to satisfy
`ConnectionLike`, which makes code using pooled connections easier
to read. A blanket impl for `r2d2::PoolConnection` would suffice but
this is more generalised as not to be r2d2 specific.
  • Loading branch information
holmesmr committed Dec 16, 2021
1 parent d4dfd43 commit 3f2b63b
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/connection.rs
@@ -1,6 +1,7 @@
use std::fmt;
use std::io::{self, Write};
use std::net::{self, TcpStream, ToSocketAddrs};
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;
use std::str::{from_utf8, FromStr};
use std::time::Duration;
Expand Down Expand Up @@ -886,6 +887,45 @@ impl ConnectionLike for Connection {
}
}

impl<C, T> ConnectionLike for T
where
C: ConnectionLike,
T: Deref<Target = C> + DerefMut<Target = C>,
{
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value> {
self.deref_mut().req_packed_command(cmd)
}

fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>> {
self.deref_mut().req_packed_commands(cmd, offset, count)
}

fn req_command(&mut self, cmd: &Cmd) -> RedisResult<Value> {
self.deref_mut().req_command(cmd)
}

fn get_db(&self) -> i64 {
self.deref().get_db()
}

fn supports_pipelining(&self) -> bool {
self.deref().supports_pipelining()
}

fn check_connection(&mut self) -> bool {
self.deref_mut().check_connection()
}

fn is_open(&self) -> bool {
self.deref().is_open()
}
}

/// The pubsub object provides convenient access to the redis pubsub
/// system. Once created you can subscribe and unsubscribe from channels
/// and listen in on messages.
Expand Down

0 comments on commit 3f2b63b

Please sign in to comment.