aboutsummaryrefslogtreecommitdiff
path: root/newlib/libc/argz/argz_replace.c
blob: e6c6ead3eee36a72e88866bf345adbf5cbffb29f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* Copyright (C) 2002 by  Red Hat, Incorporated. All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software
 * is freely granted, provided that this notice is preserved.
 */

#include <errno.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <argz.h>

#include "buf_findstr.h"

error_t
_DEFUN (argz_replace, (argz, argz_len, str, with, replace_count),
       char **argz,
       size_t *argz_len,
       const char *str,
       const char *with,
       unsigned *replace_count)
{
  const int str_len = strlen(str);
  const int with_len = strlen(with);
  const int len_diff = with_len - str_len;

  char *buf_iter = *argz;
  size_t buf_len = *argz_len;
  char *last_iter = NULL;
  char *new_argz = NULL;
  size_t new_argz_len = 0;
  char *new_argz_iter = NULL;
  char *argz_realloc = NULL;

  *replace_count = 0;
  new_argz_len = *argz_len;

  while(buf_len)
    {
      if(_buf_findstr(str, &buf_iter, &buf_len))
        {
          *replace_count += 1;
          new_argz_len += len_diff;
        }
    }

  if (*replace_count)
    {
      if (!(new_argz = (char *)malloc(new_argz_len)))
	return ENOMEM;
      
      buf_iter = *argz;
      buf_len = *argz_len;
      last_iter = buf_iter;
      new_argz_iter = new_argz;
      
      while(buf_len)
        {
          if (_buf_findstr(str, &buf_iter, &buf_len))
            {
              /* copy everything up to, but not including str, from old argz to
                 new argz. */
              memcpy(new_argz_iter, last_iter, buf_iter - last_iter - str_len);
              new_argz_iter += (buf_iter - last_iter - str_len);
              /* copy replacement string. */
              memcpy(new_argz_iter, with, with_len);
              new_argz_iter += with_len;
              last_iter = buf_iter;
            }
        }
      /* copy everything after last occurrence of str. */
      memcpy(new_argz_iter, last_iter, *argz + *argz_len - last_iter);

      /* reallocate argz, and copy over the new value. */
      if(!(argz_realloc = (char *)realloc(*argz, new_argz_len)))
        {
          free(new_argz);
          return ENOMEM;
        }
      *argz = argz_realloc;

      memcpy(*argz, new_argz, new_argz_len);
      *argz_len = new_argz_len;

      if (*argz_len == 0)
        {
          free(*argz);
          *argz = NULL;
        }
      free(new_argz);
    }

  return 0;
}