#pragma once
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

static inline void scoped_close(int *fd)
{
  if (*fd != -1)
  {
    close(*fd);
    *fd = -1;
  }
}

static inline void scoped_free(void **ptr)
{
  if (*ptr != NULL)
  {
    free(*ptr);
    *ptr = NULL;
  }
}

static inline void scoped_fclose(FILE **f)
{
  if (*f != NULL)
  {
    fclose(*f);
    *f = NULL;
  }
}

#define scoped_fd    int    __attribute__((cleanup(scoped_close)))
#define scoped_alloc void * __attribute__((cleanup(scoped_free)))
#define scoped_file  FILE * __attribute__((cleanup(scoped_fclose)))
