Safe C

safe-c-std/text.h

Raw file ยท Directory on GitHub

1/* Text without strtok, strchr or strcpy. No __unsafe, and plain C too.
2
3     str   text someone else owns: a pointer and a length, for locals and parameters
4     text  text this struct owns: it grows, and text_free frees it */
5#ifndef SAFEC_TEXT_H
6#define SAFEC_TEXT_H
7#include "safec.h"
8#include <limits.h>
9#include <stdbool.h>
10#include <stdint.h>
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#if defined(__clang__)
15#pragma clang assume_nonnull begin
16#endif
17
18struct _View str {
19  const char *__counted_by(len) p;
20  size_t len;
21};
22#define STR(literal) ((struct str){(literal), sizeof(literal) - 1})
23
24static inline int str_eq(struct str a, struct str b) {
25  return a.len == b.len && (a.len == 0 || memcmp(a.p, b.p, a.len) == 0);
26}
27
28/* Below, at or above 0, in byte order; a shorter text comes first. */
29static inline int str_cmp(struct str a, struct str b) {
30  size_t n = a.len < b.len ? a.len : b.len;
31  int r = n ? memcmp(a.p, b.p, n) : 0;
32  return r ? r : (a.len > b.len) - (a.len < b.len);
33}
34
35/* Writes s, then the end of line if there is one: 1, or 0 if it could not. */
36static inline int str_write(struct str s, const char *__null_terminated end, FILE *f) {
37  return fwrite(s.p, 1, s.len, f) == s.len && fputs(end, f) >= 0;
38}
39
40/* Where c is, or s.len. */
41static inline size_t str_find(struct str s, char c) {
42  size_t i = 0;
43  while (i < s.len && s.p[i] != c)
44    i++;
45  return i;
46}
47
48/* n bytes from 'from', or what there is. */
49static inline struct str str_part(struct str s, size_t from, size_t n) {
50  if (from > s.len)
51    from = s.len;
52  if (n > s.len - from)
53    n = s.len - from;
54  struct str r = {s.p + from, n};
55  return r;
56}
57
58/* Splitting:
59     for (struct str rest = s; rest.len; rest = str_after(rest, ','))
60       use(str_before(rest, ',')); */
61static inline struct str str_before(struct str s, char c) {
62  return str_part(s, 0, str_find(s, c));
63}
64static inline struct str str_after(struct str s, char c) {
65  return str_part(s, str_find(s, c) + 1, s.len);
66}
67
68static inline struct str str_trim(struct str s) {
69  size_t b = 0, e = s.len;
70  while (b < e && (s.p[b] == ' ' || s.p[b] == '\t' || s.p[b] == '\r' || s.p[b] == '\n'))
71    b++;
72  while (e > b && (s.p[e - 1] == ' ' || s.p[e - 1] == '\t' || s.p[e - 1] == '\r' || s.p[e - 1] == '\n'))
73    e--;
74  return str_part(s, b, e - b);
75}
76
77/* A dropped error code is an error (with -fsafe-c; a warning in plain clang). */
78#ifndef SAFEC_MUST_USE
79#if defined(__clang__)
80#define SAFEC_MUST_USE __attribute__((warn_unused_result))
81#else
82#define SAFEC_MUST_USE
83#endif
84#endif
85
86/* All of s as a number, into *out. STR_OK (0), or what is wrong; *out is set only on STR_OK. */
87enum str_number_error { STR_OK, STR_EMPTY, STR_NOT_A_NUMBER, STR_TOO_BIG };
88SAFEC_MUST_USE static inline enum str_number_error str_int(struct str s, long *out) {
89  size_t i = s.len > 0 && s.p[0] == '-';
90  int minus = i == 1;
91  long v = 0;
92  if (s.len == 0)
93    return STR_EMPTY;
94  if (i == s.len)
95    return STR_NOT_A_NUMBER;
96  for (; i < s.len; i++) {
97    int d = s.p[i] - '0';
98    if (d < 0 || d > 9)
99      return STR_NOT_A_NUMBER;
100    if (v < (LONG_MIN + d) / 10)
101      return STR_TOO_BIG;
102    v = v * 10 - d; /* counts down: there is one more negative number */
103  }
104  if (!minus && v == LONG_MIN)
105    return STR_TOO_BIG;
106  *out = minus ? v : -v;
107  return STR_OK;
108}
109
110/* A growable byte buffer, like Rust's Vec<u8>. The compiler checks that p owns
111   its memory (freed once, never copied), that p is set only together with cap,
112   and that every p[i] is inside p[0..cap) (at compile time, or a trap when it
113   runs). len <= cap is kept by these functions, not by the compiler, so they
114   check it again before trusting it; a wrong len can stop the program but
115   cannot read past the buffer. */
116struct text {
117  size_t cap;                                 /* bytes p points to */
118  char *_Owned _Nullable __counted_by(cap) p; /* NULL until the first add */
119  size_t len;                                 /* bytes in use, from p[0] */
120};
121
122static inline struct str text_str(const struct text *t) {
123  if (!t->p)
124    return STR("");
125  struct str all = {t->p, t->cap};
126  return str_part(all, 0, t->len);
127}
128
129static inline void text_free(struct text *_Empties t) {
130  free(_Take(t->p));
131  t->len = 0;
132}
133
134/* Adds n bytes: 1, or 0 and no change if there is no memory. */
135static inline int text_add(struct text *t, const char *__counted_by(n) from, size_t n) {
136  if (n > SIZE_MAX / 4 || t->len > SIZE_MAX / 4)
137    return 0;
138  size_t need = t->len + n;
139  if (!t->p || need > t->cap) {
140    size_t cap = need * 2 + 16;
141    char *_Owned _Nullable bigger = calloc(cap, 1);
142    if (!bigger)
143      return 0;
144    if (t->p && t->len <= t->cap)
145      memcpy(bigger, t->p, t->len);
146    free(_Take(t->p));
147    _Set(t->p, t->cap, bigger, cap);
148  }
149  if (!t->p)
150    return 0;
151  memcpy(t->p + t->len, from, n);
152  t->len = need;
153  return 1;
154}
155
156/* Replaces it with from: 1, or 0 and empty if there is no memory. */
157static inline int text_set(struct text *t, struct str from) {
158  t->len = 0;
159  return text_add(t, from.p, from.len);
160}
161
162/* Replaces n bytes at 'at' with others: 1, or 0 and no change. */
163static inline int text_splice(struct text *t, size_t at, size_t n, struct str with) {
164  if (at > t->len || n > t->len - at)
165    return 0;
166  size_t old = t->len, tail = old - at - n;
167  /* Adding it first makes room, and is all there is to do at the end. */
168  if (!text_add(t, with.p, with.len) || !t->p)
169    return 0;
170  memmove(t->p + at + with.len, t->p + at + n, tail);
171  memcpy(t->p + at, with.p, with.len);
172  t->len = old - n + with.len;
173  return 1;
174}
175
176/* The next line, without its '\n': 1, or 0 at the end. */
177static inline int text_line(struct text *t, FILE *f) {
178  char part[256];
179  t->len = 0;
180  for (int some = 0;; some = 1) {
181    /* A '\n' with the 0 fgets adds after it was read; any other is filler. */
182    memset(part, '\n', sizeof part);
183    if (!fgets(part, sizeof part, f))
184      return some;
185    struct str all = {part, sizeof part};
186    size_t n = str_find(all, '\n');
187    if (n == sizeof part)
188      n = sizeof part - 1; /* no end of line yet */
189    else if (n + 1 < sizeof part && part[n + 1] == 0)
190      return text_add(t, part, n);
191    else
192      return n > 0 && text_add(t, part, n - 1); /* the end of the file */
193    if (!text_add(t, part, n))
194      return 0;
195  }
196}
197
198/* A growing list of strings: all the bytes in one text, and where each is.
199     struct strings names = {0};
200     if (!strings_add(&names, STR("Ada"))) ...      no memory
201     struct str s = strings_at(&names, 0);          empty if there is no such one
202     strings_count(&names); strings_free(&names);
203   What strings_at returns ends at the next strings_add or strings_free. */
204struct strings_span_ {
205  size_t at, len;
206};
207#if defined(__clang__)
208#pragma clang assume_nonnull end /* vec.h opens its own */
209#endif
210#define VEC_NAME strings_spans_
211#define VEC_TYPE struct strings_span_
212#include "vec.h"
213#if defined(__clang__)
214#pragma clang assume_nonnull begin
215#endif
216struct strings {
217  struct text bytes;
218  struct strings_spans_ where;
219};
220
221static inline size_t strings_count(const struct strings *s) {
222  return s->where.len;
223}
224
225static inline int strings_add(struct strings *s, struct str x) {
226  size_t at = s->bytes.len;
227  if (!text_add(&s->bytes, x.p, x.len))
228    return 0;
229  struct strings_span_ w = {at, x.len};
230  if (!strings_spans__add(&s->where, w)) {
231    s->bytes.len = at; /* no change */
232    return 0;
233  }
234  return 1;
235}
236
237static inline struct str strings_at(const struct strings *s, size_t i) {
238  struct strings_span_ w;
239  if (!strings_spans__get(&s->where, i, &w))
240    return STR("");
241  return str_part(text_str(&s->bytes), w.at, w.len);
242}
243
244static inline void strings_free(struct strings *_Empties s) {
245  text_free(&s->bytes);
246  strings_spans__free(&s->where);
247}
248
249#if defined(__clang__)
250#pragma clang assume_nonnull end
251#endif
252#endif
253