/* ringallocator.h
****************************************************************************************************************
****************************************************************************************************************

    Copyright (C) 2020, 2021 Askar Almatov

    This file is part of Trafficmeter.

    Trafficmeter is free software: you can redistribute it and/or modify it under the terms of the GNU General
    Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
    option) any later version.

    Trafficmeter is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
    License for more details.

    You should have received a copy of the GNU General Public License along with Trafficmeter. If not, see
    <http://www.gnu.org/licenses/>.
*/

#ifndef __RINGALLOCATOR_H
#define __RINGALLOCATOR_H 1

#include <atomic>

namespace trafficmeter
{
    /**********************************************************************************************************/
    class RingAllocator
    {
    public:
                                        RingAllocator( int nChunks );
                                        ~RingAllocator();

        static void*                    allocate( RingAllocator* ring, unsigned size );
        static void                     deallocate( void* area );

    protected:
        struct Chunk_;

        Chunk_*                         getChunk_( unsigned );

        Chunk_*                         firstChunk_;
        Chunk_*                         lastChunk_;
        Chunk_*                         cursor_;
        std::atomic<int>                nFreeChunks_a_;
    };

    /**********************************************************************************************************/
    struct RingAllocator::Chunk_
    {
        Chunk_*                         next_;
        RingAllocator*                  ring_;
        int                             offset_;
        std::atomic<unsigned>           nObjects_a_;

                                        Chunk_( RingAllocator* );
    };
}

#endif  // __RINGALLOCATOR_H
