Jeff Atwood has a helpful article on the topic. Spoiler alert: his conclusion is that ASCII85 encoding can be used to compress a UUID down to 20 characters.
I implemented a base64 solution as an excuse to get better acquainted with Swift. The downside of using base64 is that it yields a 22 character compressed UUID. The upside is that a base64 implementation is built into Cocoa / Cocoa Touch. If you go with ASCII85 you'll have to roll your own implementation.
Please keep in mind that additional changes will need to be made to this solution if the intent is to pass the compressed UUID as part of a url string (eg. '+' and '/' characters, etc will need to be dealt with). Try it out for yourself in a Swift playground!
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 | |
// Compressing and decompressing a UUID to 22 characters via base64. | |
// Works great as a Swift playground. These articles were helpful: | |
// http://blog.codinghorror.com/equipping-our-ascii-armor/ | |
// http://69.195.124.60/~jasondoh/2013/08/14/creating-a-short-guid-in-objective-c/ | |
let identifier = NSUUID().uuidString | |
let base64TailBuffer = "=" | |
func compress(identifier: String) -> String? { | |
guard let tempUuid = NSUUID(uuidString: identifier) else { | |
return nil | |
} | |
var tempUuidBytes: UInt8 = 0 | |
tempUuid.getBytes(&tempUuidBytes) | |
let data = Data(bytes: &tempUuidBytes, count: 16) | |
let base64 = data.base64EncodedString(options: NSData.Base64EncodingOptions()) | |
return base64.replacingOccurrences(of: base64TailBuffer, with: "") | |
} | |
func rehydrate(shortenedIdentifier: String?) -> String? { | |
// Expand an identifier out of a CBAdvertisementDataLocalNameKey or service characteristic. | |
guard let shortenedIdentifier = shortenedIdentifier else { | |
return nil | |
} | |
// Rehydrate the shortenedIdentifier | |
let shortenedIdentifierWithDoubleEquals = shortenedIdentifier + base64TailBuffer + base64TailBuffer | |
let data = Data(base64Encoded: shortenedIdentifierWithDoubleEquals) | |
let uuidBytes = data?.withUnsafeBytes { $0.baseAddress?.assumingMemoryBound(to: UInt8.self) } | |
let tempUuid = NSUUID(uuidBytes: uuidBytes) | |
return tempUuid.uuidString | |
} | |
let testCompress = compress(identifier: identifier) | |
let testRehydrate = rehydrate(shortenedIdentifier: testCompress) |