Skip to content

Commit

Permalink
feat: impl redis-derive
Browse files Browse the repository at this point in the history
  • Loading branch information
keroro520 committed Jan 12, 2025
1 parent ddba6b0 commit d608e1f
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
12 changes: 12 additions & 0 deletions redis-derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "raiko-redis-derive"
version = "0.1.0"
edition = "2021"

[lib]
proc-macro = true

[dependencies]
proc-macro2 = "1.0"
quote = "1.0"
syn = "1.0"
37 changes: 37 additions & 0 deletions redis-derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(RedisValue)]
pub fn redis_value_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;

let expanded = quote! {
impl redis::ToRedisArgs for #name {
fn write_redis_args<W>(&self, out: &mut W)
where
W: ?Sized + redis::RedisWrite,
{
let serialized = serde_json::to_string(self)
.expect(&format!("Failed to serialize {}", stringify!(#name)));
out.write_arg(serialized.as_bytes());
}
}

impl redis::FromRedisValue for #name {
fn from_redis_value(v: &redis::Value) -> redis::RedisResult<Self> {
let serialized = String::from_redis_value(v)?;
serde_json::from_str(&serialized).map_err(|e| {
redis::RedisError::from((
redis::ErrorKind::TypeError,
"Deserialization failed",
e.to_string(),
))
})
}
}
};

TokenStream::from(expanded)
}

0 comments on commit d608e1f

Please sign in to comment.