//
// Created by Ht on 2022/1/12.
//

#ifndef INC_0_LIBDEVCPP_QBUFFERMANAGER_H
#define INC_0_LIBDEVCPP_QBUFFERMANAGER_H

#include "QPObjectHolder.h"
#include "QDataMemoryPool.h"

namespace qlibc {

    //每个消息最大2048，如果超越，则单独分配
    class JE_API ByteBuffer {
    public:
        size_t buff_size_ ;
        unsigned char* buff_;
        explicit ByteBuffer(size_t sz = 2048) : buff_size_(sz), buff_(new unsigned char [sz]) {
        }

        ~ByteBuffer () {
            delete[] buff_;
        }
    };

    class JE_API BufferManager {
    protected:
        qlibc::QSharedObjectHolder<ByteBuffer>            buffers_;
        qlibc::QSharedObjectMemoryPool<ByteBuffer, 8>     buffer_pool_;

    public:
        explicit BufferManager() :
                buffer_pool_([]()->ByteBuffer* { return new ByteBuffer;}) {
        }

        std::shared_ptr<ByteBuffer> getBlankBuffer() {
            return buffer_pool_.getBlankObject();
        }

        void releaseBuffer(std::shared_ptr<ByteBuffer>& buffer) {
            buffer_pool_.releaseObject(buffer);
        }

        void pushBufferWithId(const std::string& id, std::shared_ptr<ByteBuffer>& buffer) {
            buffers_.appendNewRefCopy(id, buffer);
        }

        std::shared_ptr<ByteBuffer> getBufferWithId(const std::string& id) {
            return buffers_.removeObject(id);
        }

    };
}
#endif //INC_0_LIBDEVCPP_QBUFFERMANAGER_H
