Skip to content

Commit 3b0bd87

Browse files
committed
Implemented set.copy
1 parent 1d7fb2f commit 3b0bd87

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

py/objset.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include <stdlib.h>
22
#include <stdint.h>
3+
#include <string.h>
34
#include <assert.h>
45

56
#include "nlr.h"
@@ -114,6 +115,20 @@ static mp_obj_t set_clear(mp_obj_t self_in) {
114115
}
115116
static MP_DEFINE_CONST_FUN_OBJ_1(set_clear_obj, set_clear);
116117

118+
static mp_obj_t set_copy(mp_obj_t self_in) {
119+
assert(MP_OBJ_IS_TYPE(self_in, &set_type));
120+
mp_obj_set_t *self = self_in;
121+
122+
mp_obj_set_t *other = m_new_obj(mp_obj_set_t);
123+
other->base.type = &set_type;
124+
mp_set_init(&other->set, self->set.alloc);
125+
other->set.used = self->set.used;
126+
memcpy(other->set.table, self->set.table, self->set.alloc * sizeof(mp_obj_t));
127+
128+
return other;
129+
}
130+
static MP_DEFINE_CONST_FUN_OBJ_1(set_copy_obj, set_copy);
131+
117132

118133
/******************************************************************************/
119134
/* set constructors & public C API */
@@ -122,6 +137,7 @@ static MP_DEFINE_CONST_FUN_OBJ_1(set_clear_obj, set_clear);
122137
static const mp_method_t set_type_methods[] = {
123138
{ "add", &set_add_obj },
124139
{ "clear", &set_clear_obj },
140+
{ "copy", &set_copy_obj },
125141
{ NULL, NULL }, // end-of-list sentinel
126142
};
127143

tests/basics/tests/set_copy.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
s = {1, 2, 3, 4}
2+
t = s.copy()
3+
s.add(5)
4+
t.add(7)
5+
for i in s, t:
6+
l = list(i)
7+
l.sort()
8+
print(l)

0 commit comments

Comments
 (0)