private int compareMultiSegments ( BinaryString other ) { if ( sizeInBytes == 0 || other . sizeInBytes == 0 ) { return sizeInBytes - other . sizeInBytes ; } int len = Math . min ( sizeInBytes , other . sizeInBytes ) ; MemorySegment seg1 = segments [ 0 ] ; MemorySegment seg2 = other . segments [ 0 ] ; int segmentSize = segments [ 0 ] . size ( ) ; int otherSegmentSize = other . segments [ 0 ] . size ( ) ; int sizeOfFirst1 = segmentSize - offset ; int sizeOfFirst2 = otherSegmentSize - other . offset ; int varSegIndex1 = 1 ; int varSegIndex2 = 1 ; // find the first segment of this string. while ( sizeOfFirst1 <= 0 ) { sizeOfFirst1 += segmentSize ; seg1 = segments [ varSegIndex1 ++ ] ; } while ( sizeOfFirst2 <= 0 ) { sizeOfFirst2 += otherSegmentSize ; seg2 = other . segments [ varSegIndex2 ++ ] ; } int offset1 = segmentSize - sizeOfFirst1 ; int offset2 = otherSegmentSize - sizeOfFirst2 ; int needCompare = Math . min ( Math . min ( sizeOfFirst1 , sizeOfFirst2 ) , len ) ; while ( needCompare > 0 ) { // compare in one segment. for ( int i = 0 ; i < needCompare ; i ++ ) { int res = ( seg1 . get ( offset1 + i ) & 0xFF ) - ( seg2 . get ( offset2 + i ) & 0xFF ) ; if ( res != 0 ) { return res ; } } if ( needCompare == len ) { break ; } len -= needCompare ; // next segment if ( sizeOfFirst1 < sizeOfFirst2 ) { //I am smaller seg1 = segments [ varSegIndex1 ++ ] ; offset1 = 0 ; offset2 += needCompare ; sizeOfFirst1 = segmentSize ; sizeOfFirst2 -= needCompare ; } else if ( sizeOfFirst1 > sizeOfFirst2 ) { //other is smaller seg2 = other . segments [ varSegIndex2 ++ ] ; offset2 = 0 ; offset1 += needCompare ; sizeOfFirst2 = otherSegmentSize ; sizeOfFirst1 -= needCompare ; } else { // same, should go ahead both. seg1 = segments [ varSegIndex1 ++ ] ; seg2 = other . segments [ varSegIndex2 ++ ] ; offset1 = 0 ; offset2 = 0 ; sizeOfFirst1 = segmentSize ; sizeOfFirst2 = otherSegmentSize ; } needCompare = Math . min ( Math . min ( sizeOfFirst1 , sizeOfFirst2 ) , len ) ; } checkArgument ( needCompare == len ) ; return sizeInBytes - other . sizeInBytes ; }
Find the boundaries of segments and then compare MemorySegment .