Fix 'Limits' deserialization.

Fixes #2268.
This commit is contained in:
Kevin Wang 2022-07-18 04:37:20 +00:00 committed by Sergio Benitez
parent b7c03ce2b5
commit f7e703bc5e
2 changed files with 44 additions and 2 deletions

View File

@ -122,8 +122,9 @@ use crate::http::uncased::Uncased;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)] #[serde(transparent)]
pub struct Limits { pub struct Limits {
#[serde(with = "figment::util::vec_tuple_map")] #[serde(deserialize_with = "Limits::deserialize")]
limits: Vec<(Uncased<'static>, ByteUnit)> #[serde(serialize_with = "figment::util::vec_tuple_map::serialize")]
limits: Vec<(Uncased<'static>, ByteUnit)>,
} }
impl Default for Limits { impl Default for Limits {
@ -299,6 +300,16 @@ impl Limits {
None 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 { impl fmt::Display for Limits {

View File

@ -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()));
}