diff --git a/kala-base/src/main/java/kala/text/StringSlice.java b/kala-base/src/main/java/kala/text/StringSlice.java index 292e249d..34db548d 100644 --- a/kala-base/src/main/java/kala/text/StringSlice.java +++ b/kala-base/src/main/java/kala/text/StringSlice.java @@ -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); diff --git a/src/test/java/kala/text/StringSliceTest.java b/src/test/java/kala/text/StringSliceTest.java index fa61d688..3e3256e3 100644 --- a/src/test/java/kala/text/StringSliceTest.java +++ b/src/test/java/kala/text/StringSliceTest.java @@ -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")); }