attribute.rs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. use crate::core::{OperationAttributes, OperationTransform};
  2. use crate::errors::OTError;
  3. use serde::{Deserialize, Serialize};
  4. use std::collections::HashMap;
  5. use std::fmt;
  6. use std::fmt::Display;
  7. #[derive(Debug, Clone)]
  8. pub struct AttributeEntry {
  9. pub key: AttributeKey,
  10. pub value: AttributeValue,
  11. }
  12. impl AttributeEntry {
  13. pub fn remove_value(&mut self) {
  14. self.value.ty = None;
  15. self.value.value = None;
  16. }
  17. }
  18. impl std::convert::From<AttributeEntry> for AttributeHashMap {
  19. fn from(entry: AttributeEntry) -> Self {
  20. let mut attributes = AttributeHashMap::new();
  21. attributes.insert_entry(entry);
  22. attributes
  23. }
  24. }
  25. #[derive(Default, Clone, Serialize, Deserialize, Eq, PartialEq, Debug)]
  26. pub struct AttributeHashMap(HashMap<AttributeKey, AttributeValue>);
  27. impl std::ops::Deref for AttributeHashMap {
  28. type Target = HashMap<AttributeKey, AttributeValue>;
  29. fn deref(&self) -> &Self::Target {
  30. &self.0
  31. }
  32. }
  33. impl std::ops::DerefMut for AttributeHashMap {
  34. fn deref_mut(&mut self) -> &mut Self::Target {
  35. &mut self.0
  36. }
  37. }
  38. impl AttributeHashMap {
  39. pub fn new() -> AttributeHashMap {
  40. AttributeHashMap(HashMap::new())
  41. }
  42. pub fn from_value(attribute_map: HashMap<AttributeKey, AttributeValue>) -> Self {
  43. Self(attribute_map)
  44. }
  45. pub fn insert<K: ToString, V: Into<AttributeValue>>(&mut self, key: K, value: V) {
  46. self.0.insert(key.to_string(), value.into());
  47. }
  48. pub fn insert_entry(&mut self, entry: AttributeEntry) {
  49. self.insert(entry.key, entry.value)
  50. }
  51. /// Set the key's value to None
  52. pub fn remove_value<K: AsRef<str>>(&mut self, key: K) {
  53. // if let Some(mut_value) = self.0.get_mut(key.as_ref()) {
  54. // mut_value.value = None;
  55. // }
  56. self.insert(key.as_ref().to_string(), AttributeValue::none());
  57. }
  58. /// Set all key's value to None
  59. pub fn remove_all_value(&mut self) {
  60. self.0.iter_mut().for_each(|(_, v)| {
  61. *v = AttributeValue::none();
  62. })
  63. }
  64. pub fn retain_values(&mut self, retain_keys: &[&str]) {
  65. self.0.iter_mut().for_each(|(k, v)| {
  66. if !retain_keys.contains(&k.as_str()) {
  67. *v = AttributeValue::none();
  68. }
  69. })
  70. }
  71. pub fn remove_key<K: AsRef<str>>(&mut self, key: K) {
  72. self.0.remove(key.as_ref());
  73. }
  74. /// Create a new key/value map by constructing new attributes from the other
  75. /// if it's not None and replace the key/value with self key/value.
  76. pub fn merge(&mut self, other: Option<AttributeHashMap>) {
  77. if other.is_none() {
  78. return;
  79. }
  80. let mut new_attributes = other.unwrap().0;
  81. self.0.iter().for_each(|(k, v)| {
  82. new_attributes.insert(k.clone(), v.clone());
  83. });
  84. self.0 = new_attributes;
  85. }
  86. pub fn is_empty(&self) -> bool {
  87. self.0.is_empty()
  88. }
  89. }
  90. impl Display for AttributeHashMap {
  91. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  92. for (key, value) in self.0.iter() {
  93. let _ = f.write_str(&format!("{:?}:{:?}", key, value))?;
  94. }
  95. Ok(())
  96. }
  97. }
  98. impl OperationAttributes for AttributeHashMap {
  99. fn is_empty(&self) -> bool {
  100. self.is_empty()
  101. }
  102. fn remove(&mut self) {
  103. self.retain(|_, v| v.value.is_some());
  104. }
  105. fn extend(&mut self, other: Self) {
  106. self.0.extend(other.0);
  107. }
  108. }
  109. impl OperationTransform for AttributeHashMap {
  110. fn compose(&self, other: &Self) -> Result<Self, OTError>
  111. where
  112. Self: Sized,
  113. {
  114. let mut attributes = self.clone();
  115. attributes.0.extend(other.clone().0);
  116. Ok(attributes)
  117. }
  118. fn transform(&self, other: &Self) -> Result<(Self, Self), OTError>
  119. where
  120. Self: Sized,
  121. {
  122. let a = self.iter().fold(AttributeHashMap::new(), |mut new_attributes, (k, v)| {
  123. if !other.contains_key(k) {
  124. new_attributes.insert(k.clone(), v.clone());
  125. }
  126. new_attributes
  127. });
  128. let b = other
  129. .iter()
  130. .fold(AttributeHashMap::new(), |mut new_attributes, (k, v)| {
  131. if !self.contains_key(k) {
  132. new_attributes.insert(k.clone(), v.clone());
  133. }
  134. new_attributes
  135. });
  136. Ok((a, b))
  137. }
  138. fn invert(&self, other: &Self) -> Self {
  139. let base_inverted = other.iter().fold(AttributeHashMap::new(), |mut attributes, (k, v)| {
  140. if other.get(k) != self.get(k) && self.contains_key(k) {
  141. attributes.insert(k.clone(), v.clone());
  142. }
  143. attributes
  144. });
  145. self.iter().fold(base_inverted, |mut attributes, (k, _)| {
  146. if other.get(k) != self.get(k) && !other.contains_key(k) {
  147. attributes.remove_value(k);
  148. }
  149. attributes
  150. })
  151. }
  152. }
  153. pub type AttributeKey = String;
  154. #[derive(Eq, PartialEq, Hash, Debug, Clone)]
  155. pub enum ValueType {
  156. IntType = 0,
  157. FloatType = 1,
  158. StrType = 2,
  159. BoolType = 3,
  160. }
  161. #[derive(Debug, Clone, PartialEq, Eq, Hash)]
  162. pub struct AttributeValue {
  163. pub ty: Option<ValueType>,
  164. pub value: Option<String>,
  165. }
  166. impl AttributeValue {
  167. pub fn none() -> Self {
  168. Self { ty: None, value: None }
  169. }
  170. pub fn from_int(val: usize) -> Self {
  171. let value = if val > 0_usize { Some(val.to_string()) } else { None };
  172. Self {
  173. ty: Some(ValueType::IntType),
  174. value,
  175. }
  176. }
  177. pub fn from_float(val: f64) -> Self {
  178. Self {
  179. ty: Some(ValueType::FloatType),
  180. value: Some(val.to_string()),
  181. }
  182. }
  183. pub fn from_bool(val: bool) -> Self {
  184. let value = if val { Some(val.to_string()) } else { None };
  185. Self {
  186. ty: Some(ValueType::BoolType),
  187. value,
  188. }
  189. }
  190. pub fn from_string(s: &str) -> Self {
  191. let value = if s.is_empty() { None } else { Some(s.to_string()) };
  192. Self {
  193. ty: Some(ValueType::StrType),
  194. value,
  195. }
  196. }
  197. pub fn int_value(&self) -> Option<i64> {
  198. let value = self.value.as_ref()?;
  199. Some(value.parse::<i64>().unwrap_or(0))
  200. }
  201. pub fn bool_value(&self) -> Option<bool> {
  202. let value = self.value.as_ref()?;
  203. Some(value.parse::<bool>().unwrap_or(false))
  204. }
  205. pub fn str_value(&self) -> Option<String> {
  206. self.value.clone()
  207. }
  208. pub fn float_value(&self) -> Option<f64> {
  209. let value = self.value.as_ref()?;
  210. Some(value.parse::<f64>().unwrap_or(0.0))
  211. }
  212. }
  213. impl std::convert::From<bool> for AttributeValue {
  214. fn from(value: bool) -> Self {
  215. AttributeValue::from_bool(value)
  216. }
  217. }
  218. impl std::convert::From<usize> for AttributeValue {
  219. fn from(value: usize) -> Self {
  220. AttributeValue::from_int(value)
  221. }
  222. }
  223. impl std::convert::From<&str> for AttributeValue {
  224. fn from(value: &str) -> Self {
  225. AttributeValue::from_string(value)
  226. }
  227. }
  228. impl std::convert::From<String> for AttributeValue {
  229. fn from(value: String) -> Self {
  230. AttributeValue::from_string(&value)
  231. }
  232. }
  233. #[derive(Default)]
  234. pub struct AttributeBuilder {
  235. attributes: AttributeHashMap,
  236. }
  237. impl AttributeBuilder {
  238. pub fn new() -> Self {
  239. Self::default()
  240. }
  241. pub fn insert<K: ToString, V: Into<AttributeValue>>(mut self, key: K, value: V) -> Self {
  242. self.attributes.insert(key, value);
  243. self
  244. }
  245. pub fn insert_entry(mut self, entry: AttributeEntry) -> Self {
  246. self.attributes.insert_entry(entry);
  247. self
  248. }
  249. pub fn delete<K: AsRef<str>>(mut self, key: K) -> Self {
  250. self.attributes.remove_value(key);
  251. self
  252. }
  253. pub fn build(self) -> AttributeHashMap {
  254. self.attributes
  255. }
  256. }