loro_ffi/container/
counter.rs

1use std::sync::Arc;
2
3use loro::{ContainerTrait, LoroResult};
4
5use crate::{ContainerID, DiffEvent, LoroDoc, Subscriber, Subscription};
6
7#[derive(Debug, Clone)]
8pub struct LoroCounter {
9    pub(crate) inner: loro::LoroCounter,
10}
11
12impl LoroCounter {
13    pub fn new() -> Self {
14        Self {
15            inner: loro::LoroCounter::new(),
16        }
17    }
18
19    /// Whether the container is attached to a document
20    ///
21    /// The edits on a detached container will not be persisted.
22    /// To attach the container to the document, please insert it into an attached container.
23    pub fn is_attached(&self) -> bool {
24        self.inner.is_attached()
25    }
26
27    /// If a detached container is attached, this method will return its corresponding attached handler.
28    pub fn get_attached(&self) -> Option<Arc<LoroCounter>> {
29        self.inner
30            .get_attached()
31            .map(|x| Arc::new(LoroCounter { inner: x }))
32    }
33
34    /// Return container id of the Counter.
35    pub fn id(&self) -> ContainerID {
36        self.inner.id().into()
37    }
38
39    /// Increment the counter by the given value.
40    pub fn increment(&self, value: f64) -> LoroResult<()> {
41        self.inner.increment(value)
42    }
43
44    /// Decrement the counter by the given value.
45    pub fn decrement(&self, value: f64) -> LoroResult<()> {
46        self.inner.decrement(value)
47    }
48
49    /// Get the current value of the counter.
50    pub fn get_value(&self) -> f64 {
51        self.inner.get_value()
52    }
53
54    pub fn is_deleted(&self) -> bool {
55        self.inner.is_deleted()
56    }
57
58    pub fn doc(&self) -> Option<Arc<LoroDoc>> {
59        self.inner.doc().map(|x| Arc::new(LoroDoc { doc: x }))
60    }
61
62    pub fn subscribe(&self, subscriber: Arc<dyn Subscriber>) -> Option<Arc<Subscription>> {
63        self.inner
64            .subscribe(Arc::new(move |e| {
65                subscriber.on_diff(DiffEvent::from(e));
66            }))
67            .map(|x| Arc::new(x.into()))
68    }
69}
70
71impl Default for LoroCounter {
72    fn default() -> Self {
73        Self::new()
74    }
75}