patch_addPadding method
Add some padding on text start and end so that edges can match something.
Intended to be called only from within patch_apply.
patches
is a List of Patch objects.
Returns the padding string added to each side.
Implementation
String patch_addPadding(List<Patch> patches) {
final paddingLength = Patch_Margin;
final paddingCodes = <int>[];
for (int x = 1; x <= paddingLength; x++) {
paddingCodes.add(x);
}
String nullPadding = String.fromCharCodes(paddingCodes);
// Bump all the patches forward.
for (final aPatch in patches) {
aPatch.start1 += paddingLength;
aPatch.start2 += paddingLength;
}
// Add some padding on start of first diff.
var patch = patches[0],
diffs = patch.diffs;
if (diffs.isEmpty || diffs[0].operation != Operation.equal) {
// Add nullPadding equality.
diffs.insert(0, Diff(Operation.equal, nullPadding));
patch.start1 -= paddingLength; // Should be 0.
patch.start2 -= paddingLength; // Should be 0.
patch.length1 += paddingLength;
patch.length2 += paddingLength;
} else if (paddingLength > diffs[0].text.length) {
// Grow first equality.
Diff firstDiff = diffs[0];
int extraLength = paddingLength - firstDiff.text.length;
firstDiff.text =
nullPadding.substring(firstDiff.text.length) + firstDiff.text;
patch.start1 -= extraLength;
patch.start2 -= extraLength;
patch.length1 += extraLength;
patch.length2 += extraLength;
}
// Add some padding on end of last diff.
patch = patches.last;
diffs = patch.diffs;
if (diffs.isEmpty || diffs.last.operation != Operation.equal) {
// Add nullPadding equality.
diffs.add(Diff(Operation.equal, nullPadding));
patch.length1 += paddingLength;
patch.length2 += paddingLength;
} else if (paddingLength > diffs.last.text.length) {
// Grow last equality.
final lastDiff = diffs.last;
final extraLength = paddingLength - lastDiff.text.length;
lastDiff.text = lastDiff.text + nullPadding.substring(0, extraLength);
patch.length1 += extraLength;
patch.length2 += extraLength;
}
return nullPadding;
}