// SPDX-License-Identifier: MPL-2.0
#include "memory/ring.h"
SH_STATUS sh_ring_write_byte(sh_ring_RING_BUFFER_HEADER *ring_buffer,sh_uint8 byte) {
  if (ring_buffer==SH_NULLPTR) return SH_STATUS_INVALID_PARAMETER;
  if (ring_buffer->buffer_bytes_size==0 || ring_buffer->data_start==SH_NULLPTR) return SH_STATUS_SUCCESS;
  sh_uint32 next_head=(ring_buffer->head+1)%ring_buffer->buffer_bytes_size;
  if (next_head==ring_buffer->tail) {
    ring_buffer->tail=(ring_buffer->tail+1)%ring_buffer->buffer_bytes_size;
  }
  ring_buffer->data_start[ring_buffer->head]=byte;
  ring_buffer->head=next_head;
  ring_buffer->total_bytes_written++;
  return SH_STATUS_SUCCESS;
}
SH_STATUS sh_ring_write_string(sh_ring_RING_BUFFER_HEADER *ring_buffer,char *string) {
  if (ring_buffer==SH_NULLPTR || string==SH_NULLPTR) return SH_STATUS_INVALID_PARAMETER;
  if (ring_buffer->buffer_bytes_size==0 || ring_buffer->data_start==SH_NULLPTR) return SH_STATUS_SUCCESS;
  for (sh_uint32 i=0;string[i]!='\0';i++) {
    sh_uint32 next_head=(ring_buffer->head+1)%ring_buffer->buffer_bytes_size;
    if (next_head==ring_buffer->tail) {
      ring_buffer->tail=(ring_buffer->tail+1)%ring_buffer->buffer_bytes_size;
    }
    ring_buffer->data_start[ring_buffer->head]=(sh_uint8)string[i];
    ring_buffer->head=next_head;
    ring_buffer->total_bytes_written++;
  }
  return SH_STATUS_SUCCESS;
}
SH_STATUS sh_ring_read_bytes(sh_ring_RING_BUFFER_HEADER *ring_buffer,sh_uint32 bytes_count,void *output) {
  if (ring_buffer==SH_NULLPTR || output==SH_NULLPTR) return SH_STATUS_INVALID_PARAMETER;
  if (ring_buffer->buffer_bytes_size==0 || ring_buffer->data_start==SH_NULLPTR) return SH_STATUS_INVALID_PARAMETER;
  sh_uint32 size=ring_buffer->buffer_bytes_size;
  if (bytes_count>size) return SH_STATUS_TOO_MUCH_DATA;
  sh_uint32 head=ring_buffer->head;
  sh_uint32 start=(head+size-bytes_count)%size;
  for (sh_uint32 i=0;i<bytes_count;i++) {
    sh_uint32 idx=(start+i)%size;
    ((sh_uint8*)output)[i]=ring_buffer->data_start[idx];
  }
  return SH_STATUS_SUCCESS;
}
