Created
March 14, 2019 22:13
-
-
Save mayoff/822595fed7c4670a834af80ac0b420dc to your computer and use it in GitHub Desktop.
Swift command-line script to decode dynamic UTIs
This file contains hidden or 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
#!/usr/bin/xcrun swift | |
// http://alastairs-place.net/blog/2012/06/06/utis-are-better-than-you-think-and-heres-why/ | |
extension String { | |
static let bitsForCodeUnit: [Character: [UInt8]] = { | |
var dict = [Character: [UInt8]]() | |
for (i, ch) in "abcdefghkmnpqrstuvwxyz0123456789".enumerated() { | |
let bits = Array((0 ..< 5).map({ UInt8((i >> $0) & 1) }).reversed()) | |
dict[ch] = bits | |
} | |
return dict | |
}() | |
var dynamicUTIContent: String? { | |
struct BadCodeUnit: Error { } | |
func justThrow() throws -> [UInt8] { throw BadCodeUnit() } | |
let prefix = "dyn.a" | |
guard hasPrefix(prefix) else { return nil } | |
let bitsForCodeUnit = String.bitsForCodeUnit | |
guard var bits = try? dropFirst(prefix.count).flatMap({ try bitsForCodeUnit[$0] ?? justThrow() })[...] else { return nil } | |
var bytes = [UInt8]() | |
while bits.count >= 8 { | |
bytes.append(bits.prefix(8).reduce(0, { ($0 << 1) + $1 })) | |
bits.removeFirst(8) | |
} | |
let extra = bits.isEmpty ? "" : " (extra bits: \(bits))" | |
return String(decoding: bytes, as: UTF8.self) + extra | |
} | |
} | |
for uti in CommandLine.arguments.dropFirst() { | |
let decoded = uti.dynamicUTIContent ?? "(undecodable)" | |
print("\(uti) => \(decoded)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just put it in a file and make it executable:
Then run it with one or more dynamic UTIs as command-line arguments:
Output: