1 /* Copyright (C) 2017 Wildfire Games.
2 * This file is part of 0 A.D.
4 * 0 A.D. is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
9 * 0 A.D. is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
18 #ifndef INCLUDED_SCRIPTCONVERSIONS
19 #define INCLUDED_SCRIPTCONVERSIONS
21 #include "ScriptInterface.h"
22 #include "scriptinterface/ScriptExtraHeaders.h" // for typed arrays
26 template<typename T
> static void ToJSVal_vector(JSContext
* cx
, JS::MutableHandleValue ret
, const std::vector
<T
>& val
)
29 JS::RootedObject
obj(cx
, JS_NewArrayObject(cx
, 0));
36 ENSURE(val
.size() <= std::numeric_limits
<u32
>::max());
37 for (u32 i
= 0; i
< val
.size(); ++i
)
39 JS::RootedValue
el(cx
);
40 ScriptInterface::ToJSVal
<T
>(cx
, &el
, val
[i
]);
41 JS_SetElement(cx
, obj
, i
, el
);
46 #define FAIL(msg) STMT(JS_ReportError(cx, msg); return false)
48 template<typename T
> static bool FromJSVal_vector(JSContext
* cx
, JS::HandleValue v
, std::vector
<T
>& out
)
51 JS::RootedObject
obj(cx
);
53 FAIL("Argument must be an array");
56 if (!(JS_IsArrayObject(cx
, obj
) || JS_IsTypedArrayObject(obj
)))
57 FAIL("Argument must be an array");
60 if (!JS_GetArrayLength(cx
, obj
, &length
))
61 FAIL("Failed to get array length");
64 for (u32 i
= 0; i
< length
; ++i
)
66 JS::RootedValue
el(cx
);
67 if (!JS_GetElement(cx
, obj
, i
, &el
))
68 FAIL("Failed to read array element");
70 if (!ScriptInterface::FromJSVal
<T
>(cx
, el
, el2
))
79 #define JSVAL_VECTOR(T) \
80 template<> void ScriptInterface::ToJSVal<std::vector<T> >(JSContext* cx, JS::MutableHandleValue ret, const std::vector<T>& val) \
82 ToJSVal_vector(cx, ret, val); \
84 template<> bool ScriptInterface::FromJSVal<std::vector<T> >(JSContext* cx, JS::HandleValue v, std::vector<T>& out) \
86 return FromJSVal_vector(cx, v, out); \
89 template<typename T
> bool ScriptInterface::FromJSProperty(JSContext
* cx
, const JS::HandleValue val
, const char* name
, T
& ret
)
95 JS::RootedObject
obj(cx
, &val
.toObject());
98 if (!JS_HasProperty(cx
, obj
, name
, &hasProperty
) || !hasProperty
)
101 JS::RootedValue
value(cx
);
102 if (!JS_GetProperty(cx
, obj
, name
, &value
))
105 return FromJSVal(cx
, value
, ret
);
108 #endif //INCLUDED_SCRIPTCONVERSIONS