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
15 changes: 12 additions & 3 deletions .github/workflows/pull_request.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Rust
name: Pull Request

on:
pull_request:
Expand All @@ -8,15 +8,24 @@ env:
CARGO_TERM_COLOR: always

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
- name: Build
run: cargo build --verbose
formatting:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions-rust-lang/setup-rust-toolchain@v1
- name: Install Rust
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
components: rustfmt
- uses: actions-rust-lang/rustfmt@v1
- run: cargo clippy --all-targets --all-features
- run: cargo clippy --all-features --all-targets
tests:
runs-on: ubuntu-latest
steps:
Expand Down
8 changes: 4 additions & 4 deletions examples/managing_grid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fn print_grid(grid: &GridEngine) {
for i in 0..grid.get_inner_grid().cols() {
grid_str_formatted.push_str(&format!(" {} ", i));
}
grid_str_formatted.push_str("\n");
grid_str_formatted.push('\n');

grid.get_inner_grid()
.iter_rows()
Expand All @@ -35,16 +35,16 @@ fn print_grid(grid: &GridEngine) {
if index == 0 {
grid_str_formatted.push_str(&format!("{:0>2}", row_number));
}
return match cell {
match cell {
Some(item) => {
grid_str_formatted.push_str(&format!("[{}]", item));
}
None => {
grid_str_formatted.push_str(&format!("[{}]", " ".repeat(1)));
grid_str_formatted.push_str(&format!("[{}]", " "));
}
};
});
grid_str_formatted.push_str("\n");
grid_str_formatted.push('\n');
});

println!("{}", grid_str_formatted);
Expand Down
6 changes: 3 additions & 3 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ use thiserror::Error;
#[derive(Error, Debug)]
pub enum GridEngineError {
#[error(transparent)]
InnerGridError(#[from] InnerGridError),
InnerGrid(#[from] InnerGridError),

#[error(transparent)]
ItemError(#[from] ItemError),
Item(#[from] ItemError),

// Temporary error for unhandled errors, must be removed and all errors should be handled
#[error("UnhandledError: {0}")]
UnhandledError(Box<dyn std::error::Error>),
Unhandled(Box<dyn std::error::Error>),
}

#[derive(Error, Debug)]
Expand Down
35 changes: 16 additions & 19 deletions src/grid_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ use crate::error::{GridEngineError, InnerGridError, ItemError};
use crate::grid_events::{ChangesEventValue, GridEvents};
use crate::inner_grid::{InnerGrid, UpdateGridOperation};
use crate::node::Node;
use crate::utils::{for_cell, ForCellArgs};
use crate::utils::{ForCellArgs, for_cell};
use std::{collections::BTreeMap, fmt::Debug};

/// Represents data for an item addition change
Expand Down Expand Up @@ -132,8 +132,7 @@ impl GridEngine {
}

fn new_node(&mut self, id: String, x: usize, y: usize, w: usize, h: usize) -> Node {
let node = Node::new(id, x, y, w, h);
node
Node::new(id, x, y, w, h)
}

fn create_add_change(&mut self, node: Node) {
Expand Down Expand Up @@ -196,8 +195,8 @@ impl GridEngine {
w: usize,
h: usize,
) -> Result<&Node, GridEngineError> {
if self.items.get(&id).is_some() {
return Err(GridEngineError::ItemError(ItemError::ItemAlreadyExists {
if self.items.contains_key(&id) {
return Err(GridEngineError::Item(ItemError::ItemAlreadyExists {
id: id.clone(),
}));
};
Expand All @@ -216,7 +215,7 @@ impl GridEngine {
.items
.get(&node_id)
.ok_or(InnerGridError::MismatchedGridItem { id: node_id })?;
Ok(&node)
Ok(node)
}

fn create_remove_change(&mut self, node: &Node) {
Expand Down Expand Up @@ -248,7 +247,7 @@ impl GridEngine {
pub fn remove_item(&mut self, id: &str) -> Result<Node, GridEngineError> {
let node = match self.items.get(id) {
Some(node) => node,
None => Err(GridEngineError::ItemError(ItemError::ItemNotFound {
None => Err(GridEngineError::Item(ItemError::ItemNotFound {
id: id.to_string(),
}))?,
}
Expand Down Expand Up @@ -301,7 +300,7 @@ impl GridEngine {
)?;

if !collides_with.contains(&node) {
collides_with.push(&node);
collides_with.push(node);
}
}
}
Expand Down Expand Up @@ -423,7 +422,7 @@ impl GridEngine {
) -> Result<(), GridEngineError> {
let node = match self.items.get(id) {
Some(node) => node,
None => Err(GridEngineError::ItemError(ItemError::ItemNotFound {
None => Err(GridEngineError::Item(ItemError::ItemNotFound {
id: id.to_string(),
}))?,
};
Expand Down Expand Up @@ -454,7 +453,7 @@ impl GridEngine {
/// * `Ok(())` - If all changes were applied successfully
/// * `Err(GridEngineError)` - If any change application fails
/// ```
fn apply_changes(&mut self, changes: &Vec<Change>) -> Result<(), GridEngineError> {
fn apply_changes(&mut self, changes: &[Change]) -> Result<(), GridEngineError> {
for change in changes.iter() {
match &change {
Change::Add(data) => {
Expand Down Expand Up @@ -485,7 +484,7 @@ impl GridEngine {
}

self.events.trigger_changes_event(&ChangesEventValue {
changes: changes.iter().map(|change| change.clone()).collect(),
changes: changes.to_vec(),
});
Ok(())
}
Expand Down Expand Up @@ -705,28 +704,26 @@ mod tests {
assert!(
engine
.will_collides_with(
&engine.items.get(&item_0_id).unwrap(),
engine.items.get(&item_0_id).unwrap(),
0,
0,
&mut engine.grid.clone()
)
.unwrap()
.len()
== 0
.is_empty()
);

// Asserts that does not collide with empty position
assert!(
engine
.will_collides_with(
&engine.items.get(&item_0_id).unwrap(),
engine.items.get(&item_0_id).unwrap(),
2,
2,
&mut engine.grid.clone()
)
.unwrap()
.len()
== 0
.is_empty()
);

// Asserts that collide with occupied position
Expand All @@ -736,7 +733,7 @@ mod tests {
assert!(
engine
.will_collides_with(
&engine.items.get(&item_0_id).unwrap(),
engine.items.get(&item_0_id).unwrap(),
1,
2,
&mut engine.grid.clone()
Expand All @@ -750,7 +747,7 @@ mod tests {
assert!(
engine
.will_collides_with(
&engine.items.get(&item_0_id).unwrap(),
engine.items.get(&item_0_id).unwrap(),
1,
1,
&mut engine.grid.clone()
Expand Down
14 changes: 3 additions & 11 deletions src/grid_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub struct ChangesEventValue {
///
/// These functions:
/// - Receive a reference to `ChangesEventValue`
pub type ChangesEventFn = Box<dyn Fn(&ChangesEventValue) -> () + Send + 'static + Sync>;
pub type ChangesEventFn = Box<dyn Fn(&ChangesEventValue) + Send + 'static + Sync>;

/// Represents a registered event listener function.
///
Expand All @@ -84,7 +84,7 @@ impl Debug for ListenerFunction {
/// `GridEvents` manages a collection of event listeners that are notified
/// whenever changes occur in the grid. It provides methods to register
/// and remove listeners, as well as trigger events when changes happen.
#[derive(Debug)]
#[derive(Debug, Default)]
pub struct GridEvents {
/// Collection of registered change event listeners
changes_listeners: Vec<ListenerFunction>,
Expand Down Expand Up @@ -161,14 +161,6 @@ impl GridEvents {
}
}

impl Default for GridEvents {
fn default() -> Self {
Self {
changes_listeners: Vec::new(),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -259,7 +251,7 @@ mod tests {
events.trigger_changes_event(&event);

let received = received_changes.lock().unwrap();
let received_change = received.get(0).unwrap();
let received_change = received.first().unwrap();
assert_eq!(received_change, &change);
}
}
16 changes: 9 additions & 7 deletions src/inner_grid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
//! The grid automatically expands vertically when needed, allowing for
//! flexible layout management while maintaining horizontal constraints.

use crate::{error::InnerGridError, node::Node};
use grid::Grid;
use std::ops::{Deref, DerefMut};
use crate::{error::InnerGridError, node::Node};

/// Operation to perform when updating the grid.
#[derive(Debug, Clone, Copy)]
Expand Down Expand Up @@ -134,15 +134,15 @@ impl InnerGrid {
self.handle_expansion(x, y);
}

return self.inner.get(y, x);
self.inner.get(y, x)
}

pub(crate) 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);
}

return self.inner.get_mut(y, x);
self.inner.get_mut(y, x)
}

/// Updates a cell in the grid based on the specified operation.
Expand Down Expand Up @@ -238,8 +238,9 @@ mod tests {
};

// First add the node
grid.get_mut(1, 1)
.map(|cell| *cell = Some("test_node".to_string()));
if let Some(cell) = grid.get_mut(1, 1) {
*cell = Some("test_node".to_string());
}

// Then remove it
grid.update(&node, 1, 1, UpdateGridOperation::Remove)
Expand All @@ -260,8 +261,9 @@ mod tests {
};

// Add a different node's ID
grid.get_mut(1, 1)
.map(|cell| *cell = Some("different_node".to_string()));
if let Some(cell) = grid.get_mut(1, 1) {
*cell = Some("different_node".to_string());
}

// Try to remove our node
grid.update(&node, 1, 1, UpdateGridOperation::Remove)
Expand Down
6 changes: 2 additions & 4 deletions src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
use crate::{
error::InnerGridError,
inner_grid::{InnerGrid, UpdateGridOperation},
utils::{for_cell, ForCellArgs},
utils::{ForCellArgs, for_cell},
};

/// Represents an item in the grid with position and dimensions.
Expand Down Expand Up @@ -115,9 +115,7 @@ impl Node {
grid: &mut InnerGrid,
update_operation: UpdateGridOperation,
) -> Result<(), InnerGridError> {
self.for_cell(&mut |x, y| {
return grid.update(self, x, y, update_operation);
})?;
self.for_cell(&mut |x, y| grid.update(self, x, y, update_operation))?;

Ok(())
}
Expand Down
Loading
Loading