/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. struct simplebuffer_s {
  7. uint8_t *buffer;
  8. int atomsize;
  9. int atoms;
  10. int fill;
  11. int headroom;
  12. };
  13. void *sb_init(int atoms, int atomsize, int headroom) {
  14. struct simplebuffer_s *sb;
  15. sb = (struct simplebuffer_s *)calloc(1, sizeof(struct simplebuffer_s));
  16. if (!sb)
  17. return NULL;
  18. sb->buffer = (uint8_t *)malloc(atoms*atomsize+headroom);
  19. if (!sb->buffer) {
  20. free(sb);
  21. return NULL;
  22. }
  23. sb->atoms=atoms;
  24. sb->atomsize=atomsize;
  25. sb->headroom=headroom;
  26. return sb;
  27. }
  28. void sb_free(void *sbv) {
  29. struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
  30. free(sb->buffer);
  31. free(sb);
  32. }
  33. int sb_used_atoms(void *sbv) {
  34. struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
  35. return sb->fill;
  36. }
  37. int sb_free_atoms(void *sbv) {
  38. struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
  39. return (sb->atoms-sb->fill);
  40. }
  41. int sb_add_atoms(void *sbv, uint8_t *atom, int atoms) {
  42. struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
  43. int copy;
  44. copy=MIN(atoms, sb_free_atoms(sbv));
  45. memcpy(&sb->buffer[sb->fill*sb->atomsize+sb->headroom], atom, copy*sb->atomsize);
  46. sb->fill+=copy;
  47. return copy;
  48. }
  49. uint8_t *sb_bufptr(void *sbv) {
  50. struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
  51. return sb->buffer;
  52. }
  53. int sb_buflen(void *sbv) {
  54. struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
  55. return sb->fill*sb->atomsize+sb->headroom;
  56. }
  57. void sb_zap(void *sbv) {
  58. struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
  59. sb->fill=0;
  60. }
  61. void sb_drop_atoms(void *sbv, int atoms) {
  62. struct simplebuffer_s *sb = (struct simplebuffer_s *)sbv;
  63. memmove(sb->buffer+sb->headroom,
  64. sb->buffer+sb->headroom+atoms*sb->atomsize,
  65. (sb->fill-atoms)*sb->atomsize);
  66. sb->fill-=atoms;
  67. }