2 *******************************************************************************
\r
3 * Copyright (C) 2005 - 2010, 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
12 class CharsetRecog_UTF8 extends CharsetRecognizer {
\r
19 * @see com.ibm.icu.text.CharsetRecognizer#match(com.ibm.icu.text.CharsetDetector)
\r
21 int match(CharsetDetector det) {
\r
22 boolean hasBOM = false;
\r
25 byte input[] = det.fRawInput;
\r
30 if (det.fRawLength >= 3 &&
\r
31 (input[0] & 0xFF) == 0xef && (input[1] & 0xFF) == 0xbb & (input[2] & 0xFF) == 0xbf) {
\r
35 // Scan for multi-byte sequences
\r
36 for (i=0; i<det.fRawLength; i++) {
\r
38 if ((b & 0x80) == 0) {
\r
42 // Hi bit on char found. Figure out how long the sequence should be
\r
43 if ((b & 0x0e0) == 0x0c0) {
\r
45 } else if ((b & 0x0f0) == 0x0e0) {
\r
47 } else if ((b & 0x0f8) == 0xf0) {
\r
51 if (numInvalid > 5) {
\r
57 // Verify that we've got the right number of trail bytes in the sequence
\r
60 if (i>=det.fRawLength) {
\r
64 if ((b & 0xc0) != 0x080) {
\r
68 if (--trailBytes == 0) {
\r
76 // Cook up some sort of confidence score, based on presense of a BOM
\r
77 // and the existence of valid and/or invalid multi-byte sequences.
\r
79 if (hasBOM && numInvalid==0) {
\r
81 } else if (hasBOM && numValid > numInvalid*10) {
\r
83 } else if (numValid > 3 && numInvalid == 0) {
\r
85 } else if (numValid > 0 && numInvalid == 0) {
\r
87 } else if (numValid == 0 && numInvalid == 0) {
\r
90 } else if (numValid > numInvalid*10) {
\r
91 // Probably corruput utf-8 data. Valid sequences aren't likely by chance.
\r