VirtualBox

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

Last change on this file since 87141 was 85289, checked in by vboxsync, 4 years ago

VBox/com/array.h: Probably a good idea to check the com::SafeArray::resize result before copying over new array content in the initFrom() methods and other places. Made the initFrom() methods return HRESULT. Ditto cloneTo(). bugref:9790

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