xref: /third_party/toybox/lib/linestack.c (revision 0f66f451)
1#include "toys.h"
2
3// The design idea here is indexing a big blob of (potentially mmaped) data
4// instead of copying the data into a zillion seperate malloc()s.
5
6// A linestack is an array of struct ptr_len, with a currently used len
7// and max tracking the memory allocation. This indexes existing string data,
8// the lifetime of which is tracked externally.
9
10// Insert one stack into another before position in old stack.
11// (Does not copy contents of strings, just shuffles index array contents.)
12void linestack_addstack(struct linestack **lls, struct linestack *throw,
13  long pos)
14{
15  struct linestack *catch = *lls;
16
17  if (CFG_TOYBOX_DEBUG)
18    if (pos > catch->len) error_exit("linestack_addstack past end.");
19
20  // Make a hole, allocating more space if necessary.
21  if (catch->len+throw->len >= catch->max) {
22    // New size rounded up to next multiple of 64, allocate and copy start.
23    catch->max = ((catch->len+throw->len)|63)+1;
24    *lls = xmalloc(sizeof(struct linestack)+catch->max*sizeof(struct ptr_len));
25    memcpy(*lls, catch, sizeof(struct linestack)+pos*sizeof(struct ptr_len));
26  }
27
28  // Copy end (into new allocation if necessary)
29  if (pos != catch->len)
30    memmove((*lls)->idx+pos+throw->len, catch->idx+pos,
31      (catch->len-pos)*sizeof(struct ptr_len));
32
33  // Cleanup if we had to realloc.
34  if (catch != *lls) {
35    free(catch);
36    catch = *lls;
37  }
38
39  // Copy new chunk we made space for
40  memcpy(catch->idx+pos, throw->idx, throw->len*sizeof(struct ptr_len));
41  catch->len += throw->len;
42}
43
44// Insert one line/len into a linestack at pos
45void linestack_insert(struct linestack **lls, long pos, char *line, long len)
46{
47  // alloca() was in 32V and Turbo C for DOS, but isn't in posix or c99.
48  // This allocates enough memory for the linestack to have one ptr_len.
49  // (Even if a compiler adds gratuitous padidng that just makes it bigger.)
50  struct {
51    struct ptr_len pl;
52    struct linestack ls;
53  } ls;
54
55  ls.ls.len = ls.ls.max = 1;
56  ls.ls.idx[0].ptr = line;
57  ls.ls.idx[0].len = len;
58  linestack_addstack(lls, &ls.ls, pos);
59}
60
61void linestack_append(struct linestack **lls, char *line)
62{
63  linestack_insert(lls, (*lls)->len, line, strlen(line));
64}
65
66struct linestack *linestack_load(char *name)
67{
68  FILE *fp = fopen(name, "r");
69  struct linestack *ls;
70
71  if (!fp) return 0;
72
73  ls = xzalloc(sizeof(struct linestack));
74
75  for (;;) {
76    char *line = 0;
77    ssize_t len;
78
79    if ((len = getline(&line, (void *)&len, fp))<1) break;
80    if (line[len-1]=='\n') len--;
81    linestack_insert(&ls, ls->len, line, len);
82  }
83  fclose(fp);
84
85  return ls;
86}
87
88// Show width many columns, negative means from right edge, out=0 just measure
89// if escout, send it unprintable chars, otherwise pass through raw data.
90// Returns width in columns, moves *str to end of data consumed.
91int crunch_str(char **str, int width, FILE *out, char *escmore,
92  int (*escout)(FILE *out, int cols, int wc))
93{
94  int columns = 0, col, bytes;
95  char *start, *end;
96  unsigned wc;
97
98  for (end = start = *str; *end; columns += col, end += bytes) {
99    if ((bytes = utf8towc(&wc, end, 4))>0 && (col = wcwidth(wc))>=0) {
100      if (!escmore || wc>255 || !strchr(escmore, wc)) {
101        if (width-columns<col) break;
102        if (out) fwrite(end, bytes, 1, out);
103
104        continue;
105      }
106    }
107
108    if (bytes<1) {
109      bytes = 1;
110      wc = *end;
111    }
112    col = width-columns;
113    if (col<1) break;
114    if (escout) {
115      if ((col = escout(out, col, wc))<0) break;
116    } else if (out) fwrite(end, 1, bytes, out);
117  }
118  *str = end;
119
120  return columns;
121}
122
123
124// standard escapes: ^X if <32, <XX> if invalid UTF8, U+XXXX if UTF8 !iswprint()
125int crunch_escape(FILE *out, int cols, int wc)
126{
127  char buf[11];
128  int rc;
129
130  if (wc<' ') rc = sprintf(buf, "^%c", '@'+wc);
131  else if (wc<256) rc = sprintf(buf, "<%02X>", wc);
132  else rc = sprintf(buf, "U+%04X", wc);
133
134  if (rc > cols) buf[rc = cols] = 0;
135  if (out) fputs(buf, out);
136
137  return rc;
138}
139
140// Display "standard" escapes in reverse video.
141int crunch_rev_escape(FILE *out, int cols, int wc)
142{
143  int rc;
144
145  tty_esc("7m");
146  rc = crunch_escape(out, cols, wc);
147  tty_esc("27m");
148
149  return rc;
150}
151
152// Write width chars at start of string to strdout with standard escapes
153// Returns length in columns so caller can pad it out with spaces.
154int draw_str(char *start, int width)
155{
156  return crunch_str(&start, width, stdout, 0, crunch_rev_escape);
157}
158
159// Return utf8 columns
160int utf8len(char *str)
161{
162  return crunch_str(&str, INT_MAX, 0, 0, crunch_rev_escape);
163}
164
165// Return bytes used by (up to) this many columns
166int utf8skip(char *str, int width)
167{
168  char *s = str;
169
170  crunch_str(&s, width, 0, 0, crunch_rev_escape);
171
172  return s-str;
173}
174
175// Print utf8 to stdout with standard escapes, trimmed to width and padded
176// out to padto. If padto<0 left justify. Returns columns printed
177int draw_trim_esc(char *str, int padto, int width, char *escmore,
178  int (*escout)(FILE *out, int cols, int wc))
179{
180  int apad = abs(padto), len = utf8len(str);
181
182  if (padto>=0 && len>width) str += utf8skip(str, len-width);
183  if (len>width) len = width;
184
185  // Left pad if right justified
186  if (padto>0 && apad>len) printf("%*s", apad-len, "");
187  crunch_str(&str, len, stdout, 0, crunch_rev_escape);
188  if (padto<0 && apad>len) printf("%*s", apad-len, "");
189
190  return (apad > len) ? apad : len;
191}
192
193// draw_trim_esc() with default escape
194int draw_trim(char *str, int padto, int width)
195{
196  return draw_trim_esc(str, padto, width, 0, 0);
197}
198