Last active
April 3, 2018 16:13
-
-
Save Marcocanc/0f51957b0054cac18ca081fcb6935a07 to your computer and use it in GitHub Desktop.
Apply DiffMatchPatch Diffs to a String in pure Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension String { | |
func string(withDelta deltaString: String) throws -> String { | |
var outString = String() | |
var indexPointer = self.startIndex | |
let inStringCount = self.utf16.count | |
try deltaString.components(separatedBy: "\t").forEach { string in | |
guard let firstChar = string.first else { return } | |
let param = string[string.index(after: string.startIndex)...] | |
switch firstChar { | |
case "+": | |
guard let decoded = param.removingPercentEncoding else { throw DeltaError.invalidCharacter } | |
outString += decoded | |
case "=", "-": | |
guard let n = Int(param), n > 0 else { throw DeltaError.invalidNumber } | |
let newPointer = String.Index(encodedOffset: indexPointer.encodedOffset + n) | |
guard newPointer.encodedOffset <= inStringCount else { throw DeltaError.deltaLenghtOutOfBounds } | |
if firstChar == "=" { | |
outString += self[indexPointer..<newPointer] | |
} | |
indexPointer = newPointer | |
default: | |
throw DeltaError.invalidOperation | |
} | |
} | |
return outString | |
} | |
enum DeltaError: Swift.Error { | |
case invalidCharacter | |
case invalidNumber | |
case deltaLenghtOutOfBounds | |
case invalidOperation | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment