diff --git a/src/System.Private.CoreLib/shared/System/Index.cs b/src/System.Private.CoreLib/shared/System/Index.cs index 887506ec629a..9767b981ef20 100644 --- a/src/System.Private.CoreLib/shared/System/Index.cs +++ b/src/System.Private.CoreLib/shared/System/Index.cs @@ -3,34 +3,138 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; +using System.Runtime.CompilerServices; namespace System { + /// Represent a type can be used to index a collection either from the start or the end. + /// + /// Index is used by the C# compiler to support the new index syntax + /// + /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 } ; + /// int lastElement = someArray[^1]; // lastElement = 5 + /// + /// public readonly struct Index : IEquatable { private readonly int _value; - public Index(int value, bool fromEnd) + /// Construct an Index using a value and indicating if the index is from the start or from the end. + /// The index value. it has to be zero or positive number. + /// Indicating if the index is from the start or from the end. + /// + /// 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. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Index(int value, bool fromEnd = false) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } - _value = fromEnd ? ~value : value; + if (fromEnd) + _value = ~value; + else + _value = value; } - public int Value => _value < 0 ? ~_value : _value; - public bool FromEnd => _value < 0; + // The following private constructors mainly created for perf reason to avoid the checks + private Index(int value) + { + _value = value; + } + + /// Create an Index pointing at first element. + public static Index Start => new Index(0); + + /// Create an Index pointing at beyond last element. + public static Index End => new Index(~0); + + /// Create an Index from the start at the position indicated by the value. + /// The index value from the start. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromStart(int value) + { + if (value < 0) + { + ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); + } + + return new Index(value); + } + + /// Create an Index from the end at the position indicated by the value. + /// The index value from the end. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Index FromEnd(int value) + { + if (value < 0) + { + ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); + } + + return new Index(~value); + } + + /// Returns the index value. + public int Value + { + get + { + if (_value < 0) + return ~_value; + else + return _value; + } + } + + /// Indicates whether the index is from the start or the end. + public bool IsFromEnd => _value < 0; + + /// Calculate the offset from the start using the giving collection length. + /// The length of the collection that the Index will be used with. length has to be a positive value + /// + /// For performance reason, we don't validate the input length parameter and the returned offset value against negative values. + /// we don't validate either the returned offset is greater than the input length. + /// It is expected Index will be used with collections which always have non negative length/count. If the returned offset is negative and + /// then used to index a collection will get out of range exception which will be same affect as the validation. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetOffset(int length) + { + int offset; + + if (IsFromEnd) + offset = length - (~_value); + else + offset = _value; + + return offset; + } + + /// Indicates whether the current Index object is equal to another object of the same type. + /// An object to compare with this object public override bool Equals(object value) => value is Index && _value == ((Index)value)._value; + + /// Indicates whether the current Index object is equal to another Index object. + /// An object to compare with this object public bool Equals (Index other) => _value == other._value; - public override int GetHashCode() + /// Returns the hash code for this instance. + public override int GetHashCode() => _value; + + /// Converts integer number to an Index. + public static implicit operator Index(int value) => FromStart(value); + + /// Converts the value of the current Index object to its equivalent string representation. + public override string ToString() { - return _value; - } + if (IsFromEnd) + return ToStringFromEnd(); - public override string ToString() => FromEnd ? ToStringFromEnd() : ((uint)Value).ToString(); + return ((uint)Value).ToString(); + } private string ToStringFromEnd() { @@ -41,7 +145,5 @@ private string ToStringFromEnd() return new string(span.Slice(0, charsWritten + 1)); } - public static implicit operator Index(int value) - => new Index(value, fromEnd: false); } } diff --git a/src/System.Private.CoreLib/shared/System/Memory.cs b/src/System.Private.CoreLib/shared/System/Memory.cs index 033b806c20d5..ba31a6aeaeab 100644 --- a/src/System.Private.CoreLib/shared/System/Memory.cs +++ b/src/System.Private.CoreLib/shared/System/Memory.cs @@ -30,7 +30,7 @@ public readonly struct Memory private readonly object _object; private readonly int _index; private readonly int _length; - + /// /// Creates a new memory over the entirety of the target array. /// @@ -258,6 +258,35 @@ public Memory Slice(int start, int length) return new Memory(_object, _index + start, length); } + /// + /// Forms a slice out of the given memory, beginning at 'startIndex' + /// + /// The index at which to begin this slice. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Memory Slice(Index startIndex) + { + int actualIndex = startIndex.GetOffset(_length); + return Slice(actualIndex); + } + + /// + /// Forms a slice out of the given memory using the range start and end indexes. + /// + /// The range used to slice the memory using its start and end indexes. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Memory Slice(Range range) + { + (int start, int length) = range.GetOffsetAndLength(_length); + // It is expected for _index + start to be negative if the memory is already pre-pinned. + return new Memory(_object, _index + start, length); + } + + /// + /// Forms a slice out of the given memory using the range start and end indexes. + /// + /// The range used to slice the memory using its start and end indexes. + public Memory this[Range range] => Slice(range); + /// /// Returns a span from the memory. /// @@ -336,7 +365,7 @@ public unsafe Span Span ThrowHelper.ThrowArgumentOutOfRangeException(); } #endif - + refToReturn = ref Unsafe.Add(ref refToReturn, desiredStartIndex); lengthOfUnderlyingSpan = desiredLength; } diff --git a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs index 11980fbcacb9..1e1fd90e4468 100644 --- a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs @@ -400,6 +400,54 @@ public static Span AsSpan(this T[] array, int start) return new Span(ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), start), array.Length - start); } + /// + /// Creates a new span over the portion of the target array. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsSpan(this T[] array, Index startIndex) + { + if (array == null) + { + if (!startIndex.Equals(Index.Start)) + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + + return default; + } + + if (default(T) == null && array.GetType() != typeof(T[])) + ThrowHelper.ThrowArrayTypeMismatchException(); + + int actualIndex = startIndex.GetOffset(array.Length); + if ((uint)actualIndex > (uint)array.Length) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + return new Span(ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), actualIndex), array.Length - actualIndex); + } + + /// + /// Creates a new span over the portion of the target array. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsSpan(this T[] array, Range range) + { + if (array == null) + { + Index startIndex = range.Start; + Index endIndex = range.End; + + if (!startIndex.Equals(Index.Start) || !endIndex.Equals(Index.Start)) + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + + return default; + } + + if (default(T) == null && array.GetType() != typeof(T[])) + ThrowHelper.ThrowArrayTypeMismatchException(); + + (int start, int length) = range.GetOffsetAndLength(array.Length); + return new Span(ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), start), length); + } + /// /// Creates a new readonly span over the portion of the target string. /// @@ -504,6 +552,26 @@ public static ReadOnlyMemory AsMemory(this string text, int start) return new ReadOnlyMemory(text, start, text.Length - start); } + /// Creates a new over the portion of the target string. + /// The target string. + /// The index at which to begin this slice. + public static ReadOnlyMemory AsMemory(this string text, Index startIndex) + { + if (text == null) + { + if (!startIndex.Equals(Index.Start)) + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); + + return default; + } + + int actualIndex = startIndex.GetOffset(text.Length); + if ((uint)actualIndex > (uint)text.Length) + ThrowHelper.ThrowArgumentOutOfRangeException(); + + return new ReadOnlyMemory(text, actualIndex, text.Length - actualIndex); + } + /// Creates a new over the portion of the target string. /// The target string. /// The index at which to begin this slice. @@ -532,5 +600,25 @@ public static ReadOnlyMemory AsMemory(this string text, int start, int len return new ReadOnlyMemory(text, start, length); } + + /// Creates a new over the portion of the target string. + /// The target string. + /// The range used to indicate the start and length of the sliced string. + public static ReadOnlyMemory AsMemory(this string text, Range range) + { + if (text == null) + { + Index startIndex = range.Start; + Index endIndex = range.End; + + if (!startIndex.Equals(Index.Start) || !endIndex.Equals(Index.Start)) + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); + + return default; + } + + (int start, int length) = range.GetOffsetAndLength(text.Length); + return new ReadOnlyMemory(text, start, length); + } } } diff --git a/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs b/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs index 34b49d41234e..869123a81df6 100644 --- a/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs +++ b/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs @@ -125,7 +125,7 @@ public static ReadOnlySpan TrimEnd(this ReadOnlySpan span, char trim } /// - /// Removes all leading and trailing occurrences of a set of characters specified + /// Removes all leading and trailing occurrences of a set of characters specified /// in a readonly span from the span. /// /// The source span from which the characters are removed. @@ -137,7 +137,7 @@ public static ReadOnlySpan Trim(this ReadOnlySpan span, ReadOnlySpan } /// - /// Removes all leading occurrences of a set of characters specified + /// Removes all leading occurrences of a set of characters specified /// in a readonly span from the span. /// /// The source span from which the characters are removed. @@ -166,7 +166,7 @@ public static ReadOnlySpan TrimStart(this ReadOnlySpan span, ReadOnl } /// - /// Removes all trailing occurrences of a set of characters specified + /// Removes all trailing occurrences of a set of characters specified /// in a readonly span from the span. /// /// The source span from which the characters are removed. @@ -258,7 +258,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), } /// - /// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). + /// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). /// /// The span to search. /// The value to search for. @@ -282,7 +282,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), } /// - /// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). + /// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). /// /// The span to search. /// The sequence to search for. @@ -307,7 +307,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(value)), } /// - /// Searches for the specified value and returns the index of its last occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). + /// Searches for the specified value and returns the index of its last occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). /// /// The span to search. /// The value to search for. @@ -331,7 +331,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), } /// - /// Searches for the specified sequence and returns the index of its last occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). + /// Searches for the specified sequence and returns the index of its last occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). /// /// The span to search. /// The sequence to search for. @@ -350,7 +350,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(value)), } /// - /// Determines whether two sequences are equal by comparing the elements using IEquatable{T}.Equals(T). + /// Determines whether two sequences are equal by comparing the elements using IEquatable{T}.Equals(T). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual(this Span span, ReadOnlySpan other) @@ -369,7 +369,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(other)), } /// - /// Determines the relative order of the sequences being compared by comparing the elements using IComparable{T}.CompareTo(T). + /// Determines the relative order of the sequences being compared by comparing the elements using IComparable{T}.CompareTo(T). /// public static int SequenceCompareTo(this Span span, ReadOnlySpan other) where T : IComparable @@ -392,7 +392,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(other)), } /// - /// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). + /// Searches for the specified value and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). /// /// The span to search. /// The value to search for. @@ -416,7 +416,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), } /// - /// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). + /// Searches for the specified sequence and returns the index of its first occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). /// /// The span to search. /// The sequence to search for. @@ -441,7 +441,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(value)), } /// - /// Searches for the specified value and returns the index of its last occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). + /// Searches for the specified value and returns the index of its last occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). /// /// The span to search. /// The value to search for. @@ -465,7 +465,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), } /// - /// Searches for the specified sequence and returns the index of its last occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). + /// Searches for the specified sequence and returns the index of its last occurrence. If not found, returns -1. Values are compared using IEquatable{T}.Equals(T). /// /// The span to search. /// The sequence to search for. @@ -539,7 +539,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), } /// - /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. + /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. /// /// The span to search. /// The set of values to search for. @@ -661,7 +661,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), } /// - /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. + /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. /// /// The span to search. /// One of the values to search for. @@ -690,7 +690,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), } /// - /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. + /// Searches for the first index of any of the specified values similar to calling IndexOf several times with the logical OR operator. If not found, returns -1. /// /// The span to search. /// The set of values to search for. @@ -829,7 +829,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), } /// - /// Searches for the last index of any of the specified values similar to calling LastIndexOf several times with the logical OR operator. If not found, returns -1. + /// Searches for the last index of any of the specified values similar to calling LastIndexOf several times with the logical OR operator. If not found, returns -1. /// /// The span to search. /// The set of values to search for. @@ -868,7 +868,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), } /// - /// Searches for the last index of any of the specified values similar to calling LastIndexOf several times with the logical OR operator. If not found, returns -1. + /// Searches for the last index of any of the specified values similar to calling LastIndexOf several times with the logical OR operator. If not found, returns -1. /// /// The span to search. /// One of the values to search for. @@ -890,7 +890,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), } /// - /// Searches for the last index of any of the specified values similar to calling LastIndexOf several times with the logical OR operator. If not found, returns -1. + /// Searches for the last index of any of the specified values similar to calling LastIndexOf several times with the logical OR operator. If not found, returns -1. /// /// The span to search. /// The set of values to search for. @@ -909,7 +909,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(values)), } /// - /// Determines whether two sequences are equal by comparing the elements using IEquatable{T}.Equals(T). + /// Determines whether two sequences are equal by comparing the elements using IEquatable{T}.Equals(T). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual(this ReadOnlySpan span, ReadOnlySpan other) @@ -927,7 +927,7 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(other)), } /// - /// Determines the relative order of the sequences being compared by comparing the elements using IComparable{T}.CompareTo(T). + /// Determines the relative order of the sequences being compared by comparing the elements using IComparable{T}.CompareTo(T). /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SequenceCompareTo(this ReadOnlySpan span, ReadOnlySpan other) @@ -1132,6 +1132,19 @@ public static Span AsSpan(this ArraySegment segment, int start) return new Span(segment.Array, segment.Offset + start, segment.Count - start); } + /// + /// Creates a new Span over the portion of the target array beginning + /// at 'startIndex' and ending at the end of the segment. + /// + /// The target array. + /// The index at which to begin the Span. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsSpan(this ArraySegment segment, Index startIndex) + { + int actualIndex = startIndex.GetOffset(segment.Count); + return AsSpan(segment, actualIndex); + } + /// /// Creates a new Span over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). @@ -1155,6 +1168,18 @@ public static Span AsSpan(this ArraySegment segment, int start, int len return new Span(segment.Array, segment.Offset + start, length); } + /// + /// Creates a new Span over the portion of the target array using the range start and end indexes + /// + /// The target array. + /// The range which has start and end indexes to use for slicing the array. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsSpan(this ArraySegment segment, Range range) + { + (int start, int length) = range.GetOffsetAndLength(segment.Count); + return new Span(segment.Array, segment.Offset + start, length); + } + /// /// Creates a new memory over the target array. /// @@ -1173,6 +1198,24 @@ public static Span AsSpan(this ArraySegment segment, int start, int len /// public static Memory AsMemory(this T[] array, int start) => new Memory(array, start); + /// + /// Creates a new memory over the portion of the target array starting from + /// 'startIndex' to the end of the array. + /// + public static Memory AsMemory(this T[] array, Index startIndex) + { + if (array == null) + { + if (!startIndex.Equals(Index.Start)) + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + + return default; + } + + int actualIndex = startIndex.GetOffset(array.Length); + return new Memory(array, actualIndex); + } + /// /// Creates a new memory over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). @@ -1187,6 +1230,26 @@ public static Span AsSpan(this ArraySegment segment, int start, int len /// public static Memory AsMemory(this T[] array, int start, int length) => new Memory(array, start, length); + /// + /// Creates a new memory over the portion of the target array beginning at inclusive start index of the range + /// and ending at the exclusive end index of the range. + /// + public static Memory AsMemory(this T[] array, Range range) + { + if (array == null) + { + Index startIndex = range.Start; + Index endIndex = range.End; + if (!startIndex.Equals(Index.Start) || !endIndex.Equals(Index.Start)) + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); + + return default; + } + + (int start, int length) = range.GetOffsetAndLength(array.Length); + return new Memory(array, start, length); + } + /// /// Creates a new memory over the portion of the target array. /// @@ -1237,7 +1300,7 @@ public static Memory AsMemory(this ArraySegment segment, int start, int /// Copies the contents of the array into the span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. - /// + /// ///The array to copy items from. /// The span to copy items into. /// @@ -1254,7 +1317,7 @@ public static void CopyTo(this T[] source, Span destination) /// Copies the contents of the array into the memory. If the source /// and destinations overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten. - /// + /// ///The array to copy items from. /// The memory to copy items into. /// @@ -1353,16 +1416,16 @@ public static void CopyTo(this T[] source, Memory destination) // nuint x2 = xLength // nuint y1 = (nuint)Unsafe.ByteOffset(xRef, yRef) // nuint y2 = y1 + yLength - // + // // xRef relative to xRef is 0. - // + // // x2 is simply x1 + xLength. This cannot overflow. - // + // // yRef relative to xRef is (yRef - xRef). If (yRef - xRef) is // negative, casting it to an unsigned 32-bit integer turns it into // (yRef - xRef + 2³²). So, in the example above, y1 moves to the right // of x2. - // + // // y2 is simply y1 + yLength. Note that this can overflow, as in the // example above, which must be avoided. // @@ -1389,11 +1452,11 @@ public static void CopyTo(this T[] source, Memory destination) // integers: // // == (y1 < xLength) || (y1 > -yLength) - // + // // Due to modulo arithmetic, this gives exactly same result *except* if // yLength is zero, since 2³² - 0 is 0 and not 2³². So the case // y.IsEmpty must be handled separately first. - // + // /// /// Determines whether two sequences overlap in memory. diff --git a/src/System.Private.CoreLib/shared/System/Range.cs b/src/System.Private.CoreLib/shared/System/Range.cs index b858da2fb438..0098dea17ff7 100644 --- a/src/System.Private.CoreLib/shared/System/Range.cs +++ b/src/System.Private.CoreLib/shared/System/Range.cs @@ -3,20 +3,38 @@ // See the LICENSE file in the project root for more information. using System.Diagnostics; +using System.Runtime.CompilerServices; namespace System { + /// Represent a range has start and end indexes. + /// + /// Range is used by the C# compiler to support the range syntax. + /// + /// int[] someArray = new int[5] { 1, 2, 3, 4, 5 }; + /// int[] subArray1 = someArray[0..2]; // { 1, 2 } + /// int[] subArray2 = someArray[1..^0]; // { 2, 3, 4, 5 } + /// + /// public readonly struct Range : IEquatable { + /// Represent the inclusive start index of the Range. public Index Start { get; } + + /// Represent the exclusive end index of the Range. public Index End { get; } - private Range(Index start, Index end) + /// Construct a Range object using the start and end indexes. + /// Represent the inclusive start index of the range. + /// Represent the exclusive end index of the range. + public Range(Index start, Index end) { Start = start; End = end; } + /// Indicates whether the current Range object is equal to another object of the same type. + /// An object to compare with this object public override bool Equals(object value) { if (value is Range) @@ -28,20 +46,24 @@ public override bool Equals(object value) return false; } + /// Indicates whether the current Range object is equal to another Range object. + /// An object to compare with this object public bool Equals (Range other) => other.Start.Equals(Start) && other.End.Equals(End); + /// Returns the hash code for this instance. public override int GetHashCode() { return HashCode.Combine(Start.GetHashCode(), End.GetHashCode()); } + /// Converts the value of the current Range object to its equivalent string representation. public override string ToString() { Span span = stackalloc char[2 + (2 * 11)]; // 2 for "..", then for each index 1 for '^' and 10 for longest possible uint int charsWritten; int pos = 0; - if (Start.FromEnd) + if (Start.IsFromEnd) { span[0] = '^'; pos = 1; @@ -53,7 +75,7 @@ public override string ToString() span[pos++] = '.'; span[pos++] = '.'; - if (End.FromEnd) + if (End.IsFromEnd) { span[pos++] = '^'; } @@ -64,9 +86,63 @@ public override string ToString() return new string(span.Slice(0, pos)); } - public static Range Create(Index start, Index end) => new Range(start, end); - public static Range FromStart(Index start) => new Range(start, new Index(0, fromEnd: true)); - public static Range ToEnd(Index end) => new Range(new Index(0, fromEnd: false), end); - public static Range All() => new Range(new Index(0, fromEnd: false), new Index(0, fromEnd: true)); + /// Create a Range object starting from start index to the end of the collection. + public static Range StartAt(Index start) => new Range(start, Index.End); + + /// Create a Range object starting from first element in the collection to the end Index. + public static Range EndAt(Index end) => new Range(Index.Start, end); + + /// Create a Range object starting from first element to the end. + public static Range All => new Range(Index.Start, Index.End); + + /// Destruct the range object according to a collection length and return the start offset from the beginning and the length of this range. + /// The length of the collection that the range will be used with. length has to be a positive value + /// + /// For performance reason, we don't validate the input length parameter against negative values. + /// It is expected Range will be used with collections which always have non negative length/count. + /// We validate the range is inside the length scope though. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public OffsetAndLength GetOffsetAndLength(int length) + { + int start; + Index startIndex = Start; + if (startIndex.IsFromEnd) + start = length - startIndex.Value; + else + start = startIndex.Value; + + int end; + Index endIndex = End; + if (endIndex.IsFromEnd) + end = length - endIndex.Value; + else + end = endIndex.Value; + + if ((uint)end > (uint)length || (uint)start > (uint)end) + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); + } + + return new OffsetAndLength(start, end - start); + } + + public readonly struct OffsetAndLength + { + public int Offset { get; } + public int Length { get; } + + public OffsetAndLength(int offset, int length) + { + Offset = offset; + Length = length; + } + + public void Deconstruct(out int offset, out int length) + { + offset = Offset; + length = Length; + } + } } } diff --git a/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs b/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs index 8fd659aeaa0c..6c598430adbf 100644 --- a/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs +++ b/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs @@ -187,6 +187,35 @@ public ReadOnlyMemory Slice(int start, int length) return new ReadOnlyMemory(_object, _index + start, length); } + /// + /// Forms a slice out of the given memory, beginning at 'startIndex' + /// + /// The index at which to begin this slice. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyMemory Slice(Index startIndex) + { + int actualIndex = startIndex.GetOffset(_length); + return Slice(actualIndex); + } + + /// + /// Forms a slice out of the given memory using the range start and end indexes. + /// + /// The range used to slice the memory using its start and end indexes. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlyMemory Slice(Range range) + { + (int start, int length) = range.GetOffsetAndLength(_length); + // It is expected for _index + start to be negative if the memory is already pre-pinned. + return new ReadOnlyMemory(_object, _index + start, length); + } + + /// + /// Forms a slice out of the given memory using the range start and end indexes. + /// + /// The range used to slice the memory using its start and end indexes. + public ReadOnlyMemory this[Range range] => Slice(range); + /// /// Returns a span from the memory. /// @@ -386,7 +415,7 @@ public override int GetHashCode() // code is based on object identity and referential equality, not deep equality (as common with string). return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0; } - + /// Gets the state of the memory as individual fields. /// The offset. /// The count. diff --git a/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs b/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs index b2ce53be2cd0..eb3fd1464d44 100644 --- a/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs @@ -157,20 +157,12 @@ public ref readonly T this[Index index] get { // Evaluate the actual index first because it helps performance - int actualIndex = index.FromEnd ? _length - index.Value : index.Value; + int actualIndex = index.GetOffset(_length); return ref this [actualIndex]; } } - public ReadOnlySpan this[Range range] - { - get - { - int start = range.Start.FromEnd ? _length - range.Start.Value : range.Start.Value; - int end = range.End.FromEnd ? _length - range.End.Value : range.End.Value; - return Slice(start, end - start); - } - } + public ReadOnlySpan this[Range range] => Slice(range); /// /// Returns a reference to the 0th element of the Span. If the Span is empty, returns null reference. @@ -296,6 +288,33 @@ public ReadOnlySpan Slice(int start, int length) return new ReadOnlySpan(ref Unsafe.Add(ref _pointer.Value, start), length); } + /// + /// Forms a slice out of the given read-only span, beginning at 'startIndex' + /// + /// The index at which to begin this slice. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan Slice(Index startIndex) + { + int actualIndex; + if (startIndex.IsFromEnd) + actualIndex = _length - startIndex.Value; + else + actualIndex = startIndex.Value; + + return Slice(actualIndex); + } + + /// + /// Forms a slice out of the given read-only span, beginning at range start index to the range end + /// + /// The range which has the start and end indexes used to slice the span. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ReadOnlySpan Slice(Range range) + { + (int start, int length) = range.GetOffsetAndLength(_length); + return new ReadOnlySpan(ref Unsafe.Add(ref _pointer.Value, start), length); + } + /// /// Copies the contents of this read-only span into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes diff --git a/src/System.Private.CoreLib/shared/System/Span.Fast.cs b/src/System.Private.CoreLib/shared/System/Span.Fast.cs index 490767dc53c8..66de4fe3d3f9 100644 --- a/src/System.Private.CoreLib/shared/System/Span.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/Span.Fast.cs @@ -163,20 +163,12 @@ public ref T this[Index index] get { // Evaluate the actual index first because it helps performance - int actualIndex = index.FromEnd ? _length - index.Value : index.Value; + int actualIndex = index.GetOffset(_length); return ref this [actualIndex]; } } - public Span this[Range range] - { - get - { - int start = range.Start.FromEnd ? _length - range.Start.Value : range.Start.Value; - int end = range.End.FromEnd ? _length - range.End.Value : range.End.Value; - return Slice(start, end - start); - } - } + public Span this[Range range] => Slice(range); /// /// Returns a reference to the 0th element of the Span. If the Span is empty, returns null reference. @@ -380,6 +372,28 @@ public Span Slice(int start, int length) return new Span(ref Unsafe.Add(ref _pointer.Value, start), length); } + /// + /// Forms a slice out of the given span, beginning at 'startIndex' + /// + /// The index at which to begin this slice. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span Slice(Index startIndex) + { + int actualIndex = startIndex.GetOffset(_length); + return Slice(actualIndex); + } + + /// + /// Forms a slice out of the given span, beginning at range start index to the range end + /// + /// The range which has the start and end indexes used to slice the span. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span Slice(Range range) + { + (int start, int length) = range.GetOffsetAndLength(_length); + return new Span(ref Unsafe.Add(ref _pointer.Value, start), length); + } + /// /// Copies the contents of this span into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes diff --git a/src/System.Private.CoreLib/shared/System/String.Manipulation.cs b/src/System.Private.CoreLib/shared/System/String.Manipulation.cs index f183ed6a59dc..82d74225c22a 100644 --- a/src/System.Private.CoreLib/shared/System/String.Manipulation.cs +++ b/src/System.Private.CoreLib/shared/System/String.Manipulation.cs @@ -1686,6 +1686,20 @@ public string Substring(int startIndex, int length) return InternalSubString(startIndex, length); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public string Substring(Index startIndex) + { + int actualIndex = startIndex.GetOffset(Length); + return Substring(actualIndex); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public string Substring(Range range) + { + (int start, int length) = range.GetOffsetAndLength(Length); + return Substring(start, length); + } + private unsafe string InternalSubString(int startIndex, int length) { Debug.Assert(startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!"); diff --git a/src/System.Private.CoreLib/shared/System/String.cs b/src/System.Private.CoreLib/shared/System/String.cs index 0958e865db7f..22f830a0e4c9 100644 --- a/src/System.Private.CoreLib/shared/System/String.cs +++ b/src/System.Private.CoreLib/shared/System/String.cs @@ -444,6 +444,19 @@ public static bool IsNullOrEmpty(string value) return (value == null || 0u >= (uint)value.Length) ? true : false; } + [System.Runtime.CompilerServices.IndexerName("Chars")] + public char this[Index index] + { + get + { + int actualIndex = index.GetOffset(Length); + return this[actualIndex]; + } + } + + [System.Runtime.CompilerServices.IndexerName("Chars")] + public string this[Range range] => Substring(range); + public static bool IsNullOrWhiteSpace(string value) { if (value == null) return true; @@ -672,7 +685,7 @@ private static void ThrowMustBeNullTerminatedString() // // IConvertible implementation - // + // public TypeCode GetTypeCode() { diff --git a/src/System.Private.CoreLib/shared/System/ThrowHelper.cs b/src/System.Private.CoreLib/shared/System/ThrowHelper.cs index b9276ca8a07d..1bbc7e3f63d0 100644 --- a/src/System.Private.CoreLib/shared/System/ThrowHelper.cs +++ b/src/System.Private.CoreLib/shared/System/ThrowHelper.cs @@ -119,7 +119,7 @@ internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() internal static void ThrowArgumentOutOfRangeException_ArgumentOutOfRange_Enum() { - throw GetArgumentOutOfRangeException(ExceptionArgument.type, + throw GetArgumentOutOfRangeException(ExceptionArgument.type, ExceptionResource.ArgumentOutOfRange_Enum); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index fe101e2740c8..94a6379f5f9a 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -39,14 +39,14 @@ public static object GetUninitializedObject(Type type) // GetObjectValue is intended to allow value classes to be manipulated as 'Object' // but have aliasing behavior of a value class. The intent is that you would use // this function just before an assignment to a variable of type 'Object'. If the - // value being assigned is a mutable value class, then a shallow copy is returned + // value being assigned is a mutable value class, then a shallow copy is returned // (because value classes have copy semantics), but otherwise the object itself - // is returned. + // is returned. // // Note: VB calls this method when they're about to assign to an Object - // or pass it as a parameter. The goal is to make sure that boxed - // value types work identical to unboxed value types - ie, they get - // cloned when you pass them around, and are always passed by value. + // or pass it as a parameter. The goal is to make sure that boxed + // value types work identical to unboxed value types - ie, they get + // cloned when you pass them around, and are always passed by value. // Of course, reference types are not cloned. // [MethodImplAttribute(MethodImplOptions.InternalCall)] @@ -57,8 +57,8 @@ public static object GetUninitializedObject(Type type) // have at least been started by some thread. In the absence of class constructor // deadlock conditions, the call is further guaranteed to have completed. // - // This call will generate an exception if the specified class constructor threw an - // exception when it ran. + // This call will generate an exception if the specified class constructor threw an + // exception when it ran. [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunClassConstructor(RuntimeType type); @@ -73,8 +73,8 @@ public static void RunClassConstructor(RuntimeTypeHandle type) // have at least been started by some thread. In the absence of module constructor // deadlock conditions, the call is further guaranteed to have completed. // - // This call will generate an exception if the specified module constructor threw an - // exception when it ran. + // This call will generate an exception if the specified module constructor threw an + // exception when it ran. [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunModuleConstructor(System.Reflection.RuntimeModule module); @@ -91,7 +91,7 @@ public static void RunModuleConstructor(ModuleHandle module) [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern unsafe void _PrepareMethod(IRuntimeMethodInfo method, IntPtr* pInstantiation, int cInstantiation); - public static void PrepareMethod(RuntimeMethodHandle method) + public static void PrepareMethod(RuntimeMethodHandle method) { unsafe { @@ -132,10 +132,10 @@ public static int OffsetToStringData get { // Number of bytes from the address pointed to by a reference to - // a String to the first 16-bit character in the String. Skip - // over the MethodTable pointer, & String - // length. Of course, the String reference points to the memory - // after the sync block, so don't count that. + // a String to the first 16-bit character in the String. Skip + // over the MethodTable pointer, & String + // length. Of course, the String reference points to the memory + // after the sync block, so don't count that. // This property allows C#'s fixed statement to work on Strings. // On 64 bit platforms, this should be 12 (8+4) and on 32 bit 8 (4+4). #if BIT64 @@ -197,6 +197,26 @@ public static bool IsReferenceOrContainsReferences() throw new InvalidOperationException(); } + /// + /// GetSubArray helper method for the compiler to slice an array using a range. + /// + public static T[] GetSubArray(T[] array, Range range) + { + Type elementType = array.GetType().GetElementType(); + Span source = array.AsSpan(range); + + if (elementType.IsValueType) + { + return source.ToArray(); + } + else + { + T[] newArray = (T[])Array.CreateInstance(elementType, source.Length); + source.CopyTo(newArray); + return newArray; + } + } + // Returns true iff the object has a component size; // i.e., is variable length like System.String or Array. [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -228,7 +248,7 @@ private static IntPtr GetObjectMethodTablePointer(object obj) // This is not ideal in terms of minimizing instruction count but is the best we can do at the moment. return Unsafe.Add(ref Unsafe.As(ref obj.GetRawData()), -1); - + // The JIT currently implements this as: // lea tmp, [rax + 8h] ; assume rax contains the object reference, tmp is type IntPtr& // mov tmp, qword ptr [tmp - 8h] ; tmp now contains the MethodTable* pointer diff --git a/tests/CoreFX/CoreFX.issues.json b/tests/CoreFX/CoreFX.issues.json index c249ffa25962..c76dbe762b65 100644 --- a/tests/CoreFX/CoreFX.issues.json +++ b/tests/CoreFX/CoreFX.issues.json @@ -1054,7 +1054,6 @@ "name": "System.Tests.TimeSpanTests.Parse", "reason": "Temporary disabling till merging the PR https://github.com/dotnet/corefx/pull/34561" }, - { "name": "System.Tests.SingleTests.Test_ToString", "reason" : "https://github.com/dotnet/coreclr/pull/22040" diff --git a/tests/issues.targets b/tests/issues.targets index e1f27d221477..7ee9bd90bbbf 100644 --- a/tests/issues.targets +++ b/tests/issues.targets @@ -44,6 +44,9 @@ 11408 + + 22410 + 20322 @@ -78,22 +81,22 @@ needs triage - + needs triage - + needs triage needs triage - + needs triage needs triage - + needs triage @@ -199,22 +202,22 @@ needs triage - + needs triage - + needs triage needs triage - + needs triage needs triage - + 18895 @@ -269,7 +272,7 @@ 2420. x86 JIT doesn't support implicit tail call optimization or tail. call pop ret sequence - 11469, The test causes OutOfMemory exception in crossgen mode. + 11469, The test causes OutOfMemory exception in crossgen mode. Varargs supported on this platform @@ -575,7 +578,7 @@ 22015 - + @@ -2051,7 +2054,7 @@ - +