VirtualBox

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

Last change on this file was 109191, checked in by vboxsync, 5 days ago

VBox/Main: Fixed an error in SafeArray::push_front() for the Windows (COM) implementation. See comments for details. Added some more testcases for this function. ticketref:22175

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 54.8 KB
Line 
1/** @file
2 * MS COM / XPCOM Abstraction Layer - Safe array helper class declaration.
3 */
4
5/*
6 * Copyright (C) 2006-2024 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( vt == Traits::VarType()
694 || vt == Traits::VarTypeUnsigned(),
695 ("Expected vartype %d or %d, got %d.\n",
696 Traits::VarType(), Traits::VarTypeUnsigned(), vt));
697# else /* VBOX_WITH_TYPE_TRAITS */
698 AssertMsgReturnVoid(vt == Traits::VarType(),
699 ("Expected vartype %d, got %d.\n",
700 Traits::VarType(), vt));
701# endif /* VBOX_WITH_TYPE_TRAITS */
702 rc = SafeArrayAccessData(arg, (void HUGEP **)&m.raw);
703 AssertComRCReturnVoid(rc);
704
705 m.arr = arg;
706 m.isWeak = true;
707
708#endif /* !VBOX_WITH_XPCOM */
709 }
710 }
711
712 /**
713 * Creates a deep copy of the given standard C++ container that stores
714 * T objects.
715 *
716 * @param aCntr Container object to copy.
717 *
718 * @tparam C Standard C++ container template class (normally deduced from
719 * @c aCntr).
720 */
721 template<template<typename, typename> class C, class A>
722 SafeArray(const C<T, A> & aCntr)
723 {
724 resize(aCntr.size());
725 AssertReturnVoid(!isNull());
726
727 size_t i = 0;
728 for (typename C<T, A>::const_iterator it = aCntr.begin();
729 it != aCntr.end(); ++ it, ++ i)
730#ifdef VBOX_WITH_XPCOM
731 SafeArray::Copy(*it, m.arr[i]);
732#else
733 SafeArray::Copy(*it, m.raw[i]);
734#endif
735 }
736
737 /**
738 * Creates a deep copy of the given standard C++ map that stores T objects
739 * as values.
740 *
741 * @param aMap Map object to copy.
742 *
743 * @tparam C Standard C++ map template class (normally deduced from
744 * @a aMap).
745 * @tparam L Standard C++ compare class (deduced from @a aMap).
746 * @tparam A Standard C++ allocator class (deduced from @a aMap).
747 * @tparam K Map key class (deduced from @a aMap).
748 */
749 template<template<typename, typename, typename, typename>
750 class C, class L, class A, class K>
751 SafeArray(const C<K, T, L, A> & aMap)
752 {
753 typedef C<K, T, L, A> Map;
754
755 resize(aMap.size());
756 AssertReturnVoid(!isNull());
757
758 size_t i = 0;
759 for (typename Map::const_iterator it = aMap.begin();
760 it != aMap.end(); ++ it, ++ i)
761#ifdef VBOX_WITH_XPCOM
762 SafeArray::Copy(it->second, m.arr[i]);
763#else
764 SafeArray::Copy(it->second, m.raw[i]);
765#endif
766 }
767
768 /**
769 * Destroys this instance after calling #setNull() to release allocated
770 * resources. See #setNull() for more details.
771 */
772 virtual ~SafeArray() { setNull(); }
773
774 /**
775 * Returns @c true if this instance represents a null array.
776 */
777 bool isNull() const { return m.arr == NULL; }
778
779 /**
780 * Returns @c true if this instance does not represents a null array.
781 */
782 bool isNotNull() const { return m.arr != NULL; }
783
784 /**
785 * Resets this instance to null and, if this instance is not a weak one,
786 * releases any resources occupied by the array data.
787 *
788 * @note This method destroys (cleans up) all elements of the array using
789 * the corresponding cleanup routine for the element type before the
790 * array itself is destroyed.
791 */
792 virtual void setNull() { m.uninit(); }
793
794 /**
795 * Returns @c true if this instance is weak. A weak instance doesn't own the
796 * array data and therefore operations manipulating the ownership (e.g.
797 * #detachTo()) are forbidden and will assert.
798 */
799 bool isWeak() const { return m.isWeak; }
800
801 /** Number of elements in the array. */
802 size_t size() const
803 {
804#ifdef VBOX_WITH_XPCOM
805 if (m.arr)
806 return m.size;
807 return 0;
808#else
809 if (m.arr)
810 return Traits::Size(m.arr->rgsabound[0].cElements);
811 return 0;
812#endif
813 }
814
815 /**
816 * Prepends a copy of the given element at the beginning of the array.
817 *
818 * The array size is increased by one by this method and the additional
819 * space is allocated as needed.
820 *
821 * This method is handy in cases where you want to assign a copy of the
822 * existing value to the array element, for example:
823 * <tt>Bstr string; array.push_front(string);</tt>. If you create a string
824 * just to put it in the array, you may find #appendedRaw() more useful.
825 *
826 * @param aElement Element to prepend.
827 *
828 * @return @c true on success and @c false if there is not enough
829 * memory for resizing.
830 */
831 bool push_front(const T &aElement)
832 {
833 if (!ensureCapacity(size() + 1))
834 return false;
835
836#ifdef VBOX_WITH_XPCOM
837 /* For XPCOM, size() is 0 and capacity() is 16 for the first time
838 * this function is being called on an empty array.
839 * See implementation of ensureCapacity(). */
840 for (size_t i = size(); i > 0; --i)
841 SafeArray::Copy(m.arr[i - 1], m.arr[i]);
842#else
843 /* For Windows (COM), size() always matches the array's capacity.
844 *
845 * So we here need to make sure we don't read beyond the array
846 * if this function is being called on an empty array
847 * (size is 1 and there is no element on index 1 yet). */
848 for (size_t i = size() - 1; i > 0; --i)
849 SafeArray::Copy(m.raw[i - 1], m.raw[i]);
850#endif
851
852#ifdef VBOX_WITH_XPCOM
853 SafeArray::Copy(aElement, m.arr[0]);
854 ++ m.size;
855#else
856 SafeArray::Copy(aElement, m.raw[0]);
857#endif
858 return true;
859 }
860
861 /**
862 * Appends a copy of the given element at the end of the array.
863 *
864 * The array size is increased by one by this method and the additional
865 * space is allocated as needed.
866 *
867 * This method is handy in cases where you want to assign a copy of the
868 * existing value to the array element, for example:
869 * <tt>Bstr string; array.push_back(string);</tt>. If you create a string
870 * just to put it in the array, you may find #appendedRaw() more useful.
871 *
872 * @param aElement Element to append.
873 *
874 * @return @c true on success and @c false if there is not enough
875 * memory for resizing.
876 */
877 bool push_back(const T &aElement)
878 {
879 if (!ensureCapacity(size() + 1))
880 return false;
881
882#ifdef VBOX_WITH_XPCOM
883 SafeArray::Copy(aElement, m.arr[m.size]);
884 ++ m.size;
885#else
886 SafeArray::Copy(aElement, m.raw[size() - 1]);
887#endif
888 return true;
889 }
890
891 /**
892 * Appends an empty element at the end of the array and returns a raw
893 * pointer to it suitable for assigning a raw value (w/o constructing a
894 * copy).
895 *
896 * The array size is increased by one by this method and the additional
897 * space is allocated as needed.
898 *
899 * Note that in case of raw assignment, value ownership (for types with
900 * dynamically allocated data and for interface pointers) is transferred to
901 * the safe array object.
902 *
903 * This method is handy for operations like
904 * <tt>Bstr("foo").detachTo(array.appendedRaw());</tt>. Don't use it as
905 * an l-value (<tt>array.appendedRaw() = SysAllocString(L"tralala");</tt>)
906 * since this doesn't check for a NULL condition; use #resize() instead. If
907 * you need to assign a copy of the existing value instead of transferring
908 * the ownership, look at #push_back().
909 *
910 * @return Raw pointer to the added element or NULL if no memory.
911 */
912 T *appendedRaw()
913 {
914 if (!ensureCapacity(size() + 1))
915 return NULL;
916
917#ifdef VBOX_WITH_XPCOM
918 SafeArray::Init(m.arr[m.size]);
919 ++ m.size;
920 return &m.arr[m.size - 1];
921#else
922 /* nothing to do here, SafeArrayCreate() has performed element
923 * initialization */
924 return &m.raw[size() - 1];
925#endif
926 }
927
928 /**
929 * Resizes the array preserving its contents when possible. If the new size
930 * is larger than the old size, new elements are initialized with null
931 * values. If the new size is less than the old size, the contents of the
932 * array beyond the new size is lost.
933 *
934 * @param aNewSize New number of elements in the array.
935 * @return @c true on success and @c false if there is not enough
936 * memory for resizing.
937 */
938 bool resize(size_t aNewSize)
939 {
940 if (!ensureCapacity(aNewSize))
941 return false;
942
943#ifdef VBOX_WITH_XPCOM
944
945 if (m.size < aNewSize)
946 {
947 /* initialize the new elements */
948 for (size_t i = m.size; i < aNewSize; ++ i)
949 SafeArray::Init(m.arr[i]);
950 }
951
952 /** @todo Fix this! */
953 m.size = (PRUint32)aNewSize;
954#else
955 /* nothing to do here, SafeArrayCreate() has performed element
956 * initialization */
957#endif
958 return true;
959 }
960
961 /**
962 * Reinitializes this instance by preallocating space for the given number
963 * of elements. The previous array contents is lost.
964 *
965 * @param aNewSize New number of elements in the array.
966 * @return @c true on success and @c false if there is not enough
967 * memory for resizing.
968 */
969 bool reset(size_t aNewSize)
970 {
971 m.uninit();
972 return resize(aNewSize);
973 }
974
975 /**
976 * Returns a pointer to the raw array data. Use this raw pointer with care
977 * as no type or bound checking is done for you in this case.
978 *
979 * @note This method returns @c NULL when this instance is null.
980 * @see #operator[]
981 */
982 T *raw()
983 {
984#ifdef VBOX_WITH_XPCOM
985 return m.arr;
986#else
987 return m.raw;
988#endif
989 }
990
991 /**
992 * Const version of #raw().
993 */
994 const T *raw() const
995 {
996#ifdef VBOX_WITH_XPCOM
997 return m.arr;
998#else
999 return m.raw;
1000#endif
1001 }
1002
1003 /**
1004 * Array access operator that returns an array element by reference. A bit
1005 * safer than #raw(): asserts and returns a reference to a static zero
1006 * element (const, i.e. writes will fail) if this instance is null or
1007 * if the index is out of bounds.
1008 *
1009 * @note For weak instances, this call will succeed but the behavior of
1010 * changing the contents of an element of the weak array instance is
1011 * undefined and may lead to a program crash on some platforms.
1012 */
1013 T &operator[] (size_t aIdx)
1014 {
1015 /** @todo r=klaus should do this as a AssertCompile, but cannot find a way which works. */
1016 Assert(sizeof(T) <= sizeof(Zeroes));
1017 AssertReturn(m.arr != NULL, *(T *)&Zeroes[0]);
1018 AssertReturn(aIdx < size(), *(T *)&Zeroes[0]);
1019#ifdef VBOX_WITH_XPCOM
1020 return m.arr[aIdx];
1021#else
1022 AssertReturn(m.raw != NULL, *(T *)&Zeroes[0]);
1023 return m.raw[aIdx];
1024#endif
1025 }
1026
1027 /**
1028 * Const version of #operator[] that returns an array element by value.
1029 */
1030 T operator[] (size_t aIdx) const
1031 {
1032 AssertReturn(m.arr != NULL, *(const T *)&Zeroes[0]);
1033 AssertReturn(aIdx < size(), *(const T *)&Zeroes[0]);
1034#ifdef VBOX_WITH_XPCOM
1035 return m.arr[aIdx];
1036#else
1037 AssertReturn(m.raw != NULL, *(const T *)&Zeroes[0]);
1038 return m.raw[aIdx];
1039#endif
1040 }
1041
1042 /**
1043 * Creates a copy of this array and stores it in a method parameter declared
1044 * using the ComSafeArrayOut macro. When using this call, always wrap the
1045 * parameter name in the ComSafeArrayOutArg macro call like this:
1046 * <pre>
1047 * safeArray.cloneTo(ComSafeArrayOutArg(aArg));
1048 * </pre>
1049 *
1050 * @note It is assumed that the ownership of the returned copy is
1051 * transferred to the caller of the method and he is responsible to free the
1052 * array data when it is no longer needed.
1053 *
1054 * @param aArg Output method parameter to clone to.
1055 */
1056 virtual const SafeArray &cloneTo(ComSafeArrayOut(T, aArg)) const
1057 {
1058 /// @todo Implement me!
1059#ifdef VBOX_WITH_XPCOM
1060 NOREF(aArgSize);
1061 NOREF(aArg);
1062#else
1063 NOREF(aArg);
1064#endif
1065 AssertFailedReturn(*this);
1066 }
1067
1068 HRESULT cloneTo(SafeArray<T>& aOther) const
1069 {
1070 aOther.reset(size());
1071 return aOther.initFrom(*this);
1072 }
1073
1074
1075 /**
1076 * Transfers the ownership of this array's data to the specified location
1077 * declared using the ComSafeArrayOut macro and makes this array a null
1078 * array. When using this call, always wrap the parameter name in the
1079 * ComSafeArrayOutArg macro call like this:
1080 * <pre>
1081 * safeArray.detachTo(ComSafeArrayOutArg(aArg));
1082 * </pre>
1083 *
1084 * Detaching the null array is also possible in which case the location will
1085 * receive NULL.
1086 *
1087 * @note Since the ownership of the array data is transferred to the
1088 * caller of the method, he is responsible to free the array data when it is
1089 * no longer needed.
1090 *
1091 * @param aArg Location to detach to.
1092 */
1093 virtual SafeArray &detachTo(ComSafeArrayOut(T, aArg))
1094 {
1095 AssertReturn(!m.isWeak, *this);
1096
1097#ifdef VBOX_WITH_XPCOM
1098
1099 AssertReturn(aArgSize != NULL, *this);
1100 AssertReturn(aArg != NULL, *this);
1101
1102 *aArgSize = m.size;
1103 *aArg = m.arr;
1104
1105 m.isWeak = false;
1106 m.size = 0;
1107 m.arr = NULL;
1108
1109#else /* !VBOX_WITH_XPCOM */
1110
1111 AssertReturn(aArg != NULL, *this);
1112 *aArg = m.arr;
1113
1114 if (m.raw)
1115 {
1116 HRESULT rc = SafeArrayUnaccessData(m.arr);
1117 AssertComRCReturn(rc, *this);
1118 m.raw = NULL;
1119 }
1120
1121 m.isWeak = false;
1122 m.arr = NULL;
1123
1124#endif /* !VBOX_WITH_XPCOM */
1125
1126 return *this;
1127 }
1128
1129 /**
1130 * Returns a copy of this SafeArray as RTCList<T>.
1131 */
1132 RTCList<T> toList()
1133 {
1134 RTCList<T> list(size());
1135 for (size_t i = 0; i < size(); ++i)
1136#ifdef VBOX_WITH_XPCOM
1137 list.append(m.arr[i]);
1138#else
1139 list.append(m.raw[i]);
1140#endif
1141 return list;
1142 }
1143
1144 inline HRESULT initFrom(const com::SafeArray<T> & aRef);
1145 inline HRESULT initFrom(const T* aPtr, size_t aSize);
1146
1147 // Public methods for internal purposes only.
1148
1149#ifdef VBOX_WITH_XPCOM
1150
1151 /** Internal function. Never call it directly. */
1152 PRUint32 *__asOutParam_Size() { setNull(); return &m.size; }
1153
1154 /** Internal function Never call it directly. */
1155 T **__asOutParam_Arr() { Assert(isNull()); return &m.arr; }
1156
1157#else /* !VBOX_WITH_XPCOM */
1158
1159 /** Internal function Never call it directly. */
1160 SAFEARRAY * __asInParam() { return m.arr; }
1161
1162 /** Internal function Never call it directly. */
1163 OutSafeArrayDipper __asOutParam()
1164 { setNull(); return OutSafeArrayDipper(&m.arr, (void **)&m.raw); }
1165
1166#endif /* !VBOX_WITH_XPCOM */
1167
1168 static const SafeArray Null;
1169
1170protected:
1171
1172 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP(SafeArray);
1173
1174 /**
1175 * Ensures that the array is big enough to contain aNewSize elements.
1176 *
1177 * If the new size is greater than the current capacity, a new array is
1178 * allocated and elements from the old array are copied over. The size of
1179 * the array doesn't change, only the capacity increases (which is always
1180 * greater than the size). Note that the additionally allocated elements are
1181 * left uninitialized by this method.
1182 *
1183 * If the new size is less than the current size, the existing array is
1184 * truncated to the specified size and the elements outside the new array
1185 * boundary are freed.
1186 *
1187 * If the new size is the same as the current size, nothing happens.
1188 *
1189 * @param aNewSize New size of the array.
1190 *
1191 * @return @c true on success and @c false if not enough memory.
1192 */
1193 bool ensureCapacity(size_t aNewSize)
1194 {
1195 AssertReturn(!m.isWeak, false);
1196
1197#ifdef VBOX_WITH_XPCOM
1198
1199 /* Note: we distinguish between a null array and an empty (zero
1200 * elements) array. Therefore we never use zero in malloc (even if
1201 * aNewSize is zero) to make sure we get a non-null pointer. */
1202
1203 if (m.size == aNewSize && m.arr != NULL)
1204 return true;
1205
1206 /* Allocate in 16-byte pieces. */
1207 size_t newCapacity = RT_MAX((aNewSize + 15) / 16 * 16, 16);
1208
1209 if (m.capacity != newCapacity)
1210 {
1211 T *newArr = (T *)nsMemory::Alloc(RT_MAX(newCapacity, 1) * sizeof(T));
1212 AssertReturn(newArr != NULL, false);
1213
1214 if (m.arr != NULL)
1215 {
1216 if (m.size > aNewSize)
1217 {
1218 /* Truncation takes place, uninit exceeding elements and
1219 * shrink the size. */
1220 for (size_t i = aNewSize; i < m.size; ++ i)
1221 SafeArray::Uninit(m.arr[i]);
1222
1223 /** @todo Fix this! */
1224 m.size = (PRUint32)aNewSize;
1225 }
1226
1227 /* Copy the old contents. */
1228 memcpy(newArr, m.arr, m.size * sizeof(T));
1229 nsMemory::Free((void *)m.arr);
1230 }
1231
1232 m.arr = newArr;
1233 }
1234 else
1235 {
1236 if (m.size > aNewSize)
1237 {
1238 /* Truncation takes place, uninit exceeding elements and
1239 * shrink the size. */
1240 for (size_t i = aNewSize; i < m.size; ++ i)
1241 SafeArray::Uninit(m.arr[i]);
1242
1243 /** @todo Fix this! */
1244 m.size = (PRUint32)aNewSize;
1245 }
1246 }
1247
1248 /** @todo Fix this! */
1249 m.capacity = (PRUint32)newCapacity;
1250
1251#else
1252
1253 SAFEARRAYBOUND bound = { Traits::VarCount(aNewSize), 0 };
1254 HRESULT rc;
1255
1256 if (m.arr == NULL)
1257 {
1258 m.arr = Traits::CreateSafeArray(Traits::VarType(), &bound);
1259 AssertReturn(m.arr != NULL, false);
1260 }
1261 else
1262 {
1263 SafeArrayUnaccessData(m.arr);
1264
1265 rc = SafeArrayRedim(m.arr, &bound);
1266 AssertComRCReturn(rc == S_OK, false);
1267 }
1268
1269 rc = SafeArrayAccessData(m.arr, (void HUGEP **)&m.raw);
1270 AssertComRCReturn(rc, false);
1271
1272#endif
1273 return true;
1274 }
1275
1276 struct Data
1277 {
1278 Data()
1279 : isWeak(false)
1280#ifdef VBOX_WITH_XPCOM
1281 , capacity(0), size(0), arr(NULL)
1282#else
1283 , arr(NULL), raw(NULL)
1284#endif
1285 {}
1286
1287 ~Data() { uninit(); }
1288
1289 void uninit()
1290 {
1291#ifdef VBOX_WITH_XPCOM
1292
1293 if (arr)
1294 {
1295 if (!isWeak)
1296 {
1297 for (size_t i = 0; i < size; ++ i)
1298 SafeArray::Uninit(arr[i]);
1299
1300 nsMemory::Free((void *)arr);
1301 }
1302 else
1303 isWeak = false;
1304
1305 arr = NULL;
1306 }
1307
1308 size = capacity = 0;
1309
1310#else /* !VBOX_WITH_XPCOM */
1311
1312 if (arr)
1313 {
1314 if (raw)
1315 {
1316 SafeArrayUnaccessData(arr);
1317 raw = NULL;
1318 }
1319
1320 if (!isWeak)
1321 {
1322 HRESULT rc = SafeArrayDestroy(arr);
1323 AssertComRCReturnVoid(rc);
1324 }
1325 else
1326 isWeak = false;
1327
1328 arr = NULL;
1329 }
1330
1331#endif /* !VBOX_WITH_XPCOM */
1332 }
1333
1334 bool isWeak : 1;
1335
1336#ifdef VBOX_WITH_XPCOM
1337 PRUint32 capacity;
1338 PRUint32 size;
1339 T *arr;
1340#else
1341 SAFEARRAY *arr;
1342 T *raw;
1343#endif
1344 };
1345
1346 Data m;
1347};
1348
1349/* Few fast specializations for primitive array types */
1350template<>
1351inline HRESULT com::SafeArray<BYTE>::initFrom(const com::SafeArray<BYTE> & aRef)
1352{
1353 size_t sSize = aRef.size();
1354 if (resize(sSize))
1355 {
1356 ::memcpy(raw(), aRef.raw(), sSize);
1357 return S_OK;
1358 }
1359 return E_OUTOFMEMORY;
1360}
1361template<>
1362inline HRESULT com::SafeArray<BYTE>::initFrom(const BYTE *aPtr, size_t aSize)
1363{
1364 if (resize(aSize))
1365 {
1366 ::memcpy(raw(), aPtr, aSize);
1367 return S_OK;
1368 }
1369 return E_OUTOFMEMORY;
1370}
1371
1372
1373template<>
1374inline HRESULT com::SafeArray<SHORT>::initFrom(const com::SafeArray<SHORT> & aRef)
1375{
1376 size_t sSize = aRef.size();
1377 if (resize(sSize))
1378 {
1379 ::memcpy(raw(), aRef.raw(), sSize * sizeof(SHORT));
1380 return S_OK;
1381 }
1382 return E_OUTOFMEMORY;
1383}
1384template<>
1385inline HRESULT com::SafeArray<SHORT>::initFrom(const SHORT *aPtr, size_t aSize)
1386{
1387 if (resize(aSize))
1388 {
1389 ::memcpy(raw(), aPtr, aSize * sizeof(SHORT));
1390 return S_OK;
1391 }
1392 return E_OUTOFMEMORY;
1393}
1394
1395template<>
1396inline HRESULT com::SafeArray<USHORT>::initFrom(const com::SafeArray<USHORT> & aRef)
1397{
1398 size_t sSize = aRef.size();
1399 if (resize(sSize))
1400 {
1401 ::memcpy(raw(), aRef.raw(), sSize * sizeof(USHORT));
1402 return S_OK;
1403 }
1404 return E_OUTOFMEMORY;
1405}
1406template<>
1407inline HRESULT com::SafeArray<USHORT>::initFrom(const USHORT *aPtr, size_t aSize)
1408{
1409 if (resize(aSize))
1410 {
1411 ::memcpy(raw(), aPtr, aSize * sizeof(USHORT));
1412 return S_OK;
1413 }
1414 return E_OUTOFMEMORY;
1415}
1416
1417template<>
1418inline HRESULT com::SafeArray<LONG>::initFrom(const com::SafeArray<LONG> & aRef)
1419{
1420 size_t sSize = aRef.size();
1421 if (resize(sSize))
1422 {
1423 ::memcpy(raw(), aRef.raw(), sSize * sizeof(LONG));
1424 return S_OK;
1425 }
1426 return E_OUTOFMEMORY;
1427}
1428template<>
1429inline HRESULT com::SafeArray<LONG>::initFrom(const LONG *aPtr, size_t aSize)
1430{
1431 if (resize(aSize))
1432 {
1433 ::memcpy(raw(), aPtr, aSize * sizeof(LONG));
1434 return S_OK;
1435 }
1436 return E_OUTOFMEMORY;
1437}
1438
1439
1440////////////////////////////////////////////////////////////////////////////////
1441
1442#ifdef VBOX_WITH_XPCOM
1443
1444/**
1445 * Version of com::SafeArray for arrays of GUID.
1446 *
1447 * In MS COM, GUID arrays store GUIDs by value and therefore input arrays are
1448 * represented using |GUID *| and out arrays -- using |GUID **|. In XPCOM,
1449 * GUID arrays store pointers to nsID so that input arrays are |const nsID **|
1450 * and out arrays are |nsID ***|. Due to this difference, it is impossible to
1451 * work with arrays of GUID on both platforms by simply using com::SafeArray
1452 * <GUID>. This class is intended to provide some level of cross-platform
1453 * behavior.
1454 *
1455 * The basic usage pattern is basically similar to com::SafeArray<> except that
1456 * you use ComSafeGUIDArrayIn* and ComSafeGUIDArrayOut* macros instead of
1457 * ComSafeArrayIn* and ComSafeArrayOut*. Another important nuance is that the
1458 * raw() array type is different (nsID **, or GUID ** on XPCOM and GUID * on MS
1459 * COM) so it is recommended to use operator[] instead which always returns a
1460 * GUID by value.
1461 *
1462 * Note that due to const modifiers, you cannot use SafeGUIDArray for input GUID
1463 * arrays. Please use SafeConstGUIDArray for this instead.
1464 *
1465 * Other than mentioned above, the functionality of this class is equivalent to
1466 * com::SafeArray<>. See the description of that template and its methods for
1467 * more information.
1468 *
1469 * Output GUID arrays are handled by a separate class, SafeGUIDArrayOut, since
1470 * this class cannot handle them because of const modifiers.
1471 */
1472class SafeGUIDArray : public SafeArray<nsID *>
1473{
1474public:
1475
1476 typedef SafeArray<nsID *> Base;
1477
1478 class nsIDRef
1479 {
1480 public:
1481
1482 nsIDRef(nsID * &aVal) : mVal(aVal) { AssertCompile(sizeof(nsID) <= sizeof(Zeroes)); }
1483
1484 operator const nsID &() const { return mVal ? *mVal : *(const nsID *)&Zeroes[0]; }
1485 operator nsID() const { return mVal ? *mVal : *(nsID *)&Zeroes[0]; }
1486
1487 const nsID *operator&() const { return mVal ? mVal : (const nsID *)&Zeroes[0]; }
1488
1489 nsIDRef &operator= (const nsID &aThat)
1490 {
1491 if (mVal == NULL)
1492 SafeGUIDArray::Copy(&aThat, mVal);
1493 else
1494 *mVal = aThat;
1495 return *this;
1496 }
1497
1498 private:
1499
1500 nsID * &mVal;
1501
1502 friend class SafeGUIDArray;
1503 };
1504
1505 /** See SafeArray<>::SafeArray(). */
1506 SafeGUIDArray() {}
1507
1508 /** See SafeArray<>::SafeArray(size_t). */
1509 SafeGUIDArray(size_t aSize) : Base(aSize) {}
1510
1511 /**
1512 * Array access operator that returns an array element by reference. As a
1513 * special case, the return value of this operator on XPCOM is an nsID (GUID)
1514 * reference, instead of an nsID pointer (the actual SafeArray template
1515 * argument), for compatibility with the MS COM version.
1516 *
1517 * The rest is equivalent to SafeArray<>::operator[].
1518 */
1519 nsIDRef operator[] (size_t aIdx)
1520 {
1521 Assert(m.arr != NULL);
1522 Assert(aIdx < size());
1523 return nsIDRef(m.arr[aIdx]);
1524 }
1525
1526 /**
1527 * Const version of #operator[] that returns an array element by value.
1528 */
1529 const nsID &operator[] (size_t aIdx) const
1530 {
1531 Assert(m.arr != NULL);
1532 Assert(aIdx < size());
1533 return m.arr[aIdx] ? *m.arr[aIdx] : *(const nsID *)&Zeroes[0];
1534 }
1535};
1536
1537/**
1538 * Version of com::SafeArray for const arrays of GUID.
1539 *
1540 * This class is used to work with input GUID array parameters in method
1541 * implementations. See SafeGUIDArray for more details.
1542 */
1543class SafeConstGUIDArray : public SafeArray<const nsID *,
1544 SafeArrayTraits<nsID *> >
1545{
1546public:
1547
1548 typedef SafeArray<const nsID *, SafeArrayTraits<nsID *> > Base;
1549
1550 /** See SafeArray<>::SafeArray(). */
1551 SafeConstGUIDArray() { AssertCompile(sizeof(nsID) <= sizeof(Zeroes)); }
1552
1553 /* See SafeArray<>::SafeArray(ComSafeArrayIn(T, aArg)). */
1554 SafeConstGUIDArray(ComSafeGUIDArrayIn(aArg))
1555 : Base(ComSafeGUIDArrayInArg(aArg)) {}
1556
1557 /**
1558 * Array access operator that returns an array element by reference. As a
1559 * special case, the return value of this operator on XPCOM is nsID (GUID)
1560 * instead of nsID *, for compatibility with the MS COM version.
1561 *
1562 * The rest is equivalent to SafeArray<>::operator[].
1563 */
1564 const nsID &operator[] (size_t aIdx) const
1565 {
1566 AssertReturn(m.arr != NULL, *(const nsID *)&Zeroes[0]);
1567 AssertReturn(aIdx < size(), *(const nsID *)&Zeroes[0]);
1568 return *m.arr[aIdx];
1569 }
1570
1571private:
1572
1573 /* These are disabled because of const. */
1574 bool reset(size_t aNewSize) { NOREF(aNewSize); return false; }
1575};
1576
1577#else /* !VBOX_WITH_XPCOM */
1578
1579typedef SafeArray<GUID> SafeGUIDArray;
1580typedef SafeArray<const GUID, SafeArrayTraits<GUID> > SafeConstGUIDArray;
1581
1582#endif /* !VBOX_WITH_XPCOM */
1583
1584////////////////////////////////////////////////////////////////////////////////
1585
1586#ifdef VBOX_WITH_XPCOM
1587
1588template<class I>
1589struct SafeIfaceArrayTraits
1590{
1591protected:
1592
1593 static void Init(I * &aElem) { aElem = NULL; }
1594 static void Uninit(I * &aElem)
1595 {
1596 if (aElem)
1597 {
1598 aElem->Release();
1599 aElem = NULL;
1600 }
1601 }
1602
1603 static void Copy(I * aFrom, I * &aTo)
1604 {
1605 if (aFrom != NULL)
1606 {
1607 aTo = aFrom;
1608 aTo->AddRef();
1609 }
1610 else
1611 aTo = NULL;
1612 }
1613
1614public:
1615
1616 /* Magic to workaround strict rules of par. 4.4.4 of the C++ standard. */
1617 static I **__asInParam_Arr(I **aArr) { return aArr; }
1618 static I **__asInParam_Arr(const I **aArr) { return const_cast<I **>(aArr); }
1619};
1620
1621#else /* !VBOX_WITH_XPCOM */
1622
1623template<class I>
1624struct SafeIfaceArrayTraits
1625{
1626protected:
1627
1628 static VARTYPE VarType() { return VT_DISPATCH; }
1629 static ULONG VarCount(size_t aSize) { return (ULONG)aSize; }
1630 static size_t Size(ULONG aVarCount) { return (size_t)aVarCount; }
1631
1632 static void Copy(I * aFrom, I * &aTo)
1633 {
1634 if (aFrom != NULL)
1635 {
1636 aTo = aFrom;
1637 aTo->AddRef();
1638 }
1639 else
1640 aTo = NULL;
1641 }
1642
1643 static SAFEARRAY *CreateSafeArray(VARTYPE aVarType, SAFEARRAYBOUND *aBound)
1644 {
1645 NOREF(aVarType);
1646 return SafeArrayCreateEx(VT_DISPATCH, 1, aBound, (PVOID)&COM_IIDOF(I));
1647 }
1648};
1649
1650#endif /* !VBOX_WITH_XPCOM */
1651
1652////////////////////////////////////////////////////////////////////////////////
1653
1654/**
1655 * Version of com::SafeArray for arrays of interface pointers.
1656 *
1657 * Except that it manages arrays of interface pointers, the usage of this class
1658 * is identical to com::SafeArray.
1659 *
1660 * @param I Interface class (no asterisk).
1661 */
1662template<class I>
1663class SafeIfaceArray : public SafeArray<I *, SafeIfaceArrayTraits<I> >
1664{
1665public:
1666
1667 typedef SafeArray<I *, SafeIfaceArrayTraits<I> > Base;
1668
1669 /**
1670 * Creates a null array.
1671 */
1672 SafeIfaceArray() {}
1673
1674 /**
1675 * Creates a new array of the given size. All elements of the newly created
1676 * array initialized with null values.
1677 *
1678 * @param aSize Initial number of elements in the array. Must be greater
1679 * than 0.
1680 *
1681 * @note If this object remains null after construction it means that there
1682 * was not enough memory for creating an array of the requested size.
1683 * The constructor will also assert in this case.
1684 */
1685 SafeIfaceArray(size_t aSize) { Base::resize(aSize); }
1686
1687 /**
1688 * Weakly attaches this instance to the existing array passed in a method
1689 * parameter declared using the ComSafeArrayIn macro. When using this call,
1690 * always wrap the parameter name in the ComSafeArrayOutArg macro call like
1691 * this:
1692 * <pre>
1693 * SafeArray safeArray(ComSafeArrayInArg(aArg));
1694 * </pre>
1695 *
1696 * Note that this constructor doesn't take the ownership of the array. In
1697 * particular, this means that operations that operate on the ownership
1698 * (e.g. #detachTo()) are forbidden and will assert.
1699 *
1700 * @param aArg Input method parameter to attach to.
1701 */
1702 SafeIfaceArray(ComSafeArrayIn(I *, aArg))
1703 {
1704 if (aArg)
1705 {
1706#ifdef VBOX_WITH_XPCOM
1707
1708 Base::m.size = aArgSize;
1709 Base::m.arr = aArg;
1710 Base::m.isWeak = true;
1711
1712#else /* !VBOX_WITH_XPCOM */
1713
1714 SAFEARRAY *arg = aArg;
1715
1716 AssertReturnVoid(arg->cDims == 1);
1717
1718 VARTYPE vt;
1719 HRESULT rc = SafeArrayGetVartype(arg, &vt);
1720 AssertComRCReturnVoid(rc);
1721 AssertMsgReturnVoid(vt == VT_UNKNOWN || vt == VT_DISPATCH,
1722 ("Expected vartype VT_UNKNOWN or VT_DISPATCH, got %d.\n",
1723 vt));
1724 GUID guid;
1725 rc = SafeArrayGetIID(arg, &guid);
1726 AssertComRCReturnVoid(rc);
1727 AssertMsgReturnVoid(InlineIsEqualGUID(COM_IIDOF(I), guid) || arg->rgsabound[0].cElements == 0 /* IDispatch if empty */,
1728 ("Expected IID {%RTuuid}, got {%RTuuid}.\n", &COM_IIDOF(I), &guid));
1729
1730 rc = SafeArrayAccessData(arg, (void HUGEP **)&this->m.raw);
1731 AssertComRCReturnVoid(rc);
1732
1733 this->m.arr = arg;
1734 this->m.isWeak = true;
1735
1736#endif /* !VBOX_WITH_XPCOM */
1737 }
1738 }
1739
1740 /**
1741 * Creates a deep copy of the given standard C++ container that stores
1742 * interface pointers as objects of the ComPtr\<I\> class.
1743 *
1744 * @param aCntr Container object to copy.
1745 *
1746 * @tparam C Standard C++ container template class (normally deduced from
1747 * @c aCntr).
1748 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1749 * @tparam OI Argument to the ComPtr template (deduced from @c aCntr).
1750 */
1751 template<template<typename, typename> class C, class A, class OI>
1752 SafeIfaceArray(const C<ComPtr<OI>, A> & aCntr)
1753 {
1754 typedef C<ComPtr<OI>, A> List;
1755
1756 Base::resize(aCntr.size());
1757 AssertReturnVoid(!Base::isNull());
1758
1759 size_t i = 0;
1760 for (typename List::const_iterator it = aCntr.begin(); it != aCntr.end(); ++it, ++i)
1761#ifdef VBOX_WITH_XPCOM
1762 SafeIfaceArray::Copy(*it, Base::m.arr[i]);
1763#else
1764 SafeIfaceArray::Copy(*it, Base::m.raw[i]);
1765#endif
1766 }
1767
1768 /**
1769 * Creates a deep copy of the given standard C++ container that stores
1770 * interface pointers as objects of the ComObjPtr\<I\> class.
1771 *
1772 * @param aCntr Container object to copy.
1773 *
1774 * @tparam C Standard C++ container template class (normally deduced from
1775 * @c aCntr).
1776 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1777 * @tparam OI Argument to the ComObjPtr template (deduced from @c aCntr).
1778 */
1779 template<template<typename, typename> class C, class A, class OI>
1780 SafeIfaceArray(const C<ComObjPtr<OI>, A> & aCntr)
1781 {
1782 typedef C<ComObjPtr<OI>, A> List;
1783
1784 Base::resize(aCntr.size());
1785 AssertReturnVoid(!Base::isNull());
1786
1787 size_t i = 0;
1788 for (typename List::const_iterator it = aCntr.begin(); it != aCntr.end(); ++it, ++i)
1789#ifdef VBOX_WITH_XPCOM
1790 SafeIfaceArray::Copy(*it, Base::m.arr[i]);
1791#else
1792 SafeIfaceArray::Copy(*it, Base::m.raw[i]);
1793#endif
1794 }
1795
1796 /**
1797 * Creates a deep copy of the given standard C++ map whose values are
1798 * interface pointers stored as objects of the ComPtr\<I\> class.
1799 *
1800 * @param aMap Map object to copy.
1801 *
1802 * @tparam C Standard C++ map template class (normally deduced from
1803 * @c aCntr).
1804 * @tparam L Standard C++ compare class (deduced from @c aCntr).
1805 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1806 * @tparam K Map key class (deduced from @c aCntr).
1807 * @tparam OI Argument to the ComPtr template (deduced from @c aCntr).
1808 */
1809 template<template<typename, typename, typename, typename>
1810 class C, class L, class A, class K, class OI>
1811 SafeIfaceArray(const C<K, ComPtr<OI>, L, A> & aMap)
1812 {
1813 typedef C<K, ComPtr<OI>, L, A> Map;
1814
1815 Base::resize(aMap.size());
1816 AssertReturnVoid(!Base::isNull());
1817
1818 size_t i = 0;
1819 for (typename Map::const_iterator it = aMap.begin(); it != aMap.end(); ++it, ++i)
1820#ifdef VBOX_WITH_XPCOM
1821 SafeIfaceArray::Copy(it->second, Base::m.arr[i]);
1822#else
1823 SafeIfaceArray::Copy(it->second, Base::m.raw[i]);
1824#endif
1825 }
1826
1827 /**
1828 * Creates a deep copy of the given standard C++ map whose values are
1829 * interface pointers stored as objects of the ComObjPtr\<I\> class.
1830 *
1831 * @param aMap Map object to copy.
1832 *
1833 * @tparam C Standard C++ map template class (normally deduced from
1834 * @c aCntr).
1835 * @tparam L Standard C++ compare class (deduced from @c aCntr).
1836 * @tparam A Standard C++ allocator class (deduced from @c aCntr).
1837 * @tparam K Map key class (deduced from @c aCntr).
1838 * @tparam OI Argument to the ComObjPtr template (deduced from @c aCntr).
1839 */
1840 template<template<typename, typename, typename, typename>
1841 class C, class L, class A, class K, class OI>
1842 SafeIfaceArray(const C<K, ComObjPtr<OI>, L, A> & aMap)
1843 {
1844 typedef C<K, ComObjPtr<OI>, L, A> Map;
1845
1846 Base::resize(aMap.size());
1847 AssertReturnVoid(!Base::isNull());
1848
1849 size_t i = 0;
1850 for (typename Map::const_iterator it = aMap.begin();
1851 it != aMap.end(); ++it, ++i)
1852#ifdef VBOX_WITH_XPCOM
1853 SafeIfaceArray::Copy(it->second, Base::m.arr[i]);
1854#else
1855 SafeIfaceArray::Copy(it->second, Base::m.raw[i]);
1856#endif
1857 }
1858
1859 void setElement(size_t iIdx, I* obj)
1860 {
1861#ifdef VBOX_WITH_XPCOM
1862 SafeIfaceArray::Copy(obj, Base::m.arr[iIdx]);
1863#else
1864 SafeIfaceArray::Copy(obj, Base::m.raw[iIdx]);
1865#endif
1866 }
1867};
1868
1869} /* namespace com */
1870
1871/** @} */
1872
1873#endif /* !VBOX_INCLUDED_com_array_h */
1874
Note: See TracBrowser for help on using the repository browser.

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