36位UUID压缩为22位字符串base64编解码函数(Swift)

版权声明:本文为陈云峰(www.swifty.cc)原创文章,未经允许不得转载。 https://blog.csdn.net/feosun/article/details/83788939

通用唯一标识符(UUID,也称为Windows上的GUID)是识别人群中唯一事物的有用标准。为了确保每个UUID的所有意图和用途都是唯一的,它必须是36个字符长。当在大规模网络上传输时,这些冗长的标识符会消耗带宽。有什么好的方法进行压缩?

Jeff Atwood在这个题目上有一篇有益的文章。扰流板警报:他的结论是ASCII85编码可以用来压缩UUID到20个字符。

我用一个Base64作为一个解决方案来更好地了解Swift。使用Base64的缺点是它产生了一个22字符压缩的UUID。好处是Base64的实现是建立在Cocoa/Cocoa Touch上的。如果你和ASCI85一起运行,你就必须自己滚动实现。

另外,如果要将压缩的UUID作为url字符串的一部分传递(例如,“+”和“/”字符等需要处理),则需要对该解决方案进行额外的更改。

编解码函数如下:

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.
    if shortenedIdentifier == nil {
        return nil
    } else {
        // Rehydrate the shortenedIdentifier
        let shortenedIdentifierWithDoubleEquals = shortenedIdentifier! + base64TailBuffer + base64TailBuffer
        let data = Data(base64Encoded: shortenedIdentifierWithDoubleEquals, options: Data.Base64DecodingOptions())
        let tempUuid = NSUUID(uuidBytes: data?.withUnsafeBytes({ UnsafePointer<UInt8>($0) }))
        return tempUuid.uuidString
    }
}

let testCompress = compress(identifier: identifier)
let testRehydrate = rehydrate(shortenedIdentifier: testCompress)

猜你喜欢

转载自blog.csdn.net/feosun/article/details/83788939