File indexing completed on 2025-01-05 04:37:29

0001 /*
0002     SPDX-FileCopyrightText: 2011 Joris Guisson <joris.guisson@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #ifndef BUFFERPOOL_H_
0008 #define BUFFERPOOL_H_
0009 
0010 #include <QMutex>
0011 #include <QSharedPointer>
0012 #include <QWeakPointer>
0013 #include <boost/shared_array.hpp>
0014 #include <ktorrent_export.h>
0015 #include <list>
0016 #include <map>
0017 #include <util/constants.h>
0018 
0019 namespace bt
0020 {
0021 class BufferPool;
0022 
0023 /**
0024  * Buffer object, extends boost shared_array with a size and capacity property.
0025  **/
0026 class KTORRENT_EXPORT Buffer
0027 {
0028 public:
0029     typedef QSharedPointer<Buffer> Ptr;
0030     typedef boost::shared_array<bt::Uint8> Data;
0031 
0032     Buffer(Data data, bt::Uint32 fill, bt::Uint32 cap, QWeakPointer<BufferPool> pool);
0033     virtual ~Buffer();
0034 
0035     /// Get the buffers capacity
0036     bt::Uint32 capacity() const
0037     {
0038         return cap;
0039     }
0040 
0041     /// Get the current size
0042     bt::Uint32 size() const
0043     {
0044         return fill;
0045     }
0046 
0047     /// Set the current size
0048     void setSize(bt::Uint32 s)
0049     {
0050         fill = s;
0051     }
0052 
0053     /// Get a pointer to the data
0054     bt::Uint8 *get()
0055     {
0056         return data.get();
0057     }
0058 
0059 private:
0060     Data data;
0061     bt::Uint32 fill;
0062     bt::Uint32 cap;
0063     QWeakPointer<BufferPool> pool;
0064 };
0065 
0066 /**
0067  * Keeps track of a pool of buffers.
0068  **/
0069 class KTORRENT_EXPORT BufferPool
0070 {
0071 public:
0072     BufferPool();
0073     virtual ~BufferPool();
0074 
0075     /**
0076      * Set the weak pointer to the buffer pool itself.
0077      * @param wp The weak pointer
0078      * */
0079     void setWeakPointer(QWeakPointer<BufferPool> wp)
0080     {
0081         self = wp;
0082     }
0083 
0084     /**
0085      * Get a buffer for a given size.
0086      * The buffer returned might be bigger then the requested size.
0087      * @param min_size The minimum size it should be
0088      * @return A new Buffer
0089      **/
0090     Buffer::Ptr get(bt::Uint32 min_size);
0091 
0092     /**
0093      * Release a buffer, puts it into the free list.
0094      * @param data The Buffer::Data
0095      * @param size The size of the data object
0096      **/
0097     void release(Buffer::Data data, bt::Uint32 size);
0098 
0099     /**
0100      * Clear the pool.
0101      **/
0102     void clear();
0103 
0104     typedef QSharedPointer<BufferPool> Ptr;
0105 
0106 private:
0107     typedef std::map<bt::Uint32, std::list<Buffer::Data>> FreeBufferMap;
0108     QMutex mutex;
0109     FreeBufferMap free_buffers;
0110     QWeakPointer<BufferPool> self;
0111 };
0112 } /* namespace bt */
0113 
0114 #endif /* BUFFERPOOL_H_ */