File size: 2,520 Bytes
18a519f | 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 | using System;
using System.Collections;
using System.Collections.Generic;
namespace UnityEngine.InputSystem.Utilities
{
/// <summary>
/// Helper when having either a single element or a list of elements. Avoids
/// having to allocate GC heap garbage or having to alternatively split code paths.
/// </summary>
/// <typeparam name="TValue"></typeparam>
internal struct OneOrMore<TValue, TList> : IReadOnlyList<TValue>
where TList : IReadOnlyList<TValue>
{
private readonly bool m_IsSingle;
private readonly TValue m_Single;
private readonly TList m_Multiple;
public int Count => m_IsSingle ? 1 : m_Multiple.Count;
public TValue this[int index]
{
get
{
if (!m_IsSingle)
return m_Multiple[index];
if (index < 0 || index > 1)
throw new ArgumentOutOfRangeException(nameof(index));
return m_Single;
}
}
public OneOrMore(TValue single)
{
m_IsSingle = true;
m_Single = single;
m_Multiple = default;
}
public OneOrMore(TList multiple)
{
m_IsSingle = false;
m_Single = default;
m_Multiple = multiple;
}
public static implicit operator OneOrMore<TValue, TList>(TValue single)
{
return new OneOrMore<TValue, TList>(single);
}
public static implicit operator OneOrMore<TValue, TList>(TList multiple)
{
return new OneOrMore<TValue, TList>(multiple);
}
public IEnumerator<TValue> GetEnumerator()
{
return new Enumerator { m_List = this };
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private class Enumerator : IEnumerator<TValue>
{
internal int m_Index = -1;
internal OneOrMore<TValue, TList> m_List;
public bool MoveNext()
{
++m_Index;
if (m_Index >= m_List.Count)
return false;
return true;
}
public void Reset()
{
m_Index = -1;
}
public TValue Current => m_List[m_Index];
object IEnumerator.Current => Current;
public void Dispose()
{
}
}
}
}
|