-
Notifications
You must be signed in to change notification settings - Fork 0
/
fifo.c
97 lines (76 loc) · 2.25 KB
/
fifo.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
* A simple kernel FIFO implementation.
*
* Copyright (C) 2004 Stelian Pop <stelian@popies.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fifo.h"
struct fifo *fifo_alloc(unsigned int size)
{
struct fifo *fifo;
fifo = malloc(sizeof(struct fifo));
if (!fifo)
return NULL;
fifo->buffer = malloc(size);
fifo->size = size;
fifo->in = fifo->out = 0;
return fifo;
}
void fifo_free(struct fifo *fifo)
{
free(fifo->buffer);
free(fifo);
}
unsigned int fifo_put(struct fifo *fifo, void *buffer, unsigned int len)
{
unsigned int l;
len = min(len, fifo_room(fifo));
/* first put the data starting from fifo->in to buffer end */
l = min(len, fifo->size - (fifo->in & (fifo->size - 1)));
memcpy(fifo->buffer + (fifo->in & (fifo->size - 1)), buffer, l);
/* then put the rest (if any) at the beginning of the buffer */
memcpy(fifo->buffer, buffer + l, len - l);
/*
* Ensure that we add the bytes to the fifo -before-
* we update the fifo->in index.
*/
fifo->in += len;
return len;
}
unsigned int fifo_get(struct fifo *fifo, void *buf, unsigned int len)
{
len = min(len, fifo->in - fifo->out);
if (buf) {
unsigned int l;
/*
* first get the data from fifo->out until the end of the buffer
*/
l = min(len, fifo->size - (fifo->out & (fifo->size - 1)));
memcpy(buf, fifo->buffer + (fifo->out & (fifo->size - 1)), l);
/*
* then get the rest (if any) from the beginning of the buffer
*/
memcpy(buf + l, fifo->buffer, len - l);
}
fifo->out += len;
if (fifo->in == fifo->out)
fifo->in = fifo->out = 0;
return len;
}