From 8a5f5eeb4513e38ebbc8782a2e88e034df97b1fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Tr=C4=85d?= Date: Thu, 28 Dec 2023 19:19:12 +0100 Subject: [PATCH] Fix owned deserialization (#13) --- src/api_key.rs | 48 +++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 39 insertions(+), 9 deletions(-) diff --git a/src/api_key.rs b/src/api_key.rs index a1dca7a..02d5576 100644 --- a/src/api_key.rs +++ b/src/api_key.rs @@ -1,3 +1,4 @@ +use std::borrow::Cow; use std::str::FromStr; use base64::Engine; @@ -53,7 +54,7 @@ impl<'de> serde::Deserialize<'de> for ApiKey { where D: serde::Deserializer<'de>, { - <&str>::deserialize(deserializer)? + >::deserialize(deserializer)? .parse() .map_err(serde::de::Error::custom) } @@ -105,16 +106,16 @@ mod tests { use super::*; + fn random_api_key() -> ApiKey { + let mut api_key = [0u8; 32]; + OsRng.fill_bytes(&mut api_key); + + ApiKey::new(uuid::Uuid::new_v4().to_string(), api_key) + } + #[test] fn from_to_str() { - let api_key = ApiKey { - relayer_id: uuid::Uuid::new_v4().to_string(), - api_key: { - let mut api_key = [0u8; 32]; - OsRng.fill_bytes(&mut api_key); - api_key - }, - }; + let api_key = random_api_key(); let api_key_str = api_key.to_string(); @@ -124,4 +125,33 @@ mod tests { assert_eq!(api_key, api_key_parsed); } + + #[test] + fn from_to_serde_json() { + let api_key = random_api_key(); + + let api_key_json = serde_json::to_string(&api_key).unwrap(); + + println!("api_key_str = {api_key_json}"); + + let api_key_parsed: ApiKey = + serde_json::from_str(&api_key_json).unwrap(); + + assert_eq!(api_key, api_key_parsed); + } + + #[test] + fn from_to_serde_json_owned() { + let api_key = random_api_key(); + + let api_key_json: serde_json::Value = + serde_json::to_value(&api_key).unwrap(); + + println!("api_key_str = {api_key_json}"); + + let api_key_parsed: ApiKey = + serde_json::from_value(api_key_json).unwrap(); + + assert_eq!(api_key, api_key_parsed); + } }