Skip to content

Commit

Permalink
Add serde traits to Auth
Browse files Browse the repository at this point in the history
  • Loading branch information
RCasatta committed Jun 16, 2021
1 parent 27dd8be commit f8e96ee
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 1 deletion.
71 changes: 71 additions & 0 deletions client/src/client.rs
Expand Up @@ -194,6 +194,68 @@ pub enum Auth {
CookieFile(PathBuf),
}

/// [AuthNew] is used to serialize [Auth] in a more comprensible way, once a breaking release is
/// made it could replace [Auth], removing `From` and custom serialization implementation
#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum AuthNew {
None,
UserPass {
username: String,
password: String,
},
CookieFile(PathBuf),
}

impl From<Auth> for AuthNew {
fn from(auth: Auth) -> Self {
match auth {
Auth::None => AuthNew::None,
Auth::UserPass(username, password) => AuthNew::UserPass {
username,
password,
},
Auth::CookieFile(file) => AuthNew::CookieFile(file),
}
}
}

impl From<AuthNew> for Auth {
fn from(auth_new: AuthNew) -> Self {
match auth_new {
AuthNew::None => Auth::None,
AuthNew::UserPass {
username,
password,
} => Auth::UserPass(username, password),
AuthNew::CookieFile(file) => Auth::CookieFile(file),
}
}
}

impl serde::Serialize for Auth {
fn serialize<S>(
&self,
serializer: S,
) -> std::result::Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>
where
S: serde::Serializer,
{
AuthNew::from(self.clone()).serialize(serializer)
}
}

impl<'de> serde::Deserialize<'de> for Auth {
fn deserialize<D>(
deserializer: D,
) -> std::result::Result<Self, <D as serde::Deserializer<'de>>::Error>
where
D: serde::Deserializer<'de>,
{
Ok(AuthNew::deserialize(deserializer)?.into())
}
}

impl Auth {
/// Convert into the arguments that jsonrpc::Client needs.
fn get_user_pass(self) -> Result<(Option<String>, Option<String>)> {
Expand Down Expand Up @@ -1233,4 +1295,13 @@ mod tests {
fn test_handle_defaults() {
test_handle_defaults_inner().unwrap();
}

#[test]
fn test_serde_auth() {
let auth = Auth::UserPass("mario".to_string(), "1234".to_string());
let ser = serde_json::to_string(&auth).unwrap();
assert_eq!("{\"user_pass\":{\"username\":\"mario\",\"password\":\"1234\"}}", ser);
let des: Auth = serde_json::from_str(&ser).unwrap();
assert_eq!(auth, des);
}
}
2 changes: 1 addition & 1 deletion json/src/lib.rs
Expand Up @@ -835,7 +835,7 @@ impl<'a> serde::Serialize for ImportMultiRequestScriptPubkey<'a> {
#[derive(Serialize)]
struct Tmp<'a> {
pub address: &'a Address,
};
}
serde::Serialize::serialize(
&Tmp {
address: addr,
Expand Down

0 comments on commit f8e96ee

Please sign in to comment.