1*fae548d3Szrj /* Implement the xstrndup function.
2*fae548d3Szrj Copyright (C) 2005-2020 Free Software Foundation, Inc.
3*fae548d3Szrj Written by Kaveh R. Ghazi <ghazi@caip.rutgers.edu>.
4*fae548d3Szrj
5*fae548d3Szrj This file is part of the libiberty library.
6*fae548d3Szrj Libiberty is free software; you can redistribute it and/or
7*fae548d3Szrj modify it under the terms of the GNU Library General Public
8*fae548d3Szrj License as published by the Free Software Foundation; either
9*fae548d3Szrj version 2 of the License, or (at your option) any later version.
10*fae548d3Szrj
11*fae548d3Szrj Libiberty is distributed in the hope that it will be useful,
12*fae548d3Szrj but WITHOUT ANY WARRANTY; without even the implied warranty of
13*fae548d3Szrj MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14*fae548d3Szrj Library General Public License for more details.
15*fae548d3Szrj
16*fae548d3Szrj You should have received a copy of the GNU Library General Public
17*fae548d3Szrj License along with libiberty; see the file COPYING.LIB. If
18*fae548d3Szrj not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
19*fae548d3Szrj Boston, MA 02110-1301, USA. */
20*fae548d3Szrj
21*fae548d3Szrj /*
22*fae548d3Szrj
23*fae548d3Szrj @deftypefn Replacement char* xstrndup (const char *@var{s}, size_t @var{n})
24*fae548d3Szrj
25*fae548d3Szrj Returns a pointer to a copy of @var{s} with at most @var{n} characters
26*fae548d3Szrj without fail, using @code{xmalloc} to obtain memory. The result is
27*fae548d3Szrj always NUL terminated.
28*fae548d3Szrj
29*fae548d3Szrj @end deftypefn
30*fae548d3Szrj
31*fae548d3Szrj */
32*fae548d3Szrj
33*fae548d3Szrj #ifdef HAVE_CONFIG_H
34*fae548d3Szrj #include "config.h"
35*fae548d3Szrj #endif
36*fae548d3Szrj #include <sys/types.h>
37*fae548d3Szrj #ifdef HAVE_STRING_H
38*fae548d3Szrj #include <string.h>
39*fae548d3Szrj #else
40*fae548d3Szrj # ifdef HAVE_STRINGS_H
41*fae548d3Szrj # include <strings.h>
42*fae548d3Szrj # endif
43*fae548d3Szrj #endif
44*fae548d3Szrj #include "ansidecl.h"
45*fae548d3Szrj #include "libiberty.h"
46*fae548d3Szrj
47*fae548d3Szrj char *
xstrndup(const char * s,size_t n)48*fae548d3Szrj xstrndup (const char *s, size_t n)
49*fae548d3Szrj {
50*fae548d3Szrj char *result;
51*fae548d3Szrj size_t len = strnlen (s, n);
52*fae548d3Szrj
53*fae548d3Szrj result = XNEWVEC (char, len + 1);
54*fae548d3Szrj
55*fae548d3Szrj result[len] = '\0';
56*fae548d3Szrj return (char *) memcpy (result, s, len);
57*fae548d3Szrj }
58