Repository navigation
Expand file tree
/
Copy pathLoopDetector.cs
More file actions
74 lines (65 loc) · 2.04 KB
/
Copy pathLoopDetector.cs
File metadata and controls
74 lines (65 loc) · 2.04 KB
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
// Copyright (c) The LEGO Group. All rights reserved.
namespace LEGO.AsyncAPI.Writers
{
using System;
using System.Collections.Generic;
internal class LoopDetector
{
private readonly Dictionary<Type, Stack<object>> loopStacks = new Dictionary<Type, Stack<object>>();
/// <summary>
/// Maintain history of traversals to avoid stack overflows from cycles.
/// </summary>
/// <param name="key">Identifier used for current context.</param>
/// <returns>If method returns false a loop was detected and the key is not added.</returns>
public bool PushLoop<T>(T key)
{
Stack<object> stack;
if (!this.loopStacks.TryGetValue(typeof(T), out stack))
{
stack = new Stack<object>();
this.loopStacks.Add(typeof(T), stack);
}
if (!stack.Contains(key))
{
stack.Push(key);
return true;
}
else
{
return false; // Loop detected
}
}
/// <summary>
/// Exit from the context in cycle detection.
/// </summary>
public void PopLoop<T>()
{
if (this.loopStacks[typeof(T)].Count > 0)
{
this.loopStacks[typeof(T)].Pop();
}
}
public void SaveLoop<T>(T loop)
{
if (!this.Loops.ContainsKey(typeof(T)))
{
this.Loops[typeof(T)] = new List<object>();
}
this.Loops[typeof(T)].Add(loop);
}
/// <summary>
/// Gets list of Loops detected.
/// </summary>
/// <value>
/// The loops.
/// </value>
public Dictionary<Type, List<object>> Loops { get; } = new Dictionary<Type, List<object>>();
/// <summary>
/// Reset loop tracking stack.
/// </summary>
internal void ClearLoop<T>()
{
this.loopStacks[typeof(T)].Clear();
}
}
}