Skip to content

Commit

Permalink
Fix 'Limits' deserialization.
Browse files Browse the repository at this point in the history
Fixes rwf2#2268.
  • Loading branch information
kvinwang authored and SergioBenitez committed Aug 1, 2022
1 parent b7c03ce commit f7e703b
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
15 changes: 13 additions & 2 deletions core/lib/src/data/limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Vec<(Uncased<'static>, 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 {
Expand Down
31 changes: 31 additions & 0 deletions core/lib/tests/deserialize-limits-issue-2268.rs
Original file line number Diff line number Diff line change
@@ -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()));
}

0 comments on commit f7e703b

Please sign in to comment.