File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -196,7 +196,28 @@ public ReadOnlyMemory<T> AsMemory() =>
196196 [ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
197197 public ref readonly T GetPinnableReference ( )
198198 {
199- // To match the behavior of ReadOnlySpan<T>
199+ //
200+ // Normalize the returned reference.
201+ // We must not return a reference to an element outside the bounds of our view
202+ // when the view is empty (_count = 0), even if it points to a valid element
203+ // in the underlying array. In this case, we return a null reference.
204+ //
205+ // Examples:
206+ //
207+ // Full array (_array):
208+ // [0][1][2][3][4][5][6][7][8][9]
209+ // |--------------------------|
210+ //
211+ // Case 1: Non-empty view (_index = 3, _count = 4)
212+ // [3][4][5][6]
213+ // ^ ^
214+ // |--------| <- valid range for this view
215+ //
216+ // Case 2: Empty view (_index = 3, _count = 0)
217+ // [3][4][5][6]
218+ // ^
219+ // | <- no valid reference for this view
220+ //
200221
201222 ref var p = ref Unsafe . NullRef < T > ( ) ;
202223
Original file line number Diff line number Diff line change @@ -762,7 +762,28 @@ public ReadOnlyMemory<char> AsMemory() =>
762762 [ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
763763 public ref readonly char GetPinnableReference ( )
764764 {
765- // To match the behavior of ReadOnlySpan<T>
765+ //
766+ // Normalize the returned reference.
767+ // We must not return a reference to an element outside the bounds of our view
768+ // when the view is empty (_count = 0), even if it points to a valid element
769+ // in the underlying string. In this case, we return a null reference.
770+ //
771+ // Examples:
772+ //
773+ // Full string (_value):
774+ // [0][1][2][3][4][5][6][7][8][9]
775+ // |--------------------------|
776+ //
777+ // Case 1: Non-empty view (_index = 3, _count = 4)
778+ // [3][4][5][6]
779+ // ^ ^
780+ // |--------| <- valid range for this view
781+ //
782+ // Case 2: Empty view (_index = 3, _count = 0)
783+ // [3][4][5][6]
784+ // ^
785+ // | <- no valid reference for this view
786+ //
766787
767788 ref readonly var p = ref Unsafe . NullRef < char > ( ) ;
768789
You can’t perform that action at this time.
0 commit comments