Skip to content

Commit 9980912

Browse files
authored
Merge pull request #169 from aka-nse/feature/as-readonly-span
[Proposal] Adds TextSpan.AsReadOnlySpan()
2 parents d4d602d + 546b2b5 commit 9980912

3 files changed

Lines changed: 40 additions & 0 deletions

File tree

src/Superpower/Model/TextSpan.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,16 @@ public string ToStringValue()
233233
return Source!.Substring(Position.Absolute, Length);
234234
}
235235

236+
/// <summary>
237+
/// Compute the string value of this span and return the view of source directly.
238+
/// </summary>
239+
/// <returns>A view of string with the value of this span.</returns>
240+
public ReadOnlySpan<char> AsReadOnlySpan()
241+
{
242+
EnsureHasValue();
243+
return Source!.AsSpan(Position.Absolute, Length);
244+
}
245+
236246
/// <summary>
237247
/// Compare the contents of this span with <paramref name="otherValue"/>.
238248
/// </summary>

src/Superpower/Superpower.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,7 @@
2525
<ItemGroup>
2626
<None Include="..\..\asset\Superpower-White-400px.png" Pack="true" Visible="false" PackagePath="" />
2727
</ItemGroup>
28+
<ItemGroup Condition="'$(TargetFramework)'=='netstandard2.0'">
29+
<PackageReference Include="System.Memory" Version="4.6.3" />
30+
</ItemGroup>
2831
</Project>
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using System;
2+
using Superpower.Model;
3+
using Xunit;
4+
5+
namespace Superpower.Tests.Model
6+
{
7+
public class TextSpanTest
8+
{
9+
[Theory]
10+
[InlineData("hello", 0, 5, "hello")]
11+
[InlineData("hello", 1, 3, "ell")]
12+
[InlineData("hello", 2, 0, "")]
13+
[InlineData("The quick brown fox jumps over the lazy dog", 9, 7, " brown ")]
14+
public void AsReadOnlySpanWorks(string input, int start, int length, string expected)
15+
{
16+
var span = new TextSpan(input).Skip(start).First(length);
17+
var readOnlySpan = span.AsReadOnlySpan();
18+
Assert.Equal(expected, readOnlySpan.ToString());
19+
}
20+
21+
[Fact]
22+
public void AsReadOnlySpanEnsureHasValue()
23+
{
24+
Assert.Throws<InvalidOperationException>(() => TextSpan.None.AsReadOnlySpan());
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)