Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/System.Memory/src/System/ReadOnlySpan.Portable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,17 @@ public override string ToString()
{
if (typeof(T) == typeof(char))
{
// If this wraps a string and represents the full length of the string, just return the wrapped string.
if (_byteOffset == MemoryExtensions.StringAdjustment)
{
object obj = Unsafe.As<object>(_pinnable); // minimize chances the compilers will optimize away the 'is' check
if (obj is string s && _length == s.Length)
{
return s;
}
}

// Otherwise, copy the data to a new string.
unsafe
{
fixed (char* src = &Unsafe.As<T, char>(ref DangerousGetPinnableReference()))
Expand Down
18 changes: 18 additions & 0 deletions src/System.Memory/tests/ReadOnlySpan/ToString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,23 @@ public static unsafe void ToStringForSpanOfString()
var span = new ReadOnlySpan<string>(a);
Assert.Equal("System.ReadOnlySpan<String>[3]", span.ToString());
}

[Fact]
public static void ToString_SpanOverString()
{
string orig = "hello world";
Assert.Equal(orig, orig.AsReadOnlySpan().ToString());
Assert.Equal(orig.Substring(0, 5), orig.AsReadOnlySpan(0, 5).ToString());
Assert.Equal(orig.Substring(5), orig.AsReadOnlySpan(5).ToString());
Assert.Equal(orig.Substring(1, 3), orig.AsReadOnlySpan(1, 3).ToString());
}

[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "Optimization only applies to portable span.")]
[Fact]
public static void ToString_SpanOverFullString_ReturnsOriginal()
{
string orig = "hello world";
Assert.Same(orig, orig.AsReadOnlySpan().ToString());
}
}
}