12a6b7db3Sskrll /* Implement the xstrndup function.
2*f22f0ef4Schristos    Copyright (C) 2005-2022 Free Software Foundation, Inc.
32a6b7db3Sskrll    Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu>.
42a6b7db3Sskrll 
52a6b7db3Sskrll This file is part of the libiberty library.
62a6b7db3Sskrll Libiberty is free software; you can redistribute it and/or
72a6b7db3Sskrll modify it under the terms of the GNU Library General Public
82a6b7db3Sskrll License as published by the Free Software Foundation; either
92a6b7db3Sskrll version 2 of the License, or (at your option) any later version.
102a6b7db3Sskrll 
112a6b7db3Sskrll Libiberty is distributed in the hope that it will be useful,
122a6b7db3Sskrll but WITHOUT ANY WARRANTY; without even the implied warranty of
132a6b7db3Sskrll MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
142a6b7db3Sskrll Library General Public License for more details.
152a6b7db3Sskrll 
162a6b7db3Sskrll You should have received a copy of the GNU Library General Public
172a6b7db3Sskrll License along with libiberty; see the file COPYING.LIB.  If
182a6b7db3Sskrll not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
192a6b7db3Sskrll Boston, MA 02110-1301, USA.  */
202a6b7db3Sskrll 
212a6b7db3Sskrll /*
222a6b7db3Sskrll 
232a6b7db3Sskrll @deftypefn Replacement char* xstrndup (const char *@var{s}, size_t @var{n})
242a6b7db3Sskrll 
252a6b7db3Sskrll Returns a pointer to a copy of @var{s} with at most @var{n} characters
262a6b7db3Sskrll without fail, using @code{xmalloc} to obtain memory.  The result is
272a6b7db3Sskrll always NUL terminated.
282a6b7db3Sskrll 
292a6b7db3Sskrll @end deftypefn
302a6b7db3Sskrll 
312a6b7db3Sskrll */
322a6b7db3Sskrll 
332a6b7db3Sskrll #ifdef HAVE_CONFIG_H
342a6b7db3Sskrll #include "config.h"
352a6b7db3Sskrll #endif
362a6b7db3Sskrll #include <sys/types.h>
372a6b7db3Sskrll #ifdef HAVE_STRING_H
382a6b7db3Sskrll #include <string.h>
392a6b7db3Sskrll #else
402a6b7db3Sskrll # ifdef HAVE_STRINGS_H
412a6b7db3Sskrll #  include <strings.h>
422a6b7db3Sskrll # endif
432a6b7db3Sskrll #endif
442a6b7db3Sskrll #include "ansidecl.h"
452a6b7db3Sskrll #include "libiberty.h"
462a6b7db3Sskrll 
472a6b7db3Sskrll char *
xstrndup(const char * s,size_t n)482a6b7db3Sskrll xstrndup (const char *s, size_t n)
492a6b7db3Sskrll {
502a6b7db3Sskrll   char *result;
5198f124a6Schristos   size_t len = strnlen (s, n);
522a6b7db3Sskrll 
532a6b7db3Sskrll   result = XNEWVEC (char, len + 1);
542a6b7db3Sskrll 
552a6b7db3Sskrll   result[len] = '\0';
562a6b7db3Sskrll   return (char *) memcpy (result, s, len);
572a6b7db3Sskrll }
58