Add methods to ByteBufferAllocator that allows wrapping existing Data

This commit is contained in:
Norman Maurer committed 2017-06-01 19:24:35 +02:00
1 parent 29b4ad373b
commit 488dcdcb5e
2 files changed
+24 -1

No files matched your search

+17 -1
View File
@@ -29,6 +29,18 @@ public struct ByteBufferAllocator {
public func buffer(capacity: Int, maxCapacity: Int) throws -> ByteBuffer {
return try ByteBuffer(allocator: self, startingCapacity: capacity, maxCapacity: maxCapacity)
}
public func buffer(wrapped: Data) -> ByteBuffer {
return buffer(wrapped: wrapped, offset: 0, length: wrapped.count)
}
public func buffer(wrapped: Data, offset: Int, length: Int) -> ByteBuffer {
return buffer(wrapped: wrapped, offset: offset, length: length, maxCapacity: Int.max)
}
public func buffer(wrapped: Data, offset: Int, length: Int, maxCapacity: Int) -> ByteBuffer {
return ByteBuffer(allocator: self, data: wrapped, offset: offset, length: length, maxCapacity: Int.max)
}
}
extension UInt64 {
@@ -136,7 +148,11 @@ public struct ByteBuffer { // TODO: Equatable, Comparable
self.capacity = data.count
}
private init(allocator: ByteBufferAllocator, data: Data, offset: Int, length: Int, maxCapacity: Int) {
fileprivate init(allocator: ByteBufferAllocator, data: Data, offset: Int, length: Int, maxCapacity: Int) {
precondition(offset >= 0)
precondition(length <= maxCapacity)
precondition(data.count >= length - offset)
self.allocator = allocator
self.maxCapacity = maxCapacity
self.writerIndex = length
+7
View File
@@ -25,6 +25,13 @@ class ByteBufferTest: XCTestCase {
buf = try! allocator.buffer(capacity: 1024)
}
func testWrappedData() {
let data = "Test".data(using: .utf8)!
let buffer = allocator.buffer(wrapped: data)
XCTAssertEqual(0, buffer.readerIndex)
XCTAssertEqual(data.count, buffer.writerIndex)
}
func testSimpleReadTest() throws {
buf.withReadPointer(body: { ptr, size in
XCTAssertEqual(size, 0)