BinaryEncoding

Swift: 4.0 OS: Linux | macOS License: MIT

BinaryEncoding 库旨在简化将原生 Swift 类型及其序列编码/解码为二进制数据缓冲区。

支持的类型包括:Int, UInt, Int*, UInt*, Float, Double, VarUInt, String 以及各种原生数字集合。原生数字按原样编码,使用依赖于架构的表示形式,字符串以 UTF-8 编码。VarUInt 编码等同于 Perl pack 函数的 w 格式。

要求

Swift 4.0

设计

该库提供具有写时复制行为的原始字节托管缓冲区。

BinaryEncodedData

针对所有支持的类型,具有各种 readwriteappend 方法

	init(minimumCapacity: Int = 0)

	func read<T : NativeBinaryEncoding>(_: T.Type, at offset: inout Int) throws -> T
	func read(_: VarUInt.Type, at offset: inout Int) throws -> UInt
	func read(_: BinaryEncodedData.Type, withSize: Int, at offset: inout Int) throws -> BinaryEncodedData
	func read<S : LengthItem>(_: BinaryEncodedData.Type, withSizeOf: S.Type, at offset: inout Int) throws -> BinaryEncodedData
	func read(_: BinaryEncodedData.Type, withSizeOf: VarUInt.Type, at offset: inout Int) throws -> BinaryEncodedData
	func read(_: String.Type, withSize: Int, at offset: inout Int) throws -> String
	func read<S : LengthItem>(_: String.Type, withSizeOf: S.Type, at offset: inout Int) throws -> String
	func read(_: String.Type, withSizeOf: VarUInt.Type, at offset: inout Int) throws -> String
	func read<T : SequenceItem>(arrayOf: T.Type, withSize: Int, at offset: inout Int) throws -> [T]
	func read<T : SequenceItem, S : LengthItem>(arrayOf: T.Type, withSizeOf: S.Type, at offset: inout Int) throws -> [T]
	func read<T : SequenceItem>(arrayOf: T.Type, withSizeOf: VarUInt.Type, at offset: inout Int) throws -> [T]

	mutating func write<T : NativeBinaryEncoding>(_ value: T, as: T.Type, at offset: inout Int)
	mutating func write(_ value: UInt, as: VarUInt.Type, at offset: inout Int)
	mutating func write(_ value: BinaryEncodedData, at offset: inout Int)
	mutating func write<S : LengthItem>(_ value: BinaryEncodedData, withSizeOf: S.Type, at offset: inout Int)
	mutating func write(_ value: BinaryEncodedData, withSizeOf: VarUInt.Type, at offset: inout Int)
	mutating func write(_ value: String, as: String.Type, at offset: inout Int)
	mutating func write<S : LengthItem>(_ value: String, as: String.Type, withSizeOf: S.Type, at offset: inout Int)
	mutating func write(_ value: String, as: String.Type, withSizeOf: VarUInt.Type, at offset: inout Int)
	mutating func write<C : Collection>(_ value: C, asArrayOf: C.Iterator.Element.Type, at offset: inout Int)
		where C.Iterator.Element : SequenceItem
	mutating func write<C : Collection, S : LengthItem>(_ value: C, asArrayOf: C.Iterator.Element.Type, withSizeOf: S.Type, at offset: inout Int)
		where C.Iterator.Element : SequenceItem
	mutating func write<C : Collection>(_ value: C, asArrayOf: C.Iterator.Element.Type, withSizeOf: VarUInt.Type, at offset: inout Int)
		where C.Iterator.Element : SequenceItem

	mutating func append... // same as write but without parameter (at:)

使用示例可以在测试中找到。

UnsafeRawBufferPointer.Reader 和 UnsafeMutableRawBufferPointer.Writer

这些接口是不安全的。 如果你想为了效率而使用它们,你可以在源代码中找到足够的信息。