Skip to main content

format_magic_message

Function format_magic_message 

Source
pub fn format_magic_message(
    template: &str,
    value: &Value,
    type_kind: &TypeKind,
) -> String
Expand description

Substitute printf-style format specifiers in a magic rule message.

Walks template left to right. Plain text is copied verbatim; on each %, the full specifier (%[flags][width][.precision][length]<conv>) is parsed and substituted from value. %% emits a single %. Unrecognized or malformed specifiers are passed through literally with a debug! log.

type_kind is consulted only for hex specifiers, which need the natural bit width of the underlying read to mask sign-extended values correctly. For non-hex specifiers type_kind is ignored.

ยงExamples

use libmagic_rs::output::format::format_magic_message;
use libmagic_rs::parser::ast::{TypeKind, Value};

let out = format_magic_message(
    "at_offset %lld",
    &Value::Uint(11),
    &TypeKind::Byte { signed: false },
);
assert_eq!(out, "at_offset 11");

let out = format_magic_message(
    "followed_by 0x%02x",
    &Value::Uint(0x31),
    &TypeKind::Byte { signed: false },
);
assert_eq!(out, "followed_by 0x31");

// Unknown specifier falls through literally.
let out = format_magic_message("%q", &Value::Uint(0), &TypeKind::Byte { signed: false });
assert_eq!(out, "%q");

// `%%` is an escaped literal percent.
let out = format_magic_message("100%% sure", &Value::Uint(0), &TypeKind::Byte { signed: false });
assert_eq!(out, "100% sure");