/* substrate.cc
****************************************************************************************************************
****************************************************************************************************************

    Copyright (C) 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/>.
*/

#include <cassert>
#include <cstring>
#include <new>

#include "substrate.h"
#include "ringallocator.h"

using namespace trafficmeter;

/**************************************************************************************************************/
Substrate::Substrate() :
    refCount_a_( 0 )
{
    record_ = recordsEnd_ = reinterpret_cast<uint8_t*>( this + 1 );
}

/**************************************************************************************************************/
bool
Substrate::emplaceRecords( Source* source )
{
    return source->copyRecords( &recordsEnd_, reinterpret_cast<uint8_t*>(this + 1) + SUBSTRATE_SIZE );
}

/**************************************************************************************************************/
Packet::Body*
Substrate::getPacket( Source* source )
{
    if ( record_ >= recordsEnd_ )
    {
        return nullptr;
    }

    uint8_t*        nextRecord = record_;
    Source::Packet  sourcePacket = source->getPacketFromCopy( &nextRecord );
    Packet::Body*   packetBody = reinterpret_cast<Packet::Body*>( record_ );

    packetBody->timestamp = sourcePacket.timestamp;
    packetBody->offsetSubstrate = reinterpret_cast<uint8_t*>( this ) - record_;
    packetBody->offsetLayer2 = sourcePacket.data2 - record_;
    packetBody->nBytes2 = sourcePacket.nBytes2;
    record_ = nextRecord;
    return packetBody;
}

/**************************************************************************************************************/
void
Substrate::refIncrement()
{
    ++refCount_a_;
}

/**************************************************************************************************************/
void
Substrate::refDecrement()
{
    if ( --refCount_a_ == 0 && record_ >= recordsEnd_ )
    {
        RingAllocator::deallocate( this );
    }
}

/**************************************************************************************************************/
bool
Substrate::isEmpty() const
{
    return record_ >= recordsEnd_;
}
