-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathrefs.c
92 lines (73 loc) · 1.99 KB
/
refs.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "refs.h"
// Create a global array refs in the heap stash.
void duv_ref_setup(duk_context *ctx) {
duk_push_heap_stash(ctx);
// Create a new array with one `0` at index `0`.
duk_push_array(ctx);
duk_push_int(ctx, 0);
duk_put_prop_index(ctx, -2, 0);
// Store it as "refs" in the heap stash
duk_put_prop_string(ctx, -2, "refs");
duk_pop(ctx);
}
// like luaL_ref, but assumes storage in "refs" property of heap stash
int duv_ref(duk_context *ctx) {
int ref;
if (duk_is_undefined(ctx, -1)) {
duk_pop(ctx);
return 0;
}
// Get the "refs" array in the heap stash
duk_push_heap_stash(ctx);
duk_get_prop_string(ctx, -1, "refs");
duk_remove(ctx, -2);
// ref = refs[0]
duk_get_prop_index(ctx, -1, 0);
ref = duk_get_int(ctx, -1);
duk_pop(ctx);
// If there was a free slot, remove it from the list
if (ref != 0) {
// refs[0] = refs[ref]
duk_get_prop_index(ctx, -1, ref);
duk_put_prop_index(ctx, -2, 0);
}
// Otherwise use the end of the list
else {
// ref = refs.length;
ref = duk_get_length(ctx, -1);
}
// swap the array and the user value in the stack
duk_insert(ctx, -2);
// refs[ref] = value
duk_put_prop_index(ctx, -2, ref);
// Remove the refs array from the stack.
duk_pop(ctx);
return ref;
}
void duv_push_ref(duk_context *ctx, int ref) {
if (!ref) {
duk_push_undefined(ctx);
return;
}
// Get the "refs" array in the heap stash
duk_push_heap_stash(ctx);
duk_get_prop_string(ctx, -1, "refs");
duk_remove(ctx, -2);
duk_get_prop_index(ctx, -1, ref);
duk_remove(ctx, -2);
}
void duv_unref(duk_context *ctx, int ref) {
if (!ref) return;
// Get the "refs" array in the heap stash
duk_push_heap_stash(ctx);
duk_get_prop_string(ctx, -1, "refs");
duk_remove(ctx, -2);
// Insert a new link in the freelist
// refs[ref] = refs[0]
duk_get_prop_index(ctx, -1, 0);
duk_put_prop_index(ctx, -2, ref);
// refs[0] = ref
duk_push_int(ctx, ref);
duk_put_prop_index(ctx, -2, 0);
duk_pop(ctx);
}