Skip to content

Commit 4b6145c

Browse files
authored
perf: Add write_arg_fmt to RedisWrite (redis-rs#348)
Can help avoid allocations when writing redis arguments
1 parent aaecd67 commit 4b6145c

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed

src/cmd.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::io;
1+
use std::{fmt, io};
22

33
use crate::connection::ConnectionLike;
44
use crate::types::{
@@ -243,9 +243,14 @@ fn write_pipeline(rv: &mut Vec<u8>, cmds: &[Cmd], atomic: bool) {
243243

244244
impl RedisWrite for Cmd {
245245
fn write_arg(&mut self, arg: &[u8]) {
246-
let prev = self.data.len();
247-
self.args.push(Arg::Simple(prev + arg.len()));
248246
self.data.extend_from_slice(arg);
247+
self.args.push(Arg::Simple(self.data.len()));
248+
}
249+
250+
fn write_arg_fmt(&mut self, arg: impl fmt::Display) {
251+
use std::io::Write;
252+
write!(self.data, "{}", arg).unwrap();
253+
self.args.push(Arg::Simple(self.data.len()));
249254
}
250255
}
251256

src/geo.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ impl ToRedisArgs for RadiusOptions {
212212

213213
if let Some(n) = self.count {
214214
out.write_arg(b"COUNT");
215-
out.write_arg(format!("{}", n).as_bytes());
215+
out.write_arg_fmt(n);
216216
}
217217

218218
match self.order {

src/types.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -590,12 +590,21 @@ impl InfoDict {
590590
pub trait RedisWrite {
591591
/// Accepts a serialized redis command.
592592
fn write_arg(&mut self, arg: &[u8]);
593+
594+
/// Accepts a serialized redis command.
595+
fn write_arg_fmt(&mut self, arg: impl fmt::Display) {
596+
self.write_arg(&arg.to_string().as_bytes())
597+
}
593598
}
594599

595600
impl RedisWrite for Vec<Vec<u8>> {
596601
fn write_arg(&mut self, arg: &[u8]) {
597602
self.push(arg.to_owned());
598603
}
604+
605+
fn write_arg_fmt(&mut self, arg: impl fmt::Display) {
606+
self.push(arg.to_string().into_bytes())
607+
}
599608
}
600609

601610
/// Used to convert a value into one or multiple redis argument

0 commit comments

Comments
 (0)