Skip to content

[Feature request] Moving a known length cstr to a string_t without using memcpy? #141

@F3llFr0mTh3Sky

Description

@F3llFr0mTh3Sky

Hello @P-p-H-d, I'd like to know if the following code is valid:

// FIXME Does it works???
string_s *string_create_steal_cstr_ptr(char *data, const size_t len) {
    if (data == NULL) {
        return NULL;
    }

    // It might look like an useless test but it isn't.
    if (data[len - 1] != '\0') {
        return NULL;
    }

    // FIXME Ensure str is correctly allocated on heap.
    string_s *str = (string_s *) malloc(sizeof(struct string_s));

    // FIXME Init the string_t or not???
    //string_init(*str);

    if (str == NULL) {
        // FIXME Proper error management, try using throw catch exception if possible.
        return NULL;
    }

    size_t offset = sizeof(m_str1ng_size_t);

    str->u.heap.alloc[offset-2] = 1;
    str->u.heap.alloc[offset-1] = 31;
    str->u.heap.size = len - 1,
    str->u.heap.ptr = (
        (
            struct {
                long long _n;
                // FIXME Use char *_d, char _d[sizeof(data)] or char _d[len] ???
                //char _d[sizeof(data)];
                //char _d[len];
                char *_d;
            }
        ) {
            ._n=0,
            ._d=data
        }
    )._d;

    return str;
}

In case yes, could you add such a feature to m*lib?

It would allow me to bypass using memcpy and strlen in some use cases of your library string_t structs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions