summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
blob: e219a8676962fa5c278feae20295f4482e55ee36 (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
// 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.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Security;

namespace System.Runtime.InteropServices.WindowsRuntime
{
    internal delegate IEnumerator<T> GetEnumerator_Delegate<out T>();

    // This is a set of stub methods implementing the support for the IEnumerable`1 interface on WinRT
    // objects that implement IIterable`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 IterableToEnumerableAdapter objects. Rather, they are of type
    // IIterable<T>. No actual IterableToEnumerableAdapter object is ever instantiated. Thus, you will
    // see a lot of expressions that cast "this" to "IIterable<T>". 
    internal sealed class IterableToEnumerableAdapter
    {
        private IterableToEnumerableAdapter()
        {
            Debug.Assert(false, "This class is never instantiated");
        }
        
        // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable<T>.
        internal IEnumerator<T> GetEnumerator_Stub<T>()
        {
            IIterable<T> _this = JitHelpers.UnsafeCast<IIterable<T>>(this);
            return new IteratorToEnumeratorAdapter<T>(_this.First());
        }

        // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable<T>
        // and it is possible that the implementation supports IEnumerable<Type>/IEnumerable<string>/IEnumerable<Exception>/
        // IEnumerable<array>/IEnumerable<delegate> rather than IEnumerable<T> because T is assignable from Type/string/
        // Exception/array/delegate via co-variance.
        internal IEnumerator<T> GetEnumerator_Variance_Stub<T>() where T : class
        {
            bool fUseString;
            Delegate target = System.StubHelpers.StubHelpers.GetTargetForAmbiguousVariantCall(
                this,
                typeof(IEnumerable<T>).TypeHandle.Value,
                out fUseString);

            if (target != null)
            {
                return (JitHelpers.UnsafeCast<GetEnumerator_Delegate<T>>(target))();
            }
            
            if (fUseString)
            {
                return JitHelpers.UnsafeCast<IEnumerator<T>>(GetEnumerator_Stub<string>());
            }

            return GetEnumerator_Stub<T>();
        }
    }

    internal sealed class BindableIterableToEnumerableAdapter
    {
        private BindableIterableToEnumerableAdapter()
        {
            Debug.Assert(false, "This class is never instantiated");
        }

        private sealed class NonGenericToGenericIterator : IIterator<object>
        {
            private IBindableIterator iterator;

            public NonGenericToGenericIterator(IBindableIterator iterator)
            { this.iterator = iterator; }

            public object Current  { get { return iterator.Current; } }
            public bool HasCurrent { get { return iterator.HasCurrent; } }
            public bool MoveNext() { return iterator.MoveNext(); }
            public int GetMany(object[] items) { throw new NotSupportedException(); }
        }

        // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable.
        internal IEnumerator GetEnumerator_Stub()
        {
            IBindableIterable _this = JitHelpers.UnsafeCast<IBindableIterable>(this);
            return new IteratorToEnumeratorAdapter<object>(new NonGenericToGenericIterator(_this.First()));
        }
    }

    // Adapter class which holds a Windows Runtime IIterator<T>, exposing it as a managed IEnumerator<T>


    // There are a few implementation differences between the Iterator and IEnumerator which need to be 
    // addressed. Iterator starts at index 0 while IEnumerator starts at index -1 as a result of which 
    // the first call to IEnumerator.Current is correct only after calling MoveNext(). 
    // Also IEnumerator throws an exception when we call Current after reaching the end of collection.
    internal sealed class IteratorToEnumeratorAdapter<T> : IEnumerator<T>
    {
        private IIterator<T> m_iterator;
        private bool m_hadCurrent;
        private T m_current;
        private bool m_isInitialized;

        internal IteratorToEnumeratorAdapter(IIterator<T> iterator)
        {
            Contract.Requires(iterator != null);
            m_iterator = iterator;
            m_hadCurrent = true;
            m_isInitialized = false;
        }

        public T Current
        {
            get
            {
                // The enumerator has not been advanced to the first element yet.
                if (!m_isInitialized)
                    ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
                // The enumerator has reached the end of the collection
                if (!m_hadCurrent)
                    ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
                return m_current;
            }
        }

        object IEnumerator.Current
        {
            get
            {
                // The enumerator has not been advanced to the first element yet.
                if (!m_isInitialized)
                    ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
                // The enumerator has reached the end of the collection
                if (!m_hadCurrent)
                    ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
                return m_current;
            }
        }

        public bool MoveNext()
        {
            // If we've passed the end of the iteration, IEnumerable<T> should return false, while
            // IIterable will fail the interface call
            if (!m_hadCurrent)
            {
                return false;
            }

            // IIterators start at index 0, rather than -1.  If this is the first call, we need to just
            // check HasCurrent rather than actually moving to the next element
            try
            {
                if (!m_isInitialized)
                {
                    m_hadCurrent = m_iterator.HasCurrent;
                    m_isInitialized = true;
                }
                else
                {
                    m_hadCurrent = m_iterator.MoveNext();
                }

                // We want to save away the current value for two reasons:
                //  1. Accessing .Current is cheap on other iterators, so having it be a property which is a
                //     simple field access preserves the expected performance characteristics (as opposed to
                //     triggering a COM call every time the property is accessed)
                //
                //  2. This allows us to preserve the same semantics as generic collection iteration when iterating
                //     beyond the end of the collection - namely that Current continues to return the last value
                //     of the collection
                if (m_hadCurrent)
                {
                    m_current = m_iterator.Current;
                }
            }
            catch (Exception e)
            {
                // Translate E_CHANGED_STATE into an InvalidOperationException for an updated enumeration
                if (Marshal.GetHRForException(e) == __HResults.E_CHANGED_STATE)
                {
                    ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
                }
                else
                {
                    throw;
                }
            }

            return m_hadCurrent;
        }

        public void Reset()
        {
            throw new NotSupportedException();
        }

        public void Dispose()
        {
        }
    }
}