util.rs 1.8 KB

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