Imported Upstream version 4.5.14
[platform/upstream/findutils.git] / lib / splitstring.c
1 /* splitstring.c -- split a const string into fields.
2    Copyright (C) 2011 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17 /*
18  * Written by James Youngman.
19  */
20 /* config.h must be included first. */
21 #include <config.h>
22
23 /* system headers. */
24 #include <stdbool.h>
25 #include <string.h>
26
27 /* gnulib headers would go here. */
28
29 /* find headers. */
30 #include "splitstring.h"
31
32 static size_t
33 field_length (const char *str, const char *separators)
34 {
35   /* if there are no separators, the whole input is one field. */
36   if (*separators)
37     {
38       const char *end = strpbrk (str, separators);
39       if (end)
40         return end - str;
41     }
42   return strlen (str);
43 }
44
45
46 bool
47 splitstring(const char *s, const char *separators, bool first,
48             size_t *pos, size_t *len)
49 {
50   if (first)
51     {
52       *pos = 0u;
53       *len = 0u;
54     }
55   else
56     {
57       *pos += *len;             /* advance to the next field. */
58       if (s[*pos])
59         ++*pos;                 /* skip the separator */
60       else
61         return false;           /* we reached the end. */
62     }
63   *len = field_length (&s[*pos], separators);
64   return true;
65 }