MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / remove

Method remove

publication/code/chapter06/hashmap.rs:100–137  ·  view source on GitHub ↗
(&mut self, key: usize)

Source from the content-addressed store, hash-verified

98 }
99
100 fn remove(&mut self, key: usize) -> Option<T> {
101 if 0 == key { panic!("Error: key must > 0"); }
102
103 let pos = self.hash(key);
104 if 0 == self.slot[pos] {
105 // 槽中无数据,返回 None
106 None
107 } else if key == self.slot[pos] {
108 // 找到相同 key,更新 slot 和 data
109 self.slot[pos] = 0;
110 let data = Some(self.data[pos].clone());
111 self.data[pos] = Default::default();
112 data
113 } else {
114 let mut data: Option<T> = None;
115 let mut stop = false;
116 let mut found = false;
117 let mut curr = pos;
118
119 while 0 != self.slot[curr] && !found && !stop {
120 if key == self.slot[curr] {
121 // 找到了值,删除数据
122 found = true;
123 self.slot[curr] = 0;
124 data = Some(self.data[curr].clone());
125 self.data[curr] = Default::default();
126 } else {
127 // 再哈希回到了最初位置,说明找了一圈还没有
128 curr = self.rehash(curr);
129 if curr == pos {
130 stop = true;
131 }
132 }
133 }
134
135 data
136 }
137 }
138
139 fn get_pos(&self, key: usize) -> usize {
140 if 0 == key { panic!("Error: key must > 0"); }

Callers

nothing calls this directly

Calls 2

hashMethod · 0.45
rehashMethod · 0.45

Tested by

no test coverage detected