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

通用唯一标识符(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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冯子一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值