forked from microsoft/vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoding.ts
More file actions
58 lines (45 loc) · 1.43 KB
/
Copy pathencoding.ts
File metadata and controls
58 lines (45 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import stream = require('vs/base/node/stream');
export var UTF8 = 'utf8';
export var UTF16be = 'utf16be';
export var UTF16le = 'utf16le';
export function detectEncodingByBOMFromBuffer(buffer: NodeBuffer, bytesRead: number): string {
if (!buffer || bytesRead < 2) {
return null;
}
var b0 = buffer.readUInt8(0);
var b1 = buffer.readUInt8(1);
// UTF-16 BE
if (b0 === 0xFE && b1 === 0xFF) {
return UTF16be;
}
// UTF-16 LE
if (b0 === 0xFF && b1 === 0xFE) {
return UTF16le;
}
if (bytesRead < 3) {
return null;
}
var b2 = buffer.readUInt8(2);
// UTF-8
if (b0 === 0xEF && b1 === 0xBB && b2 === 0xBF) {
return UTF8;
}
return null;
};
/**
* Detects the Byte Order Mark in a given file.
* If no BOM is detected, `encoding` will be null.
*/
export function detectEncodingByBOM(file: string, callback: (error: Error, encoding: string) => void): void {
stream.readExactlyByFile(file, 3, (err: Error, buffer: NodeBuffer, bytesRead: number) => {
if (err) {
return callback(err, null);
}
return callback(null, detectEncodingByBOMFromBuffer(buffer, bytesRead));
});
}