Monthly Archives: December 2010

More festive drinks

It turns out that stuffing my failure of an apricot liqueur full of spices has worked, and I now have a bottle of tasty festive spicy apricot vodka. Here's the recipe in full:

Ingredients

  • 300g dried apricots
  • 700ml vodka
  • 1 large cinnamon stick
  • Rind of 1 orange
  • 2 blades mace
  • 4 cloves
  • 8 juniper berries
  • ~200g granulated sugar

Method

  1. Submerge the dried apricots in boiling water and leave them overnight to re-inflate. I had to do this because I could only buy dried apricots, but I guess an equivalent mass of fresh apricots would work.
  2. Split the apricots into halves and put them into a 1.5l plastic bottle (an empty water bottle is perfect) with a cinnamon stick and the vodka. It's better to put the apricots in first so that they don't splash.
  3. Seal the bottle well and shake it.
  4. Leave the bottle in a cool, dark place for around four weeks, shaking it every day. The precise amount of time you leave the mixture to infuse doesn’t really matter, as long as it’s more than about three weeks. Try to avoid opening the bottle during this time, as that’ll introduce contaminants.
  5. After the mixture has infused for a suitable amount of time, filter it out into another bottle. This might take a day or longer, depending on your filter paper. Use fine filter paper (coffee filter papers worked well for me), and be prepared to use several filter papers, as they will get clogged up. Keep the apricots!
  6. Once filtering is complete, add sugar to the filtered liquid to taste. 200g should be about right (I used 225g this time, and it was a little too sweet). Add the cinnamon stick again (or use a fresh one), and the orange rind, mace blades, cloves and juniper berries. Seal the bottle up again and leave it for at least another two weeks, shaking it daily.
  7. After at least two weeks, filter it again. This should take a lot less time, as most of the fine sediment will have been removed during the first filtration.
  8. Drink and enjoy! The recipe produces about 700ml of spiced apricot vodka. The apricots left over from filtration are nice in a pie, though they will have lost a lot of their flavour (more so than the raspberries).

I'm sure it would be quite possible to infuse the vodka with the apricots and spices at the same time, but I didn't try this, so I can't be sure. Another thing I probably should've done is added the sugar after infusing the vodka with the spices, as that would've allowed it to be added to taste. As it was, I added what I guessed was the right amount and fortunately it turned out well.

While not busy playing around with drinks, I've got around to finishing off and releasing libgdata 0.8.0. This vastly improves upload and downloads via streaming I/O, as well as fixing a lot of race conditions, leaks and cancellation problems. This release doesn't introduce much new functionality, but breaks a lot of API, hopefully for the better.

Postconditions in C

Recently, I've been working on some code which turns out to be particularly fiendish in the number of states it can be in, and I'm finding it hard to ensure that each method actually does exactly what it's supposed to. The problem is that the code is supposed to be multi-threaded, asynchronous, cancellable and all those buzzwords, and various methods have a number of different ways of returning results (or a lack thereof). A good example of the sort of method I mean is g_input_stream_read(): it arguably has six different ways of returning results:

  1. Returning 0 if count == 0.
  2. Returning G_IO_ERROR_INVALID_ARGUMENT if count > G_MAXSSIZE.
  3. Returning the number of bytes successfully read.
  4. Returning 0 if EOF is reached.
  5. Return G_IO_ERROR_CANCELLED if it was cancelled before anything could be read.
  6. Returning the number of bytes read despite being cancelled.

Thankfully the first two of these are handled by GIO's wrapper around the actual implementation of the read method, but that still leaves four different ways of returning results.

One approach I've found quite useful in catch bugs is something similar to the design by contract approach of adding postconditions to the methods. Obviously, since this is C, I can't add postconditions the way DbC recommends (as formal specifications of behaviour which are separate from the implementation of that behaviour) — the best I can do is to add assertions before returning from the methods. I did look into existing solutions which would add proper support for formal specification, but they all seem to have died around 5 years ago.

So, this is the approach I've come up with. It's not brilliant, and it's a bit of a hassle to apply to every method I write, but it's definitely turned out useful for the complicated ones. Any comments about ways to improve it would be appreciated, as would pointers to existing solutions which I've managed to overlook.

static gssize
my_input_stream_subclass_read (GInputStream *stream, void *buffer, gsize count, GCancellable *cancellable, GError **error)
{
	/* Some vaguely realistic variables which depend on the method in question. There has to be a variable for the return value. */
	gssize length_read = -1;
	gboolean reached_eof = FALSE;

	/* We assume that there's some mechanism in place to set cancelled to TRUE if @cancellable is cancelled during a relevant period of the method's execution.
	 * We do this instead of just checking g_cancellable_is_cancelled() in the postcondition to avoid the case that the method isn't cancelled until just before the postcondition. */
	gboolean cancelled = FALSE;

	/* We use a fresh #GError so that we're guaranteed to have a #GError (since @error can be NULL) which we can examine before returning. */
	GError *child_error = NULL;

	/* Preconditions */
	g_return_val_if_fail (G_IS_INPUT_STREAM (stream), -1);
	g_return_val_if_fail (buffer != NULL, -1);
	g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), -1);
	g_return_val_if_fail (error == NULL || *error == NULL, -1);

	/* Handle one particular case */
	if (count == 0) {
		length_read = 0;
		goto done;
	}

	/* … */

	if (some_operation_which_sets_an_error (&child_error) == FALSE) {
		/* Set up the return value for this particular error condition */
		length_read = -1;
		goto done;
	}

	/* … */

	length_read = some_operation_which_sets_the_success_return_value (cancellable);

	if (length_read < 1 && g_cancellable_set_error_if_cancelled (cancellable, &child_error) == TRUE) {
		/* Handle cancellation by setting the return values to something else */
		length_read = -1;
		goto done;
	}

	/* … */

done:
	/* Unref/Free calls for various local variables could go here */

	/* Postconditions */
	g_assert1 ||
	          (count > 0 && count <= G_MAXSSIZE && reached_eof == TRUE && length_read == 0 && child_error == NULL) ||
	          (count > 0 && count <= G_MAXSSIZE && reached_eof == FALSE && length_read > 0 && child_error == NULL) ||
	          (count > 0 && count <= G_MAXSSIZE && cancelled == TRUE && length_read == -1 && g_error_matches (child_error, G_IO_ERROR, G_IO_ERROR_CANCELLED)));

	/* Move the “out” parameters to their formal parameters */
	if (child_error != NULL)
		g_propagate_error (error, child_error);

	return length_read;
}

The core of this approach is that there's only one return statement in the method; all other points in the method which would normally have returned now goto the end of the method, which checks the postconditions before actually returning.

This requires that the return value for the method is stored in a variable. Similarly, if the method can return a GError (or, for that matter, has any other “out” parameters), all places in the method where the GError (or other output variable) would be set have to set a local variable instead — only after the postconditions are checked can these “out” parameters be moved to their formal parameters.

As I said, this approach isn't ideal, as it involves some extra local variables, moving various things around unnecessarily, some extra goto statements, and changing the flow of the code. Additionally, it's prone to misbehaving if any of the statements in the postconditions have side-effects, either due to being function calls which have side-effects, or typos (e.g. mistyping my_return_value = -1 instead of my_return_value == -1) — a proper implementation of design by contract would not be prone to this, as the specification language it uses would most likely just be first order logic.

However, this approach does have the side effect that unreffing and freeing various variables and releasing various locks used in the method can now happen in one convenient place: just before the postcondition assertion. That might simplify memory management somewhat for some methods.

In summary, it's not a particularly elegant way to implement postconditions, but it's the best I could come up with, and I'll definitely be using it in the more complex code I write in future. Any comments, corrections or suggestions for improvements are more than welcome.

Update: added a missing child_error != NULL check before the g_propagate_error() call.


  1. count == 0 && length_read == 0 && child_error == NULL) || (count > G_MAXSSIZE && length_read == -1 && g_error_matches (child_error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT 

Festive drinks

Earlier in the year, I experimented with making fruit liqueur at home; I made a bottle of raspberry vodka with great success. Seeking to repeat the success and add some variety, I recently tried making apricot vodka (with the intent to have it ready for Christmas and the New Year). Unfortunately, I failed. It turns out that apricots don't have enough flavour in them to overcome the taste of vodka, and so I've ended up with pale yellow coloured bleach. I'm now attempting to rescue it by ramming it full of spices.

I realise it's a little late now for anybody who's interested in making this for Christmas, but if anyone fancies making it some other time, here's the (successful, at least in my opinion) recipe for raspberry vodka. It takes three weeks or more to do. A good recipe for apricot vodka is left as an exercise for the reader.

Ingredients

  • 675g fresh raspberries
  • ~1tbsp lemon juice
  • 700ml vodka
  • ~250g granulated sugar

Method

  1. Slightly crush the raspberries and put them into a 1.5l plastic bottle (an empty water bottle is perfect) with the lemon juice and vodka. It's better to put the raspberries in first so that they don't splash.
  2. Seal the bottle well and shake it.
  3. Leave the bottle in a cool, dark place for around four weeks, shaking it every day. The precise amount of time you leave the mixture to infuse doesn't really matter, as long as it's more than about three weeks. Try to avoid opening the bottle during this time, as that'll introduce contaminants.
  4. After the mixture has infused for a suitable amount of time, filter it out into another bottle. This might take a day or longer, depending on your filter paper. Use fine filter paper (coffee filter papers worked well for me), and be prepared to use several filter papers, as they will get clogged up. Keep the raspberries!
  5. Once filtering is complete, add sugar to the filtered liquid to taste. 250g makes it fairly sweet, so you could quite easily use less. If you're not sure, add it gradually, since it only takes a few tens of minutes (and some shaking) to dissolve.
  6. Drink and enjoy! The recipe produces just under 1l of raspberry vodka. The raspberries left over from filtration are excellent when eaten with cream or ice cream.

I can't take much credit for this, as it's based on a recipe I found here: http://www.guntheranderson.com/liqueurs/raspberr.htm. I made some alterations, though, such as doubling the ratio of raspberries to vodka. Fortunately, they seem to have worked out well.

In other news, libgdata's API documentation is now available on library.gnome.org! Thanks to Frédéric Péters for getting this sorted out.

Recent libgdata work

Having totally failed to blog much recently, I thought I'd post an update on libgdata, and the work I've been doing over the last few days on it.

I'm aiming to get libgdata 0.8.0 released in good time to be used in GNOME 3.0, since it contains a lot of fixes and API breaks. What will be new in 0.8? The major change is that libgdata will be fully asynchronous — every long-running operation now has an asynchronous API. As part of the work on this, I've changed the way uploads work, too, so that they're now conducted exclusively via streaming I/O. This means that the data being uploaded to PicasaWeb as a new photo (for example) can just as easily come from memory as it can from disk.

Other improvements include lots of XML escaping fixes, some memory leak fixes, and improvements to cancellation support. Cancellation support is one of the things left on the to-do list before 0.8.0 can be released. While I naïvely thought that cancellation support in libgdata had been fairly good, after poking around in the code for the last few days I've been shown to be very, very wrong. Cancellation doesn't work in many cases, and is racy in others. That will be fixed before 0.8.0

Funnily enough, all this work was prompted by the need to fix the test suite so that libgdata passed its tests on build.gnome.org. It turns out that due to a recent change to g_str_hash() in GLib master, libgdata's test suites started to fail, as they implicitly relied on the order of entries in a hash table when doing XML comparisons using strcmp(). Obviously, this wasn't a brilliant idea. I suppose this is a little word of warning, then: if things involving hash tables in your program suddenly break with GLib ? 2.27.4, it might be because you're (erroneously) relying on the order of entries in a hash table.

The changes to fix the test suite have been backported to libgdata's 0.6 and 0.7 branches, and are present in the new 0.6.6 release. I was a little over-eager with the 0.7 branch, and released 0.7.1 too early, so that doesn't have the fixes. They'll be in 0.7.2 though, whenever that comes out.