VirtualBox

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

Last change on this file since 97583 was 96407, checked in by vboxsync, 2 years ago

scm copyright and license note update

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

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