| 1 |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. |
| 2 |
using System; |
| 3 |
using System.Collections.Generic; |
| 4 |
using System.Runtime.CompilerServices; |
| 5 |
using System.Security; |
| 6 |
|
| 7 |
#if HAS_AWAIT |
| 8 |
namespace System.Linq |
| 9 |
{ |
| 10 |
public interface IYielder<in T> |
| 11 |
{ |
| 12 |
IAwaitable Return(T value); |
| 13 |
IAwaitable Break(); |
| 14 |
} |
| 15 |
|
| 16 |
class Yielder<T> : IYielder<T>, IAwaitable, IAwaiter |
| 17 |
{ |
| 18 |
private readonly Action<Yielder<T>> _create; |
| 19 |
private bool _running; |
| 20 |
private bool _hasValue; |
| 21 |
private T _value; |
| 22 |
private bool _stopped; |
| 23 |
private Action _continuation; |
| 24 |
|
| 25 |
public Yielder(Action<Yielder<T>> create) |
| 26 |
{ |
| 27 |
_create = create; |
| 28 |
} |
| 29 |
|
| 30 |
public IAwaitable Return(T value) |
| 31 |
{ |
| 32 |
_hasValue = true; |
| 33 |
_value = value; |
| 34 |
return this; |
| 35 |
} |
| 36 |
|
| 37 |
public IAwaitable Break() |
| 38 |
{ |
| 39 |
_stopped = true; |
| 40 |
return this; |
| 41 |
} |
| 42 |
|
| 43 |
public Yielder<T> GetEnumerator() |
| 44 |
{ |
| 45 |
return this; |
| 46 |
} |
| 47 |
|
| 48 |
public bool MoveNext() |
| 49 |
{ |
| 50 |
if (!_running) |
| 51 |
{ |
| 52 |
_running = true; |
| 53 |
_create(this); |
| 54 |
} |
| 55 |
else |
| 56 |
{ |
| 57 |
_hasValue = false; |
| 58 |
_continuation(); |
| 59 |
} |
| 60 |
|
| 61 |
return !_stopped && _hasValue; |
| 62 |
} |
| 63 |
|
| 64 |
public T Current |
| 65 |
{ |
| 66 |
get |
| 67 |
{ |
| 68 |
return _value; |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
public void Reset() |
| 73 |
{ |
| 74 |
throw new NotSupportedException(); |
| 75 |
} |
| 76 |
|
| 77 |
public IAwaiter GetAwaiter() |
| 78 |
{ |
| 79 |
return this; |
| 80 |
} |
| 81 |
|
| 82 |
public bool IsCompleted |
| 83 |
{ |
| 84 |
get { return false; } |
| 85 |
} |
| 86 |
|
| 87 |
public void GetResult() { } |
| 88 |
|
| 89 |
[SecurityCritical] |
| 90 |
public void UnsafeOnCompleted(Action continuation) |
| 91 |
{ |
| 92 |
_continuation = continuation; |
| 93 |
} |
| 94 |
|
| 95 |
public void OnCompleted(Action continuation) |
| 96 |
{ |
| 97 |
_continuation = continuation; |
| 98 |
} |
| 99 |
} |
| 100 |
} |
| 101 |
#endif |