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

Method insert

code/chapter05/hashmap.rs:32–58  ·  view source on GitHub ↗
(&mut self, key: usize, value: T)

Source from the content-addressed store, hash-verified

30 }
31
32 fn insert(&mut self, key: usize, value: T) {
33 if 0 == key { panic!("Error: key must > 0"); }
34
35 let pos = self.hash(key);
36 if 0 == self.slot[pos] { // 槽无数据直接插入
37 self.slot[pos] = key;
38 self.data[pos] = value;
39 } else { // 插入槽有数据再找下一个可行的位置
40 let mut next = self.rehash(pos);
41 while 0 != self.slot[next]
42 && key != self.slot[next] {
43 next = self.rehash(next);
44 if next == pos { // 槽满了就退出
45 println!("Error: slot is full!");
46 return;
47 }
48 }
49
50 // 在找到的槽插入数据
51 if 0 == self.slot[next] {
52 self.slot[next] = key;
53 self.data[next] = value;
54 } else {
55 self.data[next] = value;
56 }
57 }
58 }
59
60 fn remove(&mut self, key: usize) -> Option<T> {
61 if 0 == key { panic!("Error: key must > 0"); }

Callers 1

mainFunction · 0.45

Calls 2

hashMethod · 0.45
rehashMethod · 0.45

Tested by

no test coverage detected