64位整数的VarInt编码

Swift Package Manager compatible Build & Test (macos and linux)

Google Protocol Buffers VarInt 规范的 Swift 实现

目录

概述

它基于 Google Protocol Buffers varint 规范的 Go 实现。

更多细节请参考

编码规则如下:

安装

在你的 Package.swift 文件中包含以下依赖项

let package = Package(
    ...
    dependencies: [
        ...
        .package(url: "https://github.com/swift-libp2p/swift-varint.git", .upToNextMajor(from: "0.0.1"))
    ],
    
    ...
)

用法

示例

import VarInt

/// Create some arbitrary data
let bytes = [UInt8]("Hello World".data(using: .utf8)!)

/// Prefix the bytes with their length so we can recover the data later
let uVarIntLengthPrefixedBytes = putUVarInt(UInt64(bytes.count)) + bytes

/// ... send the data across a network or something ...

/// Read the length prefixed data to determine the length of the payload
let lengthPrefix = uVarInt(uVarIntLengthPrefixedBytes)
print(lengthPrefix.value)     // 11 -> `Hello World` == 11 bytes
print(lengthPrefix.bytesRead) // 1  -> The value `11` fits into 1 byte

/// So dropping the first byte will result in our original data again...
let recBytes = [UInt8](uVarIntLengthPrefixedBytes.dropFirst(lengthPrefix.bytesRead))

/// The original bytes and the recovered bytes are equal
print(bytes == recBytes) // True

API

/// Signed VarInts
public func putVarInt(_ value: Int64) -> [UInt8] 
public func varInt(_ buffer: [UInt8]) -> DecodedVarInt   // (value:  Int64, bytesRead: Int)

/// Unsigned VarInts
public func putUVarInt(_ value: UInt64) -> [UInt8]
public func uVarInt(_ buffer: [UInt8]) -> DecodedUVarInt // (value: UInt64, bytesRead: Int)

贡献

欢迎贡献!这段代码很大程度上只是一个概念验证。我可以保证有更好/更安全的方法来实现相同的结果。任何建议、改进,甚至只是批评,都非常欢迎!

让我们一起让这段代码变得更好!🤝

致谢

https://github.com/multiformats/go-varint

许可

MIT © 2022 Breth Inc.