Port ByteBuf

This implements a heap based ByteBuffer modeled on Netty's ByteBuf. It provides read and write access via Unsafe{Mutable}Pointers (withReadPointer, withMutableWritePointer) and read access via withData. Instead of providing public access to mutating readIndex/writeIndex, the mutable withPointer methods take a closure returning the number of bytes written and automatically manages the applicable index.

Read and write helper methods still largely TODO.
This commit is contained in:
Kevin Clark committed 2017-05-15 22:30:49 -07:00
1 parent bb6cb9fa81
commit 7ef823a44a
5 files changed
+313 -112

No files matched your search

-53
View File
@@ -1,53 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
public class Buffer {
var data: Data
var offset: Int
var limit: Int
init(capacity: Int32) {
self.data = Data(repeating: 0, count: Int(capacity))
self.offset = 0
self.limit = 0;
}
public func clear() {
self.offset = 0
self.limit = 0
}
}
public protocol BufferAllocator {
func buffer(capacity: Int32) -> Buffer
func buffer() -> Buffer
}
extension BufferAllocator {
public func buffer() -> Buffer {
return buffer(capacity: 256)
}
}
public class DefaultBufferAllocator : BufferAllocator {
public init() {}
public func buffer(capacity: Int32) -> Buffer {
return Buffer(capacity: capacity)
}
}
+253
View File
@@ -0,0 +1,253 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
public struct ByteBufferAllocator {
public func buffer(capacity: Int) throws -> ByteBuffer {
return try buffer(capacity: capacity, maxCapacity: Int.max)
}
public func buffer(capacity: Int, maxCapacity: Int) throws -> ByteBuffer {
return try ByteBuffer(allocator: self, startingCapacity: capacity, maxCapacity: maxCapacity)
}
}
public struct ByteBuffer { // TODO: Equatable, Comparable
enum ByteBufferError : Error {
case maxCapacityExceeded
}
private var data: Data
public private(set) var capacity = 0
/**
Adjusts the capacity of the buffer. If the new capacity is less than the current
capacity, the content of this buffer is truncated. If the new capacity is greater than the
current capacity, the buffer is appended with unspecified data of length newCapacity - currentCapacity
*/
public mutating func changeCapacity(to newCapacity: Int) throws {
let result = ensureWritable(bytesNeeded: newCapacity - writerIndex, expandIfRequired: true)
switch result {
case (true, _):
return
default:
throw ByteBufferError.maxCapacityExceeded // TODO: Possibly other reasons, yeah?
}
}
/**
Returns the maximum allowed capacity of this buffer. If a user attempts to increase the
capacity of this buffer beyond the maximum capacity, an Error will be thrown
*/ // TODO: Specify the Error
public private(set) var maxCapacity = Int.max
// The allocator that created this buffer, if any
public private(set) var allocator: ByteBufferAllocator?
public private(set) var readerIndex = 0, markedReaderIndex = 0
public private(set) var writerIndex = 0, markedWriterIndex = 0
var writableBytes: Int { return self.capacity - self.writerIndex }
var readableBytes: Int { return self.writerIndex - self.readerIndex }
public init(allocator: ByteBufferAllocator, startingCapacity: Int, maxCapacity: Int) throws {
precondition(startingCapacity >= 0)
precondition(startingCapacity <= maxCapacity)
self.allocator = allocator
self.maxCapacity = maxCapacity
self.data = Data(capacity: startingCapacity)
self.capacity = startingCapacity
}
/**
Discards the bytes between the 0th index and readerIndex. It moves the bytes between readerIndex and
writerIndex to the 0th index, and sets readerIndex to 0 and writerIndex to oldWriterIndex - oldReaderIndex
*/
public mutating func discardReadBytes() {
// TODO
}
// Tries to make sure that the number of writable bytes is equal to or greater than the specified value.
public mutating func ensureWritable(bytesNeeded: Int) throws {
if !ensureWritable(bytesNeeded: bytesNeeded, expandIfRequired: false).enoughSpace {
throw ByteBufferError.maxCapacityExceeded
}
}
@discardableResult public mutating func ensureWritable(bytesNeeded: Int, expandIfRequired: Bool)
-> (enoughSpace: Bool, capacityIncreased: Bool) {
if bytesNeeded <= writableBytes {
return (enoughSpace: true, capacityIncreased: false)
}
let deficit = bytesNeeded - writableBytes
if capacity + deficit > maxCapacity {
return (enoughSpace: false, capacityIncreased: false)
}
let oldData = self.data
data = Data(capacity: capacity + deficit) // TODO: alloc at nearest power of two
capacity += deficit
data.append(oldData)
return (enoughSpace: true, capacityIncreased: true)
}
public func withReadPointer<T>(body: (UnsafePointer<UInt8>, Int) -> T) -> T {
return data.withUnsafeBytes({ body($0 + readerIndex, readableBytes) })
}
public func withReadPointer<T>(body: (UnsafePointer<UInt8>, Int) throws -> T) throws -> T {
return try data.withUnsafeBytes({ try body($0 + readerIndex, readableBytes) })
}
public func withWritePointer<T>(body: (UnsafePointer<UInt8>, Int) -> T) -> T {
return data.withUnsafeBytes({ body($0 + writerIndex, writableBytes) })
}
public func withWritePointer<T>(body: (UnsafePointer<UInt8>, Int) throws -> T) throws -> T {
return try data.withUnsafeBytes({ try body($0 + writerIndex, writableBytes) })
}
// Mutable versions for writing to the buffer. body function returns the number of bytes written and writerIndex
// will be automatically moved.
public mutating func withMutableWritePointer(body: (UnsafeMutablePointer<UInt8>, Int) -> Int) -> Int {
let bytesWritten = data.withUnsafeMutableBytes({ return body($0 + writerIndex, writableBytes) })
advanceWriterIndex(bytesWritten)
return bytesWritten
}
public mutating func withMutableWritePointer(body: (UnsafeMutablePointer<UInt8>, Int) throws -> Int) throws -> Int {
let bytesWritten = try data.withUnsafeMutableBytes({ return try body($0 + writerIndex, writableBytes) })
advanceWriterIndex(bytesWritten)
return bytesWritten
}
public mutating func withMutableReadPointer(body: (UnsafeMutablePointer<UInt8>, Int) -> Int) -> Int {
let bytesWritten = data.withUnsafeMutableBytes({ return body($0 + readerIndex, readableBytes) })
advanceReaderIndex(bytesWritten)
return bytesWritten
}
public mutating func withMutableReadPointer(body: (UnsafeMutablePointer<UInt8>, Int) throws -> Int) throws -> Int {
let bytesWritten = try data.withUnsafeMutableBytes({ return try body($0 + readerIndex, readableBytes) })
advanceReaderIndex(bytesWritten)
return bytesWritten
}
// Provides the read portion of the buffer as Data.
public func withReadData<T>(body: (Data) -> T) -> T {
return body(data)
}
// TODO: get/skip/set for all the type conversions
// TODO: indexOf, bytesBefore, forEachByte, copy, reatinedSlice/slice, duplicate, direct buffer access?, backing byte array access?
// TODO: Generics to avoid this?
public mutating func write(string: String) {
let _ = withMutableWritePointer { (writePtr: UnsafeMutablePointer<UInt8>, size: Int) -> Int in
// TODO: Can we avoid the double copy? getBytes seems almost, but not quite right.
if let data = string.data(using: .utf8) {
let _ = data.withUnsafeBytes { writePtr.assign(from: $0, count: 1) }
return data.count
} else {
return 0
}
}
}
/**
Marks the current readerIndex in this buffer. You can reposition the current readerIndex to the marked
readerIndex by calling resetReaderIndex(). The initial value of the marked readerIndex is 0.
*/
public mutating func markReaderIndex() {
markedReaderIndex = readerIndex
}
/**
Moves the current readerIndex to the marked readerIndex in this buffer.
*/
public mutating func resetReaderIndex() {
moveReaderIndex(to: markedReaderIndex)
}
/**
Marks the current writerIndex in this buffer. You can reposition the current writerIndex to the marked
writerIndex by calling resetWriterIndex(). The initial value of the marked writerIndex is 0.
*/
public mutating func markWriterIndex() {
markedWriterIndex = writerIndex
}
/**
Moves the current writerIndex to the marked writerIndex in this buffer.
If the readerIndex is greater than the marked writerIndex nothing is returned.
*/
public mutating func resetWriterIndex() {
moveWriterIndex(to: markedWriterIndex)
}
private mutating func moveReaderIndex(to newIndex: Int) {
precondition(newIndex >= 0 && newIndex <= writerIndex)
readerIndex = newIndex
}
private mutating func moveWriterIndex(to newIndex: Int) {
precondition(newIndex >= readerIndex && newIndex <= capacity)
writerIndex = newIndex
}
private mutating func advanceWriterIndex(_ count: Int) {
moveWriterIndex(to: writerIndex + count)
}
private mutating func advanceReaderIndex(_ count: Int) {
moveReaderIndex(to: readerIndex + count)
}
/**
Sets the readerIndex and writerIndex of this buffer in one shot. This method is useful when you have to
worry about the invocation order of settings both indicies.
*/
private mutating func moveIndicies(reader: Int, writer: Int) {
precondition(0 <= reader && reader <= writer && writer <= capacity)
readerIndex = reader
writerIndex = writer
}
}
+38 -34
View File
@@ -23,25 +23,24 @@ import Darwin
#endif
public class Channel : ChannelOutboundInvoker {
public var pipeline: ChannelPipeline {
return _pipeline
}
public var config: ChannelConfig {
return _config
}
public var allocator: BufferAllocator {
public var allocator: ByteBufferAllocator {
return config.allocator
}
public let eventLoop: EventLoop
// Visible to access from EventLoop directly
internal let socket: Socket
internal var interestedEvent: InterestedEvent = .None
// TODO: This is most likely not the best datastructure for us. Linked-List would be better.
private var pendingWrites: [(Buffer, Promise<Void>)] = Array()
private var pendingWrites: [(ByteBuffer, Promise<Void>)] = Array()
private var outstanding: UInt64 = 0
public private(set) var open: Bool = true
private var readPending: Bool = false;
@@ -76,12 +75,12 @@ public class Channel : ChannelOutboundInvoker {
promise.fail(error: IOError(errno: EBADF, reason: "Channel closed"))
return
}
if let buffer = data as? Buffer {
if let buffer = data as? ByteBuffer {
pendingWrites.append((buffer, promise))
outstanding += UInt64((buffer.limit - buffer.offset))
outstanding += UInt64(buffer.readableBytes)
} else {
// Only support Buffer for now.
// Only support ByteBuffer for now.
promise.fail(error: MessageError.unsupported)
}
}
@@ -195,9 +194,6 @@ public class Channel : ChannelOutboundInvoker {
assert(open)
readPending = false
let buffer = config.recvAllocator.buffer(allocator: allocator)
defer {
// Always call the method as last
pipeline.fireChannelReadComplete()
@@ -215,15 +211,18 @@ public class Channel : ChannelOutboundInvoker {
}
do {
var buffer = try config.recvAllocator.buffer(allocator: allocator)
// TODO: Read spin ?
if let read = try socket.read(data: &buffer.data) {
guard read > 0 else {
// end-of-file
close0()
return
}
buffer.limit = Int(read)
let bytesRead = try buffer.withMutableWritePointer { try self.socket.read(pointer: $0, size: $1) ?? 0 }
if bytesRead > 0 {
pipeline.fireChannelRead(data: buffer)
} else {
// end-of-file
close0()
return
}
} catch let err {
pipeline.fireErrorCaught(error: err)
@@ -274,14 +273,19 @@ public class Channel : ChannelOutboundInvoker {
private func flushNow() -> Bool {
do {
while open, let pending = pendingWrites.first {
if let written = try socket.write(data: pending.0.data, offset: pending.0.offset, len: pending.0.limit - pending.0.offset) {
pending.0.offset += Int(written)
while open, let _ = pendingWrites.first {
// We do this because the buffer is a value type and can't be modified in place.
// If the buffer is still applicable we'll need to add it back into the queue.
var (buffer, promise) = pendingWrites.removeFirst()
let written = try buffer.withMutableReadPointer { try self.socket.write(pointer: $0, size: $1) ?? 0 }
if written > 0 {
outstanding -= UInt64(written)
if pending.0.offset == pending.0.limit {
pendingWrites.removeFirst()
pending.1.succeed(result: ())
if buffer.readerIndex == buffer.writerIndex {
promise.succeed(result: ())
} else {
pendingWrites.insert((buffer, promise), at: 0)
}
} else {
return false
@@ -317,18 +321,18 @@ public class Channel : ChannelOutboundInvoker {
}
public protocol RecvBufferAllocator {
func buffer(allocator: BufferAllocator) -> Buffer
func buffer(allocator: ByteBufferAllocator) throws -> ByteBuffer
}
public class FixedSizeBufferAllocator : RecvBufferAllocator {
private let capacity: Int32
init(capacity: Int32) {
public class FixedSizeByteBufferAllocator : RecvBufferAllocator {
let capacity: Int
init(capacity: Int) {
self.capacity = capacity
}
public func buffer(allocator: BufferAllocator) -> Buffer {
return allocator.buffer(capacity: capacity)
public func buffer(allocator: ByteBufferAllocator) throws -> ByteBuffer {
return try allocator.buffer(capacity: capacity)
}
}
@@ -340,8 +344,8 @@ public class ChannelConfig {
// Declare as weak to remove reference-cycle.
private weak var channel: Channel?
private var _autoRead: Bool = true
public var allocator: BufferAllocator = DefaultBufferAllocator()
public var recvAllocator: RecvBufferAllocator = FixedSizeBufferAllocator(capacity: 8192)
public var allocator: ByteBufferAllocator = ByteBufferAllocator()
public var recvAllocator: RecvBufferAllocator = FixedSizeByteBufferAllocator(capacity: 8192)
public var autoRead: Bool {
get {
+4 -2
View File
@@ -39,12 +39,14 @@ public class BaseSocket : Selectable {
return nil
}
}
// TODO: This needs a way to encourage proper open/close behavior.
// A closure a la Ruby's File.open may make sense.
init(descriptor : Int32) {
self.descriptor = descriptor
self.open = true
}
public func setNonBlocking() throws {
let _ = try wrapSyscall({ $0 >= 0 }, function: "fcntl") {
fcntl(self.descriptor, F_SETFL, O_NONBLOCK)
+18 -23
View File
@@ -29,36 +29,31 @@ let sysRead = Darwin.read
// TODO: Add gathering / scattering support
public class Socket : BaseSocket {
public func write(data: Data) throws -> UInt? {
public func write(data: Data) throws -> Int? {
return try write(data: data, offset: 0, len: data.count)
}
public func write(data: Data, offset: Int, len: Int) throws -> UInt? {
let res = try data.withUnsafeBytes() { [unowned self] (buffer: UnsafePointer<UInt8>) -> Int? in
try wrapSyscallMayBlock({ $0 >= 0 }, function: "write") {
sysWrite(self.descriptor, buffer.advanced(by: offset), len)
}
}
if let written = res {
return UInt(written)
}
return nil
public func write( data: Data, offset: Int, len: Int) throws -> Int? {
return try data.withUnsafeBytes({ try write(pointer: $0 + offset, size: len) })
}
public func read(data: inout Data) throws -> UInt? {
public func write(pointer: UnsafePointer<UInt8>, size: Int) throws -> Int? {
return try wrapSyscallMayBlock({ $0 >= 0 }, function: "write") {
sysWrite(self.descriptor, pointer, size)
}
}
public func read(data: inout Data) throws -> Int? {
return try read(data: &data, offset: 0, len: data.count)
}
public func read(data: inout Data, offset: Int, len: Int) throws -> UInt? {
let res = try data.withUnsafeMutableBytes() { [unowned self] (buffer: UnsafeMutablePointer<UInt8>) -> Int? in
try wrapSyscallMayBlock({ $0 >= 0 }, function: "read") {
sysRead(self.descriptor, buffer.advanced(by: offset), len)
}
public func read(data: inout Data, offset: Int, len: Int) throws -> Int? {
return try data.withUnsafeMutableBytes({ try read(pointer: $0 + offset, size: len) })
}
public func read(pointer: UnsafeMutablePointer<UInt8>, size: Int) throws -> Int? {
return try wrapSyscallMayBlock({ $0 >= 0 }, function: "read") {
sysRead(self.descriptor, pointer, size)
}
if let read = res {
return UInt(read)
}
return nil
}
}