summaryrefslogtreecommitdiff
path: root/src/common/Utilities/CircularBuffer.h
blob: 4c23099c9e314017292b94eb5fbf67817b8ff950 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
 * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE
 *
 * This file was based on
 * https://embeddedartistry.com/blog/2017/05/17/creating-a-circular-buffer-in-c-and-c/
 * https://github.com/embeddedartistry/embedded-resources/blob/master/examples/cpp/circular_buffer.cpp
 */

#ifndef AZEROTHCORE_CIRCULAR_BUFFER_H
#define AZEROTHCORE_CIRCULAR_BUFFER_H

#include <memory>
#include <mutex>
#include <vector>

template <typename T>
class CircularBuffer
{
public:
    explicit CircularBuffer(std::size_t size) :
        buf_(std::unique_ptr<T[]>(new T[size])),
        max_size_(size)
    {

    }

    void put(T item)
    {
        std::lock_guard<std::mutex> lock(mutex_);

        buf_[head_] = item;

        if (full_)
        {
            tail_ = (tail_ + 1) % max_size_;
        }

        head_ = (head_ + 1) % max_size_;

        full_ = head_ == tail_;
    }

    [[nodiscard]] bool empty() const
    {
        //if head and tail are equal, we are empty
        return (!full_ && (head_ == tail_));
    }

    [[nodiscard]] bool full() const
    {
        //If tail is ahead the head by 1, we are full
        return full_;
    }

    [[nodiscard]] std::size_t capacity() const
    {
        return max_size_;
    }

    [[nodiscard]] std::size_t size() const
    {
        std::size_t size = max_size_;

        if (!full_)
        {
            if (head_ >= tail_)
            {
                size = head_ - tail_;
            }
            else
            {
                size += head_ - tail_;
            }
        }

        return size;
    }

    // the implementation of this function is simplified by the fact that head_ will never be lower than tail_
    // when compared to the original implementation of this class
    std::vector<T> content()
    {
        std::lock_guard<std::mutex> lock(mutex_);

        return std::vector<T>(buf_.get(), buf_.get() + size());
    }

    T peak_back()
    {
        std::lock_guard<std::mutex> lock(mutex_);

        return empty() ? T() : buf_[tail_];
    }

private:
    std::mutex mutex_;
    std::unique_ptr<T[]> buf_;
    std::size_t head_ = 0;
    std::size_t tail_ = 0;
    const std::size_t max_size_;
    bool full_ = false;
};
#endif