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
/// 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.