8beef688aa488e1c4ca1f50b04679b49744a11ed
[gnulib.git] / lib / i-ring.c
1 /* a simple ring buffer
2    Copyright (C) 2006, 2009-2011 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program 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 General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://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 /* The attribute __pure__ was added in gcc 2.96.  */
25 #undef _GL_ATTRIBUTE_PURE
26 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
27 # define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
28 #else
29 # define _GL_ATTRIBUTE_PURE /* empty */
30 #endif
31
32 void
33 i_ring_init (I_ring *ir, int default_val)
34 {
35   int i;
36   ir->ir_empty = true;
37   ir->ir_front = 0;
38   ir->ir_back = 0;
39   for (i = 0; i < I_RING_SIZE; i++)
40     ir->ir_data[i] = default_val;
41   ir->ir_default_val = default_val;
42 }
43
44 bool _GL_ATTRIBUTE_PURE
45 i_ring_empty (I_ring const *ir)
46 {
47   return ir->ir_empty;
48 }
49
50 int
51 i_ring_push (I_ring *ir, int val)
52 {
53   unsigned int dest_idx = (ir->ir_front + !ir->ir_empty) % I_RING_SIZE;
54   int old_val = ir->ir_data[dest_idx];
55   ir->ir_data[dest_idx] = val;
56   ir->ir_front = dest_idx;
57   if (dest_idx == ir->ir_back)
58     ir->ir_back = (ir->ir_back + !ir->ir_empty) % I_RING_SIZE;
59   ir->ir_empty = false;
60   return old_val;
61 }
62
63 int
64 i_ring_pop (I_ring *ir)
65 {
66   int top_val;
67   if (i_ring_empty (ir))
68     abort ();
69   top_val = ir->ir_data[ir->ir_front];
70   ir->ir_data[ir->ir_front] = ir->ir_default_val;
71   if (ir->ir_front == ir->ir_back)
72     ir->ir_empty = true;
73   else
74     ir->ir_front = ((ir->ir_front + I_RING_SIZE - 1) % I_RING_SIZE);
75   return top_val;
76 }