summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
blob: 77f3a9464fa1de5201b27623baff6494b32081b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//

using System;
using System.Security;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

namespace System.Runtime.InteropServices.WindowsRuntime
{
    // This is a set of stub methods implementing the support for the IVector`1 interface on managed
    // objects that implement IList`1. Used by the interop mashaling infrastructure.
    //
    // The methods on this class must be written VERY carefully to avoid introducing security holes.
    // That's because they are invoked with special "this"! The "this" object
    // for all of these methods are not ListToVectorAdapter objects. Rather, they are of type
    // IList<T>. No actual ListToVectorAdapter object is ever instantiated. Thus, you will
    // see a lot of expressions that cast "this" to "IList<T>". 
    internal sealed class ListToVectorAdapter
    {
        private ListToVectorAdapter()
        {
            Contract.Assert(false, "This class is never instantiated");
        }

        // T GetAt(uint index)
        [SecurityCritical]
        internal T GetAt<T>(uint index)
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
            EnsureIndexInt32(index, _this.Count);        

            try
            {
                return _this[(Int32)index];
            }
            catch (ArgumentOutOfRangeException ex)
            {
                throw WindowsRuntimeMarshal.GetExceptionForHR(__HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
            }
        }

        // uint Size { get }
        [SecurityCritical]
        internal uint Size<T>()
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
            return (uint)_this.Count;
        }

        // IVectorView<T> GetView()
        [SecurityCritical]
        internal IReadOnlyList<T> GetView<T>()
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
            Contract.Assert(_this != null);

            // Note: This list is not really read-only - you could QI for a modifiable
            // list.  We gain some perf by doing this.  We believe this is acceptable.
            IReadOnlyList<T> roList = _this as IReadOnlyList<T>;
            if (roList == null)
            {
                roList = new ReadOnlyCollection<T>(_this);
            }
            return roList;
        }

        // bool IndexOf(T value, out uint index)
        [SecurityCritical]
        internal bool IndexOf<T>(T value, out uint index)
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
            int ind = _this.IndexOf(value);

            if (-1 == ind)
            {
                index = 0;
                return false;
            }

            index = (uint)ind;
            return true;
        }

        // void SetAt(uint index, T value)
        [SecurityCritical]
        internal void SetAt<T>(uint index, T value)
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
            EnsureIndexInt32(index, _this.Count);

            try
            {
                _this[(int)index] = value;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                throw WindowsRuntimeMarshal.GetExceptionForHR(__HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
            }
        }

        // void InsertAt(uint index, T value)
        [SecurityCritical]
        internal void InsertAt<T>(uint index, T value)
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);

            // Inserting at an index one past the end of the list is equivalent to appending
            // so we need to ensure that we're within (0, count + 1).
            EnsureIndexInt32(index, _this.Count + 1);

            try
            {
                _this.Insert((int)index, value);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                // Change error code to match what WinRT expects
                ex.SetErrorCode(__HResults.E_BOUNDS);
                throw;
            }
        }

        // void RemoveAt(uint index)
        [SecurityCritical]
        internal void RemoveAt<T>(uint index)
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
            EnsureIndexInt32(index, _this.Count); 

            try
            {
                _this.RemoveAt((Int32)index);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                // Change error code to match what WinRT expects
                ex.SetErrorCode(__HResults.E_BOUNDS);
                throw;
            }
        }

        // void Append(T value)
        [SecurityCritical]
        internal void Append<T>(T value)
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
            _this.Add(value);
        }

        // void RemoveAtEnd()
        [SecurityCritical]
        internal void RemoveAtEnd<T>()
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
            if (_this.Count == 0)
            {
                Exception e = new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRemoveLastFromEmptyCollection"));
                e.SetErrorCode(__HResults.E_BOUNDS);
                throw e;
            }

            uint size = (uint)_this.Count;
            RemoveAt<T>(size - 1);
        }

        // void Clear()
        [SecurityCritical]
        internal void Clear<T>()
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
            _this.Clear();
        }

        // uint GetMany(uint startIndex, T[] items)
        [SecurityCritical]
        internal uint GetMany<T>(uint startIndex, T[] items)
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
            return GetManyHelper<T>(_this, startIndex, items);
        }

        // void ReplaceAll(T[] items)
        [SecurityCritical]
        internal void ReplaceAll<T>(T[] items)
        {
            IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
            _this.Clear();

            if (items != null)
            {
                foreach (T item in items)
                {
                    _this.Add(item);
                }
            }
        }

        // Helpers:

        private static void EnsureIndexInt32(uint index, int listCapacity)
        {
            // We use '<=' and not '<' becasue Int32.MaxValue == index would imply
            // that Size > Int32.MaxValue:
            if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
            {
                Exception e = new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
                e.SetErrorCode(__HResults.E_BOUNDS);
                throw e;
            }
        }

        private static uint GetManyHelper<T>(IList<T> sourceList, uint startIndex, T[] items)
        {
            // Calling GetMany with a start index equal to the size of the list should always
            // return 0 elements, regardless of the input item size
            if (startIndex == sourceList.Count)
            {
                return 0;
            }

            EnsureIndexInt32(startIndex, sourceList.Count);

            if (items == null)
            {
                return 0;
            }

            uint itemCount = Math.Min((uint)items.Length, (uint)sourceList.Count - startIndex);
            for (uint i = 0; i < itemCount; ++i)
            {
                items[i] = sourceList[(int)(i + startIndex)];
            }

            if (typeof(T) == typeof(string))
            {
                string[] stringItems = items as string[];

                // Fill in rest of the array with String.Empty to avoid marshaling failure
                for (uint i = itemCount; i < items.Length; ++i)
                    stringItems[i] = String.Empty;
            }

            return itemCount;
        }
    }
}