1169695Skan/* Implement the xstrndup function. 2169695Skan Copyright (C) 2005 Free Software Foundation, Inc. 3169695Skan Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu>. 4169695Skan 5169695SkanThis file is part of the libiberty library. 6169695SkanLibiberty is free software; you can redistribute it and/or 7169695Skanmodify it under the terms of the GNU Library General Public 8169695SkanLicense as published by the Free Software Foundation; either 9169695Skanversion 2 of the License, or (at your option) any later version. 10169695Skan 11169695SkanLibiberty is distributed in the hope that it will be useful, 12169695Skanbut WITHOUT ANY WARRANTY; without even the implied warranty of 13169695SkanMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14169695SkanLibrary General Public License for more details. 15169695Skan 16169695SkanYou should have received a copy of the GNU Library General Public 17169695SkanLicense along with libiberty; see the file COPYING.LIB. If 18169695Skannot, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, 19169695SkanBoston, MA 02110-1301, USA. */ 20169695Skan 21169695Skan/* 22169695Skan 23169695Skan@deftypefn Replacement char* xstrndup (const char *@var{s}, size_t @var{n}) 24169695Skan 25169695SkanReturns a pointer to a copy of @var{s} with at most @var{n} characters 26169695Skanwithout fail, using @code{xmalloc} to obtain memory. The result is 27169695Skanalways NUL terminated. 28169695Skan 29169695Skan@end deftypefn 30169695Skan 31169695Skan*/ 32169695Skan 33169695Skan#ifdef HAVE_CONFIG_H 34169695Skan#include "config.h" 35169695Skan#endif 36169695Skan#include <sys/types.h> 37169695Skan#ifdef HAVE_STRING_H 38169695Skan#include <string.h> 39169695Skan#else 40169695Skan# ifdef HAVE_STRINGS_H 41169695Skan# include <strings.h> 42169695Skan# endif 43169695Skan#endif 44169695Skan#include "ansidecl.h" 45169695Skan#include "libiberty.h" 46169695Skan 47169695Skanchar * 48169695Skanxstrndup (const char *s, size_t n) 49169695Skan{ 50169695Skan char *result; 51169695Skan size_t len = strlen (s); 52169695Skan 53169695Skan if (n < len) 54169695Skan len = n; 55169695Skan 56169695Skan result = XNEWVEC (char, len + 1); 57169695Skan 58169695Skan result[len] = '\0'; 59169695Skan return (char *) memcpy (result, s, len); 60169695Skan} 61