Index.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Runtime.CompilerServices;
  6. namespace System
  7. {
  8. /// <summary>Represent a type can be used to index a collection either from the start or the end.</summary>
  9. /// <remarks>
  10. /// Index is used by the C# compiler to support the new index syntax
  11. /// <code>
  12. /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 } ;
  13. /// int lastElement = someArray[^1]; // lastElement = 5
  14. /// </code>
  15. /// </remarks>
  16. public readonly struct Index : IEquatable<Index>
  17. {
  18. private readonly int _value;
  19. /// <summary>Construct an Index using a value and indicating if the index is from the start or from the end.</summary>
  20. /// <param name="value">The index value. it has to be zero or positive number.</param>
  21. /// <param name="fromEnd">Indicating if the index is from the start or from the end.</param>
  22. /// <remarks>
  23. /// If the Index constructed from the end, index value 1 means pointing at the last element and index value 0 means pointing at beyond last element.
  24. /// </remarks>
  25. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  26. public Index(int value, bool fromEnd = false)
  27. {
  28. if (value < 0)
  29. {
  30. ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException();
  31. }
  32. if (fromEnd)
  33. _value = ~value;
  34. else
  35. _value = value;
  36. }
  37. // The following private constructors mainly created for perf reason to avoid the checks
  38. private Index(int value)
  39. {
  40. _value = value;
  41. }
  42. /// <summary>Create an Index pointing at first element.</summary>
  43. public static Index Start => new Index(0);
  44. /// <summary>Create an Index pointing at beyond last element.</summary>
  45. public static Index End => new Index(~0);
  46. /// <summary>Create an Index from the start at the position indicated by the value.</summary>
  47. /// <param name="value">The index value from the start.</param>
  48. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  49. public static Index FromStart(int value)
  50. {
  51. if (value < 0)
  52. {
  53. ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException();
  54. }
  55. return new Index(value);
  56. }
  57. /// <summary>Create an Index from the end at the position indicated by the value.</summary>
  58. /// <param name="value">The index value from the end.</param>
  59. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  60. public static Index FromEnd(int value)
  61. {
  62. if (value < 0)
  63. {
  64. ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException();
  65. }
  66. return new Index(~value);
  67. }
  68. /// <summary>Returns the index value.</summary>
  69. public int Value
  70. {
  71. get
  72. {
  73. if (_value < 0)
  74. return ~_value;
  75. else
  76. return _value;
  77. }
  78. }
  79. /// <summary>Indicates whether the index is from the start or the end.</summary>
  80. public bool IsFromEnd => _value < 0;
  81. /// <summary>Calculate the offset from the start using the giving collection length.</summary>
  82. /// <param name="length">The length of the collection that the Index will be used with. length has to be a positive value</param>
  83. /// <remarks>
  84. /// For performance reason, we don't validate the input length parameter and the returned offset value against negative values.
  85. /// we don't validate either the returned offset is greater than the input length.
  86. /// It is expected Index will be used with collections which always have non negative length/count. If the returned offset is negative and
  87. /// then used to index a collection will get out of range exception which will be same affect as the validation.
  88. /// </remarks>
  89. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  90. public int GetOffset(int length)
  91. {
  92. int offset;
  93. if (IsFromEnd)
  94. offset = length - (~_value);
  95. else
  96. offset = _value;
  97. return offset;
  98. }
  99. /// <summary>Indicates whether the current Index object is equal to another object of the same type.</summary>
  100. /// <param name="value">An object to compare with this object</param>
  101. public override bool Equals(object value) => value is Index && _value == ((Index)value)._value;
  102. /// <summary>Indicates whether the current Index object is equal to another Index object.</summary>
  103. /// <param name="other">An object to compare with this object</param>
  104. public bool Equals (Index other) => _value == other._value;
  105. /// <summary>Returns the hash code for this instance.</summary>
  106. public override int GetHashCode() => _value;
  107. /// <summary>Converts integer number to an Index.</summary>
  108. public static implicit operator Index(int value) => FromStart(value);
  109. /// <summary>Converts the value of the current Index object to its equivalent string representation.</summary>
  110. public override string ToString()
  111. {
  112. if (IsFromEnd)
  113. return ToStringFromEnd();
  114. return ((uint)Value).ToString();
  115. }
  116. private string ToStringFromEnd()
  117. {
  118. Span<char> span = stackalloc char[11]; // 1 for ^ and 10 for longest possible uint value
  119. bool formatted = ((uint)Value).TryFormat(span.Slice(1), out int charsWritten);
  120. Debug.Assert(formatted);
  121. span[0] = '^';
  122. return new string(span.Slice(0, charsWritten + 1));
  123. }
  124. }
  125. }