|
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
|
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ |
|
3 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
4 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
6 |
|
7 #ifndef __NSTARRAYHELPERS_H__ |
|
8 #define __NSTARRAYHELPERS_H__ |
|
9 |
|
10 #include "jsapi.h" |
|
11 #include "nsContentUtils.h" |
|
12 #include "nsTArray.h" |
|
13 |
|
14 template <class T> |
|
15 inline nsresult |
|
16 nsTArrayToJSArray(JSContext* aCx, const nsTArray<T>& aSourceArray, |
|
17 JSObject** aResultArray) |
|
18 { |
|
19 MOZ_ASSERT(aCx); |
|
20 |
|
21 JS::Rooted<JSObject*> arrayObj(aCx, |
|
22 JS_NewArrayObject(aCx, aSourceArray.Length())); |
|
23 if (!arrayObj) { |
|
24 NS_WARNING("JS_NewArrayObject failed!"); |
|
25 return NS_ERROR_OUT_OF_MEMORY; |
|
26 } |
|
27 |
|
28 for (uint32_t index = 0; index < aSourceArray.Length(); index++) { |
|
29 nsCOMPtr<nsISupports> obj; |
|
30 nsresult rv = aSourceArray[index]->QueryInterface(NS_GET_IID(nsISupports), getter_AddRefs(obj)); |
|
31 NS_ENSURE_SUCCESS(rv, rv); |
|
32 |
|
33 JS::RootedValue wrappedVal(aCx); |
|
34 rv = nsContentUtils::WrapNative(aCx, obj, &wrappedVal); |
|
35 NS_ENSURE_SUCCESS(rv, rv); |
|
36 |
|
37 if (!JS_SetElement(aCx, arrayObj, index, wrappedVal)) { |
|
38 NS_WARNING("JS_SetElement failed!"); |
|
39 return NS_ERROR_FAILURE; |
|
40 } |
|
41 } |
|
42 |
|
43 if (!JS_FreezeObject(aCx, arrayObj)) { |
|
44 NS_WARNING("JS_FreezeObject failed!"); |
|
45 return NS_ERROR_FAILURE; |
|
46 } |
|
47 |
|
48 *aResultArray = arrayObj; |
|
49 return NS_OK; |
|
50 } |
|
51 |
|
52 template <> |
|
53 inline nsresult |
|
54 nsTArrayToJSArray<nsString>(JSContext* aCx, |
|
55 const nsTArray<nsString>& aSourceArray, |
|
56 JSObject** aResultArray) |
|
57 { |
|
58 MOZ_ASSERT(aCx); |
|
59 |
|
60 JS::Rooted<JSObject*> arrayObj(aCx, |
|
61 JS_NewArrayObject(aCx, aSourceArray.Length())); |
|
62 if (!arrayObj) { |
|
63 NS_WARNING("JS_NewArrayObject failed!"); |
|
64 return NS_ERROR_OUT_OF_MEMORY; |
|
65 } |
|
66 |
|
67 JS::Rooted<JSString*> s(aCx); |
|
68 for (uint32_t index = 0; index < aSourceArray.Length(); index++) { |
|
69 s = JS_NewUCStringCopyN(aCx, aSourceArray[index].BeginReading(), |
|
70 aSourceArray[index].Length()); |
|
71 |
|
72 if(!s) { |
|
73 NS_WARNING("Memory allocation error!"); |
|
74 return NS_ERROR_OUT_OF_MEMORY; |
|
75 } |
|
76 |
|
77 if (!JS_SetElement(aCx, arrayObj, index, s)) { |
|
78 NS_WARNING("JS_SetElement failed!"); |
|
79 return NS_ERROR_FAILURE; |
|
80 } |
|
81 } |
|
82 |
|
83 if (!JS_FreezeObject(aCx, arrayObj)) { |
|
84 NS_WARNING("JS_FreezeObject failed!"); |
|
85 return NS_ERROR_FAILURE; |
|
86 } |
|
87 |
|
88 *aResultArray = arrayObj; |
|
89 return NS_OK; |
|
90 } |
|
91 |
|
92 #endif /* __NSTARRAYHELPERS_H__ */ |