 
 import Dispatch
 
-private final class Storage<T> {
-
-    let value: T
-
-    init(_ value: T) {
-        self.value = value
-    }
-
+// A generic catch-all queue for when you just want to throw some work into the
+// concurrent pile. As an alternative to the `QOS_CLASS_UTILITY` global queue,
+// work dispatched onto this queue matches the QoS of the caller, which is
+// generally the right behavior.
+//
+// The technique is described and used in Core Foundation:
+// http://opensource.apple.com/source/CF/CF-1153.18/CFInternal.h
+private var genericQueue: dispatch_queue_t! {
+    return dispatch_get_global_queue(qos_class_self(), 0)
 }
 
 // Atomic compare-and-swap, but safe for owned (retaining) pointers:

    }
}

// Raw Deferred storage. Using `ManagedBuffer` has advantages over a custom class:
//  - The side-table data is efficiently stored in tail-allocated buffer space.
//  - The Element buffer has a stable pointer when locked to a single element.
//  - Better holdsUniqueReference support allows for future optimization.
private final class DeferredBuffer<Value, SideData>: ManagedBuffer<SideData, Storage<Value>?> {
    
    static func create(sideData: () -> SideData) -> DeferredBuffer<Value, SideData> {
        return create(1, initialValue: { _ in sideData() }) as! DeferredBuffer<Value, SideData>
    }
    
    deinit {
        // super's init automatically destroys the Value
        withUnsafeMutablePointerToElements { elementsPtr in
            // UnsafeMutablePointer.destroy() is faster than destroy(_:)
            elementsPtr.destroy()
        }
    }
    
    func initializeWith(value: Value?) {
        let box = value.map(Storage.init)
        withUnsafeMutablePointerToElements { elementsPtr in
            elementsPtr.initialize(box)
        }
    }
    
    func withValue(body: Value -> Void) {
        withUnsafeMutablePointerToElements { elementsPtr in
            guard let box = elementsPtr.memory else { return }
            body(box.value)
        }
    }
    
    func fill(value: Value, onFill: SideData -> Void) -> Bool {
        let box = Storage(value)
        return withUnsafeMutablePointers { (valuePtr, elementsPtr) in
            guard compareAndSwap(old: nil, new: box, to: elementsPtr) else { return false }
            onFill(valuePtr.memory)
            return true
        }
    }
    
}

// A generic catch-all queue for when you just want to throw some work into the
// concurrent pile. As an alternative to the `QOS_CLASS_UTILITY` global queue,
// work dispatched onto this queue matches the QoS of the caller, which is
// generally the right behavior.
//
// The technique is described and used in Core Foundation:
// http://opensource.apple.com/source/CF/CF-1153.18/CFInternal.h
private var genericQueue: dispatch_queue_t! {
    return dispatch_get_global_queue(qos_class_self(), 0)
}

/// A deferred is a value that may become determined (or "filled") at some point
/// in the future. Once a deferred value is determined, it cannot change.
public struct Deferred<Value> {
    
    private var storage = DeferredBuffer<Value, dispatch_block_t>.create {
        dispatch_block_create(DISPATCH_BLOCK_NO_QOS_CLASS, {})
    }

    private func upon(queue: dispatch_queue_t, options inFlags: dispatch_block_flags_t, body: Value -> Void) -> dispatch_block_t {
        let flags = dispatch_block_flags_t(inFlags.rawValue | DISPATCH_BLOCK_ASSIGN_CURRENT.rawValue)
        let block = dispatch_block_create(flags) {
            self.storage.withValue(body)
        }
        dispatch_block_notify(storage.value, queue, block)
        return block
    }
    
    private func markFilled(onFilled: dispatch_block_t) {
        dispatch_block_cancel(onFilled)
        onFilled()
    }

    // MARK: -

    /// Initialize a filled Deferred with the given value.
    public init(value: Value) {
        storage.initializeWith(value)
        markFilled(storage.onFilled)
    }

    /// Check whether or not the receiver is filled.
    public var isFilled: Bool {
        return dispatch_block_testcancel(storage.onFilled) != 0
    }

    /// Determines the deferred value with a given result.
