| 1 | use loro_common::{ContainerID, ID}; |
| 2 | use serde::{Deserialize, Serialize}; |
| 3 | |
| 4 | #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] |
| 5 | pub struct Cursor { |
| 6 | |
| 7 | pub id: Option<ID>, |
| 8 | pub container: ContainerID, |
| 9 | |
| 10 | |
| 11 | |
| 12 | pub side: Side, |
| 13 | |
| 14 | |
| 15 | |
| 16 | pub(crate) origin_pos: usize, |
| 17 | } |
| 18 | |
| 19 | #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] |
| 20 | pub enum Side { |
| 21 | Left = -1, |
| 22 | #[default] |
| 23 | Middle = 0, |
| 24 | Right = 1, |
| 25 | } |
| 26 | |
| 27 | impl Side { |
| 28 | pub fn from_i32(i: i32) -> Option<Self> { |
| 29 | match i { |
| 30 | -1 => Some(Side::Left), |
| 31 | 0 => Some(Side::Middle), |
| 32 | 1 => Some(Side::Right), |
| 33 | _ => None, |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | pub fn to_i32(&self) -> i32 { |
| 38 | *self as i32 |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 43 | pub struct PosQueryResult { |
| 44 | pub update: Option<Cursor>, |
| 45 | pub current: AbsolutePosition, |
| 46 | } |
| 47 | |
| 48 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 49 | pub struct AbsolutePosition { |
| 50 | pub pos: usize, |
| 51 | |
| 52 | pub side: Side, |
| 53 | } |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | #[derive(Debug, Clone, Copy, thiserror::Error)] |
| 61 | #[non_exhaustive] |
| 62 | pub enum CannotFindRelativePosition { |
| 63 | #[error("Cannot find relative position. The container is deleted.")] |
| 64 | ContainerDeleted, |
| 65 | #[error("Cannot find relative position. It may be that the given id is deleted and the relative history is cleared.")] |
| 66 | HistoryCleared, |
| 67 | #[error("Cannot find relative position. The id is not found.")] |
| 68 | IdNotFound, |
| 69 | |
| 70 | #[error("Cannot find relative position because the document history cannot be read.")] |
| 71 | HistoryUnreadable, |
| 72 | } |
| 73 | |
| 74 | impl Cursor { |
| 75 | pub fn new(id: Option<ID>, container: ContainerID, side: Side, origin_pos: usize) -> Self { |
| 76 | Self { |
| 77 | id, |
| 78 | container, |
| 79 | side, |
| 80 | origin_pos, |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | pub fn encode(&self) -> Vec<u8> { |
| 85 | postcard::to_allocvec(self).unwrap() |
| 86 | } |
| 87 | |
| 88 | |
| 89 | pub fn decode(data: &[u8]) -> Result<Self, postcard::Error> { |
| 90 | let cursor: Self = postcard::from_bytes(data)?; |
| 91 | if cursor.id.is_some_and(|id| id.counter < 0) { |
| 92 | return Err(postcard::Error::DeserializeBadEncoding); |
| 93 | } |
| 94 | Ok(cursor) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 99 | pub enum PosType { |
| 100 | |
| 101 | Bytes, |
| 102 | |
| 103 | Unicode, |
| 104 | |
| 105 | Utf16, |
| 106 | |
| 107 | |
| 108 | Event, |
| 109 | |
| 110 | Entity, |
| 111 | } |