Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/managing_grid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ fn main() {

let mut grid = GridEngine::new(10, 12);

grid.events_mut().add_changes_listener(Box::new(|event| {
grid.events_mut().add_changes_listener(|event| {
println!("Event triggered: {:#?}", event);
}));
});

grid.add_item("a".to_string(), 2, 2, 2, 4).unwrap();
print_grid(&grid);
Expand Down
17 changes: 8 additions & 9 deletions src/grid_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ impl GridEngine {
}

/// Creates a new node with the specified parameters.
fn new_node(&mut self, id: String, x: usize, y: usize, w: usize, h: usize) -> Node {
Node::new(id, x, y, w, h)
fn new_node(&mut self, id: impl Into<String>, x: usize, y: usize, w: usize, h: usize) -> Node {
Node::new(id.into(), x, y, w, h)
}

/// Creates a change operation to add a new node to the grid.
Expand All @@ -216,7 +216,7 @@ impl GridEngine {
.push(Change::Add(AddChangeData { value: node }));
}

/// Get the nodes sorted by id
/// Get the node sorted by id
///
/// # Example
///
Expand All @@ -235,8 +235,8 @@ impl GridEngine {
/// # Ok(())
/// # }
/// ```
pub fn get_nodes(&self) -> Vec<Node> {
let mut cloned: Vec<Node> = self.items.values().cloned().collect();
pub fn get_nodes(&self) -> Vec<&Node> {
let mut cloned: Vec<&Node> = self.items.values().collect();
// Would be better to sort by some created_at
cloned.sort_by_key(|n| n.id.clone());
cloned
Expand Down Expand Up @@ -307,16 +307,15 @@ impl GridEngine {
/// ```
pub fn add_item(
&mut self,
id: String,
id: impl Into<String>,
x: usize,
y: usize,
w: usize,
h: usize,
) -> Result<&Node, GridEngineError> {
let id = id.into();
if self.items.contains_key(&id) {
return Err(GridEngineError::Item(ItemError::ItemAlreadyExists {
id: id.clone(),
}));
return Err(GridEngineError::Item(ItemError::ItemAlreadyExists { id }));
};

let node = self.new_node(id, x, y, w, h);
Expand Down
44 changes: 25 additions & 19 deletions src/grid_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@
//! let mut grid = GridEngine::new(10, 10);
//!
//! // Add a listener to track changes
//! grid.events_mut().add_changes_listener(Box::new(|event| {
//! grid.events_mut().add_changes_listener(|event| {
//! println!("Grid changed: {:?}", event.changes());
//! }));
//! });
//!
//! // Make changes to the grid
//! grid.add_item("box1".to_string(), 0, 0, 2, 2).unwrap();
Expand Down Expand Up @@ -94,8 +94,11 @@ impl ListenerFunction {
///
/// * `id` - Unique identifier for the listener
/// * `function` - The callback function to execute when changes occur
pub fn new(id: String, function: ChangesEventFn) -> Self {
Self { id, function }
pub fn new(id: impl Into<String>, function: ChangesEventFn) -> Self {
Self {
id: id.into(),
function,
}
}
}

Expand Down Expand Up @@ -139,13 +142,16 @@ impl GridEvents {
/// use grid_engine::grid_engine::GridEngine;
///
/// let mut grid = GridEngine::new(10, 10);
/// let listener_id = grid.events_mut().add_changes_listener(Box::new(|event| {
/// let listener_id = grid.events_mut().add_changes_listener(|event| {
/// println!("Changes occurred: {:?}", event.changes());
/// }));
/// });
/// ```
pub fn add_changes_listener(&mut self, function: ChangesEventFn) -> String {
pub fn add_changes_listener(
&mut self,
function: impl Fn(&ChangesEventValue) + Send + 'static + Sync,
) -> String {
let id = uuid::Uuid::new_v4().to_string();
let listener = ListenerFunction::new(id.clone(), function);
let listener = ListenerFunction::new(id.clone(), Box::new(function));

self.changes_listeners.push(listener);
id
Expand All @@ -163,7 +169,7 @@ impl GridEvents {
/// use grid_engine::grid_engine::GridEngine;
///
/// let mut grid = GridEngine::new(10, 10);
/// let listener_id = grid.events_mut().add_changes_listener(Box::new(|_| {}));
/// let listener_id = grid.events_mut().add_changes_listener(|_| {});
/// let removed = grid.events_mut().remove_changes_listener(&listener_id); // Listener removed
///
/// assert!(removed.is_some());
Expand Down Expand Up @@ -206,7 +212,7 @@ mod tests {
#[test]
fn test_add_changes_listener() {
let mut events = GridEvents::default();
let listener_id = events.add_changes_listener(Box::new(|_| {}));
let listener_id = events.add_changes_listener(|_| {});

assert_eq!(events.changes_listeners.len(), 1);
assert!(!listener_id.is_empty());
Expand All @@ -215,7 +221,7 @@ mod tests {
#[test]
fn test_remove_changes_listener() {
let mut events = GridEvents::default();
let listener_id = events.add_changes_listener(Box::new(|_| {}));
let listener_id = events.add_changes_listener(|_| {});

events.remove_changes_listener(&listener_id);
assert_eq!(events.changes_listeners.len(), 0);
Expand All @@ -224,8 +230,8 @@ mod tests {
#[test]
fn test_multiple_listeners() {
let mut events = GridEvents::default();
let _id1 = events.add_changes_listener(Box::new(|_| {}));
let _id2 = events.add_changes_listener(Box::new(|_| {}));
let _id1 = events.add_changes_listener(|_| {});
let _id2 = events.add_changes_listener(|_| {});

assert_eq!(events.changes_listeners.len(), 2);
}
Expand All @@ -236,10 +242,10 @@ mod tests {
let counter = Arc::new(Mutex::new(0));
let counter_clone = counter.clone();

events.add_changes_listener(Box::new(move |_| {
events.add_changes_listener(move |_| {
let mut count = counter_clone.lock().unwrap();
*count += 1;
}));
});

let changes = ChangesEventValue { changes: vec![] };
events.trigger_changes_event(&changes);
Expand All @@ -255,10 +261,10 @@ mod tests {
// Add two listeners that increment the same counter
for _ in 0..2 {
let counter_clone = counter.clone();
events.add_changes_listener(Box::new(move |_| {
events.add_changes_listener(move |_| {
let mut count = counter_clone.lock().unwrap();
*count += 1;
}));
});
}

let changes = ChangesEventValue { changes: vec![] };
Expand All @@ -273,10 +279,10 @@ mod tests {
let received_changes = Arc::new(Mutex::new(Vec::new()));
let received_changes_clone = received_changes.clone();

events.add_changes_listener(Box::new(move |event| {
events.add_changes_listener(move |event| {
let mut changes = received_changes_clone.lock().unwrap();
changes.extend(event.changes.clone());
}));
});

// Create a mock change
let node = crate::node::Node::new("test".to_string(), 0, 0, 1, 1);
Expand Down
4 changes: 2 additions & 2 deletions src/inner_grid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ impl InnerGrid {
self.inner.get(y, x)
}

pub(crate) fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut Option<String>> {
pub fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut Option<String>> {
if self.inner.get(y, x).is_none() {
self.handle_expansion(x, y);
}
Expand All @@ -161,7 +161,7 @@ impl InnerGrid {
///
/// * `Ok(())` - If the update was successful
/// * `Err(InnerGridError)` - If the coordinates are invalid
pub(crate) fn update(
pub fn update(
&mut self,
node: &Node,
x: usize,
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
//!
//! See the `examples` directory for more usage examples.

mod error;
pub mod error;
pub mod grid_engine;
mod grid_events;
mod inner_grid;
Expand Down
20 changes: 13 additions & 7 deletions src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,15 @@ use crate::{
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Node {
/// Unique identifier for the node
pub(crate) id: String,
pub id: String,
/// X coordinate of the top-left corner
pub(crate) x: usize,
pub x: usize,
/// Y coordinate of the top-left corner
pub(crate) y: usize,
pub y: usize,
/// Width of the node in grid cells
pub(crate) w: usize,
pub w: usize,
/// Height of the node in grid cells
pub(crate) h: usize,
pub h: usize,
}

impl Node {
Expand All @@ -63,8 +63,14 @@ impl Node {
/// * `y` - Y coordinate of the top-left corner
/// * `w` - Width in grid cells
/// * `h` - Height in grid cells
pub(crate) fn new(id: String, x: usize, y: usize, w: usize, h: usize) -> Node {
Node { id, x, y, w, h }
pub fn new(id: impl Into<String>, x: usize, y: usize, w: usize, h: usize) -> Node {
Node {
id: id.into(),
x,
y,
w,
h,
}
}

/// Iterates over all cells occupied by this node.
Expand Down
2 changes: 1 addition & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub struct ForCellArgs {
///
/// If the callback returns an error for any cell, iteration stops immediately
/// and the error is propagated to the caller.
pub(crate) fn for_cell(
pub fn for_cell(
args: ForCellArgs,
callback: &mut impl FnMut(usize, usize) -> Result<(), InnerGridError>,
) -> Result<(), InnerGridError> {
Expand Down