Untitled

 avatar
user_5152005
plain_text
5 months ago
2.6 kB
1
Indexable
/* @@@LICENSE
 *
 * (c) Copyright 2023-2024 LG Electronics, Inc.
 *
 * Confidential computer software. Valid license from LG required for
 * possession, use or copying. Consistent with FAR 12.211 and 12.212,
 * Commercial Computer Software, Computer Software Documentation, and
 * Technical Data for Commercial Items are licensed to the U.S. Government
 * under vendor's standard commercial license.
 *
 * LICENSE@@@
 */

 /**
 * @file ring_buffer.cpp
 *
 * @brief this file contains the implementation of the ring buffer  .
 */
 
#include<bits/stdc++.h>
#include "ring_buffer.h"

/**
 * @brief init the ring buffer with the capacity by parameter 
 *
 * @param the total capacity we want to init
 */

CircularBuffer::CircularBuffer(int capacity)   
{
	if (capacity ==0) {
            throw out_of_range("capacity =0 is not valid");
        }
    this->capacity = capacity;
        this->head = 0;
        this->tail = 0;
        buffer.resize(capacity);
}

/**
 * @brief pushing the element to the index in the vector with value of 'head' point to
 *
 * @param the value of the element we want to push
 *
 * @return void
 */
void CircularBuffer::push_back(int element)
    {
        buffer[head] = element;
        head = (head + 1) % capacity; 
        if (head == tail) {
            tail = (tail + 1) % capacity;
        }
    }

/**
 * @brief  pop the element to the index in the vector with value of 'tail' point to
 *
 * @return void
 */	
void CircularBuffer::pop_front()
    {
        if (empty()) {
            throw out_of_range("Buffer is empty");
        }
		// if buffer is empty we will throw to console  ("Buffer is empty");
		
        tail = (tail + 1) % capacity;
    }

/**
 * @brief  Checking is the bufffer is empty or not
 *
 * @return bool
 */	
bool CircularBuffer::empty() const	
    { return head == tail; }
	
/**
 * @brief  Checking is the bufffer is full or not
 *
 * @return bool
 */	
bool CircularBuffer::full() const
    {
        return (head + 1) % capacity == tail;
    }

/**
 * @brief  counting the size of the buffer
 *
 * @return size of the buffer
 */
int CircularBuffer::size() const
    {
        if (head >= tail) {
            return head - tail;
        }
        return capacity - (tail - head);
    }

/**
 * @brief  printout the buffer
 *
 * @return void
 */	
void CircularBuffer::printBuffer() const
    {
        int idx = tail;
        while (idx != head) {
            cout << buffer[idx] << " ";
            idx = (idx + 1) % capacity;
        }
        cout << endl;
    }	
	
Editor is loading...
Leave a Comment