2 *******************************************************************************
\r
3 * Copyright (C) 2005 - 2007, International Business Machines Corporation and *
\r
4 * others. All Rights Reserved. *
\r
5 *******************************************************************************
\r
7 package com.ibm.icu.text;
\r
10 * Charset recognizer for UTF-8
\r
14 class CharsetRecog_UTF8 extends CharsetRecognizer {
\r
21 * @see com.ibm.icu.text.CharsetRecognizer#match(com.ibm.icu.text.CharsetDetector)
\r
23 int match(CharsetDetector det) {
\r
24 boolean hasBOM = false;
\r
27 byte input[] = det.fRawInput;
\r
32 if (det.fRawLength >= 3 &&
\r
33 (input[0] & 0xFF) == 0xef && (input[1] & 0xFF) == 0xbb & (input[2] & 0xFF) == 0xbf) {
\r
37 // Scan for multi-byte sequences
\r
38 for (i=0; i<det.fRawLength; i++) {
\r
40 if ((b & 0x80) == 0) {
\r
44 // Hi bit on char found. Figure out how long the sequence should be
\r
45 if ((b & 0x0e0) == 0x0c0) {
\r
47 } else if ((b & 0x0f0) == 0x0e0) {
\r
49 } else if ((b & 0x0f8) == 0xf0) {
\r
53 if (numInvalid > 5) {
\r
59 // Verify that we've got the right number of trail bytes in the sequence
\r
62 if (i>=det.fRawLength) {
\r
66 if ((b & 0xc0) != 0x080) {
\r
70 if (--trailBytes == 0) {
\r
78 // Cook up some sort of confidence score, based on presense of a BOM
\r
79 // and the existence of valid and/or invalid multi-byte sequences.
\r
81 if (hasBOM && numInvalid==0) {
\r
83 } else if (hasBOM && numValid > numInvalid*10) {
\r
85 } else if (numValid > 3 && numInvalid == 0) {
\r
87 } else if (numValid > 0 && numInvalid == 0) {
\r
89 } else if (numValid == 0 && numInvalid == 0) {
\r
92 } else if (numValid > numInvalid*10) {
\r
93 // Probably corruput utf-8 data. Valid sequences aren't likely by chance.
\r