; ***************************************************************************
; copyright   : (C) 2025 by Martin Preuss
; email       : martin@libchipcard.de
;
; ***************************************************************************
; * This file is part of the project "AqHome".                              *
; * Please see toplevel file COPYING of that project for license details.   *
; ***************************************************************************



; ---------------------------------------------------------------------------
; @macro m_ringbuffer_writebyte
;
; @param R16 byte to write
; @param %0 constant maxBytes
; @param %1 address of usedBytes variable
; @param %2 address of readPos variable
; @param %3 address of writePos variable
; @param %4 address of buffer
; @return CFLAG set if okay, cleared on error (i.e. buffer full)
; @clobbers R17, X

.macro m_ringbuffer_writebyte
  ld r17, @1       ; usedBytes
  cpi r17, @0      ; maxBytes
  brcc l_end
  inc r17
  st @1, r17       ; usedBytes
  ld r17, @3       ; writePos
  ldi xl, LOW(@4)  ; buffer start
  ldi xh, HIGH(@4)
  add xl, r17
  adc xh, r17
  sub xh, r17
  st X, r16
  inc r17
  cpi r17, @0      ; maxBytes
  brcs l_store
  clr r17
l_store:
  st @3, r17    ; writePos
  sec
l_end:
.endmacro
; @end



; ---------------------------------------------------------------------------
; @macro m_ringbuffer_readbyte
;
; @param %0 constant maxBytes
; @param %1 address of usedBytes variable
; @param %2 address of readPos variable
; @param %3 address of writePos variable
; @param %4 address of buffer
; @return CFLAG set if okay, cleared on error (i.e. buffer full)
; @return R16 byte read
; @clobbers R17, X

.macro m_ringbuffer_readbyte
  ld r17, @1       ; usedBytes
  tst r17
  clc
  breq l_end
  dec r17
  st @1, r17       ; usedBytes
  ld r17, @2       ; readPos
  ldi xl, LOW(@4)  ; buffer start
  ldi xh, HIGH(@4)
  add xl, r17
  adc xh, r17
  sub xh, r17
  ld r16, X
  inc r17
  cpi r17, @0
  brcs l_store
  clr r17
l_store:
  st @2, r17       ; readPos
  sec
l_end:
.endmacro



; ---------------------------------------------------------------------------
; @macro m_ringbuffer_reset
;
; @param %0 constant maxBytes
; @param %1 address of usedBytes variable
; @param %2 address of readPos variable
; @param %3 address of writePos variable
; @param %4 address of buffer
; @clobbers R17

.macro m_ringbuffer_reset
  clr r17
  st @1, r17 ; usedBytes
  st @2, r17 ; readPos
  st @3, r17 ; writePos
l_end:
.endmacro
; @end




