Fri Jun 14 01:51:47 1996 Roland McGrath <roland@delasyd.gnu.ai.mit.edu>
[glibc.git] / string / argz-insert.c
bloba110060e9d67f142ae8f2d9d7576e62f9714a63a
1 /* Routines for dealing with '\0' separated arg vectors.
3 Copyright (C) 1995, 1996 Free Software Foundation, Inc.
5 Written by Miles Bader <miles@gnu.ai.mit.edu>
7 This program is free software; you can redistribute it and/or
8 modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2, or (at
10 your option) any later version.
12 This program is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
21 #include <argz.h>
22 #include <string.h>
23 #include <stdlib.h>
25 /* Insert ENTRY into ARGZ & ARGZ_LEN before BEFORE, which should be an
26 existing entry in ARGZ; if BEFORE is NULL, ENTRY is appended to the end.
27 Since ARGZ's first entry is the same as ARGZ, argz_insert (ARGZ, ARGZ_LEN,
28 ARGZ, ENTRY) will insert ENTRY at the beginning of ARGZ. If BEFORE is not
29 in ARGZ, EINVAL is returned, else if memory can't be allocated for the new
30 ARGZ, ENOMEM is returned, else 0. */
31 error_t
32 __argz_insert (char **argz, size_t *argz_len, char *before, const char *entry)
34 if (! before)
35 return __argz_add (argz, argz_len, entry);
37 if (before < *argz || before >= *argz + *argz_len)
38 return EINVAL;
40 if (before > *argz)
41 /* Make sure before is actually the beginning of an entry. */
42 while (before[-1])
43 before--;
46 size_t after_before = *argz_len - (before - *argz);
47 size_t entry_len = strlen (entry) + 1;
48 size_t new_argz_len = *argz_len + entry_len;
49 char *new_argz = realloc (*argz, new_argz_len);
51 if (new_argz)
53 before = new_argz + (before - *argz);
54 memcpy (before + entry_len, before, after_before);
55 memcpy (before, entry, entry_len);
56 *argz = new_argz;
57 *argz_len = new_argz_len;
58 return 0;
60 else
61 return ENOMEM;
64 weak_alias (__argz_insert, argz_insert)