BsDiff { static int lengthOfMatch( final RandomAccessObject oldData, final int oldStart, final RandomAccessObject newData, final int newStart) throws IOException { final int max = Math.min((int) oldData.length() - oldStart, (int) newData.length() - newStart); if (max > 0) { oldData.seek(oldStart); newData.seek(newStart); for (int offset = 0; offset < max; offset++) { if (oldData.readByte() != newData.readByte()) { return offset; } } } return max; }    }
@Test public void lengthOfMatchTest() throws IOException { String s1 = "this is a string that starts the same and has some sameness in the middle, but " + "ends differently"; String s2 = "this is a string that starts the samish and has some sameness in the middle, but " + "then ends didlyiefferently"; byte[] s1b = s1.getBytes(Charset.forName("US-ASCII")); byte[] s2b = s2.getBytes(Charset.forName("US-ASCII")); RandomAccessObject s1ro = new RandomAccessObject.RandomAccessByteArrayObject(s1b); RandomAccessObject s2ro = new RandomAccessObject.RandomAccessByteArrayObject(s2b); Assert.assertEquals(36, BsDiff.lengthOfMatch(s1ro, 0, s2ro, 0)); Assert.assertEquals(0, BsDiff.lengthOfMatch(s1ro, 5, s2ro, 0)); Assert.assertEquals(31, BsDiff.lengthOfMatch(s1ro, 5, s2ro, 5)); Assert.assertEquals(42, BsDiff.lengthOfMatch(s1ro, 37, s2ro, 39)); Assert.assertEquals(0, BsDiff.lengthOfMatch(s1ro, 38, s2ro, 39)); Assert.assertEquals(32, BsDiff.lengthOfMatch(s1ro, 47, s2ro, 49)); Assert.assertEquals(2, BsDiff.lengthOfMatch(s1ro, 90, s2ro, 83)); }