/*
 * This is free and unencumbered software released into the public domain.
 *
 * Anyone is free to copy, modify, publish, use, compile, sell, or
 * distribute this software, either in source code form or as a compiled
 * binary, for any purpose, commercial or non-commercial, and by any
 * means.
 *
 * In jurisdictions that recognize copyright laws, the author or authors
 * of this software dedicate any and all copyright interest in the
 * software to the public domain. We make this dedication for the benefit
 * of the public at large and to the detriment of our heirs and
 * successors. We intend this dedication to be an overt act of
 * relinquishment in perpetuity of all present and future rights to this
 * software under copyright law.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * For more information, please refer to <https://unlicense.org>
 */

/* https://git.datadissipation.net */
#ifndef ASPRINTF_H_
 #define ASPRINTF_H_ 1

 #ifdef ASPRINTF_INCLUDE_LIBC
  #include <stdarg.h>
  #include <stdio.h>
  #include <stdlib.h>
 #endif /* ASPRINTF_INCLUDE_LIBC */

 #ifndef HAVE_ASPRINTF
  #define HAVE_ASPRINTF 1
  #define asprintf  i_asprintf_
  #define vasprintf i_vasprintf_
  int i_vasprintf_(char **restrict strp, const char *restrict fmt, va_list ap);
  int i_asprintf_(char **restrict strp, const char *restrict fmt, ...);
 #endif /* !HAVE_ASPRINTF */

 #ifdef ASPRINTF_IMPLEMENTATION
 int
 i_vasprintf_(char **restrict strp, const char *restrict fmt, va_list ap)
 {
 	 int size, ret;
 	 va_list tp;

	 va_copy(tp, ap);
	 size = vsnprintf(NULL, 0, fmt, tp);
	 va_end(tp);

	 if (size < 0) {
		 return -1;
	 }
	 *strp = malloc(size + 1);
	 if (*strp == NULL) {
		 return -1;
	 }

	 ret = vsnprintf(*strp, size + 1, fmt, ap);
	 if (ret < 0) {
		 free(*strp);
		 return -1;
	 }

	 return ret;
 }

 int
 i_asprintf_(char **restrict strp, const char *restrict fmt, ...)
 {
	 int ret;
	 va_list ap;

	 va_start(ap, fmt);
	 ret = i_vasprintf_(strp, fmt, ap);
	 va_end(ap);

	 return ret;
 }
 #endif /* ASPRINTF_IMPLEMENTATION */
#endif /* !ASPRINTF_H_ */
