]> git.vomp.tv Git - vompserver.git/blob - ringbuffer.c
15 years that line of code has been waiting to crash
[vompserver.git] / ringbuffer.c
1 /*
2     Copyright 2004-2005 Chris Tallon
3
4     This file is part of VOMP.
5
6     VOMP is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     VOMP is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with VOMP; if not, write to the Free Software
18     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19 */
20
21 #include "ringbuffer.h"
22
23 Ringbuffer::Ringbuffer()
24 {
25   capacity = 0;
26   content = 0;
27   buffer = NULL;
28   start = NULL;
29   end = NULL;
30 }
31
32 Ringbuffer::~Ringbuffer()
33 {
34   if (buffer) free(buffer);
35   buffer = NULL;
36   capacity = 0;
37   content = 0;
38   start = NULL;
39   end = NULL;
40 }
41
42 int Ringbuffer::init(size_t size)
43 {
44   capacity = size;
45   buffer = (UCHAR*)malloc(capacity);
46   if (!buffer) return 0;
47   start = buffer;
48   end = buffer;
49   return 1;
50 }
51
52 int Ringbuffer::put(const UCHAR* from, size_t amount)
53 {
54   if (amount > capacity) return 0;
55
56   if ((end + amount) <= (buffer + capacity))
57   {
58     memcpy(end, from, amount);
59     end += amount;
60     content += amount;
61
62     if (end == (buffer + capacity)) end = buffer;
63     if (content >= capacity)
64     {
65       start = end;
66       content = capacity;
67     }
68     return 1;
69   }
70   else
71   {
72     size_t firstAmount = buffer + capacity - end;
73     return (put(from, firstAmount) && put(from + firstAmount, amount - firstAmount));
74   }
75 }
76
77 int Ringbuffer::get(UCHAR* to, size_t amount)
78 {
79   if (amount > content) return get(to, content);
80
81   if ((start + amount) <= (buffer + capacity))
82   {
83     memcpy(to, start, amount);
84     start += amount;
85     content -= amount;
86
87     if (start == (buffer + capacity)) start = buffer;
88     return amount;
89   }
90   else
91   {
92     size_t firstAmount = buffer + capacity - start;
93     return (get(to, firstAmount) + get(to + firstAmount, amount - firstAmount));
94   }
95 }
96
97 int Ringbuffer::getContent()
98 {
99   return content;
100 }