Skip to content

StrPatchFmt

Description

Patch existing bytes in out starting at offset. The formatted content must fit within the current StrLen(out); the buffer is not grown. Useful for back-patching placeholder fields after later data has been computed.

Success

Bytes [offset, offset + written) of out are replaced; returns true.

Failure

Returns false if the formatted output would extend past StrLen(out). out is left unchanged.

Usage example (Cross-references)

Usage examples (Cross-references)
            if (offset > StrLen(o) || StrLen(&tmp) > StrLen(o) - offset) {
                LOG_ERROR(
                    "StrPatchFmt: write of {} bytes at offset {} exceeds str length {}",
                    StrLen(&tmp),
                    offset,
        StrAppendFmt(&s, "AAAAAAAA");
        size before_length = StrLen(&s);
        bool ok            = StrPatchFmt(&s, 2, "{}", LVAL(1234));
        ok                 = ok && StrLen(&s) == before_length;
        ok                 = ok && StrBegin(&s)[0] == 'A' && StrBegin(&s)[1] == 'A';
    
        // Patch that would extend past the end must fail.
        ok = ok && !StrPatchFmt(&s, 6, "{}", LVAL(9999));
        ok = ok && StrLen(&s) == before_length;
        ok = ok && StrBegin(&s)[6] == 'A' && StrBegin(&s)[7] == 'A';
        // "AB{" pushes "AB" into the scratch then hits an unclosed spec ->
        // str_append_fmt returns false.
        bool r = StrPatchFmt(&o, 0, "AB{");
    
        bool ok = (r == false) && (ZstrCompare(StrBegin(&o), "-----") == 0);
        Str              o     = StrInitFromZstr("hello", &alloc);
    
        bool r = StrPatchFmt(&o, StrLen(&o), ""); // offset == length, empty render
    
        bool ok = (r == true) && (ZstrCompare(StrBegin(&o), "hello") == 0);
        Str              o     = StrInitFromZstr("-----", &alloc); // length 5
    
        bool r = StrPatchFmt(&o, 0, "12345");                      // renders exactly 5 chars
    
        bool ok = (r == true) && (ZstrCompare(StrBegin(&o), "12345") == 0);
        StrAppendFmt(&s, "AAAAAAAA");
        size before = StrLen(&s);
        ok          = ok && StrPatchFmt(&s, 2, "{}", LVAL(1234));
        ok          = ok && (StrLen(&s) == before);
        ok          = ok && StrBegin(&s)[2] == '1' && StrBegin(&s)[5] == '4';
Last updated on