 import Darwin
 #endif
 
+fileprivate class PendingWrites {
+    
+    private var head: PendingWrite?
+    private var tail: PendingWrite?
+    
+    private(set) var outstanding: UInt64 = 0
+    
+    var isEmpty: Bool {
+        return tail == nil
+    }
+    
+    func add(buffer: ByteBuffer, promise: Promise<Void>) {
+        let pending: PendingWrite = PendingWrite(buffer: buffer, promise: promise)
+        if let last = tail {
+            assert(head != nil)
+            last.next = pending
+        } else {
+            assert(tail == nil)
+            head = pending
+            tail = pending
+        }
+        outstanding += UInt64(buffer.readableBytes)
+    }
+    
+    func consumeNext(body: (UnsafeMutablePointer<UInt8>, Int) throws -> Int?) rethrows -> Bool? {
+        if let pending = head {
+            if let written = try pending.buffer.withMutableReadPointer(body: body) {
+                outstanding -= UInt64(written)
+                if (pending.buffer.readableBytes == 0) {
+                    // buffer was completely written
+                    pending.promise.succeed(result: ())
+                    head = pending.next
+                    if (head == nil) {
+                        // everything was written also reset the tail
+                        tail = nil
+                        
+                        // return nil to signal to the caller that there are no more buffers to consume
+                        return nil
+                    }
+                    return true
+                }
+            }
+            // could not write the complete buffer
+            return false
+        }
+        
+        // empty
+        return nil
+    }
+    
+    func failAll(error: Error) {
+        var next = head
+        while let pending = next {
+            pending.promise.fail(error: error)
+            next = pending.next
+        }
+        head = nil
+        tail = nil
+        outstanding = 0
+    }
+
+    private class PendingWrite {
+        var next: PendingWrite?
+        var buffer: ByteBuffer
+        let promise: Promise<Void>
+        
+        init(buffer: ByteBuffer, promise: Promise<Void>) {
+            self.buffer = buffer
+            self.promise = promise
+        }
+    }
+}
+
 public class Channel : ChannelOutboundInvoker {
     public private(set) var open: Bool = true
 

        
        
        // Fail all pending writes and so ensure all pending promises are notified
        failPendingWrites(err: IOError(errno: EBADF, reason: "Channel closed"))
    }
    
    func registerOnEventLoop(initPipeline: (ChannelPipeline) throws ->()) {

            return
        }
        if let buffer = data as? ByteBuffer {
            pendingWrites.add(buffer: buffer, promise: promise)
        } else {
            // Only support ByteBuffer for now. 
            promise.fail(error: MessageError.unsupported)
