Skip to content

Commit

Permalink
Update StringSlice::replaceRange
Browse files Browse the repository at this point in the history
  • Loading branch information
Glavo committed Jan 6, 2025
1 parent 47f54f7 commit cb44e89
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
13 changes: 8 additions & 5 deletions kala-base/src/main/java/kala/text/StringSlice.java
Original file line number Diff line number Diff line change
Expand Up @@ -306,18 +306,21 @@ public StringSlice next() {
return StringSlice.of(res.toString());
}

public @NotNull StringSlice replaceRange(int beginIndex, int endIndex, @NotNull String replacement) {
public @NotNull StringSlice replaceRange(@Index int beginIndex, @Index int endIndex, @NotNull String replacement) {
return replaceRange(beginIndex, endIndex, StringSlice.of(replacement));
}

public @NotNull StringSlice replaceRange(int beginIndex, int endIndex, @NotNull StringSlice replacement) {
Conditions.checkPositionIndices(beginIndex, endIndex, length);
public @NotNull StringSlice replaceRange(@Index int beginIndex, @Index int endIndex, @NotNull StringSlice replacement) {
beginIndex = Indexes.checkBeginIndex(beginIndex, length);
endIndex = Indexes.checkEndIndex(beginIndex, endIndex, length);

final int rangeLength = endIndex - beginIndex;

if (this.length == 0) {
if (this.length == rangeLength) {
return replacement;
}

StringBuilder builder = new StringBuilder(this.length - endIndex + beginIndex + replacement.length);
StringBuilder builder = new StringBuilder(this.length - rangeLength + replacement.length);
builder.append(this.value, offset, offset + beginIndex);
replacement.appendTo(builder);
builder.append(this.value, offset + endIndex, offset + length);
Expand Down
1 change: 1 addition & 0 deletions src/test/java/kala/text/StringSliceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ void replaceTest() {

@Test
void replaceRangeTest() {
assertSliceEquals("123", StringSlice.of("abc").replaceRange(0, ~0, "123"));
assertSliceEquals("3foo6", StringSlice.of("123456789", 2, 6).replaceRange(1, 3, "foo"));
}

Expand Down

0 comments on commit cb44e89

Please sign in to comment.