aboutsummaryrefslogtreecommitdiffstats
path: root/src/libstddjb/string_index.c
blob: c352e7773aad967cf21d5ce10cc7ff9f66fff1e6 (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
/* ISC license. */

#include <skalibs/genalloc.h>
#include <skalibs/skamisc.h>

int string_index (char *s, size_t start, size_t len, char delim, genalloc *indices)
{
  size_t origlen = genalloc_len(size_t, indices) ;
  size_t pos = start ;
  int wasnull = !indices->s ;
  int inword = 0 ;

  for (size_t i = start ; i < len ; i++)
  {
    if (s[i] == delim)
    {
      s[i] = 0 ;
      if (!genalloc_append(size_t, indices, &pos)) goto err ;
      inword = 0 ;
    }
    else if (!inword) { pos = i ; inword = 1 ; }
  }
  if (inword) goto err ;
  return 1 ;

 err:
  if (wasnull) genalloc_free(size_t, indices) ;
  else genalloc_setlen(size_t, indices, origlen) ;
  return 0 ;
}