1

I am trying to construct a Defiler struct that owns a fixed sequence and an internal state describing current position within this sequence. The idea is that it can be iterated upon, but sometimes be reset to the beginning of the sequence.

I have picked an iterator as the internal state to represent the current value of the sequence. The idea is that it would be dropped and replaced by a fresh iterator when it's time to reset.

Here is my least fancy naive try so far:

use std::slice::IterMut;

struct Defiler<'a> {
    // This sequence should not change during the whole
    // lifetime of the struct, although I have not expressed it yet.
    seq: Vec<u32>,
    // Internal state pointing towards the next element to be
    // yielded. It will be randomly replaced by a fresh one.
    current: IterMut<'a, u32>,
    // ...
}

impl<'a> Defiler<'a> {

    fn new(mut seq: Vec<u32>) -> Self {
        Defiler {
            seq,
            current: seq.iter_mut(), // move out of borrowed value, of course.
        }
    }

    // Restart the iteration from scratch.
    fn reset(&'a mut self) {
        self.current = self.seq.iter_mut();
    }

    // ...

}

I understand why the above does not compile, and I am aware that I have not expressed many things I wish the compiler to be reassured about:

  • even though its inner values are mutable, seq shall not grow or shrink during the whole lifetime of Defiler.
  • current will only iterate on owned values in seq, ever.
  • => no dangling iteration can be produced, I'm (quite) sure.

How could I write it?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
iago-lito
  • 3,098
  • 3
  • 29
  • 54
  • While the duplicate addresses this issue in the general case, you could just store the current index in `current` as a `usize`. – rodrigo Jun 09 '19 at 10:20
  • @rodrigo sure, and one could use `Box<[u32]>` over `Vec<[u32]>` for the fixed size dynamic array -- which would make this question a dup of another thing.. – Peter Varo Jun 09 '19 at 10:58
  • 2
    [The duplicates applied to your question](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=097a52e7794c058d247c5a3597e58c21) – Shepmaster Jun 09 '19 at 14:53
  • @rodrigo This was my first idea, but I guess rust iterators and borrow checking are here to prevent us from thinking this way X) – iago-lito Jun 09 '19 at 16:47
  • @Shepmaster I appreciate this much. Thank you :) – iago-lito Jun 09 '19 at 16:47

0 Answers0