build: fix make local, improve make standalone
[vis.git] / text-util.c
blob4d3406b7eb5715db7ff3fc466bfdc94cfebba337
1 #include "text-util.h"
2 #include "util.h"
3 #include <wchar.h>
4 #include <errno.h>
6 bool text_range_valid(Filerange *r) {
7 return r->start != EPOS && r->end != EPOS && r->start <= r->end;
10 size_t text_range_size(Filerange *r) {
11 return text_range_valid(r) ? r->end - r->start : 0;
14 Filerange text_range_empty(void) {
15 return (Filerange){ .start = EPOS, .end = EPOS };
18 Filerange text_range_union(Filerange *r1, Filerange *r2) {
19 if (!text_range_valid(r1))
20 return *r2;
21 if (!text_range_valid(r2))
22 return *r1;
23 return (Filerange) {
24 .start = MIN(r1->start, r2->start),
25 .end = MAX(r1->end, r2->end),
29 Filerange text_range_new(size_t a, size_t b) {
30 return (Filerange) {
31 .start = MIN(a, b),
32 .end = MAX(a, b),
36 bool text_range_equal(Filerange *r1, Filerange *r2) {
37 if (!text_range_valid(r1) && !text_range_valid(r2))
38 return true;
39 return r1->start == r2->start && r1->end == r2->end;
42 bool text_range_overlap(Filerange *r1, Filerange *r2) {
43 if (!text_range_valid(r1) || !text_range_valid(r2))
44 return false;
45 return r1->start <= r2->end && r2->start <= r1->end;
48 bool text_range_contains(Filerange *r, size_t pos) {
49 return text_range_valid(r) && r->start <= pos && pos <= r->end;
52 int text_char_count(const char *data, size_t len) {
53 int count = 0;
54 mbstate_t ps = { 0 };
55 while (len > 0) {
56 wchar_t wc;
57 size_t wclen = mbrtowc(&wc, data, len, &ps);
58 if (wclen == (size_t)-1 && errno == EILSEQ) {
59 count++;
60 while (!ISUTF8(*data))
61 data++, len--;
62 } else if (wclen == (size_t)-2) {
63 break;
64 } else if (wclen == 0) {
65 count++;
66 data++;
67 len--;
68 } else {
69 int width = wcwidth(wc);
70 if (width != 0)
71 count++;
72 data += wclen;
73 len -= wclen;
76 return count;