ec10c8c240388af62981d582eaac401d19ae28d7
[petitboot] / lib / fold / fold.c
1
2 #include "fold/fold.h"
3
4 void fold_text(const char *text,
5                 int linelen,
6                 int line_cb(void *arg, const char *start, int len),
7                 void *arg)
8 {
9         const char *start, *end, *sep;
10         int rc = 0;
11
12         start = end = sep = text;
13
14         while (!rc) {
15
16                 if (*end == '\n') {
17                         rc = line_cb(arg, start, end - start);
18                         start = sep = ++end;
19
20                 } else if (*end == '\0') {
21                         line_cb(arg, start, end - start);
22                         rc = 1;
23
24                 } else if (end - start >= linelen - 1) {
25                         if (sep != start) {
26                                 /* split on a previous word boundary, if
27                                  * possible */
28                                 rc = line_cb(arg, start, sep - start);
29                                 start = end = ++sep;
30                         } else {
31                                 /* otherwise, break the word */
32                                 end++;
33                                 rc = line_cb(arg, start, end - start);
34                                 start = sep = end;
35                         }
36
37                 } else {
38                         end++;
39                         /* record our last separator */
40                         if (*end == ' ')
41                                 sep = end;
42                 }
43         }
44 }