summaryrefslogtreecommitdiff
path: root/Components/DisplayFile/hex.js
blob: f062608526456f15651de5476427eea54465d042 (plain)
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
const chalk = require(__dirname + '/../../MistyCore/node_modules/chalk');

function hexEight(dec) {
    let hex = Math.round(dec).toString(16);
    let zero = "00000000";
    return zero.substring(0, 8 - hex.length) + hex;
}

function fixLength(string, length) {
    let end = " ".repeat(length);
    if (string.length > length) return string.substring(0, length);

    return string + end.substring(0, length - string.length);
}

module.exports = (buffer, color) => {
    let ret = "";
    let lines = buffer.toString("hex").match(/.{1,32}/g).map(i => i.match(/.{1,2}/g).join(" "));

    let byte = 0;
    for (let line of lines) {
        if (color) {
            ret += chalk.gray(hexEight(byte)) + "  " + fixLength(line, 47).split(" ").map((i, _) => {
                if ((_ + 1) % 2 === 1) {
                    return chalk.red(i);
                } else {
                    return chalk.magenta(i);
                }
            }).join(" ") + "  " + chalk.blue(Buffer.from(line.replaceAll(" ", ""), "hex").toString().replace(/[\x00-\x1F]/gm, chalk.gray("."))) + "\n";
        } else {
            ret += hexEight(byte) + "  " + fixLength(line, 47) + "  " + Buffer.from(line.replaceAll(" ", ""), "hex").toString().replace(/[\x00-\x1F]/gm, ".") + "\n";
        }

        byte += line.replaceAll(" ", "").length / 2;
    }

    if (color) {
        ret += chalk.gray(hexEight(byte));
    } else {
        ret += hexEight(byte);
    }

    return ret;
}