Guest User

Untitled

a guest
Jun 18th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdint.h>
  5.  
  6. #ifndef CHAR_QUEUE_H
  7. #define CHAR_QUEUE_H
  8. #define QUEUE_INIT_SIZE 128
  9.  
  10. typedef struct CharQueue_t{
  11. uint16_t size;
  12. uint16_t capacity;
  13. unsigned char *data;
  14. void (*append) (struct CharQueue_t *, unsigned char);
  15. void (*destroy) (struct CharQueue_t *);
  16. unsigned char (*get) (struct CharQueue_t *, uint16_t);
  17. unsigned char (*next) (struct CharQueue_t *);
  18. } CharQueue_t;
  19.  
  20. CharQueue_t *CharQueueInit();
  21.  
  22. void CharQueueAppend(struct CharQueue_t *queue, unsigned char value);
  23.  
  24. void CharQueueDestroy(struct CharQueue_t *queue);
  25.  
  26. unsigned char CharQueueGet(struct CharQueue_t *queue, uint16_t idx);
  27.  
  28. unsigned char CharQueueNext(struct CharQueue_t *queue);
  29.  
  30. #endif /* CHAR_QUEUE_H */
  31.  
  32. CharQueue_t *CharQueueInit() {
  33. CharQueue_t *queue = malloc(sizeof(CharQueue_t));
  34. // Initialize size and capacity
  35. queue->size = 0;
  36. queue->capacity = QUEUE_INIT_SIZE;
  37. queue->data = malloc(sizeof(unsigned char) * queue->capacity);
  38. queue->append = CharQueueAppend;
  39. queue->destroy = CharQueueDestroy;
  40. queue->get = CharQueueGet;
  41. queue->next = CharQueueNext;
  42. return queue;
  43. }
  44.  
  45. void CharQueueAppend(struct CharQueue_t *queue, unsigned char value) {
  46. // Resize the queue if it's at capacity
  47. if (queue->size >= queue->capacity) {
  48. queue->capacity *= 2;
  49. queue->data = realloc(queue->data, sizeof(unsigned char) * queue->capacity);
  50. }
  51. queue->data[queue->size] = value;
  52. queue->size++;
  53. }
  54.  
  55. void CharQueueDestroy(struct CharQueue_t *queue) {
  56. free(queue->data);
  57. free(queue);
  58. }
  59.  
  60. unsigned char CharQueueGet(struct CharQueue_t *queue, uint16_t idx) {
  61. if (idx >= queue->size || idx < 0) {
  62. return 0;
  63. }
  64. return queue->data[idx];
  65. }
  66.  
  67. unsigned char CharQueueNext(struct CharQueue_t *queue) {
  68. char data = queue->data[0];
  69. queue->size = queue->size - 1;
  70. // Move the pointer up the stack -- Does this leak memory?
  71. *queue->data++;
  72. return data;
  73. }
  74.  
  75. int main(void) {
  76. CharQueue_t *queue = CharQueueInit();
  77. int i;
  78. for (i = 0; i < 256; i++) {
  79. queue->append(queue, i);
  80. }
  81. printf("Queue Size is %drn", queue->size);
  82. for (i = 0; i < 256; i++) {
  83. printf("#%d in queue: 0x%drn", i, queue->next(queue));
  84. }
  85. return 0;
  86. }
  87.  
  88. // Move the pointer up the stack -- Does this leak memory?
  89. *queue->data++;
Add Comment
Please, Sign In to add comment