Re: [Libguestfs] [nbdkit PATCH 3/5] api: Add nbdkit_string_intern helper

Richard W.M. Jones
2020-08-25T19:21:33Z

On Tue, Aug 25, 2020 at 10:46:57AM -0500, Eric Blake
wrote:
> + const char *nbdkit_string_intern (const char *str);
> +
> +Returns a copy of str, so that the caller may reclaim str and use the
> +copy in its place.  If the copy is created outside the scope of a
> +connection (such as during C<.load>), the lifetime of the copy will
> +last at least through C<.unload>; if it was created within a
> +connection (such as during C<.preconnect>, C<.default_export>,
or
> +C<.open>), the lifetime will last at least through C<.close>.

Interesting - this isn't exactly how I imagined this would work.
Would it make sense to intern strings for the lifetime of the server
no matter where they are allocated from?

Another suggestion would be for the function to take a flag indicating
preferred lifetime, but that presents additional complications for the
caller.

Also I imagined that this function would be a true (LISP-style)
INTERN, in that it would return a single pointer if called twice with
the two equal strings.  But I see from the implementation later on
that this isn't the case.

> -      keys[optind] = strndup (argv[optind], n);
> -      if (keys[optind] == NULL) {
> -        perror ("strndup");
> +      CLEANUP_FREE char *key = strndup (argv[optind], n);
> +      const char *safekey = nbdkit_string_intern (key);
> +      if (safekey == NULL)
>          exit (EXIT_FAILURE);

It seems it might also be nice to have a "strndup" version of the
intern function.

I'm not completely sure which of these behaviours is better.  Ideally
back when I started writing nbdkit I would have used a pool allocator,
but that's all water under the bridge now.  So none of the above
indicates I have a preference for a particular implementation, just
ideas for further discussion.

Rich.

--
Richard Jones, Virtualization Group, Red Hat http://people.redhat.com/~rjones
Read my programming and virtualization blog: http://rwmj.wordpress.com
Fedora Windows cross-compiler. Compile Windows programs, test, and
build Windows installers. Over 100 libraries supported.