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

0001 /*
0002     SPDX-FileCopyrightText: 2010 Joris Guisson <joris.guisson@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #ifndef BT_CIRCULARBUFFER_H
0008 #define BT_CIRCULARBUFFER_H
0009 
0010 #include <ktorrent_export.h>
0011 #include <util/constants.h>
0012 #include <utility>
0013 
0014 namespace bt
0015 {
0016 /**
0017     Circular buffer class
0018 */
0019 class KTORRENT_EXPORT CircularBuffer
0020 {
0021 public:
0022     CircularBuffer(bt::Uint32 cap = 64 * 1024);
0023     virtual ~CircularBuffer();
0024 
0025     /**
0026         Read up to max_len bytes from the buffer and store it in data
0027         @param ptr The place to store the data
0028         @param max_len Maximum amount to read
0029         @return The amount read
0030     */
0031     virtual bt::Uint32 read(bt::Uint8 *ptr, bt::Uint32 max_len);
0032 
0033     /**
0034         Write up to len bytes from data and store it in the window.
0035         @param ptr The data to copy
0036         @param max_len Amount to write
0037         @return The amount written
0038     */
0039     virtual bt::Uint32 write(const bt::Uint8 *ptr, bt::Uint32 len);
0040 
0041     /// Is the buffer empty
0042     bool empty() const
0043     {
0044         return buf_size == 0;
0045     }
0046 
0047     /// Is the buffer full
0048     bool full() const
0049     {
0050         return buf_size == buf_capacity;
0051     }
0052 
0053     /// How much of the buffer is used
0054     bt::Uint32 size() const
0055     {
0056         return buf_size;
0057     }
0058 
0059     /// How much capacity is available
0060     bt::Uint32 capacity() const
0061     {
0062         return buf_capacity;
0063     }
0064 
0065     /// Get the available space
0066     bt::Uint32 available() const
0067     {
0068         return buf_capacity - buf_size;
0069     }
0070 
0071 private:
0072     typedef std::pair<bt::Uint8 *, bt::Uint32> Range;
0073 
0074     /// Get the first range
0075     Range firstRange();
0076     Range secondRange();
0077 
0078 private:
0079     bt::Uint8 *data;
0080     bt::Uint32 buf_capacity;
0081     bt::Uint32 start;
0082     bt::Uint32 buf_size;
0083 };
0084 
0085 }
0086 
0087 #endif // BT_CIRCULARBUFFER_H