Jelajahi Sumber

better dict clear

szdytom 1 tahun lalu
induk
melakukan
7549f1b95a
2 mengubah file dengan 11 tambahan dan 3 penghapusan
  1. 2 1
      include/pocketpy/objects/dict.h
  2. 9 2
      src/objects/dict.c

+ 2 - 1
include/pocketpy/objects/dict.h

@@ -8,6 +8,7 @@ extern "C" {
 #include "pocketpy/objects/pyvar.h"
 #include "pocketpy/common/vector.h"
 
+/** @brief `pkpy_Dict` is the Dict type in Python */
 typedef struct {
     int count;             /** number of elements in the dictionary */
     c11_vector _entries;   /** contains `pkpy_DictEntry` (hidden type) */
@@ -15,9 +16,9 @@ typedef struct {
     void* _hashtable;      /** contains indecies, can be `u8`, `u16` or `u32` according to size*/
 } pkpy_Dict;
 
+/** @brief `pkpy_DictIter` is used to iterate over a `pkpy_Dict` */
 typedef struct {
     const pkpy_Dict* _dict;
-    unsigned int _version;
     int _index;
 } pkpy_DictIter;
 

+ 9 - 2
src/objects/dict.c

@@ -227,8 +227,15 @@ void pkpy_Dict__update(pkpy_Dict *self, void *vm, const pkpy_Dict *other) {
 }
 
 void pkpy_Dict__clear(pkpy_Dict *self) {
-    pkpy_Dict__dtor(self);
-    pkpy_Dict__ctor(self);
+    self->count = 0;
+    c11_vector__dtor(&self->_entries);
+    c11_vector__ctor(&self->_entries, sizeof(struct pkpy_DictEntry));
+    if (self->_hashtable > 16) {
+        free(self->_hashtable);
+        self->_htcap = 16;
+        self->_hashtable = malloc(pkpy_Dict__ht_byte_size(self));
+    }
+    memset(self->_hashtable, 0xff, pkpy_Dict__ht_byte_size(self));
 }
 
 static int pkpy_Dict__next_entry_idx(const pkpy_Dict* self, int idx) {