News for hackers. Stuff that matters.
Re:Efficient string copying and concatenation in C by kzrdude on Thursday September 12, 2019 @01:14PM (#20953907)
Using size_t as the common solution seems like the way to go.

    struct string { char *data; size_t size; size_t alloc_size; };
    struct string_view { char *data; size_t size; };
And we have the same design that C++ uses.
Re:Efficient string copying and concatenation in C by nneonneo on Thursday September 12, 2019 @02:42PM (#20954847)
C++ implementations sometimes optimize for storing short strings inside the string structure itself. One approach looks something like this on 64-bit machines:

    struct string {
        union {
            struct {
                char *ptr;
                size_t capacity;
            };
            char str[16];
        } data;
        size_t length;
    };
It looks complex, but it’s actually a really nice design because it requires no separate allocation for strings less than 16 bytes long, which is a common case, and the strings are relatively compact. And, it stores a capacity parameter which allows you to know when it’s safe to grow the string without allocating, making it possible to implement efficient repeated concatenation.
Re:Efficient string copying and concatenation in C by billziss on Thursday September 12, 2019 @01:31PM (#20954072)
I do not think I have ever seen a string that needs more than 64K, but then again I do not read whole files in memory in C. (I do in Python.) So this would be wasteful in many cases.

My personal variant uses 32-bits for length and 32-bits for refcount, which aligns well on most platforms, including 64-bit ones.

Something like:

    struct string_header
    {
        int32_t refcnt;
        int32_t length;
        // character content starts here
    };
Given a char pointer to get to the header you must do:

    ((struct string_header *)p)[-1]
Re:Efficient string copying and concatenation in C by papermachete on Thursday September 12, 2019 @03:21PM (#20955316)
>I

>I

>I

There is no 'I' in standard libraries :)

Re:Efficient string copying and concatenation in C by saagarjha on Thursday September 12, 2019 @01:42PM (#20954197)
How would you use the refcount?
Re:Efficient string copying and concatenation in C by billziss on Thursday September 12, 2019 @01:53PM (#20954311)
I use the refcount to avoid copying the string when passing it around. I just refcount it instead.

To clarify this is part of a larger library that includes other memory management machinery, such as autorelease pools, etc.