Skip to content

Commit 144cd7b

Browse files
committed
Add test for resource binary
1 parent ef9fc8f commit 144cd7b

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

test/c_src/finest.cpp

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ auto y = fine::Atom("y");
2020

2121
struct TestResource {
2222
ErlNifPid pid;
23+
std::string binary;
2324

24-
TestResource(ErlNifPid pid) : pid(pid) {}
25+
TestResource(ErlNifPid pid) : pid(pid), binary("hello world") {}
2526

2627
void destructor(ErlNifEnv *env) {
2728
auto msg_env = enif_alloc_env();
@@ -186,6 +187,13 @@ ErlNifPid resource_get(ErlNifEnv *, fine::ResourcePtr<TestResource> resource) {
186187
}
187188
FINE_NIF(resource_get, 0);
188189

190+
fine::Term resource_binary(ErlNifEnv *env,
191+
fine::ResourcePtr<TestResource> resource) {
192+
return fine::make_resource_binary(env, resource, resource->binary.data(),
193+
resource->binary.size());
194+
}
195+
FINE_NIF(resource_binary, 0);
196+
189197
fine::Term make_new_binary(ErlNifEnv *env) {
190198
const char *buffer = "hello world";
191199
size_t size = 11;

test/lib/finest/nif.ex

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ defmodule Finest.NIF do
4040

4141
def resource_create(_pid), do: err!()
4242
def resource_get(_resource), do: err!()
43+
def resource_binary(_resource), do: err!()
4344

4445
def make_new_binary(), do: err!()
4546

test/test/finest_test.exs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,26 @@ defmodule FinestTest do
232232
assert_receive :destructor_with_env
233233
assert_receive :destructor_default
234234
end
235+
236+
test "resource binary keeps reference to the resource" do
237+
_ =
238+
(fn ->
239+
binary = NIF.resource_binary(NIF.resource_create(self()))
240+
:erlang.garbage_collect(self())
241+
242+
# We have reference to the binary, so the resource should
243+
# stay alive.
244+
refute_receive :destructor_default, 10
245+
246+
byte_size(binary)
247+
end).()
248+
249+
# We no longer have reference to the binary, so GC should destroy
250+
# the resource.
251+
:erlang.garbage_collect(self())
252+
253+
assert_receive :destructor_default
254+
end
235255
end
236256

237257
describe "make_new_binary" do

0 commit comments

Comments
 (0)