Skip to content

Commit 68d44e0

Browse files
committed
fix: all warining, clean up code, made it more readable
1 parent 2333347 commit 68d44e0

4 files changed

Lines changed: 132 additions & 84 deletions

File tree

src/assembler.rs

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,43 @@
1+
use std::collections::hash_map::Entry::Vacant;
12
use std::collections::HashMap;
23

34
use wg_internal::{network::NodeId, packet::Fragment};
45

56

6-
#[derive(Debug)]
7-
pub struct FragmentAssembler {
8-
pub fragments: HashMap<(u64, NodeId), Vec<Fragment>>, // session_id -> data buffer
7+
#[derive(Debug, Default)]
8+
pub struct FragmentAssembler<'a> {
9+
pub fragments: HashMap<(u64, NodeId), Vec<&'a Fragment>>, // session_id -> data buffer
910
pub expected_fragments: HashMap<(u64, NodeId), u64>, // session_id -> total_fragments
1011
pub received_fragments: HashMap<(u64, NodeId), Vec<bool>>, // session_id -> received status
1112
}
1213

13-
impl FragmentAssembler {
14-
pub fn new() -> Self {
15-
Self {
16-
fragments: HashMap::new(),
17-
expected_fragments: HashMap::new(),
18-
received_fragments: HashMap::new()
19-
}
20-
}
21-
22-
pub fn add_fragment(&mut self, fragment: Fragment, session_id: u64, sender: NodeId) -> Option<Vec<u8>> {
14+
impl<'a> FragmentAssembler<'a> {
15+
pub fn add_fragment(&mut self, fragment: &'a Fragment, session_id: u64, sender: NodeId) -> Option<Vec<u8>> {
2316
let communication_id = ( session_id, sender );
24-
if !self.fragments.contains_key(&communication_id) {
25-
self.fragments.insert(communication_id, vec![fragment.clone()]);
17+
#[allow(clippy::cast_possible_truncation)]
18+
let index = fragment.fragment_index as usize;
19+
20+
if let Vacant(entry) = self.fragments.entry(communication_id) {
21+
entry.insert(vec![fragment]);
2622
self.expected_fragments.insert(communication_id, fragment.total_n_fragments);
27-
self.received_fragments.insert(communication_id, vec![false; fragment.total_n_fragments as usize]);
23+
self.received_fragments.insert(communication_id, vec![false; index]);
2824
}
2925

3026
{
31-
let received = self.received_fragments.get_mut(&communication_id).unwrap();
32-
received[fragment.fragment_index as usize] = true;
27+
let received = self.received_fragments.get_mut(&communication_id)?;
28+
received[index] = true;
3329
}
3430

35-
let expected = self.expected_fragments.get(&communication_id).unwrap();
36-
let received = self.received_fragments.get(&communication_id).unwrap();
37-
let fragments = self.fragments.get(&communication_id).unwrap();
31+
let expected = self.expected_fragments.get(&communication_id)?;
32+
let received = self.received_fragments.get(&communication_id)?;
33+
let fragments = self.fragments.get(&communication_id)?;
3834

3935
// check if all fragments has been received
4036
if fragments.len() as u64 == *expected && received.iter().all(|f| *f){
41-
let fragments = self.fragments.get_mut(&communication_id).unwrap();
37+
let fragments = self.fragments.get_mut(&communication_id)?;
4238
fragments.sort_by(|t, n| t.fragment_index.cmp(&n.fragment_index));
4339
let mut data = vec![];
44-
for f in fragments.iter() {
40+
for f in fragments {
4541
data.copy_from_slice(&f.data);
4642
}
4743
let _ = self.fragments.remove(&communication_id);

src/network.rs

Lines changed: 41 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@ impl Display for NetworkError {
1919
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2020
match self {
2121
Self::TopologyError => write!(f, "Topology error"),
22-
Self::PathNotFound(id) => write!(f, "Path not found for node {}", id),
23-
Self::NodeNotFound(id) => write!(f, "Node {} not found", id),
24-
Self::NodeIsNotANeighbor(id) => write!(f, "Node {} is not a neighbor", id),
25-
Self::SendError(msg) => write!(f, "Send error: {}", msg),
22+
Self::PathNotFound(id) => write!(f, "Path not found for node {id}"),
23+
Self::NodeNotFound(id) => write!(f, "Node {id} not found"),
24+
Self::NodeIsNotANeighbor(id) => write!(f, "Node {id} is not a neighbor"),
25+
Self::SendError(msg) => write!(f, "Send error: {msg}"),
2626
Self::ControllerDisconnected => write!(f, "Controller disconnected"),
2727
Self::NoDestination => write!(f, "Packet has no destination specified"),
2828
Self::NoNeighborAssigned => write!(f, "No neighbor assigned"),
@@ -35,32 +35,34 @@ impl std::error::Error for NetworkError {}
3535

3636
impl<T: Send + std::fmt::Debug> From<SendError<T>> for NetworkError {
3737
fn from(value: SendError<T>) -> Self {
38-
NetworkError::SendError(format!("{:?}", value))
38+
NetworkError::SendError(format!("{value:?}"))
3939
}
4040
}
4141

4242

4343
#[derive(Clone)]
44-
pub struct Node {
45-
id: NodeId,
46-
node_type: NodeType,
44+
pub(crate) struct Node {
45+
pub id: NodeId,
46+
kind: NodeType,
4747
adjacents: Vec<NodeId>
4848
}
4949

5050

5151
impl Node {
52-
pub fn new(id: NodeId, node_type: NodeType, adjacents: Vec<NodeId>) -> Self {
53-
Self { id, node_type, adjacents }
52+
#[must_use]
53+
pub fn new(id: NodeId, kind: NodeType, adjacents: Vec<NodeId>) -> Self {
54+
Self { id, kind, adjacents }
5455
}
5556

5657
pub fn get_id(&self) -> NodeId {
5758
self.id
5859
}
5960

6061
pub fn get_node_type(&self) -> NodeType {
61-
self.node_type.clone()
62+
self.kind
6263
}
6364

65+
#[must_use]
6466
pub fn get_adjacents(&self) -> &Vec<NodeId> {
6567
&self.adjacents
6668
}
@@ -70,8 +72,9 @@ impl Node {
7072
}
7173

7274
pub fn remove_adjacent(&mut self, adj: NodeId) {
73-
let index_to_remove = self.adjacents.iter().position(|i| *i == adj).expect(&format!("Node with id {} not found in {} adjacents", adj, self.id));
74-
let _ = self.adjacents.remove(index_to_remove);
75+
if let Some(index_to_remove) = self.adjacents.iter().position(|i| *i == adj) {
76+
let _ = self.adjacents.remove(index_to_remove);
77+
}
7578
}
7679
}
7780

@@ -83,19 +86,20 @@ impl std::fmt::Debug for Node{
8386

8487
#[derive(Debug, Clone)]
8588
pub struct Network {
86-
pub nodes: Vec<Node>
89+
pub(crate) nodes: Vec<Node>
8790
}
8891

8992
impl Network {
90-
pub fn new(root: Node) -> Self {
91-
let mut nodes = vec![];
92-
nodes.push(root);
93+
#[must_use]
94+
pub(crate) fn new(root: Node) -> Self {
95+
let nodes = vec![root];
9396
Self { nodes }
9497
}
9598

96-
pub fn add_node(&mut self, new_node: Node) {
99+
100+
pub(crate) fn add_node(&mut self, new_node: Node) {
97101
for adj in new_node.get_adjacents() {
98-
if let Some(node) = self.nodes.iter_mut().find(|n| n.get_id() == *adj) {
102+
if let Some(node) = self.nodes.iter_mut().find(|n| n.id == *adj) {
99103
match (new_node.get_node_type(), node.get_node_type()) {
100104
(_, NodeType::Drone) | (NodeType::Drone, _) => {
101105
node.add_adjacent(*adj);
@@ -108,19 +112,22 @@ impl Network {
108112
self.nodes.push(new_node);
109113
}
110114

111-
pub fn remove_node(&mut self, node_id: NodeId) {
112-
for n in self.nodes.iter_mut() {
115+
pub(crate) fn remove_node(&mut self, node_id: NodeId) {
116+
for n in &mut self.nodes{
113117
if n.get_adjacents().contains(&node_id){
114118
n.remove_adjacent(node_id);
115119
}
116120
}
117-
if let Some(index_to_remove) = self.nodes.iter().position(|n| n.get_id() == node_id) {
121+
if let Some(index_to_remove) = self.nodes.iter().position(|n| n.id == node_id) {
118122
let _ = self.nodes.remove(index_to_remove);
119123
}
120124
}
121125

122-
pub fn update_node(&mut self, node_id: NodeId, adjacents: Vec<NodeId>) -> Result<(), NetworkError> {
123-
if let Some(node) = self.nodes.iter_mut().find(|n| n.get_id() == node_id) {
126+
/// Updates the node's adjacents with the provided list.
127+
/// # Errors
128+
/// If the node is not found, returns an error.
129+
pub(crate) fn update_node(&mut self, node_id: NodeId, adjacents: Vec<NodeId>) -> Result<(), NetworkError> {
130+
if let Some(node) = self.nodes.iter_mut().find(|n| n.id == node_id) {
124131
for adj in adjacents {
125132
if !node.get_adjacents().contains(&adj) {
126133
node.add_adjacent(adj);
@@ -131,20 +138,18 @@ impl Network {
131138
// automatically by the protocol
132139

133140
return Ok(());
134-
} else {
135-
return Err(NetworkError::NodeNotFound(node_id));
136141
}
142+
Err(NetworkError::NodeNotFound(node_id))
137143
}
138144

139-
pub fn change_node_type(&mut self, id: NodeId, new_type: NodeType) {
145+
pub(crate) fn change_node_type(&mut self, id: NodeId, new_type: NodeType) {
140146
if let Some(node) = self.nodes.iter_mut().find(|n| n.get_id() == id) {
141-
if node.get_node_type() != new_type {
142-
node.node_type = new_type;
143-
}
147+
node.kind = new_type;
144148
}
145149
}
146150

147-
pub fn find_path(&self, destination: NodeId) -> Option<Vec<NodeId>> {
151+
#[must_use]
152+
pub(crate) fn find_path(&self, destination: NodeId) -> Option<Vec<NodeId>> {
148153
let start = self.nodes[0].id;
149154
let mut visited = HashSet::new();
150155
let mut queue = VecDeque::new();
@@ -165,8 +170,8 @@ impl Network {
165170
return Some(path);
166171
}
167172

168-
if let Some(node) = self.nodes.iter().find(|n| n.get_id() == current) {
169-
for neighbor in node.get_adjacents().iter() {
173+
if let Some(node) = self.nodes.iter().find(|n| n.id == current) {
174+
for neighbor in node.get_adjacents() {
170175
if !visited.contains(neighbor) {
171176
visited.insert(*neighbor);
172177
parent_map.insert(neighbor, current);
@@ -192,7 +197,7 @@ mod tests {
192197
network.add_node(new_node);
193198

194199
assert_eq!(network.nodes.len(), 2);
195-
assert!(network.nodes.iter().any(|n| n.get_id() == 2));
200+
assert!(network.nodes.iter().any(|n| n.id == 2));
196201
}
197202

198203
#[test]
@@ -206,7 +211,7 @@ mod tests {
206211
network.remove_node(2);
207212

208213
assert_eq!(network.nodes.len(), 1);
209-
assert!(!network.nodes.iter().any(|n| n.get_id() == 2));
214+
assert!(!network.nodes.iter().any(|n| n.id == 2));
210215
}
211216

212217
#[test]
@@ -260,7 +265,6 @@ mod tests {
260265

261266
let result = network.find_path(3);
262267

263-
assert!(result.is_err());
264-
assert_eq!(result.unwrap_err().to_string(), "Path not found for node 3");
268+
assert!(result.is_none());
265269
}
266270
}

0 commit comments

Comments
 (0)