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
|
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel
{
using System.Collections.Generic;
using System.IdentityModel;
// Embed this struct in a class to represent a field of that class
// that is logically a list, but contains just one item in all but
// the rarest of scenarios. When this class must be passed around
// in internal APIs, use it as a ref parameter.
struct MostlySingletonList<T> where T : class
{
int count;
T singleton;
List<T> list;
public T this[int index]
{
get
{
if (this.list == null)
{
EnsureValidSingletonIndex(index);
return this.singleton;
}
else
{
return this.list[index];
}
}
}
public int Count
{
get { return this.count; }
}
public void Add(T item)
{
if (this.list == null)
{
if (this.count == 0)
{
this.singleton = item;
this.count = 1;
return;
}
this.list = new List<T>();
this.list.Add(this.singleton);
this.singleton = null;
}
this.list.Add(item);
this.count++;
}
static bool Compare(T x, T y)
{
return x == null ? y == null : x.Equals(y);
}
public bool Contains(T item)
{
return IndexOf(item) >= 0;
}
void EnsureValidSingletonIndex(int index)
{
if (this.count != 1 || index != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index"));
}
}
bool MatchesSingleton(T item)
{
return this.count == 1 && Compare(this.singleton, item);
}
public int IndexOf(T item)
{
if (this.list == null)
{
return MatchesSingleton(item) ? 0 : -1;
}
else
{
return this.list.IndexOf(item);
}
}
public bool Remove(T item)
{
if (this.list == null)
{
if (MatchesSingleton(item))
{
this.singleton = null;
this.count = 0;
return true;
}
else
{
return false;
}
}
else
{
bool result = this.list.Remove(item);
if (result)
{
this.count--;
}
return result;
}
}
public void RemoveAt(int index)
{
if (this.list == null)
{
EnsureValidSingletonIndex(index);
this.singleton = null;
this.count = 0;
}
else
{
this.list.RemoveAt(index);
this.count--;
}
}
}
}
|