VirtualBox

source: vbox/trunk/include/VBox/com/array.h@ 99772

Last change on this file since 99772 was 99772, checked in by vboxsync, 18 months ago

VBox/com: Added SafeArray::push_front() and implemented a new (initial) testcase for the SafeArray glue code [Windows build fix].

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 54.2 KB
Line 
1/** @file
2 * MS COM / XPCOM Abstraction Layer - Safe array helper class declaration.
3 */
4
5/*
6 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
7 *
8 * This file is part of VirtualBox base platform packages, as
9 * available from https://www.virtualbox.org.
10 *
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License
13 * as published by the Free Software Foundation, in version 3 of the
14 * License.
15 *
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, see <https://www.gnu.org/licenses>.
23 *
24 * The contents of this file may alternatively be used under the terms
25 * of the Common Development and Distribution License Version 1.0
26 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
27 * in the VirtualBox distribution, in which case the provisions of the
28 * CDDL are applicable instead of those of the GPL.
29 *
30 * You may elect to license modified versions of this file under the
31 * terms and conditions of either the GPL or the CDDL or both.
32 *
33 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
34 */
35
36#ifndef VBOX_INCLUDED_com_array_h
37#define VBOX_INCLUDED_com_array_h
38#ifndef RT_WITHOUT_PRAGMA_ONCE
39# pragma once
40#endif
41
42
43/** @defgroup grp_com_arrays COM/XPCOM Arrays
44 * @ingroup grp_com
45 * @{
46 *
47 * The COM/XPCOM array support layer provides a cross-platform way to pass
48 * arrays to and from COM interface methods and consists of the com::SafeArray
49 * template and a set of ComSafeArray* macros part of which is defined in
50 * VBox/com/defs.h.
51 *
52 * This layer works with interface attributes and method parameters that have
53 * the 'safearray="yes"' attribute in the XIDL definition:
54 * @code
55
56 <interface name="ISomething" ...>
57
58 <method name="testArrays">
59 <param name="inArr" type="long" dir="in" safearray="yes"/>
60 <param name="outArr" type="long" dir="out" safearray="yes"/>
61 <param name="retArr" type="long" dir="return" safearray="yes"/>
62 </method>
63
64 </interface>
65
66 * @endcode
67 *
68 * Methods generated from this and similar definitions are implemented in
69 * component classes using the following declarations:
70 * @code
71
72 STDMETHOD(TestArrays)(ComSafeArrayIn(LONG, aIn),
73 ComSafeArrayOut(LONG, aOut),
74 ComSafeArrayOut(LONG, aRet));
75
76 * @endcode
77 *
78 * And the following function bodies:
79 * @code
80
81 STDMETHODIMP Component::TestArrays(ComSafeArrayIn(LONG, aIn),
82 ComSafeArrayOut(LONG, aOut),
83 ComSafeArrayOut(LONG, aRet))
84 {
85 if (ComSafeArrayInIsNull(aIn))
86 return E_INVALIDARG;
87 if (ComSafeArrayOutIsNull(aOut))
88 return E_POINTER;
89 if (ComSafeArrayOutIsNull(aRet))
90 return E_POINTER;
91
92 // Use SafeArray to access the input array parameter
93
94 com::SafeArray<LONG> in(ComSafeArrayInArg(aIn));
95
96 for (size_t i = 0; i < in.size(); ++ i)
97 LogFlow(("*** in[%u]=%d\n", i, in[i]));
98
99 // Use SafeArray to create the return array (the same technique is used
100 // for output array parameters)
101
102 SafeArray<LONG> ret(in.size() * 2);
103 for (size_t i = 0; i < in.size(); ++ i)
104 {
105 ret[i] = in[i];
106 ret[i + in.size()] = in[i] * 10;
107 }
108
109 ret.detachTo(ComSafeArrayOutArg(aRet));
110
111 return S_OK;
112 }
113
114 * @endcode
115 *
116 * Such methods can be called from the client code using the following pattern:
117 * @code
118
119 ComPtr<ISomething> component;
120
121 // ...
122
123 com::SafeArray<LONG> in(3);
124 in[0] = -1;
125 in[1] = -2;
126 in[2] = -3;
127
128 com::SafeArray<LONG> out;
129 com::SafeArray<LONG> ret;
130
131 HRESULT rc = component->TestArrays(ComSafeArrayAsInParam(in),
132 ComSafeArrayAsOutParam(out),
133 ComSafeArrayAsOutParam(ret));
134
135 if (SUCCEEDED(rc))
136 for (size_t i = 0; i < ret.size(); ++ i)
137 printf("*** ret[%u]=%d\n", i, ret[i]);
138
139 * @endcode
140 *
141 * For interoperability with standard C++ containers, there is a template
142 * constructor that takes such a container as argument and performs a deep copy
143 * of its contents. This can be used in method implementations like this:
144 * @code
145
146 STDMETHODIMP Component::COMGETTER(Values)(ComSafeArrayOut(int, aValues))
147 {
148 // ... assume there is a |std::list<int> mValues| data member
149
150 com::SafeArray<int> values(mValues);
151 values.detachTo(ComSafeArrayOutArg(aValues));
152
153 return S_OK;
154 }
155
156 * @endcode
157 *
158 * The current implementation of the SafeArray layer supports all types normally
159 * allowed in XIDL as array element types (including 'wstring' and 'uuid').
160 * However, 'pointer-to-...' types (e.g. 'long *', 'wstring *') are not
161 * supported and therefore cannot be used as element types.
162 *
163 * Note that for GUID arrays you should use SafeGUIDArray and
164 * SafeConstGUIDArray, customized SafeArray<> specializations.
165 *
166 * Also note that in order to pass input BSTR array parameters declared
167 * using the ComSafeArrayIn(IN_BSTR, aParam) macro to the SafeArray<>
168 * constructor using the ComSafeArrayInArg() macro, you should use IN_BSTR
169 * as the SafeArray<> template argument, not just BSTR.
170 *
171 * Arrays of interface pointers are also supported but they require to use a
172 * special SafeArray implementation, com::SafeIfacePointer, which takes the
173 * interface class name as a template argument (e.g.
174 * com::SafeIfacePointer\<IUnknown\>). This implementation functions
175 * identically to com::SafeArray.
176 */
177
178#ifdef VBOX_WITH_XPCOM
179# include <nsMemory.h>
180#endif
181
182#include "VBox/com/defs.h"
183
184#if RT_GNUC_PREREQ(4, 6) || (defined(_MSC_VER) && (_MSC_VER >= 1600))
185/** @def VBOX_WITH_TYPE_TRAITS
186 * Type traits are a C++ 11 feature, so not available everywhere (yet).
187 * Only GCC 4.6 or newer and MSVC++ 16.0 (Visual Studio 2010) or newer.
188 */
189# define VBOX_WITH_TYPE_TRAITS
190#endif
191
192#ifdef VBOX_WITH_TYPE_TRAITS
193# include <type_traits>
194#endif
195
196#include "VBox/com/ptr.h"
197#include "VBox/com/assert.h"
198#include "iprt/cpp/list.h"
199
200/** @def ComSafeArrayAsInParam
201 * Wraps the given com::SafeArray instance to generate an expression that is
202 * suitable for passing it to functions that take input safearray parameters
203 * declared using the ComSafeArrayIn macro.
204 *
205 * @param aArray com::SafeArray instance to pass as an input parameter.
206 */
207
208/** @def ComSafeArrayAsOutParam
209 * Wraps the given com::SafeArray instance to generate an expression that is
210 * suitable for passing it to functions that take output safearray parameters
211 * declared using the ComSafeArrayOut macro.
212 *
213 * @param aArray com::SafeArray instance to pass as an output parameter.
214 */
215
216/** @def ComSafeArrayNullInParam
217 * Helper for passing a NULL array parameter to a COM / XPCOM method.
218 */
219
220#ifdef VBOX_WITH_XPCOM
221
222# define ComSafeArrayAsInParam(aArray) \
223 (PRUint32)(aArray).size(), (aArray).__asInParam_Arr((aArray).raw())
224
225# define ComSafeArrayAsOutParam(aArray) \
226 (aArray).__asOutParam_Size(), (aArray).__asOutParam_Arr()
227
228# define ComSafeArrayNullInParam() 0, NULL
229
230#else /* !VBOX_WITH_XPCOM */
231
232# define ComSafeArrayAsInParam(aArray) (aArray).__asInParam()
233
234# define ComSafeArrayAsOutParam(aArray) (aArray).__asOutParam()
235
236# define ComSafeArrayNullInParam() (NULL)
237
238#endif /* !VBOX_WITH_XPCOM */
239
240/**
241 *
242 */
243namespace com
244{
245
246/** Used for dummy element access in com::SafeArray, avoiding crashes. */
247extern const char Zeroes[16];
248
249
250#ifdef VBOX_WITH_XPCOM
251
252////////////////////////////////////////////////////////////////////////////////
253
254/**
255 * Provides various helpers for SafeArray.
256 *
257 * @param T Type of array elements.
258 */
259template<typename T>
260struct SafeArrayTraits
261{
262protected:
263
264 /** Initializes memory for aElem. */
265 static void Init(T &aElem) { aElem = (T)0; }
266
267 /** Initializes memory occupied by aElem. */
268 static void Uninit(T &aElem) { RT_NOREF(aElem); }
269
270 /** Creates a deep copy of aFrom and stores it in aTo. */
271 static void Copy(const T &aFrom, T &aTo) { aTo = aFrom; }
272
273public:
274
275 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard (that
276 * in particular forbid casts of 'char **' to 'const char **'). Then initial
277 * reason for this magic is that XPIDL declares input strings
278 * (char/PRUnichar pointers) as const but doesn't do so for pointers to
279 * arrays. */
280 static T *__asInParam_Arr(T *aArr) { return aArr; }
281 static T *__asInParam_Arr(const T *aArr) { return const_cast<T *>(aArr); }
282};
283
284template<typename T>
285struct SafeArrayTraits<T *>
286{
287 // Arbitrary pointers are not supported
288};
289
290template<>
291struct SafeArrayTraits<PRUnichar *>
292{
293protected:
294
295 static void Init(PRUnichar * &aElem) { aElem = NULL; }
296
297 static void Uninit(PRUnichar * &aElem)
298 {
299 if (aElem)
300 {
301 ::SysFreeString(aElem);
302 aElem = NULL;
303 }
304 }
305
306 static void Copy(const PRUnichar * aFrom, PRUnichar * &aTo)
307 {
308 AssertCompile(sizeof(PRUnichar) == sizeof(OLECHAR));
309 aTo = aFrom ? ::SysAllocString((const OLECHAR *)aFrom) : NULL;
310 }
311
312public:
313
314 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard */
315 static const PRUnichar **__asInParam_Arr(PRUnichar **aArr)
316 {
317 return const_cast<const PRUnichar **>(aArr);
318 }
319 static const PRUnichar **__asInParam_Arr(const PRUnichar **aArr) { return aArr; }
320};
321
322template<>
323struct SafeArrayTraits<const PRUnichar *>
324{
325protected:
326
327 static void Init(const PRUnichar * &aElem) { aElem = NULL; }
328 static void Uninit(const PRUnichar * &aElem)
329 {
330 if (aElem)
331 {
332 ::SysFreeString(const_cast<PRUnichar *>(aElem));
333 aElem = NULL;
334 }
335 }
336
337 static void Copy(const PRUnichar * aFrom, const PRUnichar * &aTo)
338 {
339 AssertCompile(sizeof(PRUnichar) == sizeof(OLECHAR));
340 aTo = aFrom ? ::SysAllocString((const OLECHAR *)aFrom) : NULL;
341 }
342
343public:
344
345 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard */
346 static const PRUnichar **__asInParam_Arr(const PRUnichar **aArr) { return aArr; }
347};
348
349template<>
350struct SafeArrayTraits<nsID *>
351{
352protected:
353
354 static void Init(nsID * &aElem) { aElem = NULL; }
355
356 static void Uninit(nsID * &aElem)
357 {
358 if (aElem)
359 {
360 ::nsMemory::Free(aElem);
361 aElem = NULL;
362 }
363 }
364
365 static void Copy(const nsID * aFrom, nsID * &aTo)
366 {
367 if (aFrom)
368 {
369 aTo = (nsID *) ::nsMemory::Alloc(sizeof(nsID));
370 if (aTo)
371 *aTo = *aFrom;
372 }
373 else
374 aTo = NULL;
375 }
376
377 /* This specification is also reused for SafeConstGUIDArray, so provide a
378 * no-op Init() and Uninit() which are necessary for SafeArray<> but should
379 * be never called in context of SafeConstGUIDArray. */
380
381 static void Init(const nsID * &aElem) { NOREF(aElem); AssertFailed(); }
382 static void Uninit(const nsID * &aElem) { NOREF(aElem); AssertFailed(); }
383
384public:
385
386 /** Magic to workaround strict rules of par. 4.4.4 of the C++ standard. */
387 static const nsID **__asInParam_Arr(nsID **aArr)
388 {
389 return const_cast<const nsID **>(aArr);
390 }
391 static const nsID **__asInParam_Arr(const nsID **aArr) { return aArr; }
392};
393
394#else /* !VBOX_WITH_XPCOM */
395
396////////////////////////////////////////////////////////////////////////////////
397
398struct SafeArrayTraitsBase
399{
400protected:
401
402 static SAFEARRAY *CreateSafeArray(VARTYPE aVarType, SAFEARRAYBOUND *aBound)
403 { return SafeArrayCreate(aVarType, 1, aBound); }
404};
405
406/**
407 * Provides various helpers for SafeArray.
408 *
409 * @param T Type of array elements.
410 *
411 * Specializations of this template must provide the following methods:
412 *
413 // Returns the VARTYPE of COM SafeArray elements to be used for T
414 static VARTYPE VarType();
415
416 // Returns the number of VarType() elements necessary for aSize
417 // elements of T
418 static ULONG VarCount(size_t aSize);
419
420 // Returns the number of elements of T that fit into the given number of
421 // VarType() elements (opposite to VarCount(size_t aSize)).
422 static size_t Size(ULONG aVarCount);
423
424 // Creates a deep copy of aFrom and stores it in aTo
425 static void Copy(ULONG aFrom, ULONG &aTo);
426 */
427template<typename T>
428struct SafeArrayTraits : public SafeArrayTraitsBase
429{
430protected:
431
432 // Arbitrary types are treated as passed by value and each value is
433 // represented by a number of VT_Ix type elements where VT_Ix has the
434 // biggest possible bitness necessary to represent T w/o a gap. COM enums
435 // fall into this category.
436
437 static VARTYPE VarType()
438 {
439#ifdef VBOX_WITH_TYPE_TRAITS
440 if ( std::is_integral<T>::value
441 && !std::is_signed<T>::value)
442 {
443 if (sizeof(T) % 8 == 0) return VT_UI8;
444 if (sizeof(T) % 4 == 0) return VT_UI4;
445 if (sizeof(T) % 2 == 0) return VT_UI2;
446 return VT_UI1;
447 }
448#endif
449 if (sizeof(T) % 8 == 0) return VT_I8;
450 if (sizeof(T) % 4 == 0) return VT_I4;
451 if (sizeof(T) % 2 == 0) return VT_I2;
452 return VT_I1;
453 }
454
455 /*
456 * Fallback method in case type traits (VBOX_WITH_TYPE_TRAITS)
457 * are not available. Always returns unsigned types.
458 */
459 static VARTYPE VarTypeUnsigned()
460 {
461 if (sizeof(T) % 8 == 0) return VT_UI8;
462 if (sizeof(T) % 4 == 0) return VT_UI4;
463 if (sizeof(T) % 2 == 0) return VT_UI2;
464 return VT_UI1;
465 }
466
467 static ULONG VarCount(size_t aSize)
468 {
469 if (sizeof(T) % 8 == 0) return (ULONG)((sizeof(T) / 8) * aSize);
470 if (sizeof(T) % 4 == 0) return (ULONG)((sizeof(T) / 4) * aSize);
471 if (sizeof(T) % 2 == 0) return (ULONG)((sizeof(T) / 2) * aSize);
472 return (ULONG)(sizeof(T) * aSize);
473 }
474
475 static size_t Size(ULONG aVarCount)
476 {
477 if (sizeof(T) % 8 == 0) return (size_t)(aVarCount * 8) / sizeof(T);
478 if (sizeof(T) % 4 == 0) return (size_t)(aVarCount * 4) / sizeof(T);
479 if (sizeof(T) % 2 == 0) return (size_t)(aVarCount * 2) / sizeof(T);
480 return (size_t) aVarCount / sizeof(T);
481 }
482
483 static void Copy(T aFrom, T &aTo) { aTo = aFrom; }
484};
485
486template<typename T>
487struct SafeArrayTraits<T *>
488{
489 // Arbitrary pointer types are not supported
490};
491
492/* Although the generic SafeArrayTraits template would work for all integers,
493 * we specialize it for some of them in order to use the correct VT_ type */
494
495template<>
496struct SafeArrayTraits<LONG> : public SafeArrayTraitsBase
497{
498protected:
499
500 static VARTYPE VarType() { return VT_I4; }
501 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
502 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
503
504 static void Copy(LONG aFrom, LONG &aTo) { aTo = aFrom; }
505};
506
507template<>
508struct SafeArrayTraits<ULONG> : public SafeArrayTraitsBase
509{
510protected:
511
512 static VARTYPE VarType() { return VT_UI4; }
513 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
514 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
515
516 static void Copy(ULONG aFrom, ULONG &aTo) { aTo = aFrom; }
517};
518
519template<>
520struct SafeArrayTraits<LONG64> : public SafeArrayTraitsBase
521{
522protected:
523
524 static VARTYPE VarType() { return VT_I8; }
525 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
526 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
527
528 static void Copy(LONG64 aFrom, LONG64 &aTo) { aTo = aFrom; }
529};
530
531template<>
532struct SafeArrayTraits<ULONG64> : public SafeArrayTraitsBase
533{
534protected:
535
536 static VARTYPE VarType() { return VT_UI8; }
537 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
538 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
539
540 static void Copy(ULONG64 aFrom, ULONG64 &aTo) { aTo = aFrom; }
541};
542
543template<>
544struct SafeArrayTraits<BSTR> : public SafeArrayTraitsBase
545{
546protected:
547
548 static VARTYPE VarType() { return VT_BSTR; }
549 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
550 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
551
552 static void Copy(BSTR aFrom, BSTR &aTo)
553 {
554 aTo = aFrom ? ::SysAllocString((const OLECHAR *)aFrom) : NULL;
555 }
556};
557
558template<>
559struct SafeArrayTraits<GUID> : public SafeArrayTraitsBase
560{
561protected:
562
563 /* Use the 64-bit unsigned integer type for GUID */
564 static VARTYPE VarType() { return VT_UI8; }
565
566 /* GUID is 128 bit, so we need two VT_UI8 */
567 static ULONG VarCount(size_t aSize)
568 {
569 AssertCompileSize(GUID, 16);
570 return (ULONG)(aSize * 2);
571 }
572
573 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount / 2; }
574
575 static void Copy(GUID aFrom, GUID &aTo) { aTo = aFrom; }
576};
577
578/**
579 * Helper for SafeArray::__asOutParam() that automatically updates m.raw after a
580 * non-NULL m.arr assignment.
581 */
582class OutSafeArrayDipper
583{
584 OutSafeArrayDipper(SAFEARRAY **aArr, void **aRaw)
585 : arr(aArr), raw(aRaw) { Assert(*aArr == NULL && *aRaw == NULL); }
586
587 SAFEARRAY **arr;
588 void **raw;
589
590 template<class, class> friend class SafeArray;
591
592public:
593
594 ~OutSafeArrayDipper()
595 {
596 if (*arr != NULL)
597 {
598 HRESULT rc = SafeArrayAccessData(*arr, raw);
599 AssertComRC(rc);
600 }
601 }
602
603 operator SAFEARRAY **() { return arr; }
604};
605
606#endif /* !VBOX_WITH_XPCOM */
607
608////////////////////////////////////////////////////////////////////////////////
609
610/**
611 * The SafeArray class represents the safe array type used in COM to pass arrays
612 * to/from interface methods.
613 *
614 * This helper class hides all MSCOM/XPCOM specific implementation details and,
615 * together with ComSafeArrayIn, ComSafeArrayOut and ComSafeArrayRet macros,
616 * provides a platform-neutral way to handle safe arrays in the method
617 * implementation.
618 *
619 * When an instance of this class is destroyed, it automatically frees all
620 * resources occupied by individual elements of the array as well as by the
621 * array itself. However, when the value of an element is manually changed
622 * using #operator[] or by accessing array data through the #raw() pointer, it is
623 * the caller's responsibility to free resources occupied by the previous
624 * element's value.
625 *
626 * Also, objects of this class do not support copy and assignment operations and
627 * therefore cannot be returned from functions by value. In other words, this
628 * class is just a temporary storage for handling interface method calls and not
629 * intended to be used to store arrays as data members and such -- you should
630 * use normal list/vector classes for that.
631 *
632 * @note The current implementation supports only one-dimensional arrays.
633 *
634 * @note This class is not thread-safe.
635 */
636template<typename T, class Traits = SafeArrayTraits<T> >
637class SafeArray : public Traits
638{
639public:
640
641 /**
642 * Creates a null array.
643 */
644 SafeArray() { }
645
646 /**
647 * Creates a new array of the given size. All elements of the newly created
648 * array initialized with null values.
649 *
650 * @param aSize Initial number of elements in the array.
651 *
652 * @note If this object remains null after construction it means that there
653 * was not enough memory for creating an array of the requested size.
654 * The constructor will also assert in this case.
655 */
656 SafeArray(size_t aSize) { resize(aSize); }
657
658 /**
659 * Weakly attaches this instance to the existing array passed in a method
660 * parameter declared using the ComSafeArrayIn macro. When using this call,
661 * always wrap the parameter name in the ComSafeArrayInArg macro call like
662 * this:
663 * <pre>
664 * SafeArray safeArray(ComSafeArrayInArg(aArg));
665 * </pre>
666 *
667 * Note that this constructor doesn't take the ownership of the array. In
668 * particular, it means that operations that operate on the ownership (e.g.
669 * #detachTo()) are forbidden and will assert.
670 *
671 * @param aArg Input method parameter to attach to.
672 */
673 SafeArray(ComSafeArrayIn(T, aArg))
674 {
675 if (aArg)
676 {
677#ifdef VBOX_WITH_XPCOM
678
679 m.size = aArgSize;
680 m.arr = aArg;
681 m.isWeak = true;
682
683#else /* !VBOX_WITH_XPCOM */
684
685 SAFEARRAY *arg = aArg;
686
687 AssertReturnVoid(arg->cDims == 1);
688
689 VARTYPE vt;
690 HRESULT rc = SafeArrayGetVartype(arg, &vt);
691 AssertComRCReturnVoid(rc);
692# ifndef VBOX_WITH_TYPE_TRAITS
693 AssertMsgReturnVoid(
694 vt == VarType()
695 || vt == VarTypeUnsigned(),
696 ("Expected vartype %d or %d, got %d.\n",
697 VarType(), VarTypeUnsigned(), vt));
698# else /* !VBOX_WITH_TYPE_TRAITS */
699 AssertMsgReturnVoid(
700 vt == VarType(),
701 ("Expected vartype %d, got %d.\n",
702 VarType(), vt));
703# endif
704 rc = SafeArrayAccessData(arg, (void HUGEP **)&m.raw);
705 AssertComRCReturnVoid(rc);
706
707 m.arr = arg;
708 m.isWeak = true;
709
710#endif /* !VBOX_WITH_XPCOM */
711 }
712 }
713
714 /**
715 * Creates a deep copy of the given standard C++ container that stores
716 * T objects.
717 *
718 * @param aCntr Container object to copy.
719 *
720 * @tparam C Standard C++ container template class (normally deduced from
721 * @c aCntr).
722 */
723 template<template<typename, typename> class C, class A>
724 SafeArray(const C<T, A> & aCntr)
725 {
726 resize(aCntr.size());
727 AssertReturnVoid(!isNull());
728
729 size_t i = 0;
730 for (typename C<T, A>::const_iterator it = aCntr.begin();
731 it != aCntr.end(); ++ it, ++ i)
732#ifdef VBOX_WITH_XPCOM
733 SafeArray::Copy(*it, m.arr[i]);
734#else
735 Copy(*it, m.raw[i]);
736#endif
737 }
738
739 /**
740 * Creates a deep copy of the given standard C++ map that stores T objects
741 * as values.
742 *
743 * @param aMap Map object to copy.
744 *
745 * @tparam C Standard C++ map template class (normally deduced from
746 * @a aMap).
747 * @tparam L Standard C++ compare class (deduced from @a aMap).
748 * @tparam A Standard C++ allocator class (deduced from @a aMap).
749 * @tparam K Map key class (deduced from @a aMap).
750 */
751 template<template<typename, typename, typename, typename>
752 class C, class L, class A, class K>
753 SafeArray(const C<K, T, L, A> & aMap)
754 {
755 typedef C<K, T, L, A> Map;
756
757 resize(aMap.size());
758 AssertReturnVoid(!isNull());
759
760 size_t i = 0;
761 for (typename Map::const_iterator it = aMap.begin();
762 it != aMap.end(); ++ it, ++ i)
763#ifdef VBOX_WITH_XPCOM
764 Copy(it->second, m.arr[i]);
765#else
766 Copy(it->second, m.raw[i]);
767#endif
768 }
769
770 /**
771 * Destroys this instance after calling #setNull() to release allocated
772 * resources. See #setNull() for more details.
773 */
774 virtual ~SafeArray() { setNull(); }
775
776 /**
777 * Returns @c true if this instance represents a null array.
778 */
779 bool isNull() const { return m.arr == NULL; }
780
781 /**
782 * Returns @c true if this instance does not represents a null array.
783 */
784 bool isNotNull() const { return m.arr != NULL; }
785
786 /**
787 * Resets this instance to null and, if this instance is not a weak one,
788 * releases any resources occupied by the array data.
789 *
790 * @note This method destroys (cleans up) all elements of the array using
791 * the corresponding cleanup routine for the element type before the
792 * array itself is destroyed.
793 */
794 virtual void setNull() { m.uninit(); }
795
796 /**
797 * Returns @c true if this instance is weak. A weak instance doesn't own the
798 * array data and therefore operations manipulating the ownership (e.g.
799 * #detachTo()) are forbidden and will assert.
800 */
801 bool isWeak() const { return m.isWeak; }
802
803 /** Number of elements in the array. */
804 size_t size() const
805 {
806#ifdef VBOX_WITH_XPCOM
807 if (m.arr)
808 return m.size;
809 return 0;
810#else
811 if (m.arr)
812 return Size(m.arr->rgsabound[0].cElements);
813 return 0;
814#endif
815 }
816
817 /**
818 * Prepends a copy of the given element at the beginning of the array.
819 *
820 * The array size is increased by one by this method and the additional
821 * space is allocated as needed.
822 *
823 * This method is handy in cases where you want to assign a copy of the
824 * existing value to the array element, for example:
825 * <tt>Bstr string; array.push_front(string);</tt>. If you create a string
826 * just to put it in the array, you may find #appendedRaw() more useful.
827 *
828 * @param aElement Element to prepend.
829 *
830 * @return @c true on success and @c false if there is not enough
831 * memory for resizing.
832 */
833 bool push_front(const T &aElement)
834 {
835 if (!ensureCapacity(size() + 1))
836 return false;
837
838 for (size_t i = size(); i > 0; --i)
839 {
840#ifdef VBOX_WITH_XPCOM
841 SafeArray::Copy(m.arr[i - 1], m.arr[i]);
842#else
843 Copy(m.raw[i - 1], m.raw[i]);
844#endif
845 }
846
847#ifdef VBOX_WITH_XPCOM
848 SafeArray::Copy(aElement, m.arr[0]);
849 ++ m.size;
850#else
851 Copy(aElement, m.raw[0]);
852#endif
853 return true;
854 }
855
856 /**
857 * Appends a copy of the given element at the end of the array.
858 *
859 * The array size is increased by one by this method and the additional
860 * space is allocated as needed.
861 *
862 * This method is handy in cases where you want to assign a copy of the
863 * existing value to the array element, for example:
864 * <tt>Bstr string; array.push_back(string);</tt>. If you create a string
865 * just to put it in the array, you may find #appendedRaw() more useful.
866 *
867 * @param aElement Element to append.
868 *
869 * @return @c true on success and @c false if there is not enough
870 * memory for resizing.
871 */
872 bool push_back(const T &aElement)
873 {
874 if (!ensureCapacity(size() + 1))
875 return false;
876
877#ifdef VBOX_WITH_XPCOM
878 SafeArray::Copy(aElement, m.arr[m.size]);
879 ++ m.size;
880#else
881 Copy(aElement, m.raw[size() - 1]);
882#endif
883 return true;
884 }
885
886 /**
887 * Appends an empty element at the end of the array and returns a raw
888 * pointer to it suitable for assigning a raw value (w/o constructing a
889 * copy).
890 *
891 * The array size is increased by one by this method and the additional
892 * space is allocated as needed.
893 *
894 * Note that in case of raw assignment, value ownership (for types with
895 * dynamically allocated data and for interface pointers) is transferred to
896 * the safe array object.
897 *
898 * This method is handy for operations like
899 * <tt>Bstr("foo").detachTo(array.appendedRaw());</tt>. Don't use it as
900 * an l-value (<tt>array.appendedRaw() = SysAllocString(L"tralala");</tt>)
901 * since this doesn't check for a NULL condition; use #resize() instead. If
902 * you need to assign a copy of the existing value instead of transferring
903 * the ownership, look at #push_back().
904 *
905 * @return Raw pointer to the added element or NULL if no memory.
906 */
907 T *appendedRaw()
908 {
909 if (!ensureCapacity(size() + 1))
910 return NULL;
911
912#ifdef VBOX_WITH_XPCOM
913 SafeArray::Init(m.arr[m.size]);
914 ++ m.size;
915 return &m.arr[m.size - 1];
916#else
917 /* nothing to do here, SafeArrayCreate() has performed element
918 * initialization */
919 return &m.raw[size() - 1];
920#endif
921 }
922
923 /**
924 * Resizes the array preserving its contents when possible. If the new size
925 * is larger than the old size, new elements are initialized with null
926 * values. If the new size is less than the old size, the contents of the
927 * array beyond the new size is lost.
928 *
929 * @param aNewSize New number of elements in the array.
930 * @return @c true on success and @c false if there is not enough
931 * memory for resizing.
932 */
933 bool resize(size_t aNewSize)
934 {
935 if (!ensureCapacity(aNewSize))
936 return false;
937
938#ifdef VBOX_WITH_XPCOM
939
940 if (m.size < aNewSize)
941 {
942 /* initialize the new elements */
943 for (size_t i = m.size; i < aNewSize; ++ i)
944 SafeArray::Init(m.arr[i]);
945 }
946
947 /** @todo Fix this! */
948 m.size = (PRUint32)aNewSize;
949#else
950 /* nothing to do here, SafeArrayCreate() has performed element
951 * initialization */
952#endif
953 return true;
954 }
955
956 /**
957 * Reinitializes this instance by preallocating space for the given number
958 * of elements. The previous array contents is lost.
959 *
960 * @param aNewSize New number of elements in the array.
961 * @return @c true on success and @c false if there is not enough
962 * memory for resizing.
963 */
964 bool reset(size_t aNewSize)
965 {
966 m.uninit();
967 return resize(aNewSize);
968 }
969
970 /**
971 * Returns a pointer to the raw array data. Use this raw pointer with care
972 * as no type or bound checking is done for you in this case.
973 *
974 * @note This method returns @c NULL when this instance is null.
975 * @see #operator[]
976 */
977 T *raw()
978 {
979#ifdef VBOX_WITH_XPCOM
980 return m.arr;
981#else
982 return m.raw;
983#endif
984 }
985
986 /**
987 * Const version of #raw().
988 */
989 const T *raw() const
990 {
991#ifdef VBOX_WITH_XPCOM
992 return m.arr;
993#else
994 return m.raw;
995#endif
996 }
997
998 /**
999 * Array access operator that returns an array element by reference. A bit
1000 * safer than #raw(): asserts and returns a reference to a static zero
1001 * element (const, i.e. writes will fail) if this instance is null or
1002 * if the index is out of bounds.
1003 *
1004 * @note For weak instances, this call will succeed but the behavior of
1005 * changing the contents of an element of the weak array instance is
1006 * undefined and may lead to a program crash on some platforms.
1007 */
1008 T &operator[] (size_t aIdx)
1009 {
1010 /** @todo r=klaus should do this as a AssertCompile, but cannot find a way which works. */
1011 Assert(sizeof(T) <= sizeof(Zeroes));
1012 AssertReturn(m.arr != NULL, *(T *)&Zeroes[0]);
1013 AssertReturn(aIdx < size(), *(T *)&Zeroes[0]);
1014#ifdef VBOX_WITH_XPCOM
1015 return m.arr[aIdx];
1016#else
1017 AssertReturn(m.raw != NULL, *(T *)&Zeroes[0]);
1018 return m.raw[aIdx];
1019#endif
1020 }
1021
1022 /**
1023 * Const version of #operator[] that returns an array element by value.
1024 */
1025 const T operator[] (size_t aIdx) const
1026 {
1027 AssertReturn(m.arr != NULL, *(const T *)&Zeroes[0]);
1028 AssertReturn(aIdx < size(), *(const T *)&Zeroes[0]);
1029#ifdef VBOX_WITH_XPCOM
1030 return m.arr[aIdx];
1031#else
1032 AssertReturn(m.raw != NULL, *(const T *)&Zeroes[0]);
1033 return m.raw[aIdx];
1034#endif
1035 }
1036
1037 /**
1038 * Creates a copy of this array and stores it in a method parameter declared
1039 * using the ComSafeArrayOut macro. When using this call, always wrap the
1040 * parameter name in the ComSafeArrayOutArg macro call like this:
1041 * <pre>
1042 * safeArray.cloneTo(ComSafeArrayOutArg(aArg));
1043 * </pre>
1044 *
1045 * @note It is assumed that the ownership of the returned copy is
1046 * transferred to the caller of the method and he is responsible to free the
1047 * array data when it is no longer needed.
1048 *
1049 * @param aArg Output method parameter to clone to.
1050 */
1051 virtual const SafeArray &cloneTo(ComSafeArrayOut(T, aArg)) const
1052 {
1053 /// @todo Implement me!
1054#ifdef VBOX_WITH_XPCOM
1055 NOREF(aArgSize);
1056 NOREF(aArg);
1057#else
1058 NOREF(aArg);
1059#endif
1060 AssertFailedReturn(*this);
1061 }
1062
1063 HRESULT cloneTo(SafeArray<T>& aOther) const
1064 {
1065 aOther.reset(size());
1066 return aOther.initFrom(*this);
1067 }
1068
1069
1070 /**
1071 * Transfers the ownership of this array's data to the specified location
1072 * declared using the ComSafeArrayOut macro and makes this array a null
1073 * array. When using this call, always wrap the parameter name in the
1074 * ComSafeArrayOutArg macro call like this:
1075 * <pre>
1076 * safeArray.detachTo(ComSafeArrayOutArg(aArg));
1077 * </pre>
1078 *
1079 * Detaching the null array is also possible in which case the location will
1080 * receive NULL.
1081 *
1082 * @note Since the ownership of the array data is transferred to the
1083 * caller of the method, he is responsible to free the array data when it is
1084 * no longer needed.
1085 *
1086 * @param aArg Location to detach to.
1087 */
1088 virtual SafeArray &detachTo(ComSafeArrayOut(T, aArg))
1089 {
1090 AssertReturn(!m.isWeak, *this);
1091
1092#ifdef VBOX_WITH_XPCOM
1093
1094 AssertReturn(aArgSize != NULL, *this);
1095 AssertReturn(aArg != NULL, *this);
1096
1097 *aArgSize = m.size;
1098 *aArg = m.arr;
1099
1100 m.isWeak = false;
1101 m.size = 0;
1102 m.arr = NULL;
1103
1104#else /* !VBOX_WITH_XPCOM */
1105
1106 AssertReturn(aArg != NULL, *this);
1107 *aArg = m.arr;
1108
1109 if (m.raw)
1110 {
1111 HRESULT rc = SafeArrayUnaccessData(m.arr);
1112 AssertComRCReturn(rc, *this);
1113 m.raw = NULL;
1114 }
1115
1116 m.isWeak = false;
1117 m.arr = NULL;
1118
1119#endif /* !VBOX_WITH_XPCOM */
1120
1121 return *this;
1122 }
1123
1124 /**
1125 * Returns a copy of this SafeArray as RTCList<T>.
1126 */
1127 RTCList<T> toList()
1128 {
1129 RTCList<T> list(size());
1130 for (size_t i = 0; i < size(); ++i)
1131#ifdef VBOX_WITH_XPCOM
1132 list.append(m.arr[i]);
1133#else
1134 list.append(m.raw[i]);
1135#endif
1136 return list;
1137 }
1138
1139 inline HRESULT initFrom(const com::SafeArray<T> & aRef);
1140 inline HRESULT initFrom(const T* aPtr, size_t aSize);
1141
1142 // Public methods for internal purposes only.
1143
1144#ifdef VBOX_WITH_XPCOM
1145
1146 /** Internal function. Never call it directly. */
1147 PRUint32 *__asOutParam_Size() { setNull(); return &m.size; }
1148
1149 /** Internal function Never call it directly. */
1150 T **__asOutParam_Arr() { Assert(isNull()); return &m.arr; }
1151
1152#else /* !VBOX_WITH_XPCOM */
1153
1154 /** Internal function Never call it directly. */
1155 SAFEARRAY * __asInParam() { return m.arr; }
1156
1157 /** Internal function Never call it directly. */
1158 OutSafeArrayDipper __asOutParam()
1159 { setNull(); return OutSafeArrayDipper(&m.arr, (void **)&m.raw); }
1160
1161#endif /* !VBOX_WITH_XPCOM */
1162
1163 static const SafeArray Null;
1164
1165protected:
1166
1167 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP(SafeArray);
1168
1169 /**
1170 * Ensures that the array is big enough to contain aNewSize elements.
1171 *
1172 * If the new size is greater than the current capacity, a new array is
1173 * allocated and elements from the old array are copied over. The size of
1174 * the array doesn't change, only the capacity increases (which is always
1175 * greater than the size). Note that the additionally allocated elements are
1176 * left uninitialized by this method.
1177 *
1178 * If the new size is less than the current size, the existing array is
1179 * truncated to the specified size and the elements outside the new array
1180 * boundary are freed.
1181 *
1182 * If the new size is the same as the current size, nothing happens.
1183 *
1184 * @param aNewSize New size of the array.
1185 *
1186 * @return @c true on success and @c false if not enough memory.
1187 */
1188 bool ensureCapacity(size_t aNewSize)
1189 {
1190 AssertReturn(!m.isWeak, false);
1191
1192#ifdef VBOX_WITH_XPCOM
1193
1194 /* Note: we distinguish between a null array and an empty (zero
1195 * elements) array. Therefore we never use zero in malloc (even if
1196 * aNewSize is zero) to make sure we get a non-null pointer. */
1197
1198 if (m.size == aNewSize && m.arr != NULL)
1199 return true;
1200
1201 /* Allocate in 16-byte pieces. */
1202 size_t newCapacity = RT_MAX((aNewSize + 15) / 16 * 16, 16);
1203
1204 if (m.capacity != newCapacity)
1205 {
1206 T *newArr = (T *)nsMemory::Alloc(RT_MAX(newCapacity, 1) * sizeof(T));
1207 AssertReturn(newArr != NULL, false);
1208
1209 if (m.arr != NULL)
1210 {
1211 if (m.size > aNewSize)
1212 {
1213 /* Truncation takes place, uninit exceeding elements and
1214 * shrink the size. */
1215 for (size_t i = aNewSize; i < m.size; ++ i)
1216 SafeArray::Uninit(m.arr[i]);
1217
1218 /** @todo Fix this! */
1219 m.size = (PRUint32)aNewSize;
1220 }
1221
1222 /* Copy the old contents. */
1223 memcpy(newArr, m.arr, m.size * sizeof(T));
1224 nsMemory::Free((void *)m.arr);
1225 }
1226
1227 m.arr = newArr;
1228 }
1229 else
1230 {
1231 if (m.size > aNewSize)
1232 {
1233 /* Truncation takes place, uninit exceeding elements and
1234 * shrink the size. */
1235 for (size_t i = aNewSize; i < m.size; ++ i)
1236 SafeArray::Uninit(m.arr[i]);
1237
1238 /** @todo Fix this! */
1239 m.size = (PRUint32)aNewSize;
1240 }
1241 }
1242
1243 /** @todo Fix this! */
1244 m.capacity = (PRUint32)newCapacity;
1245
1246#else
1247
1248 SAFEARRAYBOUND bound = { VarCount(aNewSize), 0 };
1249 HRESULT rc;
1250
1251 if (m.arr == NULL)
1252 {
1253 m.arr = CreateSafeArray(VarType(), &bound);
1254 AssertReturn(m.arr != NULL, false);
1255 }
1256 else
1257 {
1258 SafeArrayUnaccessData(m.arr);
1259
1260 rc = SafeArrayRedim(m.arr, &bound);
1261 AssertComRCReturn(rc == S_OK, false);
1262 }
1263
1264 rc = SafeArrayAccessData(m.arr, (void HUGEP **)&m.raw);
1265 AssertComRCReturn(rc, false);
1266
1267#endif
1268 return true;
1269 }
1270
1271 struct Data
1272 {
1273 Data()
1274 : isWeak(false)
1275#ifdef VBOX_WITH_XPCOM
1276 , capacity(0), size(0), arr(NULL)
1277#else
1278 , arr(NULL), raw(NULL)
1279#endif
1280 {}
1281
1282 ~Data() { uninit(); }
1283
1284 void uninit()
1285 {
1286#ifdef VBOX_WITH_XPCOM
1287
1288 if (arr)
1289 {
1290 if (!isWeak)
1291 {
1292 for (size_t i = 0; i < size; ++ i)
1293 SafeArray::Uninit(arr[i]);
1294
1295 nsMemory::Free((void *)arr);
1296 }
1297 else
1298 isWeak = false;
1299
1300 arr = NULL;
1301 }
1302
1303 size = capacity = 0;
1304
1305#else /* !VBOX_WITH_XPCOM */
1306
1307 if (arr)
1308 {
1309 if (raw)
1310 {
1311 SafeArrayUnaccessData(arr);
1312 raw = NULL;
1313 }
1314
1315 if (!isWeak)
1316 {
1317 HRESULT rc = SafeArrayDestroy(arr);
1318 AssertComRCReturnVoid(rc);
1319 }
1320 else
1321 isWeak = false;
1322
1323 arr = NULL;
1324 }
1325
1326#endif /* !VBOX_WITH_XPCOM */
1327 }
1328
1329 bool isWeak : 1;
1330
1331#ifdef VBOX_WITH_XPCOM
1332 PRUint32 capacity;
1333 PRUint32 size;
1334 T *arr;
1335#else
1336 SAFEARRAY *arr;
1337 T *raw;
1338#endif
1339 };
1340
1341 Data m;
1342};
1343
1344/* Few fast specializations for primitive array types */
1345template<>
1346inline HRESULT com::SafeArray<BYTE>::initFrom(const com::SafeArray<BYTE> & aRef)
1347{
1348 size_t sSize = aRef.size();
1349 if (resize(sSize))
1350 {
1351 ::memcpy(raw(), aRef.raw(), sSize);
1352 return S_OK;
1353 }
1354 return E_OUTOFMEMORY;
1355}
1356template<>
1357inline HRESULT com::SafeArray<BYTE>::initFrom(const BYTE *aPtr, size_t aSize)
1358{
1359 if (resize(aSize))
1360 {
1361 ::memcpy(raw(), aPtr, aSize);
1362 return S_OK;
1363 }
1364 return E_OUTOFMEMORY;
1365}
1366
1367
1368template<>
1369inline HRESULT com::SafeArray<SHORT>::initFrom(const com::SafeArray<SHORT> & aRef)
1370{
1371 size_t sSize = aRef.size();
1372 if (resize(sSize))
1373 {
1374 ::memcpy(raw(), aRef.raw(), sSize * sizeof(SHORT));
1375 return S_OK;
1376 }
1377 return E_OUTOFMEMORY;
1378}
1379template<>
1380inline HRESULT com::SafeArray<SHORT>::initFrom(const SHORT *aPtr, size_t aSize)
1381{
1382 if (resize(aSize))
1383 {
1384 ::memcpy(raw(), aPtr, aSize * sizeof(SHORT));
1385 return S_OK;
1386 }
1387 return E_OUTOFMEMORY;
1388}
1389
1390template<>
1391inline HRESULT com::SafeArray<USHORT>::initFrom(const com::SafeArray<USHORT> & aRef)
1392{
1393 size_t sSize = aRef.size();
1394 if (resize(sSize))
1395 {
1396 ::memcpy(raw(), aRef.raw(), sSize * sizeof(USHORT));
1397 return S_OK;
1398 }
1399 return E_OUTOFMEMORY;
1400}
1401template<>
1402inline HRESULT com::SafeArray<USHORT>::initFrom(const USHORT *aPtr, size_t aSize)
1403{
1404 if (resize(aSize))
1405 {
1406 ::memcpy(raw(), aPtr, aSize * sizeof(USHORT));
1407 return S_OK;
1408 }
1409 return E_OUTOFMEMORY;
1410}
1411
1412template<>
1413inline HRESULT com::SafeArray<LONG>::initFrom(const com::SafeArray<LONG> & aRef)
1414{
1415 size_t sSize = aRef.size();
1416 if (resize(sSize))
1417 {
1418 ::memcpy(raw(), aRef.raw(), sSize * sizeof(LONG));
1419 return S_OK;
1420 }
1421 return E_OUTOFMEMORY;
1422}
1423template<>
1424inline HRESULT com::SafeArray<LONG>::initFrom(const LONG *aPtr, size_t aSize)
1425{
1426 if (resize(aSize))
1427 {
1428 ::memcpy(raw(), aPtr, aSize * sizeof(LONG));
1429 return S_OK;
1430 }
1431 return E_OUTOFMEMORY;
1432}
1433
1434
1435////////////////////////////////////////////////////////////////////////////////
1436
1437#ifdef VBOX_WITH_XPCOM
1438
1439/**
1440 * Version of com::SafeArray for arrays of GUID.
1441 *
1442 * In MS COM, GUID arrays store GUIDs by value and therefore input arrays are
1443 * represented using |GUID *| and out arrays -- using |GUID **|. In XPCOM,
1444 * GUID arrays store pointers to nsID so that input arrays are |const nsID **|
1445 * and out arrays are |nsID ***|. Due to this difference, it is impossible to
1446 * work with arrays of GUID on both platforms by simply using com::SafeArray
1447 * <GUID>. This class is intended to provide some level of cross-platform
1448 * behavior.
1449 *
1450 * The basic usage pattern is basically similar to com::SafeArray<> except that
1451 * you use ComSafeGUIDArrayIn* and ComSafeGUIDArrayOut* macros instead of
1452 * ComSafeArrayIn* and ComSafeArrayOut*. Another important nuance is that the
1453 * raw() array type is different (nsID **, or GUID ** on XPCOM and GUID * on MS
1454 * COM) so it is recommended to use operator[] instead which always returns a
1455 * GUID by value.
1456 *
1457 * Note that due to const modifiers, you cannot use SafeGUIDArray for input GUID
1458 * arrays. Please use SafeConstGUIDArray for this instead.
1459 *
1460 * Other than mentioned above, the functionality of this class is equivalent to
1461 * com::SafeArray<>. See the description of that template and its methods for
1462 * more information.
1463 *
1464 * Output GUID arrays are handled by a separate class, SafeGUIDArrayOut, since
1465 * this class cannot handle them because of const modifiers.
1466 */
1467class SafeGUIDArray : public SafeArray<nsID *>
1468{
1469public:
1470
1471 typedef SafeArray<nsID *> Base;
1472
1473 class nsIDRef
1474 {
1475 public:
1476
1477 nsIDRef(nsID * &aVal) : mVal(aVal) { AssertCompile(sizeof(nsID) <= sizeof(Zeroes)); }
1478
1479 operator const nsID &() const { return mVal ? *mVal : *(const nsID *)&Zeroes[0]; }
1480 operator nsID() const { return mVal ? *mVal : *(nsID *)&Zeroes[0]; }
1481
1482 const nsID *operator&() const { return mVal ? mVal : (const nsID *)&Zeroes[0]; }
1483
1484 nsIDRef &operator= (const nsID &aThat)
1485 {
1486 if (mVal == NULL)
1487 Copy(&aThat, mVal);
1488 else
1489 *mVal = aThat;
1490 return *this;
1491 }
1492
1493 private:
1494
1495 nsID * &mVal;
1496
1497 friend class SafeGUIDArray;
1498 };
1499
1500 /** See SafeArray<>::SafeArray(). */
1501 SafeGUIDArray() {}
1502
1503 /** See SafeArray<>::SafeArray(size_t). */
1504 SafeGUIDArray(size_t aSize) : Base(aSize) {}
1505
1506 /**
1507 * Array access operator that returns an array element by reference. As a
1508 * special case, the return value of this operator on XPCOM is an nsID (GUID)
1509 * reference, instead of an nsID pointer (the actual SafeArray template
1510 * argument), for compatibility with the MS COM version.
1511 *
1512 * The rest is equivalent to SafeArray<>::operator[].
1513 */
1514 nsIDRef operator[] (size_t aIdx)
1515 {
1516 Assert(m.arr != NULL);
1517 Assert(aIdx < size());
1518 return nsIDRef(m.arr[aIdx]);
1519 }
1520
1521 /**
1522 * Const version of #operator[] that returns an array element by value.
1523 */
1524 const nsID &operator[] (size_t aIdx) const
1525 {
1526 Assert(m.arr != NULL);
1527 Assert(aIdx < size());
1528 return m.arr[aIdx] ? *m.arr[aIdx] : *(const nsID *)&Zeroes[0];
1529 }
1530};
1531
1532/**
1533 * Version of com::SafeArray for const arrays of GUID.
1534 *
1535 * This class is used to work with input GUID array parameters in method
1536 * implementations. See SafeGUIDArray for more details.
1537 */
1538class SafeConstGUIDArray : public SafeArray<const nsID *,
1539 SafeArrayTraits<nsID *> >
1540{
1541public:
1542
1543 typedef SafeArray<const nsID *, SafeArrayTraits<nsID *> > Base;
1544
1545 /** See SafeArray<>::SafeArray(). */
1546 SafeConstGUIDArray() { AssertCompile(sizeof(nsID) <= sizeof(Zeroes)); }
1547
1548 /* See SafeArray<>::SafeArray(ComSafeArrayIn(T, aArg)). */
1549 SafeConstGUIDArray(ComSafeGUIDArrayIn(aArg))
1550 : Base(ComSafeGUIDArrayInArg(aArg)) {}
1551
1552 /**
1553 * Array access operator that returns an array element by reference. As a
1554 * special case, the return value of this operator on XPCOM is nsID (GUID)
1555 * instead of nsID *, for compatibility with the MS COM version.
1556 *
1557 * The rest is equivalent to SafeArray<>::operator[].
1558 */
1559 const nsID &operator[] (size_t aIdx) const
1560 {
1561 AssertReturn(m.arr != NULL, *(const nsID *)&Zeroes[0]);
1562 AssertReturn(aIdx < size(), *(const nsID *)&Zeroes[0]);
1563 return *m.arr[aIdx];
1564 }
1565
1566private:
1567
1568 /* These are disabled because of const. */
1569 bool reset(size_t aNewSize) { NOREF(aNewSize); return false; }
1570};
1571
1572#else /* !VBOX_WITH_XPCOM */
1573
1574typedef SafeArray<GUID> SafeGUIDArray;
1575typedef SafeArray<const GUID, SafeArrayTraits<GUID> > SafeConstGUIDArray;
1576
1577#endif /* !VBOX_WITH_XPCOM */
1578
1579////////////////////////////////////////////////////////////////////////////////
1580
1581#ifdef VBOX_WITH_XPCOM
1582
1583template<class I>
1584struct SafeIfaceArrayTraits
1585{
1586protected:
1587
1588 static void Init(I * &aElem) { aElem = NULL; }
1589 static void Uninit(I * &aElem)
1590 {
1591 if (aElem)
1592 {
1593 aElem->Release();
1594 aElem = NULL;
1595 }
1596 }
1597
1598 static void Copy(I * aFrom, I * &aTo)
1599 {
1600 if (aFrom != NULL)
1601 {
1602 aTo = aFrom;
1603 aTo->AddRef();
1604 }
1605 else
1606 aTo = NULL;
1607 }
1608
1609public:
1610
1611 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard. */
1612 static I **__asInParam_Arr(I **aArr) { return aArr; }
1613 static I **__asInParam_Arr(const I **aArr) { return const_cast<I **>(aArr); }
1614};
1615
1616#else /* !VBOX_WITH_XPCOM */
1617
1618template<class I>
1619struct SafeIfaceArrayTraits
1620{
1621protected:
1622
1623 static VARTYPE VarType() { return VT_DISPATCH; }
1624 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
1625 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
1626
1627 static void Copy(I * aFrom, I * &aTo)
1628 {
1629 if (aFrom != NULL)
1630 {
1631 aTo = aFrom;
1632 aTo->AddRef();
1633 }
1634 else
1635 aTo = NULL;
1636 }
1637
1638 static SAFEARRAY *CreateSafeArray(VARTYPE aVarType, SAFEARRAYBOUND *aBound)
1639 {
1640 NOREF(aVarType);
1641 return SafeArrayCreateEx(VT_DISPATCH, 1, aBound, (PVOID)&COM_IIDOF(I));
1642 }
1643};
1644
1645#endif /* !VBOX_WITH_XPCOM */
1646
1647////////////////////////////////////////////////////////////////////////////////
1648
1649/**
1650 * Version of com::SafeArray for arrays of interface pointers.
1651 *
1652 * Except that it manages arrays of interface pointers, the usage of this class
1653 * is identical to com::SafeArray.
1654 *
1655 * @param I Interface class (no asterisk).
1656 */
1657template<class I>
1658class SafeIfaceArray : public SafeArray<I *, SafeIfaceArrayTraits<I> >
1659{
1660public:
1661
1662 typedef SafeArray<I *, SafeIfaceArrayTraits<I> > Base;
1663
1664 /**
1665 * Creates a null array.
1666 */
1667 SafeIfaceArray() {}
1668
1669 /**
1670 * Creates a new array of the given size. All elements of the newly created
1671 * array initialized with null values.
1672 *
1673 * @param aSize Initial number of elements in the array. Must be greater
1674 * than 0.
1675 *
1676 * @note If this object remains null after construction it means that there
1677 * was not enough memory for creating an array of the requested size.
1678 * The constructor will also assert in this case.
1679 */
1680 SafeIfaceArray(size_t aSize) { Base::resize(aSize); }
1681
1682 /**
1683 * Weakly attaches this instance to the existing array passed in a method
1684 * parameter declared using the ComSafeArrayIn macro. When using this call,
1685 * always wrap the parameter name in the ComSafeArrayOutArg macro call like
1686 * this:
1687 * <pre>
1688 * SafeArray safeArray(ComSafeArrayInArg(aArg));
1689 * </pre>
1690 *
1691 * Note that this constructor doesn't take the ownership of the array. In
1692 * particular, this means that operations that operate on the ownership
1693 * (e.g. #detachTo()) are forbidden and will assert.
1694 *
1695 * @param aArg Input method parameter to attach to.
1696 */
1697 SafeIfaceArray(ComSafeArrayIn(I *, aArg))
1698 {
1699 if (aArg)
1700 {
1701#ifdef VBOX_WITH_XPCOM
1702
1703 Base::m.size = aArgSize;
1704 Base::m.arr = aArg;
1705 Base::m.isWeak = true;
1706
1707#else /* !VBOX_WITH_XPCOM */
1708
1709 SAFEARRAY *arg = aArg;
1710
1711 AssertReturnVoid(arg->cDims == 1);
1712
1713 VARTYPE vt;
1714 HRESULT rc = SafeArrayGetVartype(arg, &vt);
1715 AssertComRCReturnVoid(rc);
1716 AssertMsgReturnVoid(vt == VT_UNKNOWN || vt == VT_DISPATCH,
1717 ("Expected vartype VT_UNKNOWN or VT_DISPATCH, got %d.\n",
1718 vt));
1719 GUID guid;
1720 rc = SafeArrayGetIID(arg, &guid);
1721 AssertComRCReturnVoid(rc);
1722 AssertMsgReturnVoid(InlineIsEqualGUID(COM_IIDOF(I), guid) || arg->rgsabound[0].cElements == 0 /* IDispatch if empty */,
1723 ("Expected IID {%RTuuid}, got {%RTuuid}.\n", &COM_IIDOF(I), &guid));
1724
1725 rc = SafeArrayAccessData(arg, (void HUGEP **)&m.raw);
1726 AssertComRCReturnVoid(rc);
1727
1728 m.arr = arg;
1729 m.isWeak = true;
1730
1731#endif /* !VBOX_WITH_XPCOM */
1732 }
1733 }
1734
1735 /**
1736 * Creates a deep copy of the given standard C++ container that stores
1737 * interface pointers as objects of the ComPtr\<I\> class.
1738 *
1739 * @param aCntr Container object to copy.
1740 *
1741 * @tparam C Standard C++ container template class (normally deduced from
1742 * @c aCntr).
1743 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1744 * @tparam OI Argument to the ComPtr template (deduced from @c aCntr).
1745 */
1746 template<template<typename, typename> class C, class A, class OI>
1747 SafeIfaceArray(const C<ComPtr<OI>, A> & aCntr)
1748 {
1749 typedef C<ComPtr<OI>, A> List;
1750
1751 Base::resize(aCntr.size());
1752 AssertReturnVoid(!Base::isNull());
1753
1754 size_t i = 0;
1755 for (typename List::const_iterator it = aCntr.begin();
1756 it != aCntr.end(); ++ it, ++ i)
1757#ifdef VBOX_WITH_XPCOM
1758 this->Copy(*it, Base::m.arr[i]);
1759#else
1760 Copy(*it, Base::m.raw[i]);
1761#endif
1762 }
1763
1764 /**
1765 * Creates a deep copy of the given standard C++ container that stores
1766 * interface pointers as objects of the ComObjPtr\<I\> class.
1767 *
1768 * @param aCntr Container object to copy.
1769 *
1770 * @tparam C Standard C++ container template class (normally deduced from
1771 * @c aCntr).
1772 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1773 * @tparam OI Argument to the ComObjPtr template (deduced from @c aCntr).
1774 */
1775 template<template<typename, typename> class C, class A, class OI>
1776 SafeIfaceArray(const C<ComObjPtr<OI>, A> & aCntr)
1777 {
1778 typedef C<ComObjPtr<OI>, A> List;
1779
1780 Base::resize(aCntr.size());
1781 AssertReturnVoid(!Base::isNull());
1782
1783 size_t i = 0;
1784 for (typename List::const_iterator it = aCntr.begin();
1785 it != aCntr.end(); ++ it, ++ i)
1786#ifdef VBOX_WITH_XPCOM
1787 SafeIfaceArray::Copy(*it, Base::m.arr[i]);
1788#else
1789 Copy(*it, Base::m.raw[i]);
1790#endif
1791 }
1792
1793 /**
1794 * Creates a deep copy of the given standard C++ map whose values are
1795 * interface pointers stored as objects of the ComPtr\<I\> class.
1796 *
1797 * @param aMap Map object to copy.
1798 *
1799 * @tparam C Standard C++ map template class (normally deduced from
1800 * @c aCntr).
1801 * @tparam L Standard C++ compare class (deduced from @c aCntr).
1802 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1803 * @tparam K Map key class (deduced from @c aCntr).
1804 * @tparam OI Argument to the ComPtr template (deduced from @c aCntr).
1805 */
1806 template<template<typename, typename, typename, typename>
1807 class C, class L, class A, class K, class OI>
1808 SafeIfaceArray(const C<K, ComPtr<OI>, L, A> & aMap)
1809 {
1810 typedef C<K, ComPtr<OI>, L, A> Map;
1811
1812 Base::resize(aMap.size());
1813 AssertReturnVoid(!Base::isNull());
1814
1815 size_t i = 0;
1816 for (typename Map::const_iterator it = aMap.begin();
1817 it != aMap.end(); ++ it, ++ i)
1818#ifdef VBOX_WITH_XPCOM
1819 SafeIfaceArray::Copy(it->second, Base::m.arr[i]);
1820#else
1821 Copy(it->second, Base::m.raw[i]);
1822#endif
1823 }
1824
1825 /**
1826 * Creates a deep copy of the given standard C++ map whose values are
1827 * interface pointers stored as objects of the ComObjPtr\<I\> class.
1828 *
1829 * @param aMap Map object to copy.
1830 *
1831 * @tparam C Standard C++ map template class (normally deduced from
1832 * @c aCntr).
1833 * @tparam L Standard C++ compare class (deduced from @c aCntr).
1834 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1835 * @tparam K Map key class (deduced from @c aCntr).
1836 * @tparam OI Argument to the ComObjPtr template (deduced from @c aCntr).
1837 */
1838 template<template<typename, typename, typename, typename>
1839 class C, class L, class A, class K, class OI>
1840 SafeIfaceArray(const C<K, ComObjPtr<OI>, L, A> & aMap)
1841 {
1842 typedef C<K, ComObjPtr<OI>, L, A> Map;
1843
1844 Base::resize(aMap.size());
1845 AssertReturnVoid(!Base::isNull());
1846
1847 size_t i = 0;
1848 for (typename Map::const_iterator it = aMap.begin();
1849 it != aMap.end(); ++ it, ++ i)
1850#ifdef VBOX_WITH_XPCOM
1851 SafeIfaceArray::Copy(it->second, Base::m.arr[i]);
1852#else
1853 Copy(it->second, Base::m.raw[i]);
1854#endif
1855 }
1856
1857 void setElement(size_t iIdx, I* obj)
1858 {
1859#ifdef VBOX_WITH_XPCOM
1860 SafeIfaceArray::Copy(obj, Base::m.arr[iIdx]);
1861#else
1862 Copy(obj, Base::m.raw[iIdx]);
1863#endif
1864 }
1865};
1866
1867} /* namespace com */
1868
1869/** @} */
1870
1871#endif /* !VBOX_INCLUDED_com_array_h */
1872
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette