/* ra -> retry, abort */

#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#include "callcheck.h"
#include "wrappers.h"

/*
 * attempts to allocate memory every 50 ms for 1000 ms, returns like malloc(3)
 * would have if errors other than ENOMEM are encountered or if it times out
 *
 * returns immediately upon success.
 */
void *ra_malloc (size_t size) {
  int i = 0;
  void *ret;

  ret = malloc(size);
  callcheck(ret != NULL || errno == ENOMEM);

  for (i = 0; ret == NULL && i < TIMEOUT_RETRIES; i++) {
    usleep(TIMEOUT_DELAY);

    ret = malloc(size);
    callcheck(ret != NULL || errno == ENOMEM);
    
    errno = 0;
  }

  return ret;
}

/*
 * attempts to re-allocate memory every 50 ms for 1000 ms, returns like
 * malloc(3)would have if errors other than ENOMEM are encountered or if it
 * times out
 *
 * returns immediately upon success.
 */
void *ra_realloc (void *ptr, size_t size) {
  int i = 0;
  void *ret;

  ret = realloc(ptr, size);
  callcheck(ret != NULL || errno == ENOMEM);
  for (i = 0; ret == NULL && i < TIMEOUT_RETRIES; i++) {
    usleep(TIMEOUT_DELAY);

    ret = realloc(ptr, size);
    callcheck(ret != NULL || errno == ENOMEM);
    
    errno = 0;
  }

  return ret;
}

