]>
git.saurik.com Git - apple/icu.git/blob - icuSources/i18n/csrutf8.cpp
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 **********************************************************************
5 * Copyright (C) 2005-2014, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 **********************************************************************
10 #include "unicode/utypes.h"
12 #if !UCONFIG_NO_CONVERSION
19 CharsetRecog_UTF8::~CharsetRecog_UTF8()
24 const char *CharsetRecog_UTF8::getName() const
29 UBool
CharsetRecog_UTF8::match(InputText
* input
, CharsetMatch
*results
) const {
32 int32_t numInvalid
= 0;
33 const uint8_t *inputBytes
= input
->fRawInput
;
35 int32_t trailBytes
= 0;
38 if (input
->fRawLength
>= 3 &&
39 inputBytes
[0] == 0xEF && inputBytes
[1] == 0xBB && inputBytes
[2] == 0xBF) {
43 // Scan for multi-byte sequences
44 for (i
=0; i
< input
->fRawLength
; i
+= 1) {
45 int32_t b
= inputBytes
[i
];
47 if ((b
& 0x80) == 0) {
51 // Hi bit on char found. Figure out how long the sequence should be
52 if ((b
& 0x0E0) == 0x0C0) {
54 } else if ((b
& 0x0F0) == 0x0E0) {
56 } else if ((b
& 0x0F8) == 0xF0) {
63 // Verify that we've got the right number of trail bytes in the sequence
67 if (i
>= input
->fRawLength
) {
73 if ((b
& 0xC0) != 0x080) {
78 if (--trailBytes
== 0) {
86 // Cook up some sort of confidence score, based on presence of a BOM
87 // and the existence of valid and/or invalid multi-byte sequences.
89 if (hasBOM
&& numInvalid
== 0) {
91 } else if (hasBOM
&& numValid
> numInvalid
*10) {
93 } else if (numValid
> 3 && numInvalid
== 0) {
95 } else if (numValid
> 0 && numInvalid
== 0) {
97 } else if (numValid
== 0 && numInvalid
== 0) {
98 // Plain ASCII. Confidence must be > 10, it's more likely than UTF-16, which
99 // accepts ASCII with confidence = 10.
101 } else if (numValid
> numInvalid
*10) {
102 // Probably corruput utf-8 data. Valid sequences aren't likely by chance.
106 results
->set(input
, this, confidence
);
107 return (confidence
> 0);