12a6b7db3Sskrll /* Implement the strndup 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 Extension char* strndup (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 in memory obtained from @code{malloc}, or @code{NULL} if insufficient
272a6b7db3Sskrll memory was available.  The result is always NUL terminated.
282a6b7db3Sskrll 
292a6b7db3Sskrll @end deftypefn
302a6b7db3Sskrll 
312a6b7db3Sskrll */
322a6b7db3Sskrll 
332a6b7db3Sskrll #include "ansidecl.h"
342a6b7db3Sskrll #include <stddef.h>
352a6b7db3Sskrll 
3698f124a6Schristos extern size_t	strnlen (const char *s, size_t maxlen);
37*f22f0ef4Schristos extern void *malloc (size_t);
38*f22f0ef4Schristos extern void *memcpy (void *, const void *, size_t);
392a6b7db3Sskrll 
402a6b7db3Sskrll char *
strndup(const char * s,size_t n)412a6b7db3Sskrll strndup (const char *s, size_t n)
422a6b7db3Sskrll {
432a6b7db3Sskrll   char *result;
4498f124a6Schristos   size_t len = strnlen (s, n);
452a6b7db3Sskrll 
462a6b7db3Sskrll   result = (char *) malloc (len + 1);
472a6b7db3Sskrll   if (!result)
482a6b7db3Sskrll     return 0;
492a6b7db3Sskrll 
502a6b7db3Sskrll   result[len] = '\0';
512a6b7db3Sskrll   return (char *) memcpy (result, s, len);
522a6b7db3Sskrll }
53