Branch data Line data Source code
1 : : /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
2 : : // SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
3 : : // SPDX-FileCopyrightText: 2023 Marco Trevisan <marco.trevisan@canonical.com>
4 : :
5 : : #pragma once
6 : :
7 : : #include <config.h>
8 : :
9 : : #include <type_traits>
10 : :
11 : : #include <js/RootingAPI.h>
12 : : #include <js/TypeDecls.h>
13 : :
14 : : #include "gjs/macros.h"
15 : :
16 : : namespace Gjs {
17 : :
18 : : class SimpleWrapper {
19 : : template <typename T>
20 : : using DestroyNotifyType = void (*)(T);
21 : :
22 : : public:
23 : : using DestroyNotify = DestroyNotifyType<void*>;
24 : :
25 : : private:
26 : : static JSObject* new_for_ptr(JSContext*, void* data, DestroyNotify);
27 : : [[nodiscard]] static void* get_ptr(JSContext*, JS::HandleObject);
28 : :
29 : : public:
30 : : template <typename T, typename DT>
31 : 102 : GJS_JSAPI_RETURN_CONVENTION static JSObject* new_for_ptr(
32 : : JSContext* cx, T* data, DT destroy_notify) {
33 : : static_assert(std::is_convertible_v<DT, DestroyNotifyType<T*>>,
34 : : "destroy notify can't be converted");
35 : 102 : return new_for_ptr(
36 : : cx, static_cast<void*>(data),
37 : : reinterpret_cast<DestroyNotify>(
38 : 203 : static_cast<DestroyNotifyType<T*>>(destroy_notify)));
39 : : }
40 : :
41 : : template <typename T>
42 : 1 : GJS_JSAPI_RETURN_CONVENTION static JSObject* new_for_ptr(JSContext* cx,
43 : : T* data) {
44 : 1 : return new_for_ptr(cx, data, nullptr);
45 : : }
46 : :
47 : : template <typename T, typename... Ts>
48 : 91 : GJS_JSAPI_RETURN_CONVENTION static JSObject* new_for_type(JSContext* cx,
49 : : Ts... args) {
50 [ + - ]: 182 : return new_for_ptr(cx, new T(args...), [](T* data) { delete data; });
51 : : }
52 : :
53 : : template <typename T>
54 : 418 : [[nodiscard]] static T* get(JSContext* cx, JS::HandleObject obj) {
55 : 418 : return static_cast<T*>(get_ptr(cx, obj));
56 : : }
57 : : };
58 : :
59 : : } // namespace Gjs
|