Skip to content

Commit 2f0c4a3

Browse files
larsxschneidergitster
authored andcommitted
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 <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 66b8af3 commit 2f0c4a3

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

utf8.c

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -401,18 +401,40 @@ void strbuf_utf8_replace(struct strbuf *sb_src, int pos, int width,
401401
strbuf_release(&sb_dst);
402402
}
403403

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+
404420
int is_encoding_utf8(const char *name)
405421
{
406422
if (!name)
407423
return 1;
408-
if (!strcasecmp(name, "utf-8") || !strcasecmp(name, "utf8"))
424+
if (same_utf_encoding("utf-8", name))
409425
return 1;
410426
return 0;
411427
}
412428

413429
int same_encoding(const char *src, const char *dst)
414430
{
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))
416438
return 1;
417439
return !strcasecmp(src, dst);
418440
}

0 commit comments

Comments
 (0)