utf8: teach same_encoding() alternative UTF encoding names
The function same_encoding() could only recognize alternative names for UTF-8 encodings. Teach it to recognize all kinds of alternative UTF encoding names (e.g. utf16). While we are at it, fix a crash that would occur if same_encoding() was called with a NULL argument and a non-NULL argument. This function is used in a subsequent commit. Signed-off-by: Lars Schneider <larsxschneider@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Lars Schneider committed
Apr 15, 2018 at 20:16 UTC
2f0c4a362c5db677ee392a6a550632bfb22d8319
1 file changed
+24
-2
utf8.c
+24
-2
@@ -401,18 +401,40 @@ out:
401
strbuf_release(&sb_dst);
402
}
403
404
+/*
405
+ * Returns true (1) if the src encoding name matches the dst encoding
406
+ * name directly or one of its alternative names. E.g. UTF-16BE is the
407
+ * same as UTF16BE.
408
+ */
409
+static int same_utf_encoding(const char *src, const char *dst)
410
+{
411
+ if (istarts_with(src, "utf") && istarts_with(dst, "utf")) {
412
+ /* src[3] or dst[3] might be '\0' */
413
+ int i = (src[3] == '-' ? 4 : 3);
414
+ int j = (dst[3] == '-' ? 4 : 3);
415
+ return !strcasecmp(src+i, dst+j);
416
+ }
417
+ return 0;
418
+}
419
+
420
int is_encoding_utf8(const char *name)
421
{
422
if (!name)
423
return 1;
408
- if (!strcasecmp(name, "utf-8") || !strcasecmp(name, "utf8"))
424
+ if (same_utf_encoding("utf-8", name))
425
return 1;
426
return 0;
427
}
428
429
int same_encoding(const char *src, const char *dst)
430
{
415
- if (is_encoding_utf8(src) && is_encoding_utf8(dst))
431
+ static const char utf8[] = "UTF-8";
432
+
433
+ if (!src)
434
+ src = utf8;
435
+ if (!dst)
436
+ dst = utf8;
437
+ if (same_utf_encoding(src, dst))
438
return 1;
439
return !strcasecmp(src, dst);
440
}