Skip to content

Instantly share code, notes, and snippets.

@AfricanSwift
Last active January 8, 2016 21:13
Show Gist options
  • Save AfricanSwift/ca05c9e82a203cac406b to your computer and use it in GitHub Desktop.
Save AfricanSwift/ca05c9e82a203cac406b to your computer and use it in GitHub Desktop.
c loops with mutable index, advance or rewind index
// The below code segment is an extraction from a compression routine for Ansi (ECMA 48) tags
// For example:
// All Ps functions are compressed through summation of Ps values, for example:
// \u{1b}[1C\u{1b}[3C\u{1b}[1B\u{1b}[1B\u{1b}[1B = \u{1b}[4C\u{1b}[3B
// All CSI Pm functions are compressed with a semicolon delimiting sub Pm values, for example:
// \u{1b}[1m\u{1b}[30m\u{1b}[45m = \u{1b}[1;30;45m
let tagArray = self.toString().characters.split(
isSeparator: { String($0) == Ansi.C0.ESC } ).map { Ansi.C0.ESC + String($0) }
for var index = 0; index < tagArray.count; index += 1
{
let tag = tagArray[index]
guard let id = parse(tag: tag) else
{
output += tag
continue
}
// Typically occurs at the conclusion of a line i.e. last with \n as suffix
guard id.suffix.isEmpty else
{
output += tag
continue
}
switch id.function
{
// If the 'm' ansi function is identified, then continue advancing forward looking for additonal 'm' functions
// strip the CSI and concatenating with a ';' If we find an incompatible function, we complete the tag with its function
// and rewind the index by 1, breaking out to the main loop.
case "m":
output += Ansi.C1.CSI + id.parameter
for _ in index + 1 ..< tagArray.count
{
index += 1
let tag2 = tagArray[index]
// Try to parse the adjacent tag if it fails (i.e. not a compressable tag)
// then complete the current tag and add the adjacent tag unchanged
guard let id2 = parse(tag: tag2) else
{
output += id.function + tag2
break
}
// If the functions are different, complete the current tag,
// and rewind index to allow re-analysis of tag2 (primary loop)
guard id.function == id2.function else
{
output += id.function
index -= 1
break
}
// If the tag includes a suffix i.e. printable character
// then complete the current tag and add the suffix
guard id2.suffix.isEmpty else
{
output += ";" + id2.parameter + id.function + id2.suffix
break
}
// If all guards were passed, add the clip instruction
// and continue the search for matching tags
output += ";" + id2.parameter
// If we're processing the last array element
// Close the function, no more tags expected
if mIndex == tagArray.count - 1
{
output += id.function
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment