Skip to content

Commit 70ce59e

Browse files
committed
Add Option_type resource type
1 parent b5d6e78 commit 70ce59e

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

native/libp2p_nif/libp2p.c

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,34 @@
3434
const uint64_t PID_LENGTH = 1024;
3535
const uint64_t BUFFER_SIZE = 4096;
3636

37+
/*************/
38+
/* NIF Setup */
39+
/*************/
40+
41+
ErlNifResourceType *Option_type;
42+
43+
// Resource type helpers
44+
void Option_type_cleanup(ErlNifEnv *env, void *arg)
45+
{
46+
uintptr_t handle = (uintptr_t)arg;
47+
DeleteHandle(handle);
48+
}
49+
50+
static int load(ErlNifEnv *env, void **priv_data, ERL_NIF_TERM load_info)
51+
{
52+
ErlNifResourceFlags flags = ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER;
53+
Option_type = enif_open_resource_type(env, NULL, "Option_type", Option_type_cleanup, flags, NULL);
54+
return Option_type == NULL ? 1 : 0;
55+
}
56+
57+
static int upgrade(ErlNifEnv *env, void **priv_data, void **old_priv_data,
58+
ERL_NIF_TERM load_info)
59+
{
60+
ErlNifResourceFlags flags = ERL_NIF_RT_TAKEOVER;
61+
Option_type = enif_open_resource_type(env, NULL, "Option_type", Option_type_cleanup, flags, NULL);
62+
return Option_type == NULL ? 1 : 0;
63+
}
64+
3765
/***********/
3866
/* Helpers */
3967
/***********/
@@ -219,4 +247,4 @@ static ErlNifFunc nif_funcs[] = {
219247
NIF_ENTRY(stream_close, 1),
220248
};
221249

222-
ERL_NIF_INIT(Elixir.Libp2p, nif_funcs, NULL, NULL, NULL, NULL)
250+
ERL_NIF_INIT(Elixir.Libp2p, nif_funcs, load, NULL, upgrade, NULL)

native/libp2p_nif/main.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ func callGetter[T any, R any](h C.uintptr_t, g func(T) R) C.uintptr_t {
4141
/* Utils */
4242
/*********/
4343

44+
//export DeleteHandle
45+
func DeleteHandle(h C.uintptr_t) {
46+
cgo.Handle(h).Delete()
47+
}
48+
4449
//export ListenAddrStrings
4550
func ListenAddrStrings(listenAddr string) C.uintptr_t {
4651
// TODO: this function is variadic

0 commit comments

Comments
 (0)