Impl '(De)Serialize' for 'contrib::Uuid'.

Resolves #1370.
This commit is contained in:
meltinglava 2020-07-22 14:47:24 +02:00 committed by Sergio Benitez
parent 5ed3c13240
commit 165f4f59b3
2 changed files with 27 additions and 5 deletions

View File

@ -30,6 +30,7 @@ serve = []
compression = ["brotli_compression", "gzip_compression"]
brotli_compression = ["brotli"]
gzip_compression = ["flate2"]
uuid = ["serde", "_uuid"]
# The barage of user-facing database features.
diesel_sqlite_pool = ["databases", "diesel/sqlite", "diesel/r2d2"]
@ -59,9 +60,6 @@ tera = { version = "1.0.2", optional = true }
notify = { version = "4.0.6", optional = true }
normpath = { version = "0.2", optional = true }
# UUID dependencies.
uuid = { version = ">=0.7.0, <0.9.0", optional = true }
# Database dependencies
diesel = { version = "1.0", default-features = false, optional = true }
postgres = { version = "0.19", optional = true }
@ -81,5 +79,14 @@ time = { version = "0.2.9", optional = true }
brotli = { version = "3.3", optional = true }
flate2 = { version = "1.0", optional = true }
[dependencies._uuid]
package = "uuid"
version = ">=0.7.0, <0.9.0"
optional = true
features = ["serde"]
[dev-dependencies]
serde_test = "1.0.114"
[package.metadata.docs.rs]
all-features = true

View File

@ -14,12 +14,14 @@
//! features = ["uuid"]
//! ```
pub extern crate uuid as uuid_crate;
pub extern crate _uuid as uuid_crate;
use std::fmt;
use std::str::FromStr;
use std::ops::Deref;
use serde::{Deserialize, Serialize};
use rocket::request::FromParam;
use rocket::form::{self, FromFormField, ValueField};
@ -63,7 +65,8 @@ type ParseError = <self::uuid_crate::Uuid as FromStr>::Err;
/// fn user(id: Uuid) -> String {
/// format!("User ID: {}", id)
/// }
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Uuid(uuid_crate::Uuid);
impl Uuid {
@ -183,4 +186,16 @@ mod test {
let uuid_str = "c1aa1e3b-9614-4895-9ebd-705255fa5bc2p";
Uuid::from_param(uuid_str.into()).unwrap();
}
#[test]
fn test_ser_de() {
// The main reason for this test is to test that UUID only serializes as
// a string token, not anything else. Like a Struct with a named field...
use serde_test::{Token, assert_tokens, Configure};
let uuid: Uuid = "c1aa1e3b-9614-4895-9ebd-705255fa5bc2".parse().unwrap();
assert_tokens(&uuid.readable(), &[
Token::Str("c1aa1e3b-9614-4895-9ebd-705255fa5bc2"),
]);
}
}