Do the two texts share a substring which is at least half the length of the longer text? This speedup can produce non-minimal diffs. Args: text1: First string. text2: Second string. Returns: Five element Array, containing the prefix of text1, the suffix of te
(text1, text2, len_text1, len_text2)
| 385 | |
| 386 | |
| 387 | def half_match(text1, text2, len_text1, len_text2): |
| 388 | """ |
| 389 | Do the two texts share a substring which is at least half the length of |
| 390 | the longer text? |
| 391 | This speedup can produce non-minimal diffs. |
| 392 | |
| 393 | Args: |
| 394 | text1: First string. |
| 395 | text2: Second string. |
| 396 | |
| 397 | Returns: |
| 398 | Five element Array, containing the prefix of text1, the suffix of text1, |
| 399 | the prefix of text2, the suffix of text2 and the common middle. Or None |
| 400 | if there was no match. |
| 401 | """ |
| 402 | reversed_diff = len_text1 > len_text2 |
| 403 | |
| 404 | if reversed_diff: |
| 405 | longtext, shorttext = text1, text2 |
| 406 | len_longtext, len_shorttext = len_text1, len_text2 |
| 407 | else: |
| 408 | shorttext, longtext = text1, text2 |
| 409 | len_shorttext, len_longtext = len_text1, len_text2 |
| 410 | |
| 411 | if len_longtext < 4 or len_shorttext * 2 < len_longtext: |
| 412 | # Pointless. |
| 413 | return None |
| 414 | |
| 415 | # First check if the second quarter is the seed for a half-match. |
| 416 | hm1 = half_match_i(longtext, shorttext, (len_longtext + 3) // 4, len_longtext) |
| 417 | |
| 418 | # Check again based on the third quarter. |
| 419 | hm2 = half_match_i(longtext, shorttext, (len_longtext + 1) // 2, len_longtext) |
| 420 | |
| 421 | if not hm1 and not hm2: |
| 422 | return None |
| 423 | |
| 424 | elif not hm2: |
| 425 | hm = hm1 |
| 426 | |
| 427 | elif not hm1: |
| 428 | hm = hm2 |
| 429 | |
| 430 | else: |
| 431 | # Both matched. Select the longest. |
| 432 | if len(hm1[4]) > len(hm2[4]): |
| 433 | hm = hm1 |
| 434 | else: |
| 435 | hm = hm2 |
| 436 | |
| 437 | # A half-match was found, sort out the return data. |
| 438 | if reversed_diff: |
| 439 | text1_a, text1_b, text2_a, text2_b, mid_common = hm |
| 440 | else: |
| 441 | text2_a, text2_b, text1_a, text1_b, mid_common = hm |
| 442 | |
| 443 | return text1_a, text1_b, text2_a, text2_b, mid_common |
| 444 |