codemp/src/lib/opfactory.rs

66 lines
1.7 KiB
Rust
Raw Normal View History

2023-04-10 01:41:22 +02:00
use operational_transform::{OperationSeq, OTError};
#[derive(Clone)]
pub struct OperationFactory {
content: String,
}
impl OperationFactory {
pub fn new(init: Option<String>) -> Self {
OperationFactory { content: init.unwrap_or(String::new()) }
}
2023-04-11 06:20:40 +02:00
// TODO remove the need for this
pub fn content(&self) -> String {
self.content.clone()
}
2023-04-10 01:41:22 +02:00
pub fn check(&self, txt: &str) -> bool {
self.content == txt
}
pub fn replace(&mut self, txt: &str) -> OperationSeq {
let out = OperationSeq::default();
if self.content == txt {
return out; // nothing to do
}
todo!()
}
pub fn insert(&mut self, txt: &str, pos: u64) -> Result<OperationSeq, OTError> {
let mut out = OperationSeq::default();
2023-04-11 14:24:53 +02:00
let len = self.content.len() as u64;
2023-04-10 01:41:22 +02:00
out.retain(pos);
out.insert(txt);
2023-04-11 14:24:53 +02:00
out.retain(len - pos);
2023-04-11 06:20:40 +02:00
self.content = out.apply(&self.content)?; // TODO does applying mutate the OpSeq itself?
2023-04-10 01:41:22 +02:00
Ok(out)
}
pub fn delete(&mut self, pos: u64, count: u64) -> Result<OperationSeq, OTError> {
let mut out = OperationSeq::default();
2023-04-11 14:24:53 +02:00
let len = self.content.len() as u64;
2023-04-10 01:41:22 +02:00
out.retain(pos - count);
out.delete(count);
2023-04-11 14:24:53 +02:00
out.retain(len - pos);
2023-04-11 06:20:40 +02:00
self.content = out.apply(&self.content)?; // TODO does applying mutate the OpSeq itself?
2023-04-10 01:41:22 +02:00
Ok(out)
}
pub fn cancel(&mut self, pos: u64, count: u64) -> Result<OperationSeq, OTError> {
let mut out = OperationSeq::default();
2023-04-11 14:24:53 +02:00
let len = self.content.len() as u64;
2023-04-10 01:41:22 +02:00
out.retain(pos);
out.delete(count);
2023-04-11 14:24:53 +02:00
out.retain(len - (pos+count));
2023-04-11 06:20:40 +02:00
self.content = out.apply(&self.content)?; // TODO does applying mutate the OpSeq itself?
2023-04-10 01:41:22 +02:00
Ok(out)
}
2023-04-11 06:20:40 +02:00
pub fn process(&mut self, op: OperationSeq) -> Result<String, OTError> {
2023-04-10 01:41:22 +02:00
self.content = op.apply(&self.content)?;
2023-04-11 06:20:40 +02:00
Ok(self.content.clone())
2023-04-10 01:41:22 +02:00
}
}