Skip to content

Commit b529f86

Browse files
committed
Revised isSameResource()
1 parent 9d29ac9 commit b529f86

File tree

2 files changed

+24
-9
lines changed

2 files changed

+24
-9
lines changed

src/main/java/org/apache/datasketches/memory/Resource.java

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -254,10 +254,15 @@ boolean equalTo(
254254
boolean isRegion();
255255

256256
/**
257-
* Returns true if the backing resource of <i>this</i> is the same as the backing resource of <i>that</i>.
258-
* This returns false if <i>this</i> and <i>that</i> are both on-heap and one of them is read-only.
257+
* Returns true if the underlying resource is the same underlying resource as <i>that</i>.
258+
*
259+
* <p>Note: for on-heap resources neither <i>this</i> nor <i>that</i> can be read-only.</p>
260+
*
261+
* <p>if two sub-regions (or slices) are derived from the same resource they both must have the same
262+
* starting offset with respect to the resource and the same size.</p>
263+
*
259264
* @param that the other Resource object
260-
* @return true if the backing resource of <i>this</i> is the same as the backing resource of <i>that</i>.
265+
* @return true if the underlying resource is the same underlying resource as <i>that</i>.
261266
*/
262267
boolean isSameResource(Resource that);
263268

src/main/java/org/apache/datasketches/memory/internal/ResourceImpl.java

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -453,13 +453,23 @@ public final boolean isRegion() {
453453

454454
@Override
455455
public final boolean isSameResource(final Resource that) {
456-
if (that == null) { return false; }
457-
final ResourceImpl that2 = (ResourceImpl) that;
458-
if (this.arena == null && that2.arena == null) { //both on heap
459-
if (this.seg.isReadOnly() || that2.seg.isReadOnly()) { return false; }
460-
return this.seg.heapBase().get() == that2.seg.heapBase().get();
456+
Objects.requireNonNull(that);
457+
final MemorySegment thisSeg = this.seg;
458+
final MemorySegment thatSeg = ((ResourceImpl)that).seg;
459+
final boolean thisNative = thisSeg.isNative();
460+
final boolean thatNative = thatSeg.isNative();
461+
if (thisNative != thatNative) { return false; }
462+
if (thisNative && thatNative) { //off-heap
463+
return thisSeg.address() == thatSeg.address()
464+
&& thisSeg.byteSize() == thatSeg.byteSize();
465+
} else { //on heap
466+
if (thisSeg.isReadOnly() || thatSeg.isReadOnly()) {
467+
throw new IllegalArgumentException("Cannot determine 'is same resource' on heap if one resource is Read-only.");
468+
}
469+
return (thisSeg.heapBase().get() == thatSeg.heapBase().get())
470+
&& (thisSeg.address() == thatSeg.address())
471+
&& thisSeg.byteSize() == thatSeg.byteSize();
461472
}
462-
return this.seg.address() == that2.seg.address();
463473
}
464474

465475
@Override

0 commit comments

Comments
 (0)