Skip to content

BufPatchFmt

Description

Overwrite existing bytes of buf starting at offset. The encoded output must fit within the current BufLength(buf); the buffer is not grown. Useful for back-patching placeholder fields (lengths, checksums) after the payload they describe has been built.

Success

Returns true; bytes [offset, offset + written) of buf are replaced.

Failure

Returns false on format-parse error or if the encoded output would extend past BufLength(buf). On overflow, buf is left unchanged.

Usage example (Cross-references)

Usage examples (Cross-references)
            if (offset > BufLength(out) || StrLen(&tmp) > BufLength(out) - offset) {
                LOG_ERROR(
                    "BufPatchFmt: write of {} bytes at offset {} exceeds buf length {}",
                    StrLen(&tmp),
                    offset,
        BufWriteU64LE(&b, 0x1122334455667788ull);
        // Patch the placeholder with the real value.
        bool     ok       = BufPatchFmt(&b, 0, "{<4r}", (u32)0xCAFEBABE);
        const u8 expect[] = {
            0xBE,
        Buf snapshot = BufInit(&alloc);
        BufPushBytes(&snapshot, BufData(&b), BufLength(&b));
        ok = ok && !BufPatchFmt(&b, BufLength(&b), "{<2r}", (u16)0);
        ok = ok && BufLength(&b) == BufLength(&snapshot);
        ok = ok && MemCompare(BufData(&b), BufData(&snapshot), BufLength(&b)) == 0;
    
        // u32 LE 0x11223344 -> bytes 44 33 22 11 at [4,8).
        ok = ok && BufPatchFmt(&b, 4, "{<4r}", (u32)0x11223344);
        ok = ok && (BufLength(&b) == 8);
        {
    
        // Empty format renders zero bytes; offset 8 == BufLength.
        ok = ok && BufPatchFmt(&b, 8, "");
        ok = ok && (BufLength(&b) == 8);
        {
    
        // {<2r}{<4r} renders 2 + 4 = 6 bytes at offset 4 -> needs [4,10), past end.
        bool rc = BufPatchFmt(&b, 4, "{<2r}{<4r}", (u16)0xBEEF, (u32)0xDEADC0DE);
        ok      = ok && (rc == false);
        ok      = ok && (BufLength(&b) == 8);
Last updated on