Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions Lib/test/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -1340,8 +1340,6 @@ def iter_and_mutate():

self.assertRaises(RuntimeError, iter_and_mutate)

# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_reversed(self):
d = {"a": 1, "b": 2, "foo": 0, "c": 3, "d": 4}
del d["foo"]
Expand Down
10 changes: 3 additions & 7 deletions vm/src/builtins/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -753,7 +753,7 @@ macro_rules! dict_iterator {
impl $reverse_iter_name {
fn new(dict: PyDictRef) -> Self {
$reverse_iter_name {
position: AtomicCell::new(1),
position: AtomicCell::new(0),
size: dict.size(),
dict,
status: AtomicCell::new(IterStatus::Active),
Expand Down Expand Up @@ -782,12 +782,8 @@ macro_rules! dict_iterator {
"dictionary changed size during iteration".to_owned(),
));
}
let count = zelf.position.fetch_add(1);
match zelf.dict.len().checked_sub(count) {
Some(mut pos) => {
let (key, value) = zelf.dict.entries.next_entry(&mut pos).unwrap();
Ok(($result_fn)(vm, key, value))
}
match zelf.dict.entries.next_entry_reversed(&zelf.position) {
Some((key, value)) => Ok(($result_fn)(vm, key, value)),
None => {
zelf.status.store(IterStatus::Exhausted);
Err(vm.new_stop_iteration())
Expand Down
13 changes: 13 additions & 0 deletions vm/src/dictdatatype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::builtins::{PyStr, PyStrRef};
use crate::common::lock::{PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard};
use crate::vm::VirtualMachine;
use crate::{IdProtocol, IntoPyObject, PyObjectRef, PyRefExact, PyResult, TypeProtocol};
use crossbeam_utils::atomic::AtomicCell;
use rustpython_common::hash;
use std::fmt;
use std::mem::size_of;
Expand Down Expand Up @@ -487,6 +488,18 @@ impl<T: Clone> Dict<T> {
}
}

pub fn next_entry_reversed(&self, position: &AtomicCell<usize>) -> Option<(PyObjectRef, T)> {
let inner = self.read();
loop {
let position_usize = position.fetch_add(1);
let position_index = inner.entries.len().checked_sub(position_usize + 1)?;
let entry = inner.entries.get(position_index)?;
if let Some(entry) = entry {
break Some((entry.key.clone(), entry.value.clone()));
}
}
}

pub fn len_from_entry_index(&self, position: EntryIndex) -> usize {
self.read().entries.len() - position
}
Expand Down