Skip to content

Instantly share code, notes, and snippets.

@uberbruns
Created October 14, 2013 18:51
Show Gist options
  • Save uberbruns/6980218 to your computer and use it in GitHub Desktop.
Save uberbruns/6980218 to your computer and use it in GitHub Desktop.
Calculates how a given NSRange is affected by replacing another range with a defined length in the same context. It's a little bit like `replaceCharactersInRange:withString:` but the receiver/result is not a string but a NSRange.
static inline NSRange UBRShiftRange(NSRange range, NSRange replacedRange, NSUInteger insertedLength) {
if (replacedRange.location > range.location + range.length) {
// Following
return range;
}
NSRange intersection = NSIntersectionRange(range, replacedRange);
if (replacedRange.location <= range.location) {
// Preceding
range.location -= (replacedRange.length - intersection.length);
range.location += insertedLength;
range.length -= intersection.length;
} else {
// Intersecting
range.length -= intersection.length;
range.length += insertedLength;
}
return range;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment