2 * Copyright (C) 2007 Benjamin Otte <otte@gnome.org>
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library 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 GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301 USA
25 #include "swfdec_ringbuffer.h"
28 swfdec_ring_buffer_new (guint element_size
, guint size
)
30 SwfdecRingBuffer
*buffer
;
32 g_return_val_if_fail (element_size
> 0, NULL
);
33 g_return_val_if_fail (size
> 1, NULL
);
35 buffer
= g_new0 (SwfdecRingBuffer
, 1);
36 buffer
->element_size
= element_size
;
38 buffer
->data
= g_malloc (element_size
* size
);
44 swfdec_ring_buffer_free (SwfdecRingBuffer
*buffer
)
46 g_return_if_fail (buffer
!= NULL
);
48 g_free (buffer
->data
);
53 swfdec_ring_buffer_get_size (SwfdecRingBuffer
*buffer
)
55 g_return_val_if_fail (buffer
!= NULL
, 0);
60 #define GET_ELEMENT(buffer,idx) (buffer->data + buffer->element_size * (idx))
62 swfdec_ring_buffer_set_size (SwfdecRingBuffer
*buffer
, guint new_size
)
64 g_return_if_fail (buffer
!= NULL
);
65 g_return_if_fail (buffer
->size
< new_size
);
67 buffer
->data
= g_realloc (buffer
->data
, buffer
->element_size
* new_size
);
68 if (buffer
->tail
<= buffer
->head
&& buffer
->n_elements
) {
69 memmove (GET_ELEMENT (buffer
, buffer
->head
+ new_size
- buffer
->size
),
70 GET_ELEMENT (buffer
, buffer
->head
),
71 buffer
->element_size
* (buffer
->size
- buffer
->head
));
72 buffer
->head
+= new_size
- buffer
->size
;
74 buffer
->size
= new_size
;
78 swfdec_ring_buffer_get_n_elements (SwfdecRingBuffer
*buffer
)
80 g_return_val_if_fail (buffer
!= NULL
, 0);
82 return buffer
->n_elements
;
86 swfdec_ring_buffer_push (SwfdecRingBuffer
*buffer
)
90 g_return_val_if_fail (buffer
!= NULL
, NULL
);
92 if (buffer
->n_elements
== buffer
->size
)
95 ret
= GET_ELEMENT (buffer
, buffer
->tail
);
96 buffer
->tail
= (buffer
->tail
+ 1) % buffer
->size
;
102 swfdec_ring_buffer_pop (SwfdecRingBuffer
*buffer
)
106 g_return_val_if_fail (buffer
!= NULL
, NULL
);
108 if (buffer
->n_elements
== 0)
111 ret
= GET_ELEMENT (buffer
, buffer
->head
);
112 buffer
->head
= (buffer
->head
+ 1) % buffer
->size
;
113 buffer
->n_elements
--;
118 swfdec_ring_buffer_peek_nth (SwfdecRingBuffer
*buffer
, guint id
)
120 g_return_val_if_fail (buffer
!= NULL
, NULL
);
121 g_return_val_if_fail (id
< buffer
->n_elements
, NULL
);
123 id
= (buffer
->head
+ id
) % buffer
->size
;
124 return GET_ELEMENT (buffer
, id
);