2 var Match = require ('../match');
5 * Charset recognizer for UTF-8
7 module.exports = function() {
8 this.name = function() {
11 this.match = function(det) {
16 input = det.fRawInput,
20 if (det.fRawLength >= 3 &&
21 (input[0] & 0xff) == 0xef && (input[1] & 0xff) == 0xbb && (input[2] & 0xff) == 0xbf) {
25 // Scan for multi-byte sequences
26 for (var i = 0; i < det.fRawLength; i++) {
31 // Hi bit on char found. Figure out how long the sequence should be
32 if ((b & 0x0e0) == 0x0c0) {
34 } else if ((b & 0x0f0) == 0x0e0) {
36 } else if ((b & 0x0f8) == 0xf0) {
45 // Verify that we've got the right number of trail bytes in the sequence
48 if (i >= det.fRawLength)
51 if ((input[i] & 0xc0) != 0x080) {
55 if (--trailBytes == 0) {
62 // Cook up some sort of confidence score, based on presense of a BOM
63 // and the existence of valid and/or invalid multi-byte sequences.
65 if (hasBOM && numInvalid == 0)
67 else if (hasBOM && numValid > numInvalid * 10)
69 else if (numValid > 3 && numInvalid == 0)
71 else if (numValid > 0 && numInvalid == 0)
73 else if (numValid == 0 && numInvalid == 0)
76 else if (numValid > numInvalid * 10)
77 // Probably corruput utf-8 data. Valid sequences aren't likely by chance.
82 return new Match(det, this, confidence);