A game about forced loneliness, made by TACStudios
1using System;
2using System.Collections;
3using System.Collections.Generic;
4
5namespace UnityEngine.TestTools
6{
7 internal class EnumeratorHelper
8 {
9 public static bool IsRunningNestedEnumerator => enumeratorStack.Count > 0;
10
11 private static IEnumerator currentEnumerator;
12 private static Stack<IEnumerator> enumeratorStack = new Stack<IEnumerator>();
13
14 /// <summary>
15 /// This method executes a given enumerator and all nested enumerators.
16 /// If any resuming (setting of pc) is needed, it needs to be done before being passed to this method.
17 /// </summary>
18 public static IEnumerator UnpackNestedEnumerators(IEnumerator testEnumerator)
19 {
20 if (testEnumerator == null)
21 {
22 throw new ArgumentNullException(nameof(testEnumerator));
23 }
24
25 currentEnumerator = testEnumerator;
26 enumeratorStack.Clear();
27
28 return ProgressOnEnumerator();
29 }
30
31 private static IEnumerator ProgressOnEnumerator()
32 {
33 while (true)
34 {
35 if (!currentEnumerator.MoveNext())
36 {
37 if (enumeratorStack.Count == 0)
38 {
39 yield break;
40 }
41 currentEnumerator = enumeratorStack.Pop();
42 continue;
43 }
44
45 if (currentEnumerator.Current is IEnumerator nestedEnumerator)
46 {
47 enumeratorStack.Push(currentEnumerator);
48 currentEnumerator = nestedEnumerator;
49 }
50 else
51 {
52 yield return currentEnumerator.Current;
53 }
54 }
55 }
56
57 public static void SetEnumeratorPC(int pc)
58 {
59 if (currentEnumerator == null)
60 {
61 throw new Exception("No enumerator is currently running.");
62 }
63
64 if (IsRunningNestedEnumerator)
65 {
66 throw new Exception("Cannot set the enumerator PC while running nested enumerators.");
67 }
68
69 ActivePcHelper.SetEnumeratorPC(currentEnumerator, pc);
70 }
71
72 public static int GetEnumeratorPC()
73 {
74 if (currentEnumerator == null)
75 {
76 throw new Exception("No enumerator is currently running.");
77 }
78
79 if (IsRunningNestedEnumerator)
80 {
81 // Restrict the getting of PC, as it will not reflect what is currently running;
82 throw new Exception("Cannot get the enumerator PC while running nested enumerators.");
83 }
84
85 return ActivePcHelper.GetEnumeratorPC(currentEnumerator);
86 }
87
88 private static TestCommandPcHelper pcHelper;
89 internal static TestCommandPcHelper ActivePcHelper
90 {
91 get
92 {
93 if (pcHelper == null)
94 {
95 pcHelper = new TestCommandPcHelper();
96 }
97
98 return pcHelper;
99 }
100 set
101 {
102 pcHelper = value;
103 }
104 }
105 }
106}