#include <id/id_alloc.h>
#include <libk/bm.h>
#include <libk/std.h>
#include <mm/liballoc.h>
#include <status.h>
#include <sync/spin_lock.h>
#include <sys/debug.h>

bool id_alloc_init (struct id_alloc* ida, size_t nbits) {
  size_t buffer_size = (nbits + 7) / 8;

  uint8_t* buffer = malloc (buffer_size);

  if (buffer == NULL)
    return false;

  bm_init (&ida->bm, buffer, nbits);
  ida->lock = SPIN_LOCK_INIT;

  return true;
}

void id_alloc_fini (struct id_alloc* ida) {
  free (ida->bm.base);
  ida->bm.base = NULL;
  ida->bm.nbits = 0;
}

int id_alloc (struct id_alloc* ida) {
  spin_lock (&ida->lock);

  for (size_t bit = 0; bit < ida->bm.nbits; bit++) {
    if (!bm_test (&ida->bm, bit)) {
      bm_set (&ida->bm, bit);

      spin_unlock (&ida->lock);
      return (int)bit;
    }
  }

  spin_unlock (&ida->lock);
  return -ST_OOM_ERROR;
}

void id_free (struct id_alloc* ida, int id) {
  if (id < 0)
    return;

  spin_lock (&ida->lock);
  bm_clear (&ida->bm, (size_t)id);
  spin_unlock (&ida->lock);
}
