]> git.ipfire.org Git - thirdparty/git.git/blame - utf8.c
utf8: fix returning negative string width
[thirdparty/git.git] / utf8.c
CommitLineData
9e832665 1#include "git-compat-util.h"
a94410c8 2#include "strbuf.h"
9e832665
JS
3#include "utf8.h"
4
5/* This code is originally from http://www.cl.cam.ac.uk/~mgk25/ucs/ */
6
aab2a1ae
TB
7static const char utf16_be_bom[] = {'\xFE', '\xFF'};
8static const char utf16_le_bom[] = {'\xFF', '\xFE'};
9static const char utf32_be_bom[] = {'\0', '\0', '\xFE', '\xFF'};
10static const char utf32_le_bom[] = {'\xFF', '\xFE', '\0', '\0'};
11
9e832665 12struct interval {
a68a67de
JK
13 ucs_char_t first;
14 ucs_char_t last;
9e832665
JS
15};
16
1640632b 17size_t display_mode_esc_sequence_len(const char *s)
4247fe79
NTND
18{
19 const char *p = s;
20 if (*p++ != '\033')
21 return 0;
22 if (*p++ != '[')
23 return 0;
24 while (isdigit(*p) || *p == ';')
25 p++;
26 if (*p++ != 'm')
27 return 0;
28 return p - s;
29}
30
9e832665 31/* auxiliary function for binary search in interval table */
f3fa1838
JH
32static int bisearch(ucs_char_t ucs, const struct interval *table, int max)
33{
9e832665
JS
34 int min = 0;
35 int mid;
36
37 if (ucs < table[0].first || ucs > table[max].last)
38 return 0;
39 while (max >= min) {
19716b21 40 mid = min + (max - min) / 2;
9e832665
JS
41 if (ucs > table[mid].last)
42 min = mid + 1;
43 else if (ucs < table[mid].first)
44 max = mid - 1;
45 else
46 return 1;
47 }
48
49 return 0;
50}
51
52/* The following two functions define the column width of an ISO 10646
53 * character as follows:
54 *
55 * - The null character (U+0000) has a column width of 0.
56 *
57 * - Other C0/C1 control characters and DEL will lead to a return
58 * value of -1.
59 *
60 * - Non-spacing and enclosing combining characters (general
61 * category code Mn or Me in the Unicode database) have a
62 * column width of 0.
63 *
64 * - SOFT HYPHEN (U+00AD) has a column width of 1.
65 *
66 * - Other format characters (general category code Cf in the Unicode
67 * database) and ZERO WIDTH SPACE (U+200B) have a column width of 0.
68 *
69 * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF)
70 * have a column width of 0.
71 *
72 * - Spacing characters in the East Asian Wide (W) or East Asian
73 * Full-width (F) category as defined in Unicode Technical
74 * Report #11 have a column width of 2.
75 *
76 * - All remaining characters (including all printable
77 * ISO 8859-1 and WGL4 characters, Unicode control characters,
78 * etc.) have a column width of 1.
79 *
28321145 80 * This implementation assumes that ucs_char_t characters are encoded
9e832665
JS
81 * in ISO 10646.
82 */
83
b51be13c 84static int git_wcwidth(ucs_char_t ch)
9e832665
JS
85{
86 /*
87 * Sorted list of non-overlapping intervals of non-spacing characters,
9e832665 88 */
e233bef4 89#include "unicode-width.h"
9e832665
JS
90
91 /* test for 8-bit control characters */
92 if (ch == 0)
93 return 0;
94 if (ch < 32 || (ch >= 0x7f && ch < 0xa0))
95 return -1;
96
97 /* binary search in table of non-spacing characters */
fa364ad7 98 if (bisearch(ch, zero_width, ARRAY_SIZE(zero_width) - 1))
9e832665
JS
99 return 0;
100
08460345 101 /* binary search in table of double width characters */
fa364ad7 102 if (bisearch(ch, double_width, ARRAY_SIZE(double_width) - 1))
08460345 103 return 2;
9e832665 104
08460345 105 return 1;
9e832665
JS
106}
107
108/*
396ccf1f
JH
109 * Pick one ucs character starting from the location *start points at,
110 * and return it, while updating the *start pointer to point at the
44b25b87
JH
111 * end of that character. When remainder_p is not NULL, the location
112 * holds the number of bytes remaining in the string that we are allowed
113 * to pick from. Otherwise we are allowed to pick up to the NUL that
114 * would eventually appear in the string. *remainder_p is also reduced
115 * by the number of bytes we have consumed.
396ccf1f
JH
116 *
117 * If the string was not a valid UTF-8, *start pointer is set to NULL
118 * and the return value is undefined.
9e832665 119 */
5e133b8c 120static ucs_char_t pick_one_utf8_char(const char **start, size_t *remainder_p)
9e832665
JS
121{
122 unsigned char *s = (unsigned char *)*start;
28321145 123 ucs_char_t ch;
44b25b87 124 size_t remainder, incr;
9e832665 125
44b25b87
JH
126 /*
127 * A caller that assumes NUL terminated text can choose
128 * not to bother with the remainder length. We will
129 * stop at the first NUL.
130 */
131 remainder = (remainder_p ? *remainder_p : 999);
132
133 if (remainder < 1) {
134 goto invalid;
135 } else if (*s < 0x80) {
9e832665
JS
136 /* 0xxxxxxx */
137 ch = *s;
44b25b87 138 incr = 1;
9e832665
JS
139 } else if ((s[0] & 0xe0) == 0xc0) {
140 /* 110XXXXx 10xxxxxx */
44b25b87
JH
141 if (remainder < 2 ||
142 (s[1] & 0xc0) != 0x80 ||
143 (s[0] & 0xfe) == 0xc0)
9e832665
JS
144 goto invalid;
145 ch = ((s[0] & 0x1f) << 6) | (s[1] & 0x3f);
44b25b87 146 incr = 2;
9e832665
JS
147 } else if ((s[0] & 0xf0) == 0xe0) {
148 /* 1110XXXX 10Xxxxxx 10xxxxxx */
44b25b87
JH
149 if (remainder < 3 ||
150 (s[1] & 0xc0) != 0x80 ||
151 (s[2] & 0xc0) != 0x80 ||
152 /* overlong? */
153 (s[0] == 0xe0 && (s[1] & 0xe0) == 0x80) ||
154 /* surrogate? */
155 (s[0] == 0xed && (s[1] & 0xe0) == 0xa0) ||
156 /* U+FFFE or U+FFFF? */
157 (s[0] == 0xef && s[1] == 0xbf &&
158 (s[2] & 0xfe) == 0xbe))
9e832665
JS
159 goto invalid;
160 ch = ((s[0] & 0x0f) << 12) |
161 ((s[1] & 0x3f) << 6) | (s[2] & 0x3f);
44b25b87 162 incr = 3;
9e832665
JS
163 } else if ((s[0] & 0xf8) == 0xf0) {
164 /* 11110XXX 10XXxxxx 10xxxxxx 10xxxxxx */
44b25b87
JH
165 if (remainder < 4 ||
166 (s[1] & 0xc0) != 0x80 ||
167 (s[2] & 0xc0) != 0x80 ||
168 (s[3] & 0xc0) != 0x80 ||
169 /* overlong? */
170 (s[0] == 0xf0 && (s[1] & 0xf0) == 0x80) ||
171 /* > U+10FFFF? */
172 (s[0] == 0xf4 && s[1] > 0x8f) || s[0] > 0xf4)
9e832665
JS
173 goto invalid;
174 ch = ((s[0] & 0x07) << 18) | ((s[1] & 0x3f) << 12) |
175 ((s[2] & 0x3f) << 6) | (s[3] & 0x3f);
44b25b87 176 incr = 4;
9e832665
JS
177 } else {
178invalid:
179 *start = NULL;
180 return 0;
181 }
182
44b25b87
JH
183 *start += incr;
184 if (remainder_p)
185 *remainder_p = remainder - incr;
396ccf1f
JH
186 return ch;
187}
188
189/*
190 * This function returns the number of columns occupied by the character
191 * pointed to by the variable start. The pointer is updated to point at
44b25b87
JH
192 * the next character. When remainder_p is not NULL, it points at the
193 * location that stores the number of remaining bytes we can use to pick
194 * a character (see pick_one_utf8_char() above).
396ccf1f 195 */
44b25b87 196int utf8_width(const char **start, size_t *remainder_p)
396ccf1f 197{
44b25b87 198 ucs_char_t ch = pick_one_utf8_char(start, remainder_p);
396ccf1f
JH
199 if (!*start)
200 return 0;
b51be13c 201 return git_wcwidth(ch);
9e832665
JS
202}
203
8a9391e9
GT
204/*
205 * Returns the total number of columns required by a null-terminated
206 * string, assuming that the string is utf8. Returns strlen() instead
207 * if the string does not look like a valid utf8 string.
208 */
522cc87f 209int utf8_strnwidth(const char *string, size_t len, int skip_ansi)
8a9391e9
GT
210{
211 int width = 0;
212 const char *orig = string;
213
2bc1e7ec 214 while (string && string < orig + len) {
17d23e8a
PS
215 int glyph_width, skip;
216
2bc1e7ec
NTND
217 while (skip_ansi &&
218 (skip = display_mode_esc_sequence_len(string)) != 0)
219 string += skip;
17d23e8a
PS
220
221 glyph_width = utf8_width(&string, NULL);
222 if (glyph_width > 0)
223 width += glyph_width;
8a9391e9 224 }
2bc1e7ec
NTND
225 return string ? width : len;
226}
227
228int utf8_strwidth(const char *string)
229{
522cc87f 230 return utf8_strnwidth(string, strlen(string), 0);
8a9391e9
GT
231}
232
9e832665
JS
233int is_utf8(const char *text)
234{
235 while (*text) {
236 if (*text == '\n' || *text == '\t' || *text == '\r') {
237 text++;
238 continue;
239 }
44b25b87 240 utf8_width(&text, NULL);
9e832665
JS
241 if (!text)
242 return 0;
243 }
244 return 1;
245}
246
37bb5d74
RS
247static void strbuf_add_indented_text(struct strbuf *buf, const char *text,
248 int indent, int indent2)
249{
250 if (indent < 0)
251 indent = 0;
252 while (*text) {
253 const char *eol = strchrnul(text, '\n');
254 if (*eol == '\n')
255 eol++;
3c0ff44a 256 strbuf_addchars(buf, ' ', indent);
68ad5e1e 257 strbuf_add(buf, text, eol - text);
37bb5d74
RS
258 text = eol;
259 indent = indent2;
260 }
261}
262
9e832665
JS
263/*
264 * Wrap the text, if necessary. The variable indent is the indent for the
265 * first line, indent2 is the indent for all other lines.
094e03b0
JS
266 * If indent is negative, assume that already -indent columns have been
267 * consumed (and no extra indent is necessary for the first line).
9e832665 268 */
e0db1765 269void strbuf_add_wrapped_text(struct strbuf *buf,
462749b7 270 const char *text, int indent1, int indent2, int width)
9e832665 271{
462749b7
RS
272 int indent, w, assume_utf8 = 1;
273 const char *bol, *space, *start = text;
274 size_t orig_len = buf->len;
9e832665 275
00d39473 276 if (width <= 0) {
462749b7 277 strbuf_add_indented_text(buf, text, indent1, indent2);
e0db1765 278 return;
00d39473
JH
279 }
280
462749b7
RS
281retry:
282 bol = text;
283 w = indent = indent1;
284 space = NULL;
094e03b0
JS
285 if (indent < 0) {
286 w = -indent;
287 space = text;
288 }
289
9e832665 290 for (;;) {
8a3c63e0
RS
291 char c;
292 size_t skip;
293
294 while ((skip = display_mode_esc_sequence_len(text)))
295 text += skip;
296
297 c = *text;
9e832665 298 if (!c || isspace(c)) {
14e1a4e1 299 if (w <= width || !space) {
9e832665 300 const char *start = bol;
ae0b2702 301 if (!c && text == start)
e0db1765 302 return;
9e832665
JS
303 if (space)
304 start = space;
305 else
3c0ff44a 306 strbuf_addchars(buf, ' ', indent);
68ad5e1e 307 strbuf_add(buf, start, text - start);
094e03b0 308 if (!c)
e0db1765 309 return;
9e832665 310 space = text;
ae0b2702
JS
311 if (c == '\t')
312 w |= 0x07;
313 else if (c == '\n') {
314 space++;
315 if (*space == '\n') {
68ad5e1e 316 strbuf_addch(buf, '\n');
ae0b2702
JS
317 goto new_line;
318 }
319 else if (!isalnum(*space))
320 goto new_line;
321 else
68ad5e1e 322 strbuf_addch(buf, ' ');
ae0b2702 323 }
9e832665
JS
324 w++;
325 text++;
326 }
327 else {
ae0b2702 328new_line:
68ad5e1e 329 strbuf_addch(buf, '\n');
62273826 330 text = bol = space + isspace(*space);
9e832665
JS
331 space = NULL;
332 w = indent = indent2;
333 }
334 continue;
335 }
462749b7 336 if (assume_utf8) {
44b25b87 337 w += utf8_width(&text, NULL);
462749b7
RS
338 if (!text) {
339 assume_utf8 = 0;
340 text = start;
341 strbuf_setlen(buf, orig_len);
342 goto retry;
343 }
344 } else {
9e832665
JS
345 w++;
346 text++;
347 }
348 }
349}
b45974a6 350
e0db1765 351void strbuf_add_wrapped_bytes(struct strbuf *buf, const char *data, int len,
98acc837
JK
352 int indent, int indent2, int width)
353{
354 char *tmp = xstrndup(data, len);
e0db1765 355 strbuf_add_wrapped_text(buf, tmp, indent, indent2, width);
98acc837 356 free(tmp);
98acc837
JK
357}
358
a7f01c6b
NTND
359void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,
360 const char *subst)
361{
362 struct strbuf sb_dst = STRBUF_INIT;
363 char *src = sb_src->buf;
364 char *end = src + sb_src->len;
365 char *dst;
366 int w = 0, subst_len = 0;
367
368 if (subst)
369 subst_len = strlen(subst);
370 strbuf_grow(&sb_dst, sb_src->len + subst_len);
371 dst = sb_dst.buf;
372
373 while (src < end) {
374 char *old;
375 size_t n;
376
377 while ((n = display_mode_esc_sequence_len(src))) {
378 memcpy(dst, src, n);
379 src += n;
380 dst += n;
381 }
382
43087596
NTND
383 if (src >= end)
384 break;
385
a7f01c6b
NTND
386 old = src;
387 n = utf8_width((const char**)&src, NULL);
388 if (!src) /* broken utf-8, do nothing */
9a012bf3 389 goto out;
a7f01c6b
NTND
390 if (n && w >= pos && w < pos + width) {
391 if (subst) {
392 memcpy(dst, subst, subst_len);
393 dst += subst_len;
394 subst = NULL;
395 }
396 w += n;
397 continue;
398 }
399 memcpy(dst, old, src - old);
400 dst += src - old;
401 w += n;
402 }
403 strbuf_setlen(&sb_dst, dst - sb_dst.buf);
980419b9 404 strbuf_swap(sb_src, &sb_dst);
9a012bf3 405out:
980419b9 406 strbuf_release(&sb_dst);
a7f01c6b
NTND
407}
408
2f0c4a36
LS
409/*
410 * Returns true (1) if the src encoding name matches the dst encoding
411 * name directly or one of its alternative names. E.g. UTF-16BE is the
412 * same as UTF16BE.
413 */
414static int same_utf_encoding(const char *src, const char *dst)
415{
89f8caba
RS
416 if (skip_iprefix(src, "utf", &src) && skip_iprefix(dst, "utf", &dst)) {
417 skip_prefix(src, "-", &src);
418 skip_prefix(dst, "-", &dst);
419 return !strcasecmp(src, dst);
2f0c4a36
LS
420 }
421 return 0;
422}
423
677cfed5
JH
424int is_encoding_utf8(const char *name)
425{
426 if (!name)
427 return 1;
2f0c4a36 428 if (same_utf_encoding("utf-8", name))
677cfed5
JH
429 return 1;
430 return 0;
431}
432
0e18bcd5
JH
433int same_encoding(const char *src, const char *dst)
434{
2f0c4a36
LS
435 static const char utf8[] = "UTF-8";
436
437 if (!src)
438 src = utf8;
439 if (!dst)
440 dst = utf8;
441 if (same_utf_encoding(src, dst))
0e18bcd5
JH
442 return 1;
443 return !strcasecmp(src, dst);
444}
445
c0821965
JX
446/*
447 * Wrapper for fprintf and returns the total number of columns required
448 * for the printed string, assuming that the string is utf8.
449 */
450int utf8_fprintf(FILE *stream, const char *format, ...)
451{
452 struct strbuf buf = STRBUF_INIT;
453 va_list arg;
454 int columns;
455
456 va_start(arg, format);
457 strbuf_vaddf(&buf, format, arg);
458 va_end(arg);
459
460 columns = fputs(buf.buf, stream);
461 if (0 <= columns) /* keep the error from the I/O */
462 columns = utf8_strwidth(buf.buf);
463 strbuf_release(&buf);
464 return columns;
465}
466
b45974a6
JH
467/*
468 * Given a buffer and its encoding, return it re-encoded
469 * with iconv. If the conversion fails, returns NULL.
470 */
471#ifndef NO_ICONV
309dbc82 472#if defined(OLD_ICONV) || (defined(__sun__) && !defined(_XPG6))
fd547a97
RJ
473 typedef const char * iconv_ibp;
474#else
475 typedef char * iconv_ibp;
476#endif
aab2a1ae
TB
477char *reencode_string_iconv(const char *in, size_t insz, iconv_t conv,
478 size_t bom_len, size_t *outsz_p)
b45974a6 479{
76759c7d 480 size_t outsz, outalloc;
fd547a97
RJ
481 char *out, *outpos;
482 iconv_ibp cp;
b45974a6 483
b45974a6 484 outsz = insz;
aab2a1ae 485 outalloc = st_add(outsz, 1 + bom_len); /* for terminating NUL */
b45974a6 486 out = xmalloc(outalloc);
aab2a1ae 487 outpos = out + bom_len;
fd547a97 488 cp = (iconv_ibp)in;
b45974a6
JH
489
490 while (1) {
491 size_t cnt = iconv(conv, &cp, &insz, &outpos, &outsz);
492
df5213b7 493 if (cnt == (size_t) -1) {
b45974a6
JH
494 size_t sofar;
495 if (errno != E2BIG) {
496 free(out);
b45974a6
JH
497 return NULL;
498 }
499 /* insz has remaining number of bytes.
500 * since we started outsz the same as insz,
501 * it is likely that insz is not enough for
502 * converting the rest.
503 */
504 sofar = outpos - out;
77aa03d6 505 outalloc = st_add3(sofar, st_mult(insz, 2), 32);
b45974a6
JH
506 out = xrealloc(out, outalloc);
507 outpos = out + sofar;
508 outsz = outalloc - sofar - 1;
509 }
510 else {
511 *outpos = '\0';
b782bbab
NTND
512 if (outsz_p)
513 *outsz_p = outpos - out;
b45974a6
JH
514 break;
515 }
516 }
76759c7d
TB
517 return out;
518}
519
3270741e
JH
520static const char *fallback_encoding(const char *name)
521{
522 /*
523 * Some platforms do not have the variously spelled variants of
524 * UTF-8, so let's fall back to trying the most official
525 * spelling. We do so only as a fallback in case the platform
526 * does understand the user's spelling, but not our official
527 * one.
528 */
529 if (is_encoding_utf8(name))
530 return "UTF-8";
531
df375588
JH
532 /*
533 * Even though latin-1 is still seen in e-mail
534 * headers, some platforms only install ISO-8859-1.
535 */
536 if (!strcasecmp(name, "latin-1"))
537 return "ISO-8859-1";
538
3270741e
JH
539 return name;
540}
541
c7d017d7 542char *reencode_string_len(const char *in, size_t insz,
b782bbab 543 const char *out_encoding, const char *in_encoding,
c7d017d7 544 size_t *outsz)
76759c7d
TB
545{
546 iconv_t conv;
547 char *out;
aab2a1ae
TB
548 const char *bom_str = NULL;
549 size_t bom_len = 0;
76759c7d
TB
550
551 if (!in_encoding)
552 return NULL;
5c680be1 553
aab2a1ae
TB
554 /* UTF-16LE-BOM is the same as UTF-16 for reading */
555 if (same_utf_encoding("UTF-16LE-BOM", in_encoding))
556 in_encoding = "UTF-16";
557
558 /*
559 * For writing, UTF-16 iconv typically creates "UTF-16BE-BOM"
560 * Some users under Windows want the little endian version
79444c92 561 *
562 * We handle UTF-16 and UTF-32 ourselves only if the platform does not
563 * provide a BOM (which we require), since we want to match the behavior
564 * of the system tools and libc as much as possible.
aab2a1ae
TB
565 */
566 if (same_utf_encoding("UTF-16LE-BOM", out_encoding)) {
567 bom_str = utf16_le_bom;
568 bom_len = sizeof(utf16_le_bom);
569 out_encoding = "UTF-16LE";
570 } else if (same_utf_encoding("UTF-16BE-BOM", out_encoding)) {
571 bom_str = utf16_be_bom;
572 bom_len = sizeof(utf16_be_bom);
573 out_encoding = "UTF-16BE";
79444c92 574#ifdef ICONV_OMITS_BOM
575 } else if (same_utf_encoding("UTF-16", out_encoding)) {
576 bom_str = utf16_be_bom;
577 bom_len = sizeof(utf16_be_bom);
578 out_encoding = "UTF-16BE";
579 } else if (same_utf_encoding("UTF-32", out_encoding)) {
580 bom_str = utf32_be_bom;
581 bom_len = sizeof(utf32_be_bom);
582 out_encoding = "UTF-32BE";
583#endif
aab2a1ae
TB
584 }
585
76759c7d 586 conv = iconv_open(out_encoding, in_encoding);
5c680be1 587 if (conv == (iconv_t) -1) {
3270741e
JH
588 in_encoding = fallback_encoding(in_encoding);
589 out_encoding = fallback_encoding(out_encoding);
590
5c680be1
JK
591 conv = iconv_open(out_encoding, in_encoding);
592 if (conv == (iconv_t) -1)
593 return NULL;
594 }
aab2a1ae 595 out = reencode_string_iconv(in, insz, conv, bom_len, outsz);
b45974a6 596 iconv_close(conv);
aab2a1ae
TB
597 if (out && bom_str && bom_len)
598 memcpy(out, bom_str, bom_len);
b45974a6
JH
599 return out;
600}
601#endif
6cd3c053 602
10ecb82e
LS
603static int has_bom_prefix(const char *data, size_t len,
604 const char *bom, size_t bom_len)
605{
606 return data && bom && (len >= bom_len) && !memcmp(data, bom, bom_len);
607}
608
10ecb82e
LS
609int has_prohibited_utf_bom(const char *enc, const char *data, size_t len)
610{
611 return (
612 (same_utf_encoding("UTF-16BE", enc) ||
613 same_utf_encoding("UTF-16LE", enc)) &&
614 (has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
615 has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
616 ) || (
617 (same_utf_encoding("UTF-32BE", enc) ||
618 same_utf_encoding("UTF-32LE", enc)) &&
619 (has_bom_prefix(data, len, utf32_be_bom, sizeof(utf32_be_bom)) ||
620 has_bom_prefix(data, len, utf32_le_bom, sizeof(utf32_le_bom)))
621 );
622}
623
c6e48652
LS
624int is_missing_required_utf_bom(const char *enc, const char *data, size_t len)
625{
626 return (
627 (same_utf_encoding(enc, "UTF-16")) &&
628 !(has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
629 has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
630 ) || (
631 (same_utf_encoding(enc, "UTF-32")) &&
632 !(has_bom_prefix(data, len, utf32_be_bom, sizeof(utf32_be_bom)) ||
633 has_bom_prefix(data, len, utf32_le_bom, sizeof(utf32_le_bom)))
634 );
635}
636
6cd3c053
KS
637/*
638 * Returns first character length in bytes for multi-byte `text` according to
639 * `encoding`.
640 *
641 * - The `text` pointer is updated to point at the next character.
642 * - When `remainder_p` is not NULL, on entry `*remainder_p` is how much bytes
643 * we can consume from text, and on exit `*remainder_p` is reduced by returned
644 * character length. Otherwise `text` is treated as limited by NUL.
645 */
646int mbs_chrlen(const char **text, size_t *remainder_p, const char *encoding)
647{
648 int chrlen;
649 const char *p = *text;
650 size_t r = (remainder_p ? *remainder_p : SIZE_MAX);
651
652 if (r < 1)
653 return 0;
654
655 if (is_encoding_utf8(encoding)) {
656 pick_one_utf8_char(&p, &r);
657
658 chrlen = p ? (p - *text)
659 : 1 /* not valid UTF-8 -> raw byte sequence */;
660 }
661 else {
662 /*
663 * TODO use iconv to decode one char and obtain its chrlen
664 * for now, let's treat encodings != UTF-8 as one-byte
665 */
666 chrlen = 1;
667 }
668
669 *text += chrlen;
670 if (remainder_p)
671 *remainder_p -= chrlen;
672
673 return chrlen;
674}
6162a1d3
JK
675
676/*
6aaf956b
JK
677 * Pick the next char from the stream, ignoring codepoints an HFS+ would.
678 * Note that this is _not_ complete by any means. It's just enough
6162a1d3
JK
679 * to make is_hfs_dotgit() work, and should not be used otherwise.
680 */
681static ucs_char_t next_hfs_char(const char **in)
682{
683 while (1) {
684 ucs_char_t out = pick_one_utf8_char(in, NULL);
685 /*
686 * check for malformed utf8. Technically this
687 * gets converted to a percent-sequence, but
688 * returning 0 is good enough for is_hfs_dotgit
689 * to realize it cannot be .git
690 */
691 if (!*in)
692 return 0;
693
694 /* these code points are ignored completely */
695 switch (out) {
696 case 0x200c: /* ZERO WIDTH NON-JOINER */
697 case 0x200d: /* ZERO WIDTH JOINER */
698 case 0x200e: /* LEFT-TO-RIGHT MARK */
699 case 0x200f: /* RIGHT-TO-LEFT MARK */
700 case 0x202a: /* LEFT-TO-RIGHT EMBEDDING */
701 case 0x202b: /* RIGHT-TO-LEFT EMBEDDING */
702 case 0x202c: /* POP DIRECTIONAL FORMATTING */
703 case 0x202d: /* LEFT-TO-RIGHT OVERRIDE */
704 case 0x202e: /* RIGHT-TO-LEFT OVERRIDE */
705 case 0x206a: /* INHIBIT SYMMETRIC SWAPPING */
706 case 0x206b: /* ACTIVATE SYMMETRIC SWAPPING */
707 case 0x206c: /* INHIBIT ARABIC FORM SHAPING */
708 case 0x206d: /* ACTIVATE ARABIC FORM SHAPING */
709 case 0x206e: /* NATIONAL DIGIT SHAPES */
710 case 0x206f: /* NOMINAL DIGIT SHAPES */
711 case 0xfeff: /* ZERO WIDTH NO-BREAK SPACE */
712 continue;
713 }
714
6aaf956b 715 return out;
6162a1d3
JK
716 }
717}
718
0fc333ba
JK
719static int is_hfs_dot_generic(const char *path,
720 const char *needle, size_t needle_len)
6162a1d3
JK
721{
722 ucs_char_t c;
723
6aaf956b
JK
724 c = next_hfs_char(&path);
725 if (c != '.')
726 return 0;
6aaf956b
JK
727
728 /*
729 * there's a great deal of other case-folding that occurs
0fc333ba
JK
730 * in HFS+, but this is enough to catch our fairly vanilla
731 * hard-coded needles.
6aaf956b 732 */
0fc333ba
JK
733 for (; needle_len > 0; needle++, needle_len--) {
734 c = next_hfs_char(&path);
735
736 /*
737 * We know our needles contain only ASCII, so we clamp here to
738 * make the results of tolower() sane.
739 */
740 if (c > 127)
741 return 0;
742 if (tolower(c) != *needle)
743 return 0;
744 }
745
6162a1d3
JK
746 c = next_hfs_char(&path);
747 if (c && !is_dir_sep(c))
748 return 0;
749
750 return 1;
751}
dde843e7 752
0fc333ba
JK
753/*
754 * Inline wrapper to make sure the compiler resolves strlen() on literals at
755 * compile time.
756 */
757static inline int is_hfs_dot_str(const char *path, const char *needle)
758{
759 return is_hfs_dot_generic(path, needle, strlen(needle));
760}
761
762int is_hfs_dotgit(const char *path)
763{
764 return is_hfs_dot_str(path, "git");
765}
766
767int is_hfs_dotgitmodules(const char *path)
768{
769 return is_hfs_dot_str(path, "gitmodules");
770}
771
772int is_hfs_dotgitignore(const char *path)
773{
774 return is_hfs_dot_str(path, "gitignore");
775}
776
777int is_hfs_dotgitattributes(const char *path)
778{
779 return is_hfs_dot_str(path, "gitattributes");
780}
781
dde843e7
JH
782const char utf8_bom[] = "\357\273\277";
783
784int skip_utf8_bom(char **text, size_t len)
785{
786 if (len < strlen(utf8_bom) ||
787 memcmp(*text, utf8_bom, strlen(utf8_bom)))
788 return 0;
789 *text += strlen(utf8_bom);
790 return 1;
791}
110dcda5
KN
792
793void strbuf_utf8_align(struct strbuf *buf, align_type position, unsigned int width,
794 const char *s)
795{
522cc87f 796 size_t slen = strlen(s);
110dcda5
KN
797 int display_len = utf8_strnwidth(s, slen, 0);
798 int utf8_compensation = slen - display_len;
799
800 if (display_len >= width) {
801 strbuf_addstr(buf, s);
802 return;
803 }
804
805 if (position == ALIGN_LEFT)
806 strbuf_addf(buf, "%-*s", width + utf8_compensation, s);
807 else if (position == ALIGN_MIDDLE) {
808 int left = (width - display_len) / 2;
809 strbuf_addf(buf, "%*s%-*s", left, "", width - left + utf8_compensation, s);
810 } else if (position == ALIGN_RIGHT)
811 strbuf_addf(buf, "%*s", width + utf8_compensation, s);
812}