diff --git a/Cargo.lock b/Cargo.lock index 0fb9d57..40afa3f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1210,6 +1210,8 @@ dependencies = [ "parking_lot 0.8.0", "rust-crypto", "rustc-serialize", + "serde", + "serde_json", "slab 0.2.0", "thiserror", "tokio 1.8.1", diff --git a/proto/Cargo.toml b/proto/Cargo.toml index 4215070..a2ebd1b 100644 --- a/proto/Cargo.toml +++ b/proto/Cargo.toml @@ -18,9 +18,13 @@ mio = "^0.6" parking_lot = "^0.8" rust-crypto = "^0.2.34" rustc-serialize = "^0.3.17" +serde = { version = "1.0", features = ["derive"] } slab = "^0.2" thiserror = "^1.0" tokio = { version = "1", features = ["full"] } tokio-core = "^0.1" tokio-io = "^0.1" tokio-codec = "^0.1" + +[dev-dependencies] +serde_json = "1.0" diff --git a/proto/src/core/user.rs b/proto/src/core/user.rs index 90557c0..26d92e9 100644 --- a/proto/src/core/user.rs +++ b/proto/src/core/user.rs @@ -1,5 +1,7 @@ use std::io; +use serde::{Deserialize, Serialize}; + use crate::core::value::{ ValueDecode, ValueDecodeError, ValueDecoder, ValueEncode, ValueEncodeError, ValueEncoder, @@ -23,6 +25,8 @@ const STATUS_ONLINE: u32 = 3; PartialOrd, RustcDecodable, RustcEncodable, + Serialize, + Deserialize, )] pub enum UserStatus { /// The user if offline. @@ -90,7 +94,16 @@ impl ValueDecode for UserStatus { /// This structure contains the last known information about a fellow user. #[derive( - Clone, Debug, Eq, Ord, PartialEq, PartialOrd, RustcDecodable, RustcEncodable, + Clone, + Debug, + Eq, + Ord, + PartialEq, + PartialOrd, + RustcDecodable, + RustcEncodable, + Serialize, + Deserialize, )] pub struct User { /// The name of the user. @@ -112,3 +125,40 @@ pub struct User { /// The user's country code. pub country: String, } + +#[cfg(test)] +mod tests { + use super::{User, UserStatus}; + + #[test] + fn serialize_user_status() { + assert_eq!( + serde_json::to_string(&UserStatus::Offline).unwrap(), + r#""Offline""# + ); + } + + #[test] + fn serialize_user() { + assert_eq!( + serde_json::to_string(&User { + name: "karandeep".to_string(), + status: UserStatus::Online, + average_speed: 1, + num_downloads: 2, + unknown: 3, + num_files: 4, + num_folders: 5, + num_free_slots: 6, + country: "IN".to_string(), + }) + .unwrap(), + [ + r#"{"name":"karandeep","status":"Online","average_speed":1,"#, + r#""num_downloads":2,"unknown":3,"num_files":4,"num_folders":5,"#, + r#""num_free_slots":6,"country":"IN"}"#, + ] + .join("") + ); + } +}