1 /* Author: Domen Puncer <domen@cba.si>. License: WTFPL, see file LICENSE */
6 void circ_buf_init(struct circ_buf
*cb
, u8
*buf
, unsigned size
)
10 cb
->head
= cb
->tail
= 0;
13 unsigned circ_buf_len(struct circ_buf
*cb
)
16 tmp
= cb
->size
+ cb
->head
- cb
->tail
;
22 unsigned circ_buf_free(struct circ_buf
*cb
)
25 tmp
= cb
->size
+ cb
->tail
- cb
->head
- 1;
31 __inline
static void memcpy_(u8
*dest
, const u8
*src
, int len
)
37 unsigned circ_buf_put(struct circ_buf
*cb
, const u8
*data
, unsigned len
)
42 size
= circ_buf_free(cb
);
49 len_til_end
= cb
->size
- cb
->head
;
50 if (len_til_end
> len
)
53 memcpy_(cb
->data
+cb
->head
, data
, len_til_end
);
54 memcpy_(cb
->data
, data
+len_til_end
, len
-len_til_end
);
57 if (cb
->head
>= cb
->size
)
62 unsigned circ_buf_get(struct circ_buf
*cb
, u8
*data
, unsigned len
)
67 size
= circ_buf_len(cb
);
74 len_til_end
= cb
->size
- cb
->tail
;
75 if (len_til_end
> len
)
78 memcpy_(data
, cb
->data
+cb
->tail
, len_til_end
);
79 memcpy_(data
+len_til_end
, cb
->data
, len
-len_til_end
);
82 if (cb
->tail
>= cb
->size
)
88 int circ_buf_put_one(struct circ_buf
*cb
, u8 data
)
90 if (circ_buf_free(cb
) == 0)
93 cb
->data
[cb
->head
++] = data
;
94 if (cb
->head
>= cb
->size
)
99 int circ_buf_get_one(struct circ_buf
*cb
)
102 if (circ_buf_len(cb
) == 0)
105 data
= cb
->data
[cb
->tail
++];
106 if (cb
->tail
>= cb
->size
)
107 cb
->tail
-= cb
->size
;