Tizen 2.0 Release
[external/tizen-coreutils.git] / lib / i-ring.c
1 /* a simple ring buffer
2    Copyright (C) 2006 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 2, or (at your option)
7    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, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* written by Jim Meyering */
19
20 #include <config.h>
21 #include "i-ring.h"
22
23 #include <stdlib.h>
24
25 void
26 i_ring_init (I_ring *ir, int default_val)
27 {
28   int i;
29   ir->ir_empty = true;
30   ir->ir_front = 0;
31   ir->ir_back = 0;
32   for (i = 0; i < I_RING_SIZE; i++)
33     ir->ir_data[i] = default_val;
34   ir->ir_default_val = default_val;
35 }
36
37 bool
38 i_ring_empty (I_ring const *ir)
39 {
40   return ir->ir_empty;
41 }
42
43 int
44 i_ring_push (I_ring *ir, int val)
45 {
46   unsigned int dest_idx = (ir->ir_front + !ir->ir_empty) % I_RING_SIZE;
47   int old_val = ir->ir_data[dest_idx];
48   ir->ir_data[dest_idx] = val;
49   ir->ir_front = dest_idx;
50   if (dest_idx == ir->ir_back)
51     ir->ir_back = (ir->ir_back + !ir->ir_empty) % I_RING_SIZE;
52   ir->ir_empty = false;
53   return old_val;
54 }
55
56 int
57 i_ring_pop (I_ring *ir)
58 {
59   int top_val;
60   if (i_ring_empty (ir))
61     abort ();
62   top_val = ir->ir_data[ir->ir_front];
63   ir->ir_data[ir->ir_front] = ir->ir_default_val;
64   if (ir->ir_front == ir->ir_back)
65     ir->ir_empty = true;
66   else
67     ir->ir_front = ((ir->ir_front + I_RING_SIZE - 1) % I_RING_SIZE);
68   return top_val;
69 }