diff --git a/src/main/java/io/airlift/slice/Slice.java b/src/main/java/io/airlift/slice/Slice.java index 05a8ea0..711b0d8 100644 --- a/src/main/java/io/airlift/slice/Slice.java +++ b/src/main/java/io/airlift/slice/Slice.java @@ -1075,7 +1075,7 @@ public int compareTo(int offset, int length, Slice that, int otherOffset, int ot } // Find index of the first mismatched byte - long mismatch = MemorySegment.mismatch(segment, offset, offset + length, that.segment, otherOffset, otherOffset + otherLength); + long mismatch = mismatch(offset, length, that, otherOffset, otherLength); if (mismatch == -1) { return 0; } @@ -1088,6 +1088,16 @@ public int compareTo(int offset, int length, Slice that, int otherOffset, int ot return Byte.compareUnsigned(segment.get(BYTE, offset + mismatch), that.segment.get(BYTE, otherOffset + mismatch)); } + public int mismatch(int offset, int length, Slice that, int otherOffset, int otherLength) + { + return toIntExact(MemorySegment.mismatch(segment, offset, offset + length, that.segment, otherOffset, otherOffset + otherLength)); + } + + public int mismatch(Slice that) + { + return mismatch(0, length(), that, 0, that.length()); + } + /** * Compares the specified object with this slice for equality. Equality is * solely based on the contents of the slice. @@ -1237,7 +1247,7 @@ public ByteBuffer toByteBuffer(int offset, int length) return EMPTY_BYTE_BUFFER; } - return segment.asByteBuffer().slice(offset, length); + return segment.asSlice(offset, length).asByteBuffer(); } public ByteBuffer toByteBuffer(int offset) diff --git a/src/test/java/io/airlift/slice/TestSlice.java b/src/test/java/io/airlift/slice/TestSlice.java index 279a22f..155eb6f 100644 --- a/src/test/java/io/airlift/slice/TestSlice.java +++ b/src/test/java/io/airlift/slice/TestSlice.java @@ -313,6 +313,41 @@ public void testInt() } } + @Test + public void testMismatch() + { + Slice first = Slices.utf8Slice("ala ma kota"); + Slice second = Slices.utf8Slice("ala ma psa"); + + int mismatch = first.mismatch(second); + assertThat(mismatch).isEqualTo(7); + + assertThat(first.toStringUtf8().substring(0, mismatch)) + .isEqualTo(second.toStringUtf8().substring(0, mismatch)); + + assertThat(first.toStringUtf8().substring(0, mismatch + 1)) + .isNotEqualTo(second.toStringUtf8().substring(0, mismatch + 1)); + + // Different slices + assertThat(first.mismatch(utf8Slice("pies i kot"))) + .isEqualTo(0); + + assertThat(first.mismatch(0, first.length(), second, 5, second.length() - 5)) + .isEqualTo(1); + + assertThat(first.mismatch(first)) + .isEqualTo(-1); + + assertThat(second.mismatch(second)) + .isEqualTo(-1); + + assertThat(first.slice(0, mismatch).mismatch(second.slice(0, mismatch))) + .isEqualTo(-1); + + assertThat(first.mismatch(0, mismatch, second, 0, mismatch)) + .isEqualTo(-1); + } + private static void assertInt(Slice slice, int index) { // fill slice with FF