VirtualBox

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

Last change on this file since 62361 was 62361, checked in by vboxsync, 8 years ago

VBox/com/array.h: preparation for -Wconversion

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