Looking for feedback on my iterator


#1

So I tried implementing an iterator, and I would like to have some feedback, if I did it “right”. The code can be found here. Some background:

PlayersMap is a struct to save the player list in a game. I want to get players by their name, so the basic building block is a HashMap<String, Player>. For sake of simplicity, a Player contains just his name.

But in the game, the players take turns, so there is some order, using a Vec<String>, and a pointer “current” to the current player.

The iterator I wrote should start at the current player and then iterate over all players in order.

I would appreciate any feedback on this approach.


#2

You can use an OrderMap (from the ordermap crate) that efficiently implements a HashMap that remembers the insertion order with a nice interface.


#3

I think the iterator impl is fine although you can probably simplify it a bit by removing the starting_off field and instead computing the starting position in the new function that creates the iterator.

Also you can consider using Cow<'a, str> or Rc<String> to avoid cloning the strings within PlayersMap. The Cow will make your PlayersMap gain a lifetime parameter though. But it can allow passing constant strings if that’s even possible in the real game (probably not).


#4

Nice to know about ordermap, but I want to start my iterator in the middle of the list, and then start over, until the starting point is reached. I don’t see a way to do this with ordermap.


#5

starting_off is mainly used to differentiate the two cases, where current == start. This is the case when the iterator is started (so starting_off == true), and when the iterator is at it’s end (starting_off == false). Maybe there is a more elegant way to differentiate those cases, but nothing came to my mind.


#6

See what you think of this: https://play.rust-lang.org/?gist=351e3d48e424bb4b49b7923d617c2989&version=stable


#7

That really looks nice and clean!