Skip to content

Commit a1b7ba3

Browse files
committed
Reference counting parent bindings
1 parent 74eb453 commit a1b7ba3

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

binding.c

+16-1
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@ struct Entry_ {
1212

1313
struct Binding_ {
1414
Binding *parent;
15+
long reference_count;
1516
Entry *first;
1617
};
1718

19+
static Binding *use_binding(Binding *);
1820
static Entry *create_entry(Entry *, char *, Object *);
1921
static Object *free_entry(Entry *);
2022
static Entry **vacancy(Binding *);
@@ -23,23 +25,36 @@ static int key_matches(char *, char *);
2325

2426
Binding *create_binding(Binding *parent) {
2527
Binding *binding = (Binding *)malloc(sizeof(Binding));
26-
binding->parent = parent;
28+
binding->parent = use_binding(parent);
29+
binding->reference_count = 0L;
2730
binding->first = NULL;
2831
return binding;
2932
}
3033

3134
Binding *free_binding(Binding *binding) {
35+
if (binding->reference_count > 1L) {
36+
binding->reference_count--;
37+
return binding->parent;
38+
}
3239
Binding *parent = binding->parent;
3340
Entry *entry = binding->first;
3441
while (entry != NULL) {
3542
Entry *next = entry->next;
3643
destroy(free_entry(entry));
3744
entry = next;
3845
}
46+
free_binding(binding->parent);
3947
free(binding);
4048
return parent;
4149
}
4250

51+
static Binding *use_binding(Binding *binding) {
52+
if (binding != NULL) {
53+
binding->reference_count++;
54+
}
55+
return binding;
56+
}
57+
4358
void add(Binding *binding, char *key, Object *object) {
4459
Entry **slot = vacancy(binding);
4560
*slot = create_entry(NULL, key, object);

0 commit comments

Comments
 (0)