Updated to fedora-glibc-20080524T2218
[glibc.git] / string / argz-insert.c
blob8ab9a8b4f3926a040b50eb7602af9b29d2a8be77
1 /* Routines for dealing with '\0' separated arg vectors.
2 Copyright (C) 1995, 1996, 1997 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Written by Miles Bader <miles@gnu.ai.mit.edu>
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, write to the Free
18 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 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 memmove (before + entry_len, before, after_before);
55 memmove (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)