Files
ImHex-Patterns/patterns/bencode.hexpat
Niketin ee8d2f50b7 pattern/bencode: Various fixes (#393)
* Fix bencode dictionary

When parsing a bencode dictionary, the end character 'e' was never
consumed. This caused a misinterpretation of the character as struct Value of
an unknown type 'e'.

* Fix bencode list

A list was not included in the Value's parsing logic so it may have
been mistakenly parsed as a string.

* Fix std::ctype::isprint not including space

The space character, 0x20, is considered as a printable character in ASCII
and in >=C89. Adding it to the range of std::ctype::isprint also fixes
other std::ctype functions that use it.

* Fix bencode byte string formatting

Byte strings do not render nicely in pattern data's value column if they
contain non-printable characters. This commit makes the value of byte
strings to be surrounded by quotation marks, and renders a warning text
without quotation marks if the byte string contains non-printable
characters.
2025-05-10 13:34:36 +02:00

86 lines
1.7 KiB
Rust

#pragma author WerWolv
#pragma description Torrent data (Bencode)
#pragma MIME application/x-bittorrent
import std.ctype;
import std.mem;
import std.string;
namespace bencode {
struct ASCIIDecimal {
char value[while(std::ctype::isdigit(std::mem::read_unsigned($, 1)))];
} [[sealed, format("bencode::format_ascii_decimal"), transform("bencode::format_ascii_decimal")]];
fn format_ascii_decimal(ASCIIDecimal adsasd) {
return std::string::parse_int(adsasd.value, 10);
};
enum Type : u8 {
Integer = 'i',
Dictionary = 'd',
List = 'l',
String0 = '0',
String1 = '1',
String2 = '2',
String3 = '3',
String4 = '4',
String5 = '5',
String6 = '6',
String7 = '7',
String8 = '8',
String9 = '9'
};
struct String {
ASCIIDecimal length;
char separator [[hidden]];
char value[length];
} [[sealed, format("bencode::format_string")]];
fn format_string(String string) {
for (u64 i = 0, i < string.length, i = i + 1) {
if (!std::ctype::isprint(string.value[i])) {
return "Contains non-printable characters";
}
}
return std::format("\"{}\"", string.value);
};
using Bencode;
using Value;
struct DictionaryEntry {
String key;
Value value;
};
struct Value {
Type type;
if (type == Type::Dictionary) {
DictionaryEntry entry[while(std::mem::read_unsigned($, 1) != 'e')];
char end;
} else if (type == Type::List) {
Value entry[while(std::mem::read_unsigned($, 1) != 'e')];
char end;
} else if (type == Type::Integer) {
ASCIIDecimal value;
char end;
} else {
$ -= 1;
String value;
}
};
struct Bencode {
Value value[while(!std::mem::eof())] [[inline]];
char end;
};
}
bencode::Bencode bencode @ 0x00;