MCPcopy Create free account
hub / github.com/Acode-Foundation/Acode / detectEncoding

Function detectEncoding

src/utils/encodings.js:92–152  ·  view source on GitHub ↗
(buffer)

Source from the content-addressed store, hash-verified

90}
91
92export async function detectEncoding(buffer) {
93 if (!buffer || buffer.byteLength === 0) {
94 const def = settings.value.defaultFileEncoding;
95 return def === "auto" ? "UTF-8" : def || "UTF-8";
96 }
97
98 const bytes = new Uint8Array(buffer);
99
100 const bomEncoding = detectBOM(bytes);
101 if (bomEncoding) return bomEncoding;
102
103 const sample = bytes.subarray(0, Math.min(2048, bytes.length));
104 let nulls = 0,
105 ascii = 0;
106
107 for (const byte of sample) {
108 if (byte === 0) nulls++;
109 else if (byte < 0x80) ascii++;
110 }
111
112 if (nulls > sample.length * 0.3) return "UTF-16LE";
113
114 if (isValidUTF8(sample)) return "UTF-8";
115
116 const encodings = [
117 ...new Set([
118 "UTF-8",
119 settings.value.defaultFileEncoding === "auto"
120 ? "UTF-8"
121 : settings.value.defaultFileEncoding || "UTF-8",
122 "windows-1252",
123 "ISO-8859-1",
124 ]),
125 ];
126
127 const testSample = sample.subarray(0, 512);
128 const testBuffer = testSample.buffer.slice(
129 testSample.byteOffset,
130 testSample.byteOffset + testSample.byteLength,
131 );
132
133 for (const encoding of encodings) {
134 try {
135 const encodingObj = getEncoding(encoding);
136 if (!encodingObj) continue;
137
138 const text = await execDecode(testBuffer, encodingObj.name);
139 if (
140 !text.includes("\uFFFD") &&
141 !/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(text)
142 ) {
143 return encoding;
144 }
145 } catch (error) {
146 continue;
147 }
148 }
149

Callers 1

openFile.jsFile · 0.90

Calls 4

detectBOMFunction · 0.85
isValidUTF8Function · 0.85
getEncodingFunction · 0.85
execDecodeFunction · 0.85

Tested by

no test coverage detected