Add GLib.RefString from glib 2.58
I read an article Reference counting in modern GLib. Most of it seems to be useful only in C, but GRefString could come in handy in Vala too. I'm playing with this VAPI:
[CCode (cprefix = "G", lower_case_cprefix = "g_", cheader_filename = "glib.h", gir_namespace = "GLib", gir_version = "2.0")]
namespace GLib {
[Version (since = "2.58")]
[Compact]
[CCode (ref_function = "g_ref_string_acquire", unref_function = "g_ref_string_release", cheader_filename = "glib.h")]
public class RefString {
public RefString(string str);
public RefString.intern(string str);
public RefString.len(string str, ssize_t len);
public size_t length();
[CCode(cname="vala_g_ref_string_get")]
public unowned string @get() {
return (string*) this;
}
[CCode(cname="vala_g_ref_string_to_string")]
public unowned string to_string() {
return (string*) this;
}
}
}
I did not attempt to make the RefString
a proper subclass of string
because the memory management is incompatible - you cannot use g_free()
with RefString
. Instead, I added get()
method to access the C string and to_string()
method to support template strings.
I'd like to use RefString in long-lived lists of strings with frequent iteration where Gee.List
creates a throw-away copy of the string values, which is unnecessary.
var list = new Gee.LinkedList<string>();
// Here a throw-away copies of string values are made
foreach (string s in list) {}
var list = new Gee.LinkedList<RefString>();
list.add(new RefString.len("cars", 3));
list.add(new RefString("bus"));
list.add(new RefString("train"));
list.add(new RefString.intern("plane"));
foreach (RefString s in list) {
stderr.printf("%u %s\n", (uint) s.length(), s.get());
stderr.printf(@"$(s.length()) $s\n");
}