]>
git.saurik.com Git - apple/icu.git/blob - icuSources/i18n/csrutf8.cpp
2 **********************************************************************
3 * Copyright (C) 2005-2012, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 **********************************************************************
8 #include "unicode/utypes.h"
10 #if !UCONFIG_NO_CONVERSION
17 CharsetRecog_UTF8::~CharsetRecog_UTF8()
22 const char *CharsetRecog_UTF8::getName() const
27 UBool
CharsetRecog_UTF8::match(InputText
* input
, CharsetMatch
*results
) const {
30 int32_t numInvalid
= 0;
31 const uint8_t *inputBytes
= input
->fRawInput
;
33 int32_t trailBytes
= 0;
36 if (input
->fRawLength
>= 3 &&
37 inputBytes
[0] == 0xEF && inputBytes
[1] == 0xBB && inputBytes
[2] == 0xBF) {
41 // Scan for multi-byte sequences
42 for (i
=0; i
< input
->fRawLength
; i
+= 1) {
43 int32_t b
= inputBytes
[i
];
45 if ((b
& 0x80) == 0) {
49 // Hi bit on char found. Figure out how long the sequence should be
50 if ((b
& 0x0E0) == 0x0C0) {
52 } else if ((b
& 0x0F0) == 0x0E0) {
54 } else if ((b
& 0x0F8) == 0xF0) {
66 // Verify that we've got the right number of trail bytes in the sequence
70 if (i
>= input
->fRawLength
) {
76 if ((b
& 0xC0) != 0x080) {
81 if (--trailBytes
== 0) {
89 // Cook up some sort of confidence score, based on presense of a BOM
90 // and the existence of valid and/or invalid multi-byte sequences.
92 if (hasBOM
&& numInvalid
== 0) {
94 } else if (hasBOM
&& numValid
> numInvalid
*10) {
96 } else if (numValid
> 3 && numInvalid
== 0) {
98 } else if (numValid
> 0 && numInvalid
== 0) {
100 } else if (numValid
== 0 && numInvalid
== 0) {
103 } else if (numValid
> numInvalid
*10) {
104 // Probably corruput utf-8 data. Valid sequences aren't likely by chance.
108 results
->set(input
, this, confidence
);
109 return (confidence
> 0);