util.rs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. use crate::client_folder::AtomicNodeTree;
  2. use crate::errors::SyncResult;
  3. use lib_ot::core::{AttributeHashMap, AttributeValue, Changeset, NodeId, NodeOperation};
  4. use std::sync::Arc;
  5. pub fn get_attributes_str_value(
  6. tree: Arc<AtomicNodeTree>,
  7. node_id: &NodeId,
  8. key: &str,
  9. ) -> Option<String> {
  10. tree
  11. .read()
  12. .get_node(*node_id)
  13. .and_then(|node| node.attributes.get(key).cloned())
  14. .and_then(|value| value.str_value())
  15. }
  16. pub fn set_attributes_str_value(
  17. tree: Arc<AtomicNodeTree>,
  18. node_id: &NodeId,
  19. key: &str,
  20. value: String,
  21. ) -> SyncResult<()> {
  22. let old_attributes = match get_attributes(tree.clone(), node_id) {
  23. None => AttributeHashMap::new(),
  24. Some(attributes) => attributes,
  25. };
  26. let mut new_attributes = old_attributes.clone();
  27. new_attributes.insert(key, value);
  28. let path = tree.read().path_from_node_id(*node_id);
  29. let update_operation = NodeOperation::Update {
  30. path,
  31. changeset: Changeset::Attributes {
  32. new: new_attributes,
  33. old: old_attributes,
  34. },
  35. };
  36. tree.write().apply_op(update_operation)?;
  37. Ok(())
  38. }
  39. #[allow(dead_code)]
  40. pub fn get_attributes_int_value(
  41. tree: Arc<AtomicNodeTree>,
  42. node_id: &NodeId,
  43. key: &str,
  44. ) -> Option<i64> {
  45. tree
  46. .read()
  47. .get_node(*node_id)
  48. .and_then(|node| node.attributes.get(key).cloned())
  49. .and_then(|value| value.int_value())
  50. }
  51. pub fn get_attributes(tree: Arc<AtomicNodeTree>, node_id: &NodeId) -> Option<AttributeHashMap> {
  52. tree
  53. .read()
  54. .get_node(*node_id)
  55. .map(|node| node.attributes.clone())
  56. }
  57. #[allow(dead_code)]
  58. pub fn get_attributes_value(
  59. tree: Arc<AtomicNodeTree>,
  60. node_id: &NodeId,
  61. key: &str,
  62. ) -> Option<AttributeValue> {
  63. tree
  64. .read()
  65. .get_node(*node_id)
  66. .and_then(|node| node.attributes.get(key).cloned())
  67. }