Skip to content

BufAppendFmt

Description

Append encoded bytes to the end of buf. Existing contents are preserved; new bytes land after buf->length. Directives are {<Nr} / {>Nr} with N in {1, 2, 4, 8}.

Success

Returns true; buf extended by exactly the encoded bytes.

Failure

Returns false on format-parse error or grow-buffer failure. buf may be left partially extended.

Usage example (Cross-references)

Usage examples (Cross-references)
        u16 qtype  = (u16)type;
        u16 qclass = 1u;
        return BufAppendFmt(out, "{>2r}{>2r}", qtype, qclass);
    }
        Buf              b     = BufInit(&alloc);
        BufWriteU8(&b, 0x99); // existing byte; append must preserve
        bool     ok       = BufAppendFmt(&b, "{<2r}{>4r}", (u16)0xCAFE, (u32)0xDEADBEEF);
        const u8 expect[] = {0x99, 0xFE, 0xCA, 0xDE, 0xAD, 0xBE, 0xEF};
        ok                = ok && BufLength(&b) == sizeof(expect) && MemCompare(BufData(&b), expect, sizeof(expect)) == 0;
        Buf              b     = BufInit(&alloc);
        // Reserve a 4-byte length placeholder followed by 8 bytes of body.
        BufAppendFmt(&b, "{<4r}", (u32)0);
        BufWriteU64LE(&b, 0x1122334455667788ull);
        // Patch the placeholder with the real value.
        DefaultAllocator alloc = DefaultAllocatorInit();
        Buf              b     = BufInit(&alloc);
        BufAppendFmt(&b, "{<2r}{>4r}{<8r}", (u16)0x1234, (u32)0xDEADBEEF, (u64)0x0102030405060708ull);
    
        BufIter it = BufIterFromBuf(&b);
        DefaultAllocator alloc = DefaultAllocatorInit();
        Buf              b     = BufInit(&alloc);
        BufAppendFmt(&b, "{<2r}", (u16)0xABCD); // only 2 bytes; reader wants 6
    
        BufIter it    = BufIterFromBuf(&b);
Last updated on