  */
 import Swift
 
-internal class CollectionBuffer<E>: ManagedBuffer<Int,E> {
+internal struct CollectionBufferHeader {
+    var capacity: Int
+    var count: Int
+}
+
+internal class CollectionBuffer<E>: ManagedBuffer<CollectionBufferHeader,E> {
 
     internal typealias Element = E
 
     deinit {
-        self.withUnsafeMutablePointerToElements { elements->Void in
-            elements.deinitialize(count: self.header)
+        self.withUnsafeMutablePointers { header, elements -> Void in
+            elements.deinitialize(count: header.pointee.count)
+            header.deinitialize()
         }
     }
 }

extension CollectionBuffer {

    func clone() -> CollectionBuffer<Element> {
        return self.withUnsafeMutablePointerToElements { oldElements->CollectionBuffer<Element> in

            return CollectionBuffer<Element>.create(minimumCapacity: self.capacity) { newBuffer in

                newBuffer.withUnsafeMutablePointerToElements { newElements -> Void in
                    newElements.initialize(from: oldElements, count: self.header)
                }

                return self.header

            } as! CollectionBuffer<Element> // swiftlint:disable:this force_cast


    }

    func resize(_ newSize: Int) -> CollectionBuffer<Element> {
        return self.withUnsafeMutablePointerToElements { oldElems -> CollectionBuffer<Element> in

            let elementCount = self.header.count

            return CollectionBuffer<Element>.create(minimumCapacity: newSize) { newBuffer -> CollectionBufferHeader in

                newBuffer.withUnsafeMutablePointerToElements { newElements -> Void in

                    newElements.moveInitialize(from: oldElems, count: elementCount)
                }

                // Clear the old buffer since we moved the values
                self.header.count = 0

                return CollectionBufferHeader(capacity: newSize, count: elementCount)

            } as! CollectionBuffer<Element> // swiftlint:disable:this force_cast
        }
