@@ -40,20 +40,17 @@ impl<T> LinkedList<T> {
40
40
41
41
pub fn add ( & mut self , obj : T ) {
42
42
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 } ,
56
52
}
53
+ self . end = node_ptr;
57
54
self . length += 1 ;
58
55
}
59
56
@@ -62,14 +59,12 @@ impl<T> LinkedList<T> {
62
59
}
63
60
64
61
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
+ } ,
73
68
}
74
69
}
75
70
}
79
74
T : Display ,
80
75
{
81
76
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 ( ( ) ) ,
87
80
}
88
81
}
89
82
}
93
86
T : Display ,
94
87
{
95
88
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) ,
101
92
}
102
93
}
103
94
}
0 commit comments