MCPcopy Create free account
hub / github.com/scriptscat/scriptcat / getEncoding

Function getEncoding

src/pkg/utils/istextorbinary.ts:35–97  ·  view source on GitHub ↗

* Get the encoding of a buffer. * Checks the start, middle, and end of the buffer for characters that are unrecognized within UTF8 encoding. * History has shown that inspection at all three locations is necessary. * @returns Will be `null` if `buffer` was not provided. Otherwise will be either `'

(buffer: Uint8Array, opts?: EncodingOpts)

Source from the content-addressed store, hash-verified

33 * @returns Will be `null` if `buffer` was not provided. Otherwise will be either `'utf8'` or `'binary'`
34 */
35function getEncoding(buffer: Uint8Array, opts?: EncodingOpts): "utf8" | "binary" | null {
36 // Check
37 if (!buffer) return null;
38
39 // Prepare
40 const textEncoding = "utf8";
41 const binaryEncoding = "binary";
42 const chunkLength = opts?.chunkLength ?? 24;
43 let chunkBegin = opts?.chunkBegin ?? 0;
44
45 // Discover
46 if (opts?.chunkBegin === undefined) {
47 // Start
48 let encoding = getEncoding(buffer, { chunkLength, chunkBegin });
49 if (encoding === textEncoding) {
50 // Middle
51 chunkBegin = Math.max(0, Math.floor(buffer.length / 2) - chunkLength);
52 encoding = getEncoding(buffer, {
53 chunkLength,
54 chunkBegin,
55 });
56 if (encoding === textEncoding) {
57 // End
58 chunkBegin = Math.max(0, buffer.length - chunkLength);
59 encoding = getEncoding(buffer, {
60 chunkLength,
61 chunkBegin,
62 });
63 }
64 }
65
66 // Return
67 return encoding;
68 } else {
69 // Extract
70 chunkBegin = getChunkBegin(buffer, chunkBegin);
71 if (chunkBegin === -1) {
72 return binaryEncoding;
73 }
74
75 const chunkEnd = getChunkEnd(buffer, Math.min(buffer.length, chunkBegin + chunkLength));
76
77 if (chunkEnd > buffer.length) {
78 return binaryEncoding;
79 }
80
81 const contentChunkUTF8 = buffer.slice(chunkBegin, chunkEnd);
82
83 // Detect encoding
84 for (let i = 0; i < contentChunkUTF8.length; ++i) {
85 const charCode = contentChunkUTF8[i];
86 if (charCode === 65533 || charCode <= 8) {
87 // 8 and below are control characters (e.g. backspace, null, eof, etc.)
88 // 65533 is the unknown character
89 // console.log(charCode, contentChunkUTF8[i])
90 return binaryEncoding;
91 }
92 }

Callers 1

isTextFunction · 0.85

Calls 3

getChunkBeginFunction · 0.85
getChunkEndFunction · 0.85
sliceMethod · 0.45

Tested by

no test coverage detected