ot_rs/core/
operation.rs

1/// `op`
2/// 定义了如何将一个字符串转化为另一个字符串的的三种原子操作
3#[derive(Debug, PartialEq, Eq, Clone)]
4pub(super) enum Operation {
5    /// 保持 - 将 base 字符串游标位置后侧的字符串拷贝到 buffer 中,并将 base 字符串游标向右移动相应长度
6    Retain(usize),
7    /// 插入 - 向 buffer 中插入字符串,且 base 字符串的游标保持不变
8    Insert(String),
9    /// 删除 - 移动游标在 base 字符串中,向右移动相应长度,不操作 buffer
10    Delete(usize),
11}
12
13impl ToString for Operation {
14    fn to_string(&self) -> String {
15        match self {
16            &Self::Retain(n) => format!("retain({})", n),
17            Self::Insert(str) => format!("insert(\"{}\")", str.replace('"', "\\\"")),
18            &Self::Delete(n) => format!("delete({})", n),
19        }
20    }
21}
22
23#[cfg(test)]
24mod tests {
25
26    use super::Operation;
27
28    #[test]
29    fn it_works() {
30        assert_eq!("retain(1)", Operation::Retain(1).to_string());
31        assert_eq!(
32            "insert(\"abc\")",
33            Operation::Insert("abc".to_string()).to_string()
34        );
35        assert_eq!(
36            "insert(\"abc\\\"\")",
37            Operation::Insert("abc\"".to_string()).to_string()
38        );
39    }
40}