#include // for size_t #include // for malloc() and free() #include #include "utils.h" #include "cycle.h" /* cycling iterable */ struct Cycle { const void *base; size_t i; size_t memb_n; size_t memb_size; }; /* * cycle_new: create a new cycle of array startinng at 'base' with memb_n * elements each of size 'memb_size' */ struct Cycle * cycle_new(const void *base, size_t memb_n, size_t memb_size) { assert(base != NULL); assert(memb_n > 0); assert(memb_size > 0); struct Cycle *cycle = malloc(sizeof *cycle); if (cycle == NULL) { return NULL; } cycle->base = base; cycle->i = 0; cycle->memb_n = memb_n; cycle->memb_size = memb_size; return cycle; } /* cycle_free: free memmory used by cycle */ void cycle_free(struct Cycle *cycle) { assert(cycle != NULL); free(cycle); } /* cycle_index: get index of current element of cycle */ size_t cycle_index(struct Cycle *cycle) { assert(cycle != NULL); return cycle->i; } /* cycle_current: get current element of cycle */ const void * cycle_current(struct Cycle *cycle) { assert(cycle != NULL); return (const char *)cycle->base + cycle->memb_size*cycle->i; } /* cycle_next: point cycle to next element and return it */ const void * cycle_next(struct Cycle *cycle) { assert(cycle != NULL); cycle->i = (cycle->i >= cycle->memb_n-1) ? 0 : cycle->i+1; return cycle_current(cycle); } /* cycle_prev: point cycle to previous elemetn and return it */ const void * cycle_prev(struct Cycle *cycle) { assert(cycle != NULL); cycle->i = (cycle->i <= 0) ? cycle->memb_n-1 : cycle->i-1; return cycle_current(cycle); }