Re: Lacking of a ref-counted string.

On Sat, 23 Aug 2008 09:58:12 -0400
"Havoc Pennington" <hp pobox com> wrote:

> If you're talking about converting existing APIs to refcounted
> strings, that's a very different proposal from just adding some kind
> of refcounted string feature. It would break thousands of apps, or
> else duplicate hundreds of API entry points ...

Personally, I didn't have in mind a change of existing API; simply an
addition of something new:

  typedef struct {
    gchar *str;
    gsize  len;
    gint   refcount;
  } GCString;

  GCString *g_cstring_new_static(gchar *data);
  GCString *g_cstring_new_from_gstring(GString *clone);

  GCString *g_cstring_ref(GCString *str);
  void      g_cstring_unref(GCstring *str);

should be sufficient for immutable strings. copy-on-write mutable ones
would probably want allocated length in the struct too, and add something

  GCString *g_cstring_dup(GCString *clone);

which can then sit in the beginning of the modifier functions, looking
something like

  GCstring *g_cstring_append(GCstring *s, gchar *data)
    if(s->refcount > 1)
      s = g_cstring_dup(s);

    /* now modify s */
    return s;

From my experience using GString I'd find the following macro useful;

#define GCSTR(s) (s?s->str:NULL)

Then you can

  printf("Hello, my name is %s\n", GCSTR(s));

a little safer.

Or note that C requires the address of a struct must be the address of
its first member; so a simple cast is sufficient

  printf("Hello, my name is %s\n", (gchar*)s);

Paul "LeoNerd" Evans

leonerd leonerd org uk
ICQ# 4135350       |  Registered Linux# 179460

Attachment: signature.asc
Description: PGP signature

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]