Skip to content

Commit

Permalink
Merge pull request #376 from Kuadrant/btrees
Browse files Browse the repository at this point in the history
🔥 all HashMap usages where we want actual ordering
  • Loading branch information
alexsnaps authored Oct 2, 2024
2 parents b6e5c7a + 004fe2c commit 9cb6336
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 17 deletions.
4 changes: 2 additions & 2 deletions limitador-server/src/http_api/request_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use limitador::counter::Counter as LimitadorCounter;
use limitador::limit::Limit as LimitadorLimit;
use paperclip::actix::Apiv2Schema;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};

// We need to define the Limit and Counter types. They're basically the same as
// defined in the lib but with some modifications to be able to derive
Expand Down Expand Up @@ -73,7 +73,7 @@ impl From<Limit> for LimitadorLimit {
#[derive(Debug, Eq, PartialEq, Serialize, Apiv2Schema)]
pub struct Counter {
limit: Limit,
set_variables: HashMap<String, String>,
set_variables: BTreeMap<String, String>,
remaining: Option<u64>,
expires_in_seconds: Option<u64>,
}
Expand Down
19 changes: 4 additions & 15 deletions limitador/src/counter.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::limit::{Limit, Namespace};
use serde::{Deserialize, Serialize, Serializer};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::hash::{Hash, Hasher};
use std::sync::Arc;
Expand All @@ -9,23 +9,12 @@ use std::time::Duration;
pub struct Counter {
limit: Arc<Limit>,

// Need to sort to generate the same object when using the JSON as a key or
// value in Redis.
#[serde(serialize_with = "ordered_map")]
set_variables: HashMap<String, String>,
set_variables: BTreeMap<String, String>,

remaining: Option<u64>,
expires_in: Option<Duration>,
}

fn ordered_map<S>(value: &HashMap<String, String>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let ordered: BTreeMap<_, _> = value.iter().collect();
ordered.serialize(serializer)
}

impl Counter {
pub fn new<L: Into<Arc<Limit>>>(limit: L, set_variables: HashMap<String, String>) -> Self {
// TODO: check that all the variables defined in the limit are set.
Expand All @@ -36,7 +25,7 @@ impl Counter {

Self {
limit,
set_variables: vars,
set_variables: vars.into_iter().collect(),
remaining: None,
expires_in: None,
}
Expand Down Expand Up @@ -80,7 +69,7 @@ impl Counter {
self.limit.namespace()
}

pub fn set_variables(&self) -> &HashMap<String, String> {
pub fn set_variables(&self) -> &BTreeMap<String, String> {
&self.set_variables
}

Expand Down

0 comments on commit 9cb6336

Please sign in to comment.