/*
 * tina - a personal information manager
 * Copyright (C) 2001  Matt Kraai
 * Copyright (C) 2016  Peter Pentchev <roam@ringlet.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#define _GNU_SOURCE

#include <stdlib.h>
#include <string.h>

#include "error.h"
#include "memory.h"

void *
xrealloc (void *ptr, size_t size)
{
  ptr = realloc (ptr, size);
  if (ptr == NULL && size != 0)
    fatal_error ("You are out of memory.");

  return ptr;
}

void *
xmalloc (size_t size)
{
  void *ptr;

  ptr = malloc (size);
  if (ptr == NULL && size != 0)
    fatal_error ("You are out of memory.");

  return ptr;
}

void *
xcalloc (size_t nmemb, size_t size)
{
  void *ptr;

  ptr = calloc (nmemb, size);
  if (ptr == NULL && nmemb != 0 && size != 0)
    fatal_error ("You are out of memory.");

  return ptr;
}

char *
xstrdup (const char *s)
{
  char *news;

  news = strdup (s);
  if (news == NULL)
    fatal_error ("You are out of memory.");

  return news;
}

char *
xstrndup (const char *s, size_t n)
{
  char *news;
  size_t len;

  len = strlen (s);
  if (n < len)
    len = n;

  news = xmalloc (len + 1);
  memcpy (news, s, len);
  news[len] = '\0';

  return news;
}
