Skip to content

Commit acb87d7

Browse files
authored
Make unsafe blocks smaller (TheAlgorithms#158)
* Make unsafe blocks smaller * Remove redundant write!() call
1 parent d490bfe commit acb87d7

File tree

1 file changed

+22
-31
lines changed

1 file changed

+22
-31
lines changed

src/data_structures/linked_list.rs

Lines changed: 22 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -40,20 +40,17 @@ impl<T> LinkedList<T> {
4040

4141
pub fn add(&mut self, obj: T) {
4242
let mut node = Box::new(Node::new(obj));
43-
unsafe {
44-
// Since we are adding node at the end, next will always be None
45-
node.next = None;
46-
node.prev = self.end;
47-
// Get a pointer to node
48-
let node_ptr = Some(NonNull::new_unchecked(Box::into_raw(node)));
49-
match self.end {
50-
// This is the case of empty list
51-
None => self.start = node_ptr,
52-
Some(end_ptr) => (*end_ptr.as_ptr()).next = node_ptr,
53-
}
54-
55-
self.end = node_ptr;
43+
// Since we are adding node at the end, next will always be None
44+
node.next = None;
45+
node.prev = self.end;
46+
// Get a pointer to node
47+
let node_ptr = Some(unsafe { NonNull::new_unchecked(Box::into_raw(node)) });
48+
match self.end {
49+
// This is the case of empty list
50+
None => self.start = node_ptr,
51+
Some(end_ptr) => unsafe { (*end_ptr.as_ptr()).next = node_ptr },
5652
}
53+
self.end = node_ptr;
5754
self.length += 1;
5855
}
5956

@@ -62,14 +59,12 @@ impl<T> LinkedList<T> {
6259
}
6360

6461
fn get_ith_node<'a>(&'a mut self, node: Option<NonNull<Node<T>>>, index: i32) -> Option<&'a T> {
65-
unsafe {
66-
match node {
67-
None => None,
68-
Some(next_ptr) => match index {
69-
0 => Some(&(*next_ptr.as_ptr()).val),
70-
_ => self.get_ith_node((*next_ptr.as_ptr()).next, index - 1),
71-
},
72-
}
62+
match node {
63+
None => None,
64+
Some(next_ptr) => match index {
65+
0 => Some(unsafe { &(*next_ptr.as_ptr()).val }),
66+
_ => self.get_ith_node(unsafe { (*next_ptr.as_ptr()).next }, index - 1),
67+
},
7368
}
7469
}
7570
}
@@ -79,11 +74,9 @@ where
7974
T: Display,
8075
{
8176
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
82-
unsafe {
83-
match self.start {
84-
Some(node) => write!(f, "{}", node.as_ref()),
85-
None => write!(f, ""),
86-
}
77+
match self.start {
78+
Some(node) => write!(f, "{}", unsafe { node.as_ref() }),
79+
None => Ok(()),
8780
}
8881
}
8982
}
@@ -93,11 +86,9 @@ where
9386
T: Display,
9487
{
9588
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
96-
unsafe {
97-
match self.next {
98-
Some(node) => write!(f, "{}, {}", self.val, node.as_ref()),
99-
None => write!(f, "{}", self.val),
100-
}
89+
match self.next {
90+
Some(node) => write!(f, "{}, {}", self.val, unsafe { node.as_ref() }),
91+
None => write!(f, "{}", self.val),
10192
}
10293
}
10394
}

0 commit comments

Comments
 (0)