VirtualBox

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

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

*: scm --fix-header-guard-endif

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