1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
6 using System.Diagnostics;
7 using Internal.Runtime.CompilerServices;
9 namespace System.Runtime.InteropServices.WindowsRuntime
11 // This is a set of stub methods implementing the support for the ICollection`1 interface on WinRT
12 // objects that support IVector`1. Used by the interop mashaling infrastructure.
14 // The methods on this class must be written VERY carefully to avoid introducing security holes.
15 // That's because they are invoked with special "this"! The "this" object
16 // for all of these methods are not VectorToCollectionAdapter objects. Rather, they are of type
17 // IVector<T>. No actual VectorToCollectionAdapter object is ever instantiated. Thus, you will see
18 // a lot of expressions that cast "this" to "IVector<T>".
19 internal sealed class VectorToCollectionAdapter
21 private VectorToCollectionAdapter()
23 Debug.Fail("This class is never instantiated");
27 internal int Count<T>()
29 IVector<T> _this = Unsafe.As<IVector<T>>(this);
30 uint size = _this.Size;
31 if (((uint)int.MaxValue) < size)
33 throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
39 // bool IsReadOnly { get }
40 internal bool IsReadOnly<T>()
46 internal void Add<T>(T item)
48 IVector<T> _this = Unsafe.As<IVector<T>>(this);
53 internal void Clear<T>()
55 IVector<T> _this = Unsafe.As<IVector<T>>(this);
59 // bool Contains(T item)
60 internal bool Contains<T>(T item)
62 IVector<T> _this = Unsafe.As<IVector<T>>(this);
65 return _this.IndexOf(item, out index);
68 // void CopyTo(T[] array, int arrayIndex)
69 internal void CopyTo<T>(T[] array, int arrayIndex)
72 throw new ArgumentNullException(nameof(array));
75 throw new ArgumentOutOfRangeException(nameof(arrayIndex));
77 if (array.Length <= arrayIndex && Count<T>() > 0)
78 throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds);
80 if (array.Length - arrayIndex < Count<T>())
81 throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
84 IVector<T> _this = Unsafe.As<IVector<T>>(this);
85 int count = Count<T>();
86 for (int i = 0; i < count; i++)
88 array[i + arrayIndex] = VectorToListAdapter.GetAt<T>(_this, (uint)i);
92 // bool Remove(T item)
93 internal bool Remove<T>(T item)
95 IVector<T> _this = Unsafe.As<IVector<T>>(this);
98 bool exists = _this.IndexOf(item, out index);
103 if (((uint)int.MaxValue) < index)
105 throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
108 VectorToListAdapter.RemoveAtHelper<T>(_this, index);