From 53208182f80d1fc34041d3eae1050a7380406d91 Mon Sep 17 00:00:00 2001 From: djrmarques <31391588+djrmarques@users.noreply.github.com> Date: Mon, 25 Apr 2022 08:04:33 +0200 Subject: [PATCH] Changed PyAttributes type to IndexMap --- vm/src/builtins/type.rs | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/vm/src/builtins/type.rs b/vm/src/builtins/type.rs index 60f87afa6..3be890647 100644 --- a/vm/src/builtins/type.rs +++ b/vm/src/builtins/type.rs @@ -13,13 +13,9 @@ use crate::{ types::{Callable, GetAttr, PyTypeFlags, PyTypeSlots, SetAttr}, AsObject, Context, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, }; +use indexmap::{map::Entry, IndexMap}; use itertools::Itertools; -use std::{ - borrow::Borrow, - collections::{HashMap, HashSet}, - fmt, - ops::Deref, -}; +use std::{borrow::Borrow, collections::HashSet, fmt, ops::Deref}; /// type(object_or_name, bases, dict) /// type(object) -> the object's type @@ -36,10 +32,10 @@ pub struct PyType { pub type PyTypeRef = PyRef; -/// For attributes we do not use a dict, but a hashmap. This is probably -/// faster, unordered, and only supports strings as keys. -/// TODO: class attributes should maintain insertion order (use IndexMap here) -pub type PyAttributes = HashMap; +/// For attributes we do not use a dict, but an IndexMap, which is an Hash Table +/// that maintains order and is compatible with the standard HashMap This is probably +/// faster and only supports strings as keys. +pub type PyAttributes = IndexMap; impl fmt::Display for PyType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -271,7 +267,7 @@ impl PyType { fn dir(zelf: PyRef, vm: &VirtualMachine) -> PyList { let attributes: Vec = zelf .get_attributes() - .drain() + .drain(..) .map(|(k, _)| vm.ctx.new_str(k).into()) .collect(); PyList::from(attributes) @@ -495,7 +491,6 @@ impl PyType { } if let Some(current_frame) = vm.current_frame() { - use std::collections::hash_map::Entry; let entry = attributes.entry("__module__".to_owned()); if matches!(entry, Entry::Vacant(_)) { let module_name =