帮我用rust写一个IdFactory<T>结构体,里面包含一个BTreeSet<T>和一个T类型的字段,实现一个generate_id方法。
时间: 2024-02-16 08:03:19 浏览: 26
好的,下面是一个简单的实现:
```rust
use std::collections::BTreeSet;
struct IdFactory<T> {
ids: BTreeSet<T>,
next_id: T,
}
impl<T: Ord + Copy> IdFactory<T> {
fn new(start_id: T) -> Self {
IdFactory {
ids: BTreeSet::new(),
next_id: start_id,
}
}
fn generate_id(&mut self) -> T {
while self.ids.contains(&self.next_id) {
self.next_id = match self.next_id.checked_add(&1) {
Some(next) => next,
None => {
// This is unlikely to happen, but if we run out of ids,
// we'll start over from the lowest possible value.
self.ids.clear();
self.next_id = Default::default();
continue;
}
};
}
let id = self.next_id;
self.ids.insert(id);
id
}
}
```
这个实现使用了一个 `BTreeSet` 来存储已经生成的 id,保证了生成的 id 是唯一的且有序的。`next_id` 字段表示下一个可用的 id,每次调用 `generate_id` 方法时,它会在 `ids` 集合中查找是否已经有相同的 id,如果有,就继续向后查找,直到找到一个未被使用的 id。如果所有的 id 都已被使用,就会从最小的可能值重新开始。