From ead5ffc49c849540bae8abda4da41797f89a7ccb Mon Sep 17 00:00:00 2001 From: alemi Date: Mon, 17 Apr 2023 14:57:06 +0200 Subject: [PATCH] chore: struct for storing cursor states --- src/lib/cursor.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/lib/cursor.rs diff --git a/src/lib/cursor.rs b/src/lib/cursor.rs new file mode 100644 index 0000000..c6ed07a --- /dev/null +++ b/src/lib/cursor.rs @@ -0,0 +1,56 @@ +use std::{collections::HashMap, sync::Mutex}; + +use crate::proto::CursorMov; + +/// Note that this differs from any hashmap in its put method: no &mut! +pub trait CursorStorage { + fn get(&self, id: &String) -> Option; + fn put(&self, id: String, val: Cursor); + + fn update(&self, event: CursorMov) -> Option { + let mut cur = self.get(&event.user)?; + cur.buffer = event.path; + cur.start = (event.row, event.col).into(); + self.put(event.user, cur.clone()); + Some(cur) + } +} + +#[derive(Copy, Clone)] +pub struct Position { + row: i64, + col: i64, +} + +impl From::<(i64, i64)> for Position { + fn from((row, col): (i64, i64)) -> Self { + Position { row, col } + } +} + +#[derive(Clone)] +pub struct Cursor { + buffer: String, + start: Position, + end: Position, +} + +pub struct CursorController { + users: Mutex>, +} + +impl CursorController { + pub fn new() -> Self { + CursorController { users: Mutex::new(HashMap::new()) } + } +} + +impl CursorStorage for CursorController { + fn get(&self, id: &String) -> Option { + Some(self.users.lock().unwrap().get(id)?.clone()) + } + + fn put(&self, id: String, val: Cursor) { + self.users.lock().unwrap().insert(id, val); + } +}