VirtualBox

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

Last change on this file was 99828, checked in by vboxsync, 12 months ago

*: A bunch of adjustments that allows using /permissive- with Visual C++ (qt 6.x necessity).

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

© 2023 Oracle
ContactPrivacy policyTerms of Use