Skip to content

Commit 757c26d

Browse files
committed
Fix bug with IndexOf
1 parent 19e1633 commit 757c26d

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ All notable changes to **ValueStringBuilder** will be documented in this file. T
99
### Added
1010
- Added `Reverse` function
1111

12+
### Changed
13+
- Fixed a bug where two empty strings return the wrong value in (Last)IndexOf
14+
1215
## [1.12.2] - 2023-02-21
1316

1417
### Changed

src/LinkDotNet.StringBuilder/NaiveSearch.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ public static ReadOnlySpan<int> FindAll(ReadOnlySpan<char> text, ReadOnlySpan<ch
4949
/// <returns>The index of the found <paramref name="word"/> in <paramref name="text"/> or -1 if not found.</returns>
5050
public static int FindFirst(ReadOnlySpan<char> text, ReadOnlySpan<char> word)
5151
{
52+
if (text.IsEmpty && word.IsEmpty)
53+
{
54+
return 0;
55+
}
56+
5257
if (text.IsEmpty || word.IsEmpty)
5358
{
5459
return -1;
@@ -86,6 +91,11 @@ public static int FindFirst(ReadOnlySpan<char> text, ReadOnlySpan<char> word)
8691
/// <returns>The index of the found <paramref name="word"/> in <paramref name="text"/> or -1 if not found.</returns>
8792
public static int FindLast(ReadOnlySpan<char> text, ReadOnlySpan<char> word)
8893
{
94+
if (text.IsEmpty && word.IsEmpty)
95+
{
96+
return 0;
97+
}
98+
8999
if (text.IsEmpty || word.IsEmpty)
90100
{
91101
return -1;

tests/LinkDotNet.StringBuilder.UnitTests/ValueStringBuilderTests.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,16 @@ public void ShouldReturnMinusOneIfNotFound()
206206
index.Should().Be(-1);
207207
}
208208

209+
[Fact]
210+
public void ShouldReturnZeroIfBothEmpty()
211+
{
212+
using var stringBuilder = new ValueStringBuilder();
213+
214+
var index = stringBuilder.IndexOf(string.Empty);
215+
216+
index.Should().Be(0);
217+
}
218+
209219
[Fact]
210220
public void ShouldReturnMinusOneWordIsLongerThanString()
211221
{
@@ -307,6 +317,16 @@ public void ShouldReturnZeroWhenEmptyStringInIndexOf()
307317
index.Should().Be(0);
308318
}
309319

320+
[Fact]
321+
public void ShouldReturnZeroIfBothEmptyLastIndexOf()
322+
{
323+
using var stringBuilder = new ValueStringBuilder();
324+
325+
var index = stringBuilder.LastIndexOf(string.Empty);
326+
327+
index.Should().Be(0);
328+
}
329+
310330
[Fact]
311331
public void ShouldReturnZeroWhenEmptyStringInLastIndexOf()
312332
{

0 commit comments

Comments
 (0)