diff --git a/core/lib/src/data/limits.rs b/core/lib/src/data/limits.rs index 5011f4ab..9606304e 100644 --- a/core/lib/src/data/limits.rs +++ b/core/lib/src/data/limits.rs @@ -122,8 +122,9 @@ use crate::http::uncased::Uncased; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct Limits { - #[serde(with = "figment::util::vec_tuple_map")] - limits: Vec<(Uncased<'static>, ByteUnit)> + #[serde(deserialize_with = "Limits::deserialize")] + #[serde(serialize_with = "figment::util::vec_tuple_map::serialize")] + limits: Vec<(Uncased<'static>, ByteUnit)>, } impl Default for Limits { @@ -299,6 +300,16 @@ impl Limits { None } + + /// Deserialize a `Limits` vector from a map. Ensures that the resulting + /// vector is properly sorted for futures lookups via binary search. + fn deserialize<'de, D>(de: D) -> Result, ByteUnit)>, D::Error> + where D: serde::Deserializer<'de> + { + let mut limits = figment::util::vec_tuple_map::deserialize(de)?; + limits.sort(); + Ok(limits) + } } impl fmt::Display for Limits { diff --git a/core/lib/tests/deserialize-limits-issue-2268.rs b/core/lib/tests/deserialize-limits-issue-2268.rs new file mode 100644 index 00000000..ffc1a957 --- /dev/null +++ b/core/lib/tests/deserialize-limits-issue-2268.rs @@ -0,0 +1,31 @@ +use rocket::config::Config; +use rocket::data::Limits; +use rocket::figment::{providers::Serialized, Figment}; +use ubyte::ToByteUnit; + +#[test] +fn deserialize_mixed_case_limits_should_work() { + let figment = Figment::default() + .merge(Serialized::default("key1", 1.kibibytes())) + .merge(Serialized::default("key5", 5.kibibytes())) + .merge(Serialized::default("key3", 3.kibibytes())) + .merge(Serialized::default("Key2", 2.kibibytes())) + .merge(Serialized::default("Key4", 4.kibibytes())) + .merge(Serialized::default("Key6", 6.kibibytes())); + + let limits: Limits = figment.extract().unwrap(); + assert_eq!(limits.get("key1"), Some(1.kibibytes())); + assert_eq!(limits.get("key2"), Some(2.kibibytes())); + assert_eq!(limits.get("key3"), Some(3.kibibytes())); + assert_eq!(limits.get("key4"), Some(4.kibibytes())); + assert_eq!(limits.get("key5"), Some(5.kibibytes())); + assert_eq!(limits.get("key6"), Some(6.kibibytes())); +} + +#[test] +fn deserialize_extra_limits_in_config_should_work() { + let extra_limits = Limits::new().limit("Phactory", 1.kibibytes()); + let figment = Config::figment().merge(("limits", extra_limits)); + let config = Config::from(figment); + assert_eq!(config.limits.get("Phactory"), Some(1.kibibytes())); +}