You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.0 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. /* -*- coding: utf-8 -*-
  2. * ----------------------------------------------------------------------
  3. * Copyright © 2011-2014, RedJack, LLC.
  4. * All rights reserved.
  5. *
  6. * Please see the COPYING file in this distribution for license details.
  7. * ----------------------------------------------------------------------
  8. */
  9. #include <stdlib.h>
  10. #include "libcork/core/allocator.h"
  11. #include "libcork/core/types.h"
  12. #include "libcork/ds/ring-buffer.h"
  13. int
  14. cork_ring_buffer_init(struct cork_ring_buffer *self, size_t size)
  15. {
  16. self->elements = cork_calloc(size, sizeof(void *));
  17. self->allocated_size = size;
  18. self->size = 0;
  19. self->read_index = 0;
  20. self->write_index = 0;
  21. return 0;
  22. }
  23. struct cork_ring_buffer *
  24. cork_ring_buffer_new(size_t size)
  25. {
  26. struct cork_ring_buffer *buf = cork_new(struct cork_ring_buffer);
  27. cork_ring_buffer_init(buf, size);
  28. return buf;
  29. }
  30. void
  31. cork_ring_buffer_done(struct cork_ring_buffer *self)
  32. {
  33. cork_cfree(self->elements, self->allocated_size, sizeof(void *));
  34. }
  35. void
  36. cork_ring_buffer_free(struct cork_ring_buffer *buf)
  37. {
  38. cork_ring_buffer_done(buf);
  39. cork_delete(struct cork_ring_buffer, buf);
  40. }
  41. int
  42. cork_ring_buffer_add(struct cork_ring_buffer *self, void *element)
  43. {
  44. if (cork_ring_buffer_is_full(self)) {
  45. return -1;
  46. }
  47. self->elements[self->write_index++] = element;
  48. self->size++;
  49. if (self->write_index == self->allocated_size) {
  50. self->write_index = 0;
  51. }
  52. return 0;
  53. }
  54. void *
  55. cork_ring_buffer_pop(struct cork_ring_buffer *self)
  56. {
  57. if (cork_ring_buffer_is_empty(self)) {
  58. return NULL;
  59. } else {
  60. void *result = self->elements[self->read_index++];
  61. self->size--;
  62. if (self->read_index == self->allocated_size) {
  63. self->read_index = 0;
  64. }
  65. return result;
  66. }
  67. }
  68. void *
  69. cork_ring_buffer_peek(struct cork_ring_buffer *self)
  70. {
  71. if (cork_ring_buffer_is_empty(self)) {
  72. return NULL;
  73. } else {
  74. return self->elements[self->read_index];
  75. }
  76. }