this post was submitted on 21 Aug 2026
11 points (100.0% liked)

Rust

8239 readers
32 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 3 years ago
MODERATORS
 

I've been trying to contribute to statrs recently, and one of the issues I've been running into is that I'm trying to have an iterator that returns items in sorted order without cloning the underlying data. I'm working this PR if you wanted to take a look at my code so far. I looked up this problem and found this StackOverflow post about this topic from years ago but, frankly, I don't believe it. Assuming you're iterating from a vector, mutating the underlying vector is akin to keeping state on the order of the vector. Why cant that happen in a separate data structure? Is there a more efficient way to represent ordinality other than a vector? Creating an iterator is simply tracking traversal through that structure, which I think could be done using a bloom filter to track which indices have not been traversed yet. That just leaves the traversal algorithm itself. What information would an iterator need to know to make the best decision? Could I adapt a sorting algorithm to be an iterator?

I'm asking a lot of questions because I'm a statistics guys, not an algorithms guy. Any starting point or input is much appreciated!

you are viewing a single comment's thread
view the rest of the comments
[–] sukhmel@programming.dev 4 points 1 day ago

I haven't looked at the code, so my two cents may be irrelevant, but it sounds like you could define a structure that borrows the vector, keeps a separate vector of indices into borrowed vector, and has a current element index.

struct SortFacadeIterator<'a, T: Ord> {
    data: &'a Vec<T>,
    indices: Vec<usize>,
    position: usize,
}

Then in new you would need to sort the original vector but instead of mutating it you would store indices of a resulting sorted elements from the original, i.e. when passed ["b", "a", "c"] you would create index storage of [1, 0, 2]. After that you can iterate both ways, returning an element by index:

impl<'a, T: Ord> SortFacadeIterator<'a, T> {
    fn current(&self) -> &T {
        self.data[self.indices[self.position]]
    }
}

I think, maybe sorting a vector could be done by enumerating original vector and sort_by a value, also I'm not sure you need a full ordering, but I don't remember what a sort expects