Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- #ifndef CHAR_QUEUE_H
- #define CHAR_QUEUE_H
- #define QUEUE_INIT_SIZE 128
- typedef struct CharQueue_t{
- uint16_t size;
- uint16_t capacity;
- unsigned char *data;
- void (*append) (struct CharQueue_t *, unsigned char);
- void (*destroy) (struct CharQueue_t *);
- unsigned char (*get) (struct CharQueue_t *, uint16_t);
- unsigned char (*next) (struct CharQueue_t *);
- } CharQueue_t;
- CharQueue_t *CharQueueInit();
- void CharQueueAppend(struct CharQueue_t *queue, unsigned char value);
- void CharQueueDestroy(struct CharQueue_t *queue);
- unsigned char CharQueueGet(struct CharQueue_t *queue, uint16_t idx);
- unsigned char CharQueueNext(struct CharQueue_t *queue);
- #endif /* CHAR_QUEUE_H */
- CharQueue_t *CharQueueInit() {
- CharQueue_t *queue = malloc(sizeof(CharQueue_t));
- // Initialize size and capacity
- queue->size = 0;
- queue->capacity = QUEUE_INIT_SIZE;
- queue->data = malloc(sizeof(unsigned char) * queue->capacity);
- queue->append = CharQueueAppend;
- queue->destroy = CharQueueDestroy;
- queue->get = CharQueueGet;
- queue->next = CharQueueNext;
- return queue;
- }
- void CharQueueAppend(struct CharQueue_t *queue, unsigned char value) {
- // Resize the queue if it's at capacity
- if (queue->size >= queue->capacity) {
- queue->capacity *= 2;
- queue->data = realloc(queue->data, sizeof(unsigned char) * queue->capacity);
- }
- queue->data[queue->size] = value;
- queue->size++;
- }
- void CharQueueDestroy(struct CharQueue_t *queue) {
- free(queue->data);
- free(queue);
- }
- unsigned char CharQueueGet(struct CharQueue_t *queue, uint16_t idx) {
- if (idx >= queue->size || idx < 0) {
- return 0;
- }
- return queue->data[idx];
- }
- unsigned char CharQueueNext(struct CharQueue_t *queue) {
- char data = queue->data[0];
- queue->size = queue->size - 1;
- // Move the pointer up the stack -- Does this leak memory?
- *queue->data++;
- return data;
- }
- int main(void) {
- CharQueue_t *queue = CharQueueInit();
- int i;
- for (i = 0; i < 256; i++) {
- queue->append(queue, i);
- }
- printf("Queue Size is %drn", queue->size);
- for (i = 0; i < 256; i++) {
- printf("#%d in queue: 0x%drn", i, queue->next(queue));
- }
- return 0;
- }
- // Move the pointer up the stack -- Does this leak memory?
- *queue->data++;
Add Comment
Please, Sign In to add comment