ImmutableList.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. namespace System.Reactive
  5. {
  6. internal sealed class ImmutableList<T>
  7. {
  8. public static readonly ImmutableList<T> Empty = new ImmutableList<T>();
  9. private readonly T[] _data;
  10. private ImmutableList()
  11. {
  12. _data = new T[0];
  13. }
  14. public ImmutableList(T[] data)
  15. {
  16. _data = data;
  17. }
  18. public T[] Data => _data;
  19. public ImmutableList<T> Add(T value)
  20. {
  21. var newData = new T[_data.Length + 1];
  22. Array.Copy(_data, newData, _data.Length);
  23. newData[_data.Length] = value;
  24. return new ImmutableList<T>(newData);
  25. }
  26. public ImmutableList<T> Remove(T value)
  27. {
  28. var i = IndexOf(value);
  29. if (i < 0)
  30. {
  31. return this;
  32. }
  33. var length = _data.Length;
  34. if (length == 1)
  35. {
  36. return Empty;
  37. }
  38. var newData = new T[length - 1];
  39. Array.Copy(_data, 0, newData, 0, i);
  40. Array.Copy(_data, i + 1, newData, i, length - i - 1);
  41. return new ImmutableList<T>(newData);
  42. }
  43. private int IndexOf(T value)
  44. {
  45. for (var i = 0; i < _data.Length; ++i)
  46. {
  47. if (object.Equals(_data[i], value))
  48. {
  49. return i;
  50. }
  51. }
  52. return -1;
  53. }
  54. }
  55. }