Struct loro::LoroDoc

source ·
pub struct LoroDoc { /* private fields */ }
Expand description

LoroDoc is the entry for the whole document. When it’s dropped, all the associated [Handler]s will be invalidated.

Implementations§

source§

impl LoroDoc

source

pub fn new() -> Self

Create a new LoroDoc instance.

source

pub fn config(&self) -> &Configure

Get the configureations of the document.

source

pub fn decode_import_blob_meta(bytes: &[u8]) -> LoroResult<ImportBlobMetadata>

Decodes the metadata for an imported blob from the provided bytes.

source

pub fn set_record_timestamp(&self, record: bool)

Set whether to record the timestamp of each change. Default is false.

If enabled, the Unix timestamp will be recorded for each change automatically.

You can set each timestamp manually when commiting a change.

NOTE: Timestamps are forced to be in ascending order. If you commit a new change with a timestamp that is less than the existing one, the largest existing timestamp will be used instead.

source

pub fn set_change_merge_interval(&self, interval: i64)

Set the interval of mergeable changes, in milliseconds.

If two continuous local changes are within the interval, they will be merged into one change. The defualt value is 1000 seconds.

source

pub fn set_fractional_index_jitter(&self, jitter: u8)

Set the jitter of the tree position(Fractional Index).

The jitter is used to avoid conflicts when multiple users are creating the node at the same position. value 0 is default, which means no jitter, any value larger than 0 will enable jitter. Generally speaking, jitter will affect the growth rate of document size.

source

pub fn config_text_style(&self, text_style: StyleConfigMap)

Set the rich text format configuration of the document.

You need to config it if you use rich text mark method. Specifically, you need to config the expand property of each style.

Expand is used to specify the behavior of expanding when new text is inserted at the beginning or end of the style.

source

pub fn attach(&self)

Attach the document state to the latest known version.

The document becomes detached during a checkout operation. Being detached implies that the DocState is not synchronized with the latest version of the OpLog. In a detached state, the document is not editable, and any import operations will be recorded in the OpLog without being applied to the DocState.

source

pub fn checkout(&self, frontiers: &Frontiers) -> LoroResult<()>

Checkout the DocState to a specific version.

The document becomes detached during a checkout operation. Being detached implies that the DocState is not synchronized with the latest version of the OpLog. In a detached state, the document is not editable, and any import operations will be recorded in the OpLog without being applied to the DocState.

You should call attach to attach the DocState to the lastest version of OpLog.

source

pub fn checkout_to_latest(&self)

Checkout the DocState to the latest version.

The document becomes detached during a checkout operation. Being detached implies that the DocState is not synchronized with the latest version of the OpLog. In a detached state, the document is not editable, and any import operations will be recorded in the OpLog without being applied to the DocState.

This has the same effect as attach.

source

pub fn cmp_with_frontiers(&self, other: &Frontiers) -> Ordering

Compare the frontiers with the current OpLog’s version.

If other contains any version that’s not contained in the current OpLog, return Ordering::Less.

source

pub fn cmp_frontiers( &self, a: &Frontiers, b: &Frontiers ) -> Result<Option<Ordering>, FrontiersNotIncluded>

Compare two frontiers.

If the frontiers are not included in the document, return FrontiersNotIncluded.

source

pub fn detach(&mut self)

Force the document enter the detached mode.

In this mode, when you importing new updates, the loro_internal::DocState will not be changed.

Learn more at https://loro.dev/docs/advanced/doc_state_and_oplog#attacheddetached-status

source

pub fn import_batch(&mut self, bytes: &[Vec<u8>]) -> LoroResult<()>

Import a batch of updates/snapshot.

The data can be in arbitrary order. The import result will be the same.

source

pub fn get_movable_list<I: IntoContainerId>(&self, id: I) -> LoroMovableList

Get a LoroMovableList by container id.

If the provided id is string, it will be converted into a root container id with the name of the string.

source

pub fn get_list<I: IntoContainerId>(&self, id: I) -> LoroList

Get a LoroList by container id.

If the provided id is string, it will be converted into a root container id with the name of the string.

source

pub fn get_map<I: IntoContainerId>(&self, id: I) -> LoroMap

Get a LoroMap by container id.

If the provided id is string, it will be converted into a root container id with the name of the string.

source

pub fn get_text<I: IntoContainerId>(&self, id: I) -> LoroText

Get a LoroText by container id.

If the provided id is string, it will be converted into a root container id with the name of the string.

source

pub fn get_tree<I: IntoContainerId>(&self, id: I) -> LoroTree

Get a LoroTree by container id.

If the provided id is string, it will be converted into a root container id with the name of the string.

source

pub fn commit(&self)

Commit the cumulative auto commit transaction.

There is a transaction behind every operation. It will automatically commit when users invoke export or import. The event will be sent after a transaction is committed

source

pub fn commit_with(&self, options: CommitOptions)

Commit the cumulative auto commit transaction with custom configure.

There is a transaction behind every operation. It will automatically commit when users invoke export or import. The event will be sent after a transaction is committed

source

pub fn is_detached(&self) -> bool

Whether the document is in detached mode, where the loro_internal::DocState is not synchronized with the latest version of the loro_internal::OpLog.

source

pub fn import(&self, bytes: &[u8]) -> Result<(), LoroError>

Import updates/snapshot exported by LoroDoc::export_snapshot or LoroDoc::export_from.

source

pub fn import_with(&self, bytes: &[u8], origin: &str) -> Result<(), LoroError>

Import updates/snapshot exported by LoroDoc::export_snapshot or LoroDoc::export_from.

It marks the import with a custom origin string. It can be used to track the import source in the generated events.

source

pub fn export_from(&self, vv: &VersionVector) -> Vec<u8>

Export all the ops not included in the given VersionVector

source

pub fn export_snapshot(&self) -> Vec<u8>

Export the current state and history of the document.

source

pub fn frontiers_to_vv(&self, frontiers: &Frontiers) -> Option<VersionVector>

Convert Frontiers into VersionVector

source

pub fn vv_to_frontiers(&self, vv: &VersionVector) -> Frontiers

Convert VersionVector into Frontiers

source

pub fn with_oplog<R>(&self, f: impl FnOnce(&OpLog) -> R) -> R

Access the OpLog.

source

pub fn oplog_vv(&self) -> VersionVector

Get the VersionVector version of OpLog

source

pub fn state_vv(&self) -> VersionVector

Get the VersionVector version of OpLog

source

pub fn len_ops(&self) -> usize

Get the total number of operations in the OpLog

source

pub fn len_changes(&self) -> usize

Get the total number of changes in the OpLog

source

pub fn get_deep_value(&self) -> LoroValue

Get the current state of the document.

source

pub fn oplog_frontiers(&self) -> Frontiers

Get the Frontiers version of OpLog

source

pub fn state_frontiers(&self) -> Frontiers

Get the Frontiers version of DocState

Learn more about Frontiers

source

pub fn peer_id(&self) -> PeerID

Get the PeerID

source

pub fn set_peer_id(&self, peer: PeerID) -> LoroResult<()>

Change the PeerID

NOTE: You need ot make sure there is no chance two peer have the same PeerID. If it happens, the document will be corrupted.

source

pub fn subscribe( &self, container_id: &ContainerID, callback: Subscriber ) -> SubID

Subscribe the events of a container.

The callback will be invoked when the container is changed. Returns a subscription id that can be used to unsubscribe.

§Example
let doc = LoroDoc::new();
let text = doc.get_text("text");
let ran = Arc::new(AtomicBool::new(false));
let ran2 = ran.clone();
doc.subscribe(
    &text.id(),
    Arc::new(move |event| {
        assert!(event.triggered_by.is_local());
        for event in event.events {
            let delta = event.diff.as_text().unwrap();
            let d = TextDelta::Insert {
                insert: "123".into(),
                attributes: Default::default(),
            };
            assert_eq!(delta, &vec![d]);
            ran2.store(true, std::sync::atomic::Ordering::Relaxed);
        }
    }),
);
text.insert(0, "123").unwrap();
doc.commit();
assert!(ran.load(std::sync::atomic::Ordering::Relaxed));
source

pub fn subscribe_root(&self, callback: Subscriber) -> SubID

Subscribe all the events.

The callback will be invoked when any part of the loro_internal::DocState is changed. Returns a subscription id that can be used to unsubscribe.

source

pub fn unsubscribe(&self, id: SubID)

Remove a subscription.

source

pub fn log_estimate_size(&self)

Estimate the size of the document states in memory.

source

pub fn check_state_correctness_slow(&self)

Check the correctness of the document state by comparing it with the state calculated by applying all the history.

source

pub fn get_by_path(&self, path: &[Index]) -> Option<ValueOrContainer>

Get the handler by the path.

source

pub fn get_by_str_path(&self, path: &str) -> Option<ValueOrContainer>

Get the handler by the string path.

source

pub fn get_cursor_pos( &self, cursor: &Cursor ) -> Result<PosQueryResult, CannotFindRelativePosition>

Get the absolute position of the given cursor.

§Example
let doc = LoroDoc::new();
let text = &doc.get_text("text");
text.insert(0, "01234").unwrap();
let pos = text.get_cursor(5, Default::default()).unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 5);
text.insert(0, "01234").unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 10);
text.delete(0, 10).unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 0);
text.insert(0, "01234").unwrap();
assert_eq!(doc.get_cursor_pos(&pos).unwrap().current.pos, 5);
source

pub fn inner(&self) -> &InnerLoroDoc

Get the inner LoroDoc ref.

Trait Implementations§

source§

impl Debug for LoroDoc

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for LoroDoc

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> ZeroElement for T
where T: Default,