in core/src/main/java/com/datastax/oss/driver/internal/core/metadata/token/TokenRangeBase.java [219:260]
public TokenRange mergeWith(@NonNull TokenRange that) {
if (this.equals(that)) {
return this;
}
if (!(this.intersects(that)
|| this.end.equals(that.getStart())
|| that.getEnd().equals(this.start))) {
throw new IllegalArgumentException(
String.format(
"Can't merge %s with %s because they neither intersect nor are adjacent",
this, that));
}
if (this.isEmpty()) {
return that;
}
if (that.isEmpty()) {
return this;
}
// That's actually "starts in or is adjacent to the end of"
boolean thisStartsInThat = contains(that, this.start, true) || this.start.equals(that.getEnd());
boolean thatStartsInThis =
contains(this, that.getStart(), true) || that.getStart().equals(this.end);
// This takes care of all the cases that return the full ring, so that we don't have to worry
// about them below
if (thisStartsInThat && thatStartsInThis) {
return fullRing();
}
// Starting at this.start, see how far we can go while staying in at least one of the ranges.
Token mergedEnd =
(thatStartsInThis && !contains(this, that.getEnd(), false)) ? that.getEnd() : this.end;
// Repeat in the other direction.
Token mergedStart = thisStartsInThat ? that.getStart() : this.start;
return newTokenRange(mergedStart, mergedEnd);
}