ImmutableList.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. namespace UniRx.InternalUtil
  3. {
  4. // ImmutableList is sometimes useful, use for public.
  5. public class ImmutableList<T>
  6. {
  7. public static readonly ImmutableList<T> Empty = new ImmutableList<T>();
  8. T[] data;
  9. public T[] Data
  10. {
  11. get { return data; }
  12. }
  13. ImmutableList()
  14. {
  15. data = new T[0];
  16. }
  17. public ImmutableList(T[] data)
  18. {
  19. this.data = data;
  20. }
  21. public ImmutableList<T> Add(T value)
  22. {
  23. var newData = new T[data.Length + 1];
  24. Array.Copy(data, newData, data.Length);
  25. newData[data.Length] = value;
  26. return new ImmutableList<T>(newData);
  27. }
  28. public ImmutableList<T> Remove(T value)
  29. {
  30. var i = IndexOf(value);
  31. if (i < 0) return this;
  32. var length = data.Length;
  33. if (length == 1) return Empty;
  34. var newData = new T[length - 1];
  35. Array.Copy(data, 0, newData, 0, i);
  36. Array.Copy(data, i + 1, newData, i, length - i - 1);
  37. return new ImmutableList<T>(newData);
  38. }
  39. public int IndexOf(T value)
  40. {
  41. for (var i = 0; i < data.Length; ++i)
  42. {
  43. // ImmutableList only use for IObserver(no worry for boxed)
  44. if (object.Equals(data[i], value)) return i;
  45. }
  46. return -1;
  47. }
  48. }
  49. }