问题描述
struct MyType {
// stuff
}
struct Snapshot {
// stuff
}
impl MyType {
pub fn iter(&mut self) -> MyIterator {
MyIterator {
foo: self
}
}
}
struct MyIterator<'a> {
foo: &'a mut MyType
}
impl<'a> Iterator for MyIterator<'a> {
type Item = Snapshot;
fn next(&mut self) -> Option<Self::Item> {
if self.cheap_condition() {
self.cheap_mutation(); // Inexpensive
let s: Snapshot = self.snapshot(); // Expensive copying
Some(s)
} else {
None
}
}
}
如果我想使用生成的 Snapshot
的每个实例,这很好用,但是如果我想使用像 Iterator::step_by
或 Iterator::last
这样的东西,我不关心中间Snapshot
秒,生成这些未使用的值所产生的成本会对性能造成巨大影响。
我可以覆盖 Iterator
的每一个方法,这样昂贵的操作只在必要时发生,但我觉得必须有一种更简单、更惯用的方法来做到这一点,或者,如果 Snapshot
没有被再次调用,则延迟生成与 Item
的中间类型迭代对应的 Iterator::next
的方法。
我不想返回对 MyType
的引用,因为我希望我 do 生成的 Snapshot
具有独立的生命周期,例如,启用结果Iterator::collect()
的寿命比 MyType
的实例长。
解决方法
您不必覆盖每个 Iterator
方法。唯一相关的是 nth
、last
、count
、step_by
和 skip
。所有其他方法都需要以某种方式检查 Self::Item
,因此您无法避免为它们生成 Snapshot
。幸运的是,step_by
和 skip
在内部使用 nth
,因此实际上只剩下 nth
、count
和 last
,我们必须覆盖它们:
use core::marker::PhantomData;
struct Snapshot;
struct MyType<'a> {
item: PhantomData<&'a ()>,}
impl<'a> MyType<'a> {
fn cheap_condition(&self) -> bool {
todo!()
}
fn cheap_mutation(&mut self) {
todo!()
}
fn snapshot(&self) -> Snapshot {
Snapshot
}
}
impl<'a> Iterator for MyType<'a> {
type Item = Snapshot;
fn next(&mut self) -> Option<Self::Item> {
if self.cheap_condition() {
self.cheap_mutation(); // Inexpensive
Some(self.snapshot()) // Expensive
} else {
None
}
}
// also covers skip & step_by methods
fn nth(&mut self,n: usize) -> Option<Self::Item> {
for _ in 0..n {
if self.cheap_condition() {
self.cheap_mutation();
} else {
return None;
}
}
self.next()
}
fn count(mut self) -> usize
where
Self: Sized,{
let mut count: usize = 0;
while self.cheap_condition() {
self.cheap_mutation();
count += 1;
}
count
}
fn last(mut self) -> Option<Self::Item>
where
Self: Sized,{
while self.cheap_condition() {
self.cheap_mutation();
if !self.cheap_condition() {
return Some(self.snapshot());
}
}
None
}
}
如果您想通过检查 Iterator
而不是 filter
的谓词来使 MyType<'a>
等其他 Snapshot
方法变得懒惰,您必须定义自己的 Iterator
-like trait for that,因为所有其他方法仅适用于 Self::Item
。