From 3f2b63b278a39142dd2e1b302eba44c2474b2cca Mon Sep 17 00:00:00 2001 From: Michael Holmes Date: Thu, 16 Dec 2021 18:07:30 +0000 Subject: [PATCH] Auto-implement ConnectionLike for Deref + DerefMut 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. --- src/connection.rs | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/connection.rs b/src/connection.rs index b84095454..e99f6324f 100644 --- a/src/connection.rs +++ b/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; @@ -886,6 +887,45 @@ impl ConnectionLike for Connection { } } +impl ConnectionLike for T +where + C: ConnectionLike, + T: Deref + DerefMut, +{ + fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult { + self.deref_mut().req_packed_command(cmd) + } + + fn req_packed_commands( + &mut self, + cmd: &[u8], + offset: usize, + count: usize, + ) -> RedisResult> { + self.deref_mut().req_packed_commands(cmd, offset, count) + } + + fn req_command(&mut self, cmd: &Cmd) -> RedisResult { + 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.