VirtualBox

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

Last change on this file since 80373 was 80373, checked in by vboxsync, 6 years ago

com/array.h: handling empty base elements better (hopefully will eliminate static code analysis issues) by using a const array as the representation.

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

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