The Trusted Iterator Length Problem

Oh, I would just have exact_size be an unsafe method and implementing it would therefore require typing unsafe.

@reem, thatā€™s the problem that @P1start (and the rest of the thread :wink: ) is describing: a method declared unsafe in the trait doesnā€™t require the implementer to write unsafe.

That seems wrong then.

Currently the unsafe declaration in the trait just means that the function is unsafe to call, so it might have to fulfill a contract. This doesnā€™t necessarily mean that every implementation of this function has to rely on that contract, and when they donā€™t they can just omit the unsafe.

We need real specialization based on optionally available traits. An impl of an unsafe trait TrustedIteratorLength could be present, and functions should be able to specialize for that case.

Filed an issue for making ExactSizeIterator unsafe

Iā€™m not sure if this is sensible, but if not it might inspire someone to have a better idea:

unsafe trait ExactSizeIterator {}
trait MaybeExactSizeIterator {
    // Edit: The `&self` isn't actually used in the blanket impls, but it
    // seems necessary for object safety?
    fn size_hint_is_exact(&self) -> bool;
}
impl<T> MaybeExactSizeIterator for T where T: ExactSizeIterator {
    fn size_hint_is_exact(&self) -> bool { true }
}
impl<T> MaybeExactSizeIterator for T where T: !ExactSizeIterator {
    fn size_hint_is_exact(&self) -> bool { false }
}
trait Iterator : MaybeExactSizeIterator {
    // ...
}

Pros:

  • Addresses this issue.
  • Everyone who accepts an Iterator can get this information without loss of generality.
  • unsafe is in the right place.

Cons:

  • It makes no sense to implement ExactSizeIterator without also implementing Iterator, so the dependence is a bit weird.
  • We have to have specialization that can get something like the above past the coherence rules. If you donā€™t have negative bounds of some sort, you unfortunately canā€™t express anything about the absence of an unsafe trait.

I just wanted to note that this is no longer true now that PR Move fn safety out of the subtyping relationship and into coercions by nikomatsakis Ā· Pull Request #23452 Ā· rust-lang/rust Ā· GitHub has landed. If you have an unsafe fn in a trait, the impl must now implement it with an unsafe fn as well.

1 Like

Great! I think Iā€™m pretty happy with the unsafe method solution now.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.