Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift command-line script to decode dynamic UTIs
#!/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)")
}
@mayoff

This comment has been minimized.

Copy link
Owner Author

commented Mar 14, 2019

Just put it in a file and make it executable:

curl https://gist.githubusercontent.com/mayoff/822595fed7c4670a834af80ac0b420dc/raw/01b25536da13ed25bcd0c9c6562777dcea95a27b/decode-dyn-uti.swift > ~/bin/decode-dyn-uti
chmod +x ~/bin/decode-dyn-uti

Then run it with one or more dynamic UTIs as command-line arguments:

~/bin/decode-dyn-uti dyn.ah62d4r34gq81k3p2su1zuppgsm10esvvhzxhe55c dyn.ah62d4r34qr104pxftbu046dqqy1fg6dfqry0c5cytf2gntpgr710e2pw

Output:

dyn.ah62d4r34gq81k3p2su1zuppgsm10esvvhzxhe55c => ?0=7:3=text/X-frob:1=frob
dyn.ah62d4r34qr104pxftbu046dqqy1fg6dfqry0c5cytf2gntpgr710e2pw => ?0=7:com.example.SpecialType=foobar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.