fix: im dumb forgot to actually add api folder

also im lazy and dont want to redo last 2 commits because i wrote a ton
into last one :(
This commit is contained in:
əlemi 2023-09-10 03:03:49 +02:00
parent 5277eceb01
commit 56dcf99778
3 changed files with 276 additions and 0 deletions

89
src/api/controller.rs Normal file
View file

@ -0,0 +1,89 @@
//! # Controller
//!
//! this generic trait is implemented by actors managing stream procedures.
//! events can be enqueued for dispatching without blocking ([Controller::send]), and an async blocking
//! api ([Controller::recv]) is provided to wait for server events. Additional sync blocking
//! ([Controller::blocking_recv]) and callback-based ([Controller::callback]) are implemented.
use crate::Result;
use std::sync::Arc;
use tokio::runtime::Runtime;
#[tonic::async_trait]
pub(crate) trait ControllerWorker<T : Sized + Send + Sync> {
type Controller : Controller<T>;
type Tx;
type Rx;
fn subscribe(&self) -> Self::Controller;
async fn work(self, tx: Self::Tx, rx: Self::Rx);
}
/// async and threadsafe handle to a generic bidirectional stream
#[tonic::async_trait]
pub trait Controller<T : Sized + Send + Sync> : Sized + Send + Sync {
/// type of upstream values, used in [Self::send]
type Input;
/// enqueue a new value to be sent
fn send(&self, x: Self::Input) -> Result<()>;
/// get next value from stream, blocking until one is available
///
/// this is just an async trait function wrapped by `async_trait`:
///
/// `async fn recv(&self) -> codemp::Result<T>;`
async fn recv(&self) -> Result<T> {
if let Some(x) = self.try_recv()? {
return Ok(x); // short circuit if already available
}
self.poll().await?;
Ok(self.try_recv()?.expect("no message available after polling"))
}
/// block until next value is added to the stream without removing any element
///
/// this is just an async trait function wrapped by `async_trait`:
///
/// `async fn poll(&self) -> codemp::Result<()>;`
async fn poll(&self) -> Result<()>;
/// attempt to receive a value without blocking, return None if nothing is available
fn try_recv(&self) -> Result<Option<T>>;
/// sync variant of [Self::recv], blocking invoking thread
fn blocking_recv(&self, rt: &Runtime) -> Result<T> {
rt.block_on(self.recv())
}
/// register a callback to be called for each received stream value
///
/// this will spawn a new task on given runtime invoking [Self::recv] in loop and calling given
/// callback for each received value. a stop channel should be provided, and first value sent
/// into it will stop the worker loop.
///
/// note: creating a callback handler will hold an Arc reference to the given controller,
/// preventing it from being dropped (and likely disconnecting). using the stop channel is
/// important for proper cleanup
fn callback<F>(
self: &Arc<Self>,
rt: &tokio::runtime::Runtime,
mut stop: tokio::sync::mpsc::UnboundedReceiver<()>,
mut cb: F
) where
Self : 'static,
F : FnMut(T) + Sync + Send + 'static
{
let _self = self.clone();
rt.spawn(async move {
loop {
tokio::select! {
Ok(data) = _self.recv() => cb(data),
Some(()) = stop.recv() => break,
else => break,
}
}
});
}
}

173
src/api/factory.rs Normal file
View file

@ -0,0 +1,173 @@
//! ### factory
//!
//! a helper trait to produce Operation Sequences, knowing the current
//! state of the buffer
//!
//! ```rust
//! use codemp::buffer::factory::{OperationFactory, SimpleOperationFactory};
//!
//! let mut factory = SimpleOperationFactory::from("");
//! let op = factory.insert("asd", 0);
//! factory.update(op)?;
//! assert_eq!(factory.content(), "asd");
//! # Ok::<(), codemp::ot::OTError>(())
//! ```
//!
//! use [OperationFactory::insert] to add new characters at a specific index
//!
//! ```rust
//! # use codemp::buffer::factory::{OperationFactory, SimpleOperationFactory};
//! # let mut factory = SimpleOperationFactory::from("asd");
//! factory.update(factory.insert(" dsa", 3))?;
//! assert_eq!(factory.content(), "asd dsa");
//! # Ok::<(), codemp::ot::OTError>(())
//! ```
//!
//! use [OperationFactory::delta] to arbitrarily change text at any position
//!
//! ```rust
//! # use codemp::buffer::factory::{OperationFactory, SimpleOperationFactory};
//! # let mut factory = SimpleOperationFactory::from("asd dsa");
//! let op = factory.delta(2, " xxx ", 5).expect("replaced region is equal to origin");
//! factory.update(op)?;
//! assert_eq!(factory.content(), "as xxx sa");
//! # Ok::<(), codemp::ot::OTError>(())
//! ```
//!
//! use [OperationFactory::delete] to remove characters from given index
//!
//! ```rust
//! # use codemp::buffer::factory::{OperationFactory, SimpleOperationFactory};
//! # let mut factory = SimpleOperationFactory::from("as xxx sa");
//! factory.update(factory.delete(2, 5))?;
//! assert_eq!(factory.content(), "assa");
//! # Ok::<(), codemp::ot::OTError>(())
//! ```
//!
//! use [OperationFactory::replace] to completely replace buffer content
//!
//! ```rust
//! # use codemp::buffer::factory::{OperationFactory, SimpleOperationFactory};
//! # let mut factory = SimpleOperationFactory::from("assa");
//! let op = factory.replace("from scratch").expect("replace is equal to origin");
//! factory.update(op)?;
//! assert_eq!(factory.content(), "from scratch");
//! # Ok::<(), codemp::ot::OTError>(())
//! ```
//!
//! use [OperationFactory::cancel] to remove characters at index, but backwards
//!
//! ```rust
//! # use codemp::buffer::factory::{OperationFactory, SimpleOperationFactory};
//! # let mut factory = SimpleOperationFactory::from("from scratch");
//! factory.update(factory.cancel(12, 8))?;
//! assert_eq!(factory.content(), "from");
//! # Ok::<(), codemp::ot::OTError>(())
//! ```
//!
//!
//! This trait provides an implementation for String, but plugin developers
//! should implement their own operation factory interfacing directly with the editor
//! buffer when possible.
use std::ops::Range;
use operational_transform::{OperationSeq, Operation};
use similar::{TextDiff, ChangeTag};
/// calculate leading no-ops in given opseq
pub const fn leading_noop(seq: &[Operation]) -> u64 { count_noop(seq.first()) }
/// calculate tailing no-ops in given opseq
pub const fn tailing_noop(seq: &[Operation]) -> u64 { count_noop(seq.last()) }
const fn count_noop(op: Option<&Operation>) -> u64 {
match op {
None => 0,
Some(Operation::Retain(n)) => *n,
Some(_) => 0,
}
}
/// return the range on which the operation seq is actually applying its changes
pub fn op_effective_range(op: &OperationSeq) -> Range<u64> {
let first = leading_noop(op.ops());
let last = op.base_len() as u64 - tailing_noop(op.ops());
first..last
}
/// a helper trait that any string container can implement, which generates opseqs
pub trait OperationFactory {
/// the current content of the buffer
fn content(&self) -> String;
/// completely replace the buffer with given text
fn replace(&self, txt: &str) -> Option<OperationSeq> {
self.delta(0, txt, self.content().len())
}
/// transform buffer in range [start..end] with given text
fn delta(&self, start: usize, txt: &str, end: usize) -> Option<OperationSeq> {
let mut out = OperationSeq::default();
let content = self.content();
let tail_skip = content.len() - end; // TODO len is number of bytes, not chars
let content_slice = &content[start..end];
if content_slice == txt {
// if slice equals given text, no operation should be taken
return None;
}
out.retain(start as u64);
let diff = TextDiff::from_chars(content_slice, txt);
for change in diff.iter_all_changes() {
match change.tag() {
ChangeTag::Equal => out.retain(1),
ChangeTag::Delete => out.delete(1),
ChangeTag::Insert => out.insert(change.value()),
}
}
out.retain(tail_skip as u64);
Some(out)
}
/// insert given chars at target position
fn insert(&self, txt: &str, pos: u64) -> OperationSeq {
let mut out = OperationSeq::default();
let total = self.content().len() as u64;
out.retain(pos);
out.insert(txt);
out.retain(total - pos);
out
}
/// delete n characters forward at given position
fn delete(&self, pos: u64, count: u64) -> OperationSeq {
let mut out = OperationSeq::default();
let len = self.content().len() as u64;
out.retain(pos);
out.delete(count);
out.retain(len - (pos+count));
out
}
/// delete n characters backwards at given position
fn cancel(&self, pos: u64, count: u64) -> OperationSeq {
let mut out = OperationSeq::default();
let len = self.content().len() as u64;
out.retain(pos - count);
out.delete(count);
out.retain(len - pos);
out
}
}
impl OperationFactory for String {
fn content(&self) -> String {
self.clone()
}
}

14
src/api/mod.rs Normal file
View file

@ -0,0 +1,14 @@
//! # api
//!
//! these traits represent the internal api for the codemp library.
//! more methods and structs are provided but these are the core interfaces to
//! interact with the client.
/// a generic async provider for bidirectional communication
pub mod controller;
/// a helper trait to generate operation sequences
pub mod factory;
pub use controller::Controller;
pub use factory::OperationFactory;