Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/util/common/hexdump.ts
13397 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
/**
7
* Formats a byte range from a Uint8Array in a hexdump-style format.
8
*
9
* Each line contains:
10
* - An 8-character hex offset
11
* - Up to 16 bytes shown as two-digit hex values (grouped in pairs of 8)
12
* - An ASCII representation where non-printable bytes are shown as '.'
13
*
14
* Example output:
15
* ```
16
* 00000000 4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00 |MZ..............|
17
* 00000010 b8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00 |........@.......|
18
* ```
19
*/
20
export function formatHexdump(data: Uint8Array, startOffset: number = 0, maxBytes?: number): string {
21
const bytesToFormat = maxBytes !== undefined ? Math.min(data.length - startOffset, maxBytes) : data.length - startOffset;
22
if (bytesToFormat <= 0) {
23
return '';
24
}
25
26
const lines: string[] = [];
27
const bytesPerLine = 16;
28
29
for (let i = 0; i < bytesToFormat; i += bytesPerLine) {
30
const offset = startOffset + i;
31
const lineBytes = Math.min(bytesPerLine, bytesToFormat - i);
32
const slice = data.subarray(startOffset + i, startOffset + i + lineBytes);
33
34
// Offset column
35
const offsetStr = offset.toString(16).padStart(8, '0');
36
37
// Hex columns (two groups of 8 bytes)
38
const hexParts: string[] = [];
39
for (let j = 0; j < bytesPerLine; j++) {
40
if (j === 8) {
41
hexParts.push('');
42
}
43
if (j < lineBytes) {
44
hexParts.push(slice[j].toString(16).padStart(2, '0'));
45
} else {
46
hexParts.push(' ');
47
}
48
}
49
const hexStr = hexParts.join(' ');
50
51
// ASCII column
52
let ascii = '';
53
for (let j = 0; j < lineBytes; j++) {
54
const byte = slice[j];
55
ascii += (byte >= 0x20 && byte <= 0x7e) ? String.fromCharCode(byte) : '.';
56
}
57
58
lines.push(`${offsetStr} ${hexStr} |${ascii}|`);
59
}
60
61
return lines.join('\n');
62
}
63
64
/**
65
* Returns true if the data appears to be binary content rather than valid text.
66
* Uses the same heuristic as git: the presence of any null byte (0x00) in the
67
* first 8KB indicates binary content.
68
*/
69
export function isBinaryContent(data: Uint8Array): boolean {
70
const checkLength = Math.min(data.length, 8192);
71
for (let i = 0; i < checkLength; i++) {
72
if (data[i] === 0) {
73
return true;
74
}
75
}
76
return false;
77
}
78
79