Skip to content
StrTryInitFromCstrAlloc

StrTryInitFromCstrAlloc

Description

Initialize a Str from a C string buffer using an explicit allocator.

Parameters

Name Direction Description
out out Destination string.
cstr in Source character buffer.
len in Number of bytes to copy from cstr.
alloc in Allocator to bind to out.

Success

Returns true. *out is initialized: length is len, the first len bytes are a copy of cstr, capacity is at least len + 1 (for the implicit terminator slot), and alloc is bound into the string’s allocator.

Failure

Returns false on allocation failure for the byte buffer. *out is left as an initialized-but-empty Str so the caller can safely deinit it.

Usage example (Cross-references)

Usage examples (Cross-references)
    static Str *string_va_printf(Str *str, const char *fmt, va_list args);
    
    bool StrTryInitFromCstrAlloc(Str *out, const char *cstr, size len, Allocator alloc) {
        if (!out || !cstr) {
            LOG_FATAL("Invalid arguments");
        Str result = StrInit(alloc);
    
        if (!StrTryInitFromCstrAlloc(&result, cstr, len, alloc)) {
            return result;
        }
    #define STR_TRY_INIT_FROM_CSTR_HAS_ARGS(...)                             STR_TRY_INIT_FROM_CSTR_HAS_ARGS_IMPL(__VA_ARGS__, 4, 3, 2, 1, 0)
    #define StrTryInitFromCstr(...)                                          CONCAT(StrTryInitFromCstr_, STR_TRY_INIT_FROM_CSTR_HAS_ARGS(__VA_ARGS__))(__VA_ARGS__)
    #define StrTryInitFromCstr_3(out, cstr, len)                             StrTryInitFromCstrAlloc((out), (cstr), (len), DefaultAllocator())
    #define StrTryInitFromCstr_4(out, cstr, len, alloc)                      StrTryInitFromCstrAlloc((out), (cstr), (len), (alloc))
    #define StrTryInitFromCstr(...)                                          CONCAT(StrTryInitFromCstr_, STR_TRY_INIT_FROM_CSTR_HAS_ARGS(__VA_ARGS__))(__VA_ARGS__)
    #define StrTryInitFromCstr_3(out, cstr, len)                             StrTryInitFromCstrAlloc((out), (cstr), (len), DefaultAllocator())
    #define StrTryInitFromCstr_4(out, cstr, len, alloc)                      StrTryInitFromCstrAlloc((out), (cstr), (len), (alloc))
    
    ///
Last updated on