/*
 * SPDX-FileCopyrightText: 2025 Copyright contributors to the cppTango project
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */
#ifndef TANGO_INTERNAL_EVENT_PERF_MONITOR_RINGBUFFER_H
#define TANGO_INTERNAL_EVENT_PERF_MONITOR_RINGBUFFER_H

#include <cstddef>
#include <ostream>

namespace Tango
{
template <typename T>
struct RingBuffer
{
    static constexpr const size_t size = 256;
    T buffer[size];
    size_t index = 0;
    bool first_pass = true;

    void reset()
    {
        index = 0;
        first_pass = true;
    }

    void push(const T &v)
    {
        buffer[index] = v;
        index = (index + 1) % size;
        if(index == 0)
        {
            first_pass = false;
        }
    }

    void json_dump(std::ostream &os)
    {
        os << "[";
        bool first = true;
        auto print_elem = [&first, &os, this](size_t i)
        {
            if(!first)
            {
                os << ",";
            }

            buffer[i].json_dump(os);

            first = false;
        };

        if(!first_pass)
        {
            for(size_t i = index; i < size; ++i)
            {
                print_elem(i);
            }
        }

        for(size_t i = 0; i < index; ++i)
        {
            print_elem(i);
        }
        os << "]";
    }
};
} // namespace Tango

#endif // TANGO_INTERNAL_EVENT_PERF_MONITOR_RINGBUFFER_H
