trs_dataframe/dataframe/
key.rs

1//use flexstr::SharedStr as SharedString;
2#[cfg(feature = "python")]
3use pyo3::prelude::*;
4#[cfg(feature = "utoipa")]
5use utoipa::ToSchema;
6
7use smartstring::alias::String as SString;
8
9use crate::DataType;
10
11/// [`Key`] holds information about key. It's used to identify the feature
12/// Mostly is represented as a string but inside is stored as a hash and the [`DataType`]
13/// of the feature/value which is stored in [`crate::DataFrame`]
14#[derive(Clone, Eq, serde::Deserialize, serde::Serialize, Default)]
15#[cfg_attr(feature = "python", pyo3::pyclass)]
16#[cfg_attr(feature = "utoipa", derive(ToSchema))]
17pub struct Key {
18    pub key: u32,
19    #[cfg_attr(feature = "utoipa", schema(schema_with = smart_string_schema))]
20    pub name: SString,
21    pub ctype: DataType,
22}
23
24#[cfg(feature = "utoipa")]
25fn smart_string_schema() -> utoipa::openapi::Object {
26    utoipa::openapi::ObjectBuilder::new()
27        .schema_type(utoipa::openapi::schema::Type::String)
28        .build()
29}
30
31impl Key {
32    pub fn name(&self) -> &str {
33        self.name.as_str()
34    }
35
36    pub fn id(&self) -> u32 {
37        self.key
38    }
39    pub fn key(&self) -> crate::Key {
40        self.clone()
41    }
42}
43impl PartialEq for Key {
44    fn eq(&self, other: &Self) -> bool {
45        self.key == other.key
46    }
47}
48impl PartialOrd for Key {
49    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
50        Some(self.key.cmp(&other.key))
51    }
52}
53impl Ord for Key {
54    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
55        self.key.cmp(&other.key)
56    }
57}
58
59#[cfg(feature = "python")]
60#[pymethods]
61impl Key {
62    #[new]
63    #[pyo3(signature = (name, ctype=None))]
64    pub fn init(name: String, ctype: Option<DataType>) -> Self {
65        Self::new(name.as_str(), ctype.unwrap_or(DataType::Unknown))
66    }
67
68    #[pyo3(name = "name")]
69    pub fn py_name(&self) -> &str {
70        self.name()
71    }
72
73    #[pyo3(name = "id")]
74    pub fn py_id(&self) -> u32 {
75        self.key
76    }
77}
78
79impl std::fmt::Display for Key {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        write!(f, "{}", self.name)
82    }
83}
84impl std::fmt::Debug for Key {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        write!(f, "{self}")
87    }
88}
89
90impl From<&str> for Key {
91    fn from(name: &str) -> Self {
92        Self {
93            key: crate::utils::fnv1a_hash_str_32(name),
94            name: name.into(),
95            ctype: DataType::Unknown,
96        }
97    }
98}
99impl From<SString> for Key {
100    fn from(name: SString) -> Self {
101        Self::from(name.as_str())
102    }
103}
104impl From<String> for Key {
105    fn from(name: String) -> Self {
106        Self::from(name.as_str())
107    }
108}
109
110impl From<&String> for Key {
111    fn from(name: &String) -> Self {
112        Self::from(name.as_str())
113    }
114}
115
116impl Key {
117    pub fn new(name: &str, ctype: DataType) -> Self {
118        Self {
119            key: crate::utils::fnv1a_hash_str_32(name),
120            name: name.into(),
121            ctype,
122        }
123    }
124}
125
126impl std::hash::Hash for Key {
127    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
128        state.write_u32(self.key);
129    }
130}
131
132#[cfg(test)]
133mod test {
134    use super::*;
135    #[test]
136    fn dummy_test() {
137        let key = Key::from("test");
138        assert_eq!(key.key, 2949673445);
139        assert_eq!(key.id(), 2949673445);
140        assert_eq!(key.key(), key);
141        assert_eq!(key.name, "test");
142        let s = String::from("test");
143        let key1 = Key::from(s);
144        assert_eq!(key1.key, 2949673445);
145        assert_eq!(key1.name, "test");
146        assert_eq!(key1, key);
147        assert!(key1.cmp(&key) == std::cmp::Ordering::Equal);
148        let s = SString::from("test");
149        let key = Key::from(s);
150        assert_eq!(key.key, 2949673445);
151        assert_eq!(key.name, "test");
152        let key = Key::new("test", DataType::Unknown);
153        assert_eq!(key.key, 2949673445);
154        assert_eq!(key.name, "test");
155        assert_eq!(key.ctype, DataType::Unknown);
156        assert_eq!(format!("{}", key), "test");
157        let s = format!("{:?}", key);
158        println!("{}", s);
159        let key = Key::from(&("test".to_string()));
160        assert_eq!(key.key, 2949673445);
161        assert_eq!(key.name, "test");
162        let key_serialized = serde_json::to_string(&key).expect("BUG: Cannot serialize");
163        let key_deserialized: Key =
164            serde_json::from_str(&key_serialized).expect("BUG: Cannot deserialize");
165        assert_eq!(key, key_deserialized);
166    }
167
168    #[cfg(feature = "python")]
169    #[test]
170    fn py_test() {
171        let key = Key::init("test".into(), Some(DataType::String));
172        assert_eq!(key.key, 2949673445);
173        assert_eq!(key.name, "test");
174        assert_eq!(key.ctype, DataType::String);
175        assert_eq!(key.py_name(), "test");
176        assert_eq!(key.py_id(), 2949673445);
177    }
178}