summaryrefslogtreecommitdiff
path: root/gi/value.h
blob: 99aeb09e5781dfe9a745838073b30fd0b47f1994 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
// SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
// SPDX-FileCopyrightText: 2008 litl, LLC

#ifndef GI_VALUE_H_
#define GI_VALUE_H_

#include <config.h>

#include <utility>  // for move, swap
#include <vector>   // for vector

#include <glib-object.h>

#include <js/TypeDecls.h>

#include "gjs/macros.h"

namespace Gjs {
struct AutoGValue : GValue {
    AutoGValue() {
        static_assert(sizeof(AutoGValue) == sizeof(GValue));
        *static_cast<GValue*>(this) = G_VALUE_INIT;
    }
    explicit AutoGValue(GType gtype) : AutoGValue() {
        g_value_init(this, gtype);
    }
    AutoGValue(AutoGValue const& src) : AutoGValue(G_VALUE_TYPE(&src)) {
        g_value_copy(&src, this);
    }
    AutoGValue& operator=(AutoGValue other) {
        // We need to cast to GValue here not to make swap to recurse here
        std::swap(*static_cast<GValue*>(this), *static_cast<GValue*>(&other));
        return *this;
    }
    AutoGValue(AutoGValue&& src) {
        switch (G_VALUE_TYPE(&src)) {
            case G_TYPE_NONE:
            case G_TYPE_CHAR:
            case G_TYPE_UCHAR:
            case G_TYPE_BOOLEAN:
            case G_TYPE_INT:
            case G_TYPE_UINT:
            case G_TYPE_LONG:
            case G_TYPE_ULONG:
            case G_TYPE_INT64:
            case G_TYPE_UINT64:
            case G_TYPE_FLOAT:
            case G_TYPE_DOUBLE:
                *static_cast<GValue*>(this) =
                    std::move(static_cast<GValue const&&>(src));
                break;
            default:
                // We can't safely move in complex cases, so let's just copy
                *static_cast<GValue*>(this) = G_VALUE_INIT;
                *this = src;
                g_value_unset(&src);
        }
    }
    ~AutoGValue() { g_value_unset(this); }
};
}  // namespace Gjs

using AutoGValueVector = std::vector<Gjs::AutoGValue>;

GJS_JSAPI_RETURN_CONVENTION
bool       gjs_value_to_g_value         (JSContext      *context,
                                         JS::HandleValue value,
                                         GValue         *gvalue);
GJS_JSAPI_RETURN_CONVENTION
bool       gjs_value_to_g_value_no_copy (JSContext      *context,
                                         JS::HandleValue value,
                                         GValue         *gvalue);

GJS_JSAPI_RETURN_CONVENTION
bool gjs_value_from_g_value(JSContext             *context,
                            JS::MutableHandleValue value_p,
                            const GValue          *gvalue);


#endif  // GI_VALUE_H_