Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sakiwei/753896fbc00af6e8005f8d98b5faff6f to your computer and use it in GitHub Desktop.
Save sakiwei/753896fbc00af6e8005f8d98b5faff6f to your computer and use it in GitHub Desktop.
extension NSData {
func rangeOfData_dd(dataToFind: NSData) -> NSRange {
let bytes = self.bytes
let len = self.length
let searchBytes = dataToFind.bytes
let searchLen = dataToFind.length
var searchIndex = 0
var foundRange = NSMakeRange(NSNotFound, searchLen)
// 1.
for i in 0..<len {
// 2.
if UnsafePointer<CChar>(bytes)[i] == UnsafePointer<CChar>(searchBytes)[searchIndex] {
if foundRange.location == NSNotFound {
foundRange.location = i
}
searchIndex += 1
if searchIndex >= searchLen {
return foundRange
}
} else {
searchIndex = 0
foundRange.location = NSNotFound
}
}
return foundRange
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment