summaryrefslogtreecommitdiffstats
path: root/toolkit/components/uniffi-bindgen-gecko-js/fixtures/tests/xpcshell/test_refcounts.js
blob: 790d981104cef24d5454c94a3b8d520557db5208 (plain)
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
/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

const { getSingleton, getJsRefcount } = ChromeUtils.importESModule(
  "resource://gre/modules/RustRefcounts.sys.mjs"
);

// Test refcounts when we call methods.
//
// Each method call requires that we clone the Arc pointer on the JS side, then pass it to Rust
// which will consumer the reference.  Make sure we get this right

function createObjectAndCallMethods() {
  const obj = getSingleton();
  obj.method();
}

add_test(() => {
  // Create an object that we'll keep around.  If the ref count ends up being low, we don't want
  // to reduce it below 0, since the Rust code may catch that and clamp it
  const obj = getSingleton();
  createObjectAndCallMethods();
  Cu.forceGC();
  Cu.forceCC();
  do_test_pending();
  do_timeout(500, () => {
    Assert.equal(getJsRefcount(), 1);
    // Use `obj` to avoid unused warnings and try to ensure that JS doesn't destroy it early
    obj.method();
    do_test_finished();
    run_next_test();
  });
});

// Test refcounts when creating/destroying objects
function createAndDeleteObjects() {
  [getSingleton(), getSingleton(), getSingleton()];
}

add_test(() => {
  const obj = getSingleton();
  createAndDeleteObjects();
  Cu.forceGC();
  Cu.forceCC();
  do_timeout(500, () => {
    Assert.equal(getJsRefcount(), 1);
    obj.method();
    do_test_finished();
    run_next_test();
  });
});

// As we implement more UniFFI features we should probably add refcount tests for it.
// Some features that should probably have tests:
//   - Async methods
//   - UniFFI builtin trait methods like 'to_string'
//   - Rust trait objects