From 488dcdcb5e1debcefd19e3f76f2a5981ef1af14e Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Thu, 1 Jun 2017 19:24:35 +0200 Subject: [PATCH] Add methods to ByteBufferAllocator that allows wrapping existing Data --- Sources/NIO/ByteBuffer.swift | 18 +++++++++++++++++- Tests/NIOTests/ByteBufferTest.swift | 7 +++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Sources/NIO/ByteBuffer.swift b/Sources/NIO/ByteBuffer.swift index 8a2313b62..731a044d0 100644 --- a/Sources/NIO/ByteBuffer.swift +++ b/Sources/NIO/ByteBuffer.swift @@ -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 diff --git a/Tests/NIOTests/ByteBufferTest.swift b/Tests/NIOTests/ByteBufferTest.swift index d8814a6d4..fe30af512 100644 --- a/Tests/NIOTests/ByteBufferTest.swift +++ b/Tests/NIOTests/ByteBufferTest.swift @@ -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)