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

Method insert

publication/code/chapter06/hashmap.rs:68–98  ·  view source on GitHub ↗
(&mut self, key: usize, value: T)

Source from the content-addressed store, hash-verified

66 }
67
68 fn insert(&mut self, key: usize, value: T) {
69 if 0 == key { panic!("Error: key must > 0"); }
70
71 let pos = self.hash(key);
72 if 0 == self.slot[pos] {
73 // 槽无数据直接插入
74 self.slot[pos] = key;
75 self.data[pos] = value;
76 } else {
77 // 插入槽有数据再找下一个可行的位置
78 let mut next = self.rehash(pos);
79 while 0 != self.slot[next]
80 && key != self.slot[next] {
81 next = self.rehash(next);
82
83 // 槽满了就退出
84 if next == pos {
85 println!("Error: slot is full!");
86 return;
87 }
88 }
89
90 // 在找到的槽插入数据
91 if 0 == self.slot[next] {
92 self.slot[next] = key;
93 self.data[next] = value;
94 } else {
95 self.data[next] = value;
96 }
97 }
98 }
99
100 fn remove(&mut self, key: usize) -> Option<T> {
101 if 0 == key { panic!("Error: key must > 0"); }

Callers 2

basicFunction · 0.45
iterFunction · 0.45

Calls 2

hashMethod · 0.45
rehashMethod · 0.45

Tested by

no test coverage detected