PageRenderTime 22ms CodeModel.GetById 15ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/simplebuffer.c

https://bitbucket.org/a84/gs_public/
C | 86 lines | 67 code | 19 blank | 0 comment | 2 complexity | 1b525a1280ee0eb732886b470424c641 MD5 | raw file
 1#include <stdint.h>
 2#include <stdlib.h>
 3#include <string.h>
 4#include <stdio.h>
 5#include <sys/param.h>
 6
 7struct simplebuffer_s {
 8	uint8_t		*buffer;
 9	int		atomsize;
10	int		atoms;
11	int		fill;
12	int		headroom;
13};
14
15void *sb_init(int atoms, int atomsize, int headroom) {
16	struct simplebuffer_s	*sb;
17
18	sb = (struct simplebuffer_s *)calloc(1, sizeof(struct simplebuffer_s));
19	if (!sb)
20		return NULL;
21
22
23	sb->buffer = (uint8_t *)malloc(atoms*atomsize+headroom);
24	if (!sb->buffer) {
25		free(sb);
26		return NULL;
27	}
28
29	sb->atoms=atoms;
30	sb->atomsize=atomsize;
31	sb->headroom=headroom;
32
33	return sb;
34}
35
36void sb_free(void *sbv) {
37	struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
38	free(sb->buffer);
39	free(sb);
40}
41
42int sb_used_atoms(void *sbv) {
43	struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
44	return sb->fill;
45}
46
47int sb_free_atoms(void *sbv) {
48	struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
49	return (sb->atoms-sb->fill);
50}
51
52int sb_add_atoms(void *sbv, uint8_t *atom, int atoms) {
53	struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
54	int	copy;
55
56	copy=MIN(atoms, sb_free_atoms(sbv));
57	memcpy(&sb->buffer[sb->fill*sb->atomsize+sb->headroom], atom, copy*sb->atomsize);
58	sb->fill+=copy;
59
60	return copy;
61}
62
63uint8_t *sb_bufptr(void *sbv) {
64	struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
65	return sb->buffer;
66}
67
68int sb_buflen(void *sbv) {
69	struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
70	return sb->fill*sb->atomsize+sb->headroom;
71}
72
73void sb_zap(void *sbv) {
74	struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
75	sb->fill=0;
76}
77
78void sb_drop_atoms(void *sbv, int atoms) {
79	struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
80
81	memmove(sb->buffer+sb->headroom,
82		sb->buffer+sb->headroom+atoms*sb->atomsize,
83		(sb->fill-atoms)*sb->atomsize);
84
85	sb->fill-=atoms;
86}