| 1 |
/* a simple ring buffer |
| 2 |
Copyright (C) 2006, 2009-2026 Free Software Foundation, Inc. |
| 3 |
|
| 4 |
This file is free software: you can redistribute it and/or modify |
| 5 |
it under the terms of the GNU Lesser General Public License as |
| 6 |
published by the Free Software Foundation, either version 3 of the |
| 7 |
License, or (at your option) any later version. |
| 8 |
|
| 9 |
This file is distributed in the hope that it will be useful, |
| 10 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
GNU Lesser General Public License for more details. |
| 13 |
|
| 14 |
You should have received a copy of the GNU Lesser General Public License |
| 15 |
along with this program. If not, see <https://www.gnu.org/licenses/>. */ |
| 16 |
|
| 17 |
/* written by Jim Meyering */ |
| 18 |
|
| 19 |
#include <config.h> |
| 20 |
#include "i-ring.h" |
| 21 |
|
| 22 |
#include <stdlib.h> |
| 23 |
|
| 24 |
void |
| 25 |
i_ring_init (I_ring *ir, int default_val) |
| 26 |
{ |
| 27 |
ir->ir_empty = true; |
| 28 |
ir->ir_front = 0; |
| 29 |
ir->ir_back = 0; |
| 30 |
for (int i = 0; i < I_RING_SIZE; i++) |
| 31 |
ir->ir_data[i] = default_val; |
| 32 |
ir->ir_default_val = default_val; |
| 33 |
} |
| 34 |
|
| 35 |
bool |
| 36 |
i_ring_empty (I_ring const *ir) |
| 37 |
{ |
| 38 |
return ir->ir_empty; |
| 39 |
} |
| 40 |
|
| 41 |
int |
| 42 |
i_ring_push (I_ring *ir, int val) |
| 43 |
{ |
| 44 |
unsigned int dest_idx = (ir->ir_front + !ir->ir_empty) % I_RING_SIZE; |
| 45 |
int old_val = ir->ir_data[dest_idx]; |
| 46 |
ir->ir_data[dest_idx] = val; |
| 47 |
ir->ir_front = dest_idx; |
| 48 |
if (dest_idx == ir->ir_back) |
| 49 |
ir->ir_back = (ir->ir_back + !ir->ir_empty) % I_RING_SIZE; |
| 50 |
ir->ir_empty = false; |
| 51 |
return old_val; |
| 52 |
} |
| 53 |
|
| 54 |
int |
| 55 |
i_ring_pop (I_ring *ir) |
| 56 |
{ |
| 57 |
if (i_ring_empty (ir)) |
| 58 |
abort (); |
| 59 |
int top_val = ir->ir_data[ir->ir_front]; |
| 60 |
ir->ir_data[ir->ir_front] = ir->ir_default_val; |
| 61 |
if (ir->ir_front == ir->ir_back) |
| 62 |
ir->ir_empty = true; |
| 63 |
else |
| 64 |
ir->ir_front = ((ir->ir_front + I_RING_SIZE - 1) % I_RING_SIZE); |
| 65 |
return top_val; |
| 66 |
} |