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