/*
 * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
 *
 * This software is dual-licensed to you under the MIT License (MIT) and
 * the Universal Permissive License (UPL). See the LICENSE file in the root
 * directory for license terms. You may choose either license, or both.
 */

#include <string.h>
#include "util/util_array_queue.h"
#include "messaging/msg_private.h"

void util_array_queue_init(util_array_queue *queue, size_t capacity, size_t item_size, int8_t* buffer) {
    queue->push_idx = 0;
    queue->pop_idx = 0;
    queue->capacity = capacity;
    queue->item_cnt = 0;
    queue->item_size = item_size;
    queue->buffer = buffer;
}

iotcs_result util_array_queue_push(util_array_queue* queue, util_array_queue_item_addr msg) {

    if (UTIL_ARRAY_QUEUE_IS_FULL(queue)) {
        return IOTCS_RESULT_FAIL;
    }

    memcpy(queue->buffer + (queue->push_idx) * queue->item_size, msg, queue->item_size);

    queue->item_cnt++;
    queue->push_idx++;
    if (queue->push_idx == queue->capacity) {
        queue->push_idx = 0;
    }

    return IOTCS_RESULT_OK;
}

iotcs_result util_array_queue_pop(util_array_queue* queue, util_array_queue_item_addr msg) {

    if (UTIL_ARRAY_QUEUE_IS_EMPTY(queue)) {
        return IOTCS_RESULT_FAIL;
    }

    memcpy(msg, queue->buffer + (queue->pop_idx) * queue->item_size, queue->item_size);

    queue->item_cnt--;
    queue->pop_idx++;
    if (queue->pop_idx == queue->capacity) {
        queue->pop_idx = 0;
    }

    return IOTCS_RESULT_OK;
}
