Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sakiwei/2025dcf04aa8e9baa559a83d08c2fb08 to your computer and use it in GitHub Desktop.
Save sakiwei/2025dcf04aa8e9baa559a83d08c2fb08 to your computer and use it in GitHub Desktop.
@interface NSData (DDAdditions)
- (NSRange) rangeOfData_dd:(NSData *)dataToFind;
@end
@implementation NSData (DDAdditions)
- (NSRange) rangeOfData_dd:(NSData *)dataToFind {
const void * bytes = [self bytes];
NSUInteger length = [self length];
const void * searchBytes = [dataToFind bytes];
NSUInteger searchLength = [dataToFind length];
NSUInteger searchIndex = 0;
NSRange foundRange = {NSNotFound, searchLength};
for (NSUInteger index = 0; index < length; index++) {
if (((char *)bytes)[index] == ((char *)searchBytes)[searchIndex]) {
//the current character matches
if (foundRange.location == NSNotFound) {
foundRange.location = index;
}
searchIndex++;
if (searchIndex >= searchLength) { return foundRange; }
} else {
searchIndex = 0;
foundRange.location = NSNotFound;
}
}
return foundRange;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment