helix_db/protocol/
remapping.rs

1use super::return_values::ReturnValue;
2use sonic_rs::{Deserialize, Serialize};
3use std::{
4    cell::{RefCell, RefMut},
5    collections::HashMap,
6};
7
8#[derive(Deserialize, Debug, Clone)]
9pub struct Remapping {
10    pub exclude: bool,
11    pub new_name: Option<String>,
12    pub return_value: ReturnValue,
13}
14
15impl Serialize for Remapping {
16    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
17    where
18        S: serde::ser::Serializer,
19    {
20        self.return_value.serialize(serializer)
21    }
22}
23
24impl Remapping {
25    pub fn new(exclude: bool, new_name: Option<String>, return_value: Option<ReturnValue>) -> Self {
26        assert!(
27            !exclude || (!new_name.is_some() || !return_value.is_some()),
28            "Cannot have both exclude and new_name set"
29        );
30        Self {
31            exclude,
32            new_name,
33            return_value: return_value.unwrap_or_default(),
34        }
35    }
36}
37
38#[derive(Deserialize, Debug, Clone)]
39pub struct ResponseRemapping {
40    pub remappings: HashMap<String, Remapping>,
41    pub should_spread: bool,
42}
43
44impl Serialize for ResponseRemapping {
45    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
46    where
47        S: serde::ser::Serializer,
48    {
49        self.remappings.serialize(serializer)
50    }
51}
52
53impl ResponseRemapping {
54    pub fn new(remappings: HashMap<String, Remapping>, should_spread: bool) -> Self {
55        Self {
56            remappings,
57            should_spread,
58        }
59    }
60
61    pub fn insert(&mut self, key: String, remapping: Remapping) {
62        self.remappings.insert(key, remapping);
63    }
64}
65
66pub struct RemappingMap {
67    pub remappings: RefCell<HashMap<u128, ResponseRemapping>>,
68}
69
70impl RemappingMap {
71    pub fn new() -> Self {
72        Self {
73            remappings: RefCell::new(HashMap::new()),
74        }
75    }
76
77    #[inline(always)]
78    pub fn insert(&self, key: u128, remapping: ResponseRemapping) {
79        let remapping = match self.remappings.borrow_mut().remove(&key) {
80            Some(mut old_remapping) => {
81                old_remapping.remappings.extend(remapping.remappings);
82                old_remapping
83            }
84            None => remapping,
85        };
86        self.remappings.borrow_mut().insert(key, remapping);
87    }
88
89    #[inline(always)]
90    pub fn borrow_mut(&self) -> RefMut<HashMap<u128, ResponseRemapping>> {
91        self.remappings.borrow_mut()
92    }
93}