<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Making Life Easier</title>
	<atom:link href="http://landheer-cieslak.com/wordpress/feed/" rel="self" type="application/rss+xml" />
	<link>http://landheer-cieslak.com/wordpress</link>
	<description>one byte at a time</description>
	<lastBuildDate>Sat, 04 Sep 2010 00:51:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Home Search, Where Art Thou?</title>
		<link>http://landheer-cieslak.com/wordpress/home-search-where-art-thou/</link>
		<comments>http://landheer-cieslak.com/wordpress/home-search-where-art-thou/#comments</comments>
		<pubDate>Sat, 04 Sep 2010 00:51:43 +0000</pubDate>
		<dc:creator>Ronald Landheer-Cieslak</dc:creator>
				<category><![CDATA[Opinions]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://landheer-cieslak.com/wordpress/?p=892</guid>
		<description><![CDATA[In my day to day life, there are few things I truly dislike doing: I&#8217;m a pretty happy person. There is one thing, though, that I really don&#8217;t like &#8211; at all &#8211; and that strikes me as a truly pointless exercise in futility: searching. Shouldn&#8217;t we have a solution for that by now? It [...]]]></description>
			<content:encoded><![CDATA[
<p>In my day to day life, there are few things I truly dislike doing: I&#8217;m a pretty happy person. There is one thing, though, that I really don&#8217;t like &#8211; at all &#8211; and that strikes me as a truly pointless exercise in futility: searching. Shouldn&#8217;t we have a solution for that by now?</p>
<p>It strikes me we already have all of the necessary technology to come up with a viable solution: I&#8217;ve worked with most of them! Let&#8217;s have a look what this might look like.</p>
<h2>How It Would Work</h2>
<p>Let&#8217;s say you&#8217;ve misplaced you pen: you whip out the portable device of your choice (in my case, my iPod Touch), launch the search app and type &#8220;pen&#8221;. This would either access a local index over the network, or an index on the web, and would start looking where an item that matches &#8220;pen&#8221; was last seen. Say you have seven pens at your home: one in the bedroom, three in your home office, two in the living room (of which one in the couch, between the cushions) and one in the laundry room.</p>
<p>In order for the search service to know where your pen is, the amount of data you need is surprisingly small: it needs to know where you are, what a pen is, which pens you might be looking for and where those pens were last &#8220;seen&#8221;. How would we go about getting this information?</p>
<p>Let&#8217;s start by looking at how to know where the pens were last seen: in order for a computer to &#8220;see&#8221; anything, it needs a sensor of some kind. That sensor, in our case, needs to provide enough information for the computer to know where it is and what it has observed. If we look at solutions for similar problems (always a good way to start an analysis), we might take a look at EPCIS (Electronic Product Code Information System): it is a system based on event captures in which sensors among the supply chain generate events that are stored in an <em>EPCIS repository</em> where they can later be analyzed. EPCIS events consist of several fields, including the EPC itself (an electronic product code), an action, a disposition and a read point. Each of these is identified by a URN that might look a bit like this: <code>urn:epc:id:sgtin:1234567.123456.123</code> (which would be an EPC). Some of the information is inherent to the scanner (e.g. the read point) or its context (action and disposition), but one of the bits of information is part of the product: the EPC.</p>
<p>An EPC contains a lot of information, some of which we don&#8217;t need for our purposes: an SGTIN, for example, contains a serial number and a GTIN, which is a Global Trade Identification Number. The GTIN contains a Company Prefix and an Item Reference, which identifies the company that made (or imported, or distributed) the pen and the type of item it is (a pen). You can find the same information in a barcode. For example: 1-88874-84006-6 is a UPC-12 barcode that contains a company prefix 88874, identifying EMF Tea &#038; Wares, and an item reference 84006, identifying a 120g container of &#8220;Th&eacute; au Jasmin&#8221;. Now, the way that EPCs are usually read is either by scanning a barcode that contains the EPC (usually a data matrix barcode), or by reading an RFID tag. RFID tags are relatively expensive &#8211; sufficiently so to hamper their rapid adoption for serialization (for supply line security) in the pharmaceutical industry &#8211; so we shouldn&#8217;t expect pens to be outfitted with RFID tags any time soon. However, while RFID tags are relatively expensive for production purposes, they are relatively <em>inexpensive</em> for retail purposes: a tag costs a few cents. RFID tags are also fairly small: they can be embedded into a label you&#8217;d find on a bottle of pills, for example. A typical tag would be about a 2 cm wide square, most of which is the tag&#8217;s antenna. It would be feasible, therefore, to tag objects you want to be able to search for with a stick-on RFID tag: you could basically put the tag inside the pen, rolled up, provided the pen is mostly made of plastic (or the tag could be embedded in a label that you stick to the pen).</p>
<p>RFID has the advantage of being &#8220;transparent&#8221; in two ways: because it works with radio waves, most objects are transparent to it (as are you, mostly), so your pen can be in your pocket and still be visible the the RFID reader. The other way it is transparent is that once you&#8217;ve stuck the tag on your object, you don&#8217;t have to think about it anymore: when you carry it around, an RFID reader will see the tag and generate an appropriate event.</p>
<p>This takes care of half of our first problem: items that already have an RFID tag that has a GTIN or (better yet) an SGTIN in it are duly identified and are now visible to RFID readers. The ones you tag, you have to associate with the object, so you can imagine having an RFID reader with your computer and, when you tag an object, scanning it and answering a few questions about the object (such as what it is). This begs the question, though: how do we get those tags to tell the readers where they are?</p>
<p>The answer is: we don&#8217;t. The tags I&#8217;m thinking of are <em>passive</em> tasks, so they wouldn&#8217;t normally be very chatty: they only talk when talked to (and get the energy to talk from the antenna, so there&#8217;s no batteries required). Antennas would be strategically placed around the house, where it makes sense. In my case, I&#8217;d put one at the top of the stairs, at each doorpost (on the inside of each room) etc. That way, an tagged object in my house would be &#8220;seen&#8221; by those readers at those strategic places. It would be practicallty impossible for my pen to end up in the laundry room without going, one morning, from the master bedroom down the stairs and through the door of the laundry room. Even if one of the readers doesn&#8217;t pick it up (e.g. the one in the laundry room) I can follow its trajectory down the stairs and have a good guess where it might end up if, say, the laundry basket took the same route at the same time.</p>
<h2>Security</h2>
<p>So, we now have a basic solution. I think the use-cases are obvious (they are to me, at least). What about abuse cases? Say I tagged a diamond necklace, which I would happen to have laying about the house. A thief coming into the house and whipping out his iPad could do a quick inventory of the place, know exactly where everything is and clean me out in no time, right?</p>
<p>That&#8217;s what you need security for: you don&#8217;t want any-one to have an idea of the inventory of your home, so if at all possible, the information should stay in your home &#8211; which means this becomes a localized solution. The database and software could easily be housed in a little box that could be installed next to your home router, and to which the various RFID readers would send their info through wireless LAN or through a home-area network (they wouldn&#8217;t have to be on-line all the time, either: battery-powered RFID readers would only need a simple motion sensor to turn themselves on, perform a reading, send the result and go back to sleep). The other bit of security &#8211; not allowing the burglar to read the data &#8211; is a question of securing your network and putting a password on the server. Of course, the readings being sent would have to be secured as well: both sides would have an X.509 certificate identifying themselves and thus allowing them to communicate. </p>
<h2>Roaming</h2>
<p>So, let&#8217;s say all of your friends have tagged their iPods, iPads, iMacs, laptops, pens, secret diaries, jewelery, family heirlooms, etc. as have you. You go to a party at one of your friends&#8217; and fall asleep on the couch. When you wake up, you want to check the time on your tagged thingamajig and find it missing. What do you do?</p>
<p>Well, because your friend conveniently places a reader at the front door, his system picked up a &#8220;foreign object&#8221; belonging to user ID 12345 (part of the tag you put on it). Your friend whips out his Android phone, fires up the app and instructs it to tell it where anything belonging to user 12345 is. Most of it, being on your person, is reported as being in the living room but, somehow, your thingamajig left a few hours ago. At about the same time, a whole bunch of stuff belonging to user 23456 left as well. User 23456 being your girlfriend, you rest assured and hope she isn&#8217;t too mad at you for falling asleep on the couch (while she was talking to you).</p>
<h2>Conclusion</h2>
<p>Our time of searching for stuff should be over! If some-one would be willing to come up with the venture capital, I&#8217;ll be happy to make a product out of this idea. I already know everything I need to know to get the ball rolling and I can come up with a pretty good sketch of what both the software and hardware should look like pretty quickly.</p>

<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F&amp;title=Home+Search%2C+Where+Art+Thou%3F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F&amp;title=Home+Search%2C+Where+Art+Thou%3F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F&amp;title=Home+Search%2C+Where+Art+Thou%3F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F&amp;headline=Home+Search%2C+Where+Art+Thou%3F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Home+Search%2C+Where+Art+Thou%3F&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Home+Search%2C+Where+Art+Thou%3F&amp;u=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Home+Search%2C+Where+Art+Thou%3F&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Home+Search%2C+Where+Art+Thou%3F&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Home+Search%2C+Where+Art+Thou%3F&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F&amp;title=Home+Search%2C+Where+Art+Thou%3F&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fhome-search-where-art-thou%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://landheer-cieslak.com/wordpress/home-search-where-art-thou/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;Given the existence of A, B will create itself, therefore, C had nothing to do with it&#8221;</title>
		<link>http://landheer-cieslak.com/wordpress/given-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it/</link>
		<comments>http://landheer-cieslak.com/wordpress/given-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it/#comments</comments>
		<pubDate>Sat, 04 Sep 2010 00:07:51 +0000</pubDate>
		<dc:creator>Ronald Landheer-Cieslak</dc:creator>
				<category><![CDATA[Opinions]]></category>
		<category><![CDATA[Science]]></category>

		<guid isPermaLink="false">http://landheer-cieslak.com/wordpress/?p=908</guid>
		<description><![CDATA[Stephen Hawking&#8217;s new book promises a lot of hype. CNN Already published two separate articles about it on their site even hough no-one has read it yet. I&#8217;ve added it to my Amazon Science Books Wishlist, and will buy it when I come round to it unless some generous soul wants to offer it to [...]]]></description>
			<content:encoded><![CDATA[
<p>Stephen Hawking&#8217;s new book promises a lot of hype. CNN Already published two separate articles about it on their site even hough no-one has read it yet. I&#8217;ve added it to my <a href="http://amzn.com/w/2NIU712R6L9YF">Amazon Science Books Wishlist</a>, and will buy it when I come round to it unless some generous soul wants to offer it to me first. About the hype, though:<br />
<span id="more-908"></span><br />
&#8220;Given the existence of gravity &#8230;&#8221;</p>
<p>OK, but given by whom?</p>
<p>I love a good debate, and I am open to one: I have a few opinions to offer to start one off, too!</p>
<ol>
<li>The purpose of science is not to ask &#8220;why?&#8221;, but rather to ask &#8220;how?&#8221;<br/>In fact, science cannot answer the question of &#8220;why?&#8221; because that question is, by its nature, part of the realm of metaphysics and philosophy rather than that of science. Even Kant with his &#8220;Kritik der reinen Vernunft&#8221; (Critique on pure reason) cannot get around the &#8220;every event must have a cause&#8221; logic of his predecessors and, as far as I know, no-one has.</li>
<li>If something is to be given, it must be given <em>by</em> someone (or something).<br/>In fact, &#8220;given the existence of gravity&#8221; doesn&#8217;t explain much other than the shape and form of the universe. The eleven dimensions proposed by Hawking aren&#8217;t new to his new book and may be explained by the existence of gravity &#8211; I haven&#8217;t read the book yet &#8211; but that hardly explains gravity.</li>
</ol>
<p>Opinions?</p>

<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F&amp;title=%22Given+the+existence+of+A%2C+B+will+create+itself%2C+therefore%2C+C+had+nothing+to+do+with+it%22" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F&amp;title=%22Given+the+existence+of+A%2C+B+will+create+itself%2C+therefore%2C+C+had+nothing+to+do+with+it%22" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F&amp;title=%22Given+the+existence+of+A%2C+B+will+create+itself%2C+therefore%2C+C+had+nothing+to+do+with+it%22" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F&amp;headline=%22Given+the+existence+of+A%2C+B+will+create+itself%2C+therefore%2C+C+had+nothing+to+do+with+it%22" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=%22Given+the+existence+of+A%2C+B+will+create+itself%2C+therefore%2C+C+had+nothing+to+do+with+it%22&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=%22Given+the+existence+of+A%2C+B+will+create+itself%2C+therefore%2C+C+had+nothing+to+do+with+it%22&amp;u=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=%22Given+the+existence+of+A%2C+B+will+create+itself%2C+therefore%2C+C+had+nothing+to+do+with+it%22&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=%22Given+the+existence+of+A%2C+B+will+create+itself%2C+therefore%2C+C+had+nothing+to+do+with+it%22&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=%22Given+the+existence+of+A%2C+B+will+create+itself%2C+therefore%2C+C+had+nothing+to+do+with+it%22&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F&amp;title=%22Given+the+existence+of+A%2C+B+will+create+itself%2C+therefore%2C+C+had+nothing+to+do+with+it%22&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fgiven-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://landheer-cieslak.com/wordpress/given-the-existence-of-a-b-will-create-itself-therefore-c-had-nothing-to-do-with-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Opacity: Encapsulation at its best (and worst)</title>
		<link>http://landheer-cieslak.com/wordpress/opacity-encapsulation-at-its-best-and-worst/</link>
		<comments>http://landheer-cieslak.com/wordpress/opacity-encapsulation-at-its-best-and-worst/#comments</comments>
		<pubDate>Wed, 01 Sep 2010 12:00:20 +0000</pubDate>
		<dc:creator>Ronald Landheer-Cieslak</dc:creator>
				<category><![CDATA[C++ for the self-taught]]></category>

		<guid isPermaLink="false">http://landheer-cieslak.com/wordpress/?p=891</guid>
		<description><![CDATA[One thing you may have noticed when looking at the code of our abstract factory, is that the base classes (interfaces) of each of our abstract objects don&#8217;t have much to tell their users: there are hardly any accessors or mutators to be found. This is an attribute of encapsulation called opacity and in this [...]]]></description>
			<content:encoded><![CDATA[
<div style="width: 200px; height: 100px; float:right"><iframe src="http://vlinder.ca/podcasts/play.php?file=22-opacity" width="200" height="70" scrolling="no"></iframe><form class='donate' method='post' action='https://www.paypal.com/cgi-bin/webscr'>		<input type='hidden' value='2.50' name='amount'/>		<input type='hidden' value='_xclick' name='cmd'/>		<input type='hidden' value='ronald@landheer-cieslak.com' name='business'/>		<input type='hidden' value='Donate for the C++ for the self-taught podcast' name='item_name'/>		<input type='hidden' value='1' name='no_shipping'/>		<input type='hidden' value='ttp://landheer-cieslak.com/wordpress/thanks/' name='return'/>		<input type='hidden' value='http://landheer-cieslak.com' name='cancel_return'/>		<input type='hidden' value='CAD' name='currency_code'/>		<input type='hidden' value='' name='page_style'/>		<input type='hidden' value='0' name='tax'/>		<input type='image' alt='PayPal - The safer, easier way to pay online' name='submit' style='border: 0pt none ;' src='http://landheer-cieslak.com/donate.png'/></form></div>
<p>One thing you may have noticed when looking at the code of our abstract factory, is that the base classes (interfaces) of each of our abstract objects don&#8217;t have much to tell their users: there are hardly any accessors or mutators to be found. This is an attribute of encapsulation called <em>opacity</em> and in this installment, we&#8217;ll explore its advantages and disadvantages.<br />
<span id="more-891"></span><br />
Let&#8217;s look at the <code>Mechanism</code> class: the base class says very little about the mechanism itself: it doesn&#8217;t even allow you to get its name. It currently only allows you to get credentials from the current mechanism and will eventually serve as the primary interface to interact with the mechanism. It will not, however, allow you any knowledge as to what that mechanism is. That knowledge, once it is handed to the <code>MechanismFactory</code>, is lost (unless you keep it around elsewhere).</p>
<p>The <code>Credentials</code> class is arguably even worse: it doesn&#8217;t allow you to know <em>anything</em> about the credentials and is effectively an opaque handle to the credentials behind them. This will remain true for the most part throughout the development of these libaries.</p>
<p>The opacity of both of these classes illustrates a general design principle that has definite advantages, but also some drawbacks. We will focus only on the opacity-attribute of this principle &#8211; the principle being <em>encapsulation</em>. The other attributes of the design principle of encapsulation will be handled at another time.</p>
<h2>The general effect of opacity in design</h2>
<p>One of the phrases that has become well-known for reasons outside of software design is the reply &#8220;that is on a need to know basis&#8221;. This particular phrase is also a mantra in object-oriented design as far as encapsulation is concerned, and it is why, in our case, the <code>Credentials</code> class is completely opaque &#8211; and why the <code>Mechanism</code> class is not. Each of these classes or, more generally, interfaces (as we are discussing the abstract classes in the <code>Security</code> namespace here) exposes nothing more than absolutely necessary in order to use them. When credentials have to be presented somewhere, they will be presented as either a pointer or a reference to an instance of this opaque class, which the code behind the scenes will know significantly more about than the code that lugs the instance around. <em>Everything</em> about these interfaces is on a need to know basis: you don&#8217;t need to know how to construct an instance of any of these classes, so you are not given the opportunity to even try. You don&#8217;t need to know what&#8217;s behind the credentials, so you can&#8217;t look. You don&#8217;t need to know how the mechanism works internally, so you don&#8217;t even get the slightest clue as to how it might work. All you get is what you absolutely need in order to use these classes.</p>
<p>Especially in distributed architectures (not what we are working on right now, but an interesting subject nontheless), this design mantra can be pushed to extremes. Sometimes, this is to the detriment of important functional aspects of the solution, such as its run-time performance: if in order to accomplish a task the program needs to take a &#8220;scenic route&#8221; to get the information it needs, something is evidently too opaque. The trade-off, however, may be in the maintainability of the program: taking short-cuts for the benefit of run-time performance may make the code very difficult to maintain in the long run. The point is: like everything, encapsulation should be used in moderation. </p>
<h2>Opacity in Chausette</h2>
<p>We start seeing how these two classes (<code>Credentials</code> and <code>Mechanism</code>), and the need to know, are different when we add the <em>security context</em> to the mix. The security context is the context in which authorization takes place. It is established between the server and the client application and it allows both the server and the client to mutually agree on what each may do with the other. The context is the result of a negotiation between the security mechanism implementations on either side of the link. In order to perform this negotiation, the two sides exchange tokes with each other &#8211; tokens we already know and have implemented a while ago. Neither SSPI nor GSS dictate how the tokens should be exchanged but both have similar concepts of contexts, so we&#8217;ll start by implementing the ones for SSPI and adapt our implementation to GSS afterwards.</p>
<p>First, let&#8217;s take a look at our new <code>Context</code> class:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #339900;">#ifndef chausette_security_context_h</span>
<span style="color: #339900;">#define chausette_security_context_h</span>
&nbsp;
<span style="color: #339900;">#include &quot;Details/prologue.h&quot;</span>
&nbsp;
<span style="color: #0000ff;">namespace</span> Vlinder <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">namespace</span> Chausette <span style="color: #008000;">&#123;</span> <span style="color: #0000ff;">namespace</span> Security <span style="color: #008000;">&#123;</span> 
	<span style="color: #0000ff;">class</span> VLINDER_CHAUSETTE_SECURITY_API Context
	<span style="color: #008000;">&#123;</span>
	<span style="color: #0000ff;">public</span> <span style="color: #008080;">:</span>
		<span style="color: #0000ff;">virtual</span> ~Context<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
&nbsp;
	<span style="color: #0000ff;">protected</span> <span style="color: #008080;">:</span>
		Context<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
	<span style="color: #0000ff;">private</span> <span style="color: #008080;">:</span>
		<span style="color: #666666;">// neither CopyConstructible nor Assignable</span>
		Context<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> Context <span style="color: #000040;">&amp;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
		Context <span style="color: #000040;">&amp;</span> operator<span style="color: #000080;">=</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> Context <span style="color: #000040;">&amp;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008000;">&#125;</span><span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #339900;">#endif</span></pre></div></div>

<p>As you can see, it is an almost exact copy of the <code>Credentials</code> class. It won&#8217;t stay that way but, for now, all we need to know is that such a thing as a context exists &#8211; just like all we needed to know about credentials is that they exist. </p>
<p>The negotiation that takes place between the client and the server in order to obtain a context has a variable number of steps and includes the exchange of tokens from either side. The mechanism can fail in several different ways to complete the creation of the context, and some of those failures may be fatal whereas others will not be fatal but will simply imply that more work needs to be done. We need to tell the calling code if anything went wrong, and what to do if that is the case.</p>
<p>The same is not true for credentials: if the mechanism can&#8217;t create the credentials requested, there can only be very few reasons why that might be so and, although we don&#8217;t handle those reasons at the moment, handling them will be significantly easier than handling the reasons for failing to create a context.</p>
<p>In <a href="http://landheer-cieslak.com/wordpress/error-handling-in-c/" target="_blank">one of my previous posts</a> I explain what&#8217;s needed to handle an error correctly (in C, in this case): the calling code needs to know:
<ul>
<li><strong>what</strong> went wrong &#8211; which post-condition was not met, what action(s) did not take place, what action(s) failed</li>
<li><strong>why</strong> the function that was being called was called, and perhaps why it didn&#8217;t work</li>
<li><strong>how</strong> we got to where we were and how it went wrong</li>
</ul>
<p>All of this information should be wrapped into an exception class, which will be the subject of my next installment. That exception, however, should only be thrown if there is an actual error: if the failure to create a complete context is simply a result of the negotiation process, the context may not be ready for use, but that is not an error. The context will therefore possibly need to be <em>partial</em> or, alternatively, the mechanism may need to keep it while it is being worked on.</p>
<h2>Trade-offs</h2>
<p>As far as opacity is concerned, however, the question becomes how much of this needs to be known to the user: does the user need to know that a given context is ready for use? Should the user have access to a context that is not ready for use yet? Should the user be allowed to interrupt a negotiation and start a new one? Should the user be allowed to have more than one on-going negotiation at the same time?</p>
<p>Each of these questions &#8211; or rather, the answers to them &#8211; have an impact on the opacity of the negotiation process, which is specific to the implementation of the mechanism; the opacity of the <code>Context</code> class and the opacity of the <code>Mechanism</code> class.</p>
<p>Let&#8217;s analyze each of these questions in more detail:</p>
<h3>Does the user need to know that a given context is ready for use?</h3>
<p>Of course, the user does need to know that a given context can be used. There will only be a doubt about this, however, if the user has access to contexts that cannot be used &#8211; e.g. partial contexts. Later during the life-time of the context a situation might occur in which the context is no longer usable &#8211; e.g. when it expires. The user should have a way to know this.</p>
<p>The easiest way to resolve this is to add an accessor to the base class, like this:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">--- a/lib/security/Context.h
<span style="color: #888822;">+++ b/lib/security/Context.h</span>
<span style="color: #440088;">@@ -<span style="">9</span>,<span style="">6</span> +<span style="">9</span>,<span style="">8</span> @@ namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace Security <span style="">&#123;</span></span>
 	public :
 		virtual ~Context<span style="">&#40;</span><span style="">&#41;</span> = <span style="">0</span>;
&nbsp;
<span style="color: #00b000;">+		virtual bool good<span style="">&#40;</span><span style="">&#41;</span> const throw<span style="">&#40;</span><span style="">&#41;</span> = <span style="">0</span>;</span>
<span style="color: #00b000;">+</span>
 	protected :
&nbsp;
 		Context<span style="">&#40;</span><span style="">&#41;</span>;</pre></div></div>

<p>Although that doesn&#8217;t tell the user <em>why</em> a context is not ok to be used, it does give her an indication that such is the case.</p>
<h3>Should the user have access to a context that is not ready for use yet?</h3>
<p>This is a trickier question: the negotiation process produces information in its intermediary states that needs to be stored somewhere and ultimately produces the context. The context itself has very little to do with those states, though many implementations will partially construct the context, doing so and returning the context may lead to confusion. On the other hand, it just might be the easiest way to handle the on-going negotiation process.</p>
<p>I see two alternatives: the information pertaining a particular negotiation can be stored in a new <code>Negotiation</code> object, which can be created using a <code>startNegotiation</code> method on the <code>Mechanism</code> class and would eventually be destroyed when the negotiation is either complete or abandoned; or the information can be stored in the <code>Mechanism</code> class itself, which would preclude the possibility of having more than one negotiation at a time, which leads to the next two questions.</p>
<h3>Should the user be allowed to interrupt a negotiation and start a new one?</h3>
<p>I think the answer to this should be a resounding &#8220;yes&#8221;. That means that regardless of the way we choose to implement negotiations, there must be a way to abort them. If we implement them using a <code>Negotiation</code> class, that will amount of destroying the class&#8217; instance. If we keep the negotiation information in the <code>Context</code> class, destroying the context will destroy the information. If we keep it in the <code>Mechanism</code> class, we will have to add a method to abort the on-going negotiation.</p>
<h3>Should the user be allowed to have more than one on-going negotiation at the same time?</h3>
<p>I really don&#8217;t see much reason <em>not</em> to allow this, except if we choose to store the negotiation information inside the <code>Mechanism</code> object, in which case it would unnecessarily complicate our implementation.</p>
<p>These are the kinds of trade-offs that the &#8220;need to know basis&#8221; mantra takes us to: as we analyze our options, we find that the user will have to know that a negotiation is taking place, at least if we want him to be able to have any influence in the matter. As the architecture we have chosen since the beginning leaves the transport of tokens outside of the part of the solution we are currently working on (i.e. there is no concept of a &#8220;channel&#8221; that we can hand to the mechanism in order for it to talk to its counterpart on the other side) all such communication must necessarily go through the user&#8217;s code, which means we have to give her <em>some</em> control over the negotiation process. As long as that is the case, I believe that it should be done explicitly, so the negotiation itself should be encapsulated in a <code>Negotiation</code> object that, although completely opaque to the user, gives her a handle on the process so she can interrupt it, or manage it as she pleases.</p>
<h2>Conclusion</h2>
<p>Encapsulation in general, and opacity in particular, leads to trade-offs as you ask &#8220;what does the user need to know?&#8221; and &#8220;how should I tell her?&#8221;. In this particular case, we made the negotiation process transparent and thus left a large part of our implementation opaque, but we made the process transparent because the implementation is in the dark as far as communication is concerned. An alternative we haven&#8217;t discussed is to leave the negotiation opaque by bringing the communication into this part of the implementation. I&#8217;ll be happy to entertain a discussion on the merits of that solution if there&#8217;s any interest.</p>
<p>The code ends up looking like this:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">diff --git a/lib/security/Details/Negotiation.cpp b/lib/security/Details/Negotiation.cpp
new file mode <span style="">100644</span>
index 0000000..d3cda9e
<span style="color: #888822;">--- /dev/null</span>
<span style="color: #888822;">+++ b/lib/security/Details/Negotiation.cpp</span>
<span style="color: #440088;">@@ -<span style="">0</span>,<span style="">0</span> +<span style="">1</span>,<span style="">9</span> @@</span>
<span style="color: #00b000;">+#include &quot;Negotiation.h&quot;</span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace Security <span style="">&#123;</span> namespace Details <span style="">&#123;</span></span>
<span style="color: #00b000;">+	/*virtual */Negotiation::~Negotiation<span style="">&#40;</span><span style="">&#41;</span>/* = <span style="">0</span>*/</span>
<span style="color: #00b000;">+	<span style="">&#123;</span> /* no-op */ <span style="">&#125;</span></span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+	Negotiation::Negotiation<span style="">&#40;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+	<span style="">&#123;</span> /* no-op */ <span style="">&#125;</span></span>
<span style="color: #00b000;">+<span style="">&#125;</span><span style="">&#125;</span><span style="">&#125;</span><span style="">&#125;</span></span>
diff --git a/lib/security/Details/Negotiation.h b/lib/security/Details/Negotiation.h
new file mode <span style="">100644</span>
index 0000000..ba78bfa
<span style="color: #888822;">--- /dev/null</span>
<span style="color: #888822;">+++ b/lib/security/Details/Negotiation.h</span>
<span style="color: #440088;">@@ -<span style="">0</span>,<span style="">0</span> +<span style="">1</span>,<span style="">20</span> @@</span>
<span style="color: #00b000;">+#ifndef chausette_security_details_negotiation_h</span>
<span style="color: #00b000;">+#define chausette_security_details_negotiation_h</span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace Security <span style="">&#123;</span> namespace Details <span style="">&#123;</span></span>
<span style="color: #00b000;">+	class VLINDER_CHAUSETTE_SECURITY_API Negotiation</span>
<span style="color: #00b000;">+	<span style="">&#123;</span></span>
<span style="color: #00b000;">+	public :</span>
<span style="color: #00b000;">+		virtual ~Negotiation<span style="">&#40;</span><span style="">&#41;</span> = <span style="">0</span>;</span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+	protected :</span>
<span style="color: #00b000;">+		Negotiation<span style="">&#40;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+	private :</span>
<span style="color: #00b000;">+		// neither CopyConstructible nor Assignable</span>
<span style="color: #00b000;">+		Negotiation<span style="">&#40;</span>const Negotiation &amp;<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		Negotiation &amp; operator=<span style="">&#40;</span>const Negotiation &amp;<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	<span style="">&#125;</span>;</span>
<span style="color: #00b000;">+<span style="">&#125;</span><span style="">&#125;</span><span style="">&#125;</span><span style="">&#125;</span></span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+#endif</span>
diff --git a/lib/security/Mechanism.h b/lib/security/Mechanism.h
index 3e9fadd..<span style="color: #440088;">95a2</span>e2f <span style="">100644</span>
<span style="color: #888822;">--- a/lib/security/Mechanism.h</span>
<span style="color: #888822;">+++ b/lib/security/Mechanism.h</span>
<span style="color: #440088;">@@ -<span style="">4</span>,<span style="">6</span> +<span style="">4</span>,<span style="">7</span> @@</span>
 #include &quot;Details/prologue.h&quot;
 #include &lt;memory&gt;
 #include &lt;string&gt;
<span style="color: #00b000;">+#include &quot;Details/Negotiation.h&quot;</span>
&nbsp;
 namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace RFC1961 <span style="">&#123;</span> class Token; <span style="">&#125;</span><span style="">&#125;</span><span style="">&#125;</span>
 namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace Security <span style="">&#123;</span> 
<span style="color: #440088;">@@ -<span style="">14</span>,<span style="">8</span> +<span style="">15</span>,<span style="">13</span> @@ namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace Security <span style="">&#123;</span></span>
 	public :
 		virtual ~Mechanism<span style="">&#40;</span><span style="">&#41;</span> = <span style="">0</span>;
&nbsp;
<span style="color: #00b000;">+		virtual std::auto_ptr&lt; Details::Negotiation &gt; startNegotiation<span style="">&#40;</span><span style="">&#41;</span> = <span style="">0</span>;</span>
 		virtual std::auto_ptr&lt; Credentials &gt; getCredentials<span style="">&#40;</span>const std::string &amp; principal, int flags<span style="">&#41;</span> = <span style="">0</span>;
<span style="color: #991111;">-		virtual std::auto_ptr&lt; Context &gt; getContext<span style="">&#40;</span>RFC1961::Token *&amp; out_token, Credentials &amp; credentials, const std::string &amp; resource_name<span style="">&#41;</span> = <span style="">0</span>;</span>
<span style="color: #00b000;">+		virtual std::auto_ptr&lt; Context &gt; getContext<span style="">&#40;</span></span>
<span style="color: #00b000;">+			Details::Negotiation &amp; negotiation,</span>
<span style="color: #00b000;">+			RFC1961::Token *&amp; out_token,</span>
<span style="color: #00b000;">+			Credentials &amp; credentials,</span>
<span style="color: #00b000;">+			const std::string &amp; resource_name<span style="">&#41;</span> = <span style="">0</span>;</span>
&nbsp;
 	protected :
 		Mechanism<span style="">&#40;</span><span style="">&#41;</span>;
diff --git a/lib/sspi/Mechanism.cpp b/lib/sspi/Mechanism.cpp
index 0ffef6f..26df07a <span style="">100644</span>
<span style="color: #888822;">--- a/lib/sspi/Mechanism.cpp</span>
<span style="color: #888822;">+++ b/lib/sspi/Mechanism.cpp</span>
<span style="color: #440088;">@@ -<span style="">40</span>,<span style="">6</span> +<span style="">40</span>,<span style="">12</span> @@ namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace SSPI <span style="">&#123;</span></span>
 		delete data_;
 	<span style="">&#125;</span>
&nbsp;
<span style="color: #00b000;">+	/*virtual */std::auto_ptr&lt; Security::Details::Negotiation &gt; Mechanism::startNegotiation<span style="">&#40;</span><span style="">&#41;</span>/* = <span style="">0</span>*/</span>
<span style="color: #00b000;">+	<span style="">&#123;</span></span>
<span style="color: #00b000;">+		//TODO implement this</span>
<span style="color: #00b000;">+		return std::auto_ptr&lt; Security::Details::Negotiation &gt;<span style="">&#40;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	<span style="">&#125;</span></span>
<span style="color: #00b000;">+</span>
 	/*virtual */std::auto_ptr&lt; Security::Credentials &gt; Mechanism::getCredentials<span style="">&#40;</span>const std::string &amp; principal, int flags<span style="">&#41;</span>/* = <span style="">0</span>*/
 	<span style="">&#123;</span>
 		CredHandle cred_handle;
<span style="color: #440088;">@@ -<span style="">70</span>,<span style="">7</span> +<span style="">76</span>,<span style="">11</span> @@ namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace SSPI <span style="">&#123;</span></span>
 		<span style="">&#125;</span>
 	<span style="">&#125;</span>
&nbsp;
<span style="color: #991111;">-	/*virtual */std::auto_ptr&lt; Security::Context &gt; Mechanism::getContext<span style="">&#40;</span>RFC1961::Token *&amp; out_token, Security::Credentials &amp; credentials, const std::string &amp; resource_name<span style="">&#41;</span>/* = <span style="">0</span>*/</span>
<span style="color: #00b000;">+	/*virtual */std::auto_ptr&lt; Security::Context &gt; Mechanism::getContext<span style="">&#40;</span></span>
<span style="color: #00b000;">+		Security::Details::Negotiation &amp; negotiation,</span>
<span style="color: #00b000;">+		RFC1961::Token *&amp; out_token,</span>
<span style="color: #00b000;">+		Security::Credentials &amp; credentials,</span>
<span style="color: #00b000;">+		const std::string &amp; resource_name<span style="">&#41;</span>/* = <span style="">0</span>*/</span>
 	<span style="">&#123;</span>
 		Credentials &amp; credentials_<span style="">&#40;</span>dynamic_cast&lt; Credentials&amp; &gt;<span style="">&#40;</span>credentials<span style="">&#41;</span><span style="">&#41;</span>; // note: throws if the wrong type is given
 		CtxtHandle context_handle;
diff --git a/lib/sspi/Mechanism.h b/lib/sspi/Mechanism.h
index aa114b7..<span style="color: #440088;">1c62</span>b68 <span style="">100644</span>
<span style="color: #888822;">--- a/lib/sspi/Mechanism.h</span>
<span style="color: #888822;">+++ b/lib/sspi/Mechanism.h</span>
<span style="color: #440088;">@@ -<span style="">13</span>,<span style="">8</span> +<span style="">13</span>,<span style="">13</span> @@ namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace SSPI <span style="">&#123;</span></span>
 		Mechanism<span style="">&#40;</span>const std::string &amp; package_name<span style="">&#41;</span>;
 		virtual ~Mechanism<span style="">&#40;</span><span style="">&#41;</span>;
&nbsp;
<span style="color: #00b000;">+		virtual std::auto_ptr&lt; Security::Details::Negotiation &gt; startNegotiation<span style="">&#40;</span><span style="">&#41;</span>/* = <span style="">0</span>*/;</span>
 		virtual std::auto_ptr&lt; Security::Credentials &gt; getCredentials<span style="">&#40;</span>const std::string &amp; principal, int flags<span style="">&#41;</span>/* = <span style="">0</span>*/;
<span style="color: #991111;">-		virtual std::auto_ptr&lt; Security::Context &gt; getContext<span style="">&#40;</span>RFC1961::Token *&amp; out_token, Security::Credentials &amp; credentials, const std::string &amp; resource_name<span style="">&#41;</span>/* = <span style="">0</span>*/;</span>
<span style="color: #00b000;">+		virtual std::auto_ptr&lt; Security::Context &gt; getContext<span style="">&#40;</span></span>
<span style="color: #00b000;">+			Security::Details::Negotiation &amp; negotiation,</span>
<span style="color: #00b000;">+			RFC1961::Token *&amp; out_token,</span>
<span style="color: #00b000;">+			Security::Credentials &amp; credentials,</span>
<span style="color: #00b000;">+			const std::string &amp; resource_name<span style="">&#41;</span>/* = <span style="">0</span>*/;</span>
&nbsp;
 	private :
 		// neither CopyConstructible nor Assignable</pre></div></div>

<p>Much of this code still needs to be filled in but, before we do that, we have to figure out a way of handling errors &#8211; which we will do in the next installment. Until then, have fun!</p>

<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F&amp;title=Opacity%3A+Encapsulation+at+its+best+%28and+worst%29" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F&amp;title=Opacity%3A+Encapsulation+at+its+best+%28and+worst%29" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F&amp;title=Opacity%3A+Encapsulation+at+its+best+%28and+worst%29" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F&amp;headline=Opacity%3A+Encapsulation+at+its+best+%28and+worst%29" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Opacity%3A+Encapsulation+at+its+best+%28and+worst%29&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Opacity%3A+Encapsulation+at+its+best+%28and+worst%29&amp;u=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Opacity%3A+Encapsulation+at+its+best+%28and+worst%29&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Opacity%3A+Encapsulation+at+its+best+%28and+worst%29&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Opacity%3A+Encapsulation+at+its+best+%28and+worst%29&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F&amp;title=Opacity%3A+Encapsulation+at+its+best+%28and+worst%29&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fopacity-encapsulation-at-its-best-and-worst%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://landheer-cieslak.com/wordpress/opacity-encapsulation-at-its-best-and-worst/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Setting up a FLOSS development environment on Windows</title>
		<link>http://landheer-cieslak.com/wordpress/setting-up-a-floss-development-environment-on-windows/</link>
		<comments>http://landheer-cieslak.com/wordpress/setting-up-a-floss-development-environment-on-windows/#comments</comments>
		<pubDate>Sun, 29 Aug 2010 14:04:43 +0000</pubDate>
		<dc:creator>Ronald Landheer-Cieslak</dc:creator>
				<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://landheer-cieslak.com/wordpress/?p=895</guid>
		<description><![CDATA[Setting up a Free/Libre/OSS development environment on Windows is surprisingly easy: all you have to do is mix two or thee ingredients, and add salt to taste. The ingredients you&#8217;ll need are a toolchain and an IDE. Depending on the type of programming you want to do, your options vary. If, for example, you want [...]]]></description>
			<content:encoded><![CDATA[
<p>Setting up a Free/Libre/OSS development environment on Windows is surprisingly easy: all you have to do is mix two or thee ingredients, and add salt to taste.<br />
<span id="more-895"></span><br />
The ingredients you&#8217;ll need are a toolchain and an IDE. Depending on the type of programming you want to do, your options vary. If, for example, you want to do GUI programmng, your choices will depend on the GUI toolkit you want to use. Each of them comes with its own tools, a d its own requirements wrt a toolchain. </p>
<p>If, on the other hand, you want to do &#8220;core&#8221; programming, you have still different options in front of you.</p>
<p>The advantage you have in any of these cases, however, is that in tge majority of cases, the FLOSS tools have good reputations and are, for the most part, portable to other target platforms as well. </p>
<h2>Toolchains</h2>
<p>There are really only two FLOSS toolchains for Windows: <a target="_blank" href="http://cygwin.com">Cygwin</a> and Windows: <a target="_blank" href="http://mingw.org">MingW</a>.</p>
<h3>Cygwin</h3>
<p>Cygwin is a Linux-like environment on Windows. It consists of a DLL (cygwin1.dll) and a large number of tools, all of which can be installed with a single installer, <a href="http://cygwin.com/setup.exe">Cygwin Setup</a>. This installer can be run any number of times, to add parts to the system and/or to update them. Cygwin is quite a bit more than just a toolchain (compiler, assembler, linker and related tools) but provides a complete environment to develop in, even including an X-windows environment. I recommend everyone who is familiar with the GNU system to install Cygwin on their Windows computer.</p>
<h3>MinGW</h3>
<p>MinGW is Minimalist GNU for Windows. It is a port of the entire toolchain (compiler, assembler, linker and related tools) to Windows and, unlike Cygwin, produces binaries that are native to Windows (binaries produced by the Cygwin toolchain need Cygwin to run). MinGW comes with MSYS, the Minimalist SYStem, which is a fork of Cygwin.</p>
<p>Most FLOSS tools that target Windows are based on the MinGW toolchain, and some ship it with their IDEs. Some don&#8217;t, in which case you can download and install it yourself using the MinGW installer, which you can download from SourceForge at <a href="http://sourceforge.net/projects/mingw/" target="_blank">the MinGW project page</a>. Note, though, that the automated installed doesn&#8217;t necessarily install the latest versions of everything: manual installation instructions can be found <a href="http://mingw.org/wiki/InstallationHOWTOforMinGW" target="_blank">here</a>.</p>
<h2>GUI Toolkits</h2>
<p>There are several well-known FLOSS GUI toolkits available for Windows, most of which are either ports to Windows of well-known GNU/*NIX GUI toolkits, or toolkits that are free implementations of previously known Windows toolkits. I will treat only three in this article, each of which is very well-known and widely used: GTK+, wxWindows and Qt.</p>
<h3>GTK+</h3>
<p>GTK+ is a GUI framework written entirely in C. It is part of the GNU project and is at the heart of GNOME and the GIMP. It comes with a very interesting tool for GUI designed, called Glade, which generates an XML file that is interpreted at run-time to generate the on-screen GUI. Glade is licensed under GNU GPL, while GTK+ is licensed under GNU LGPL. GTK has bindings for many programming languages, including C++, and has a good reputation, being in-use for many well-reputed applications for several years now. It is under active maintenance by a team of volunteers. Windows ports exist and are also maintained.</p>
<p>Due to the fact that GTK+ is written in C, is part of the GNU project and uses only Free/Libre software, many of the basic building blocks that we tend to take for granted in a C++ environment that comes with the standard library, including the STL, have been re-implemented for GTK+. GTK+ is based on <b>GLib</b>, a low-level &#8220;core&#8221; library including ADTs and portability wrappers for things such as threads, and event loops; <b>Pango</b>, a text rendering library; <b>Cairo</b>, a 2D graphics rendering library; <b>ATK</b>, an accessibility toolkit. Each of these building blocks can be used separately (though there are dependencies between them).</p>
<p>For new projects written in C that need a GUI, this is probably the best choice for a GUI toolkit: there are many examples, the port to Windows is up-to-date and maintained and the port to most other platforms is up-to-date and maintained as well. The learning curve may be a bit steep to climb at first, but that is true for any full-fledged kit written in C. For new projects written in C++, there are GUI kits that are better suited for C++ development, which we will get to.</p>
<p>To obtain Windows binaries (and sources) of GTK+, you can go to <a target="_blank" href="http://www.gtk.org/download-windows.html">this page</a> for complete instructions.</p>
<h3>wxWidgets</h3>
<p>The wxWidgets project set out to create a low-cost, portable, open-source, easy-to-use GUI framework for C++ programming, and they have succeeded in doing so. It builds upon the native APIs for Windows and MacOS (though I&#8217;m not sure it uses Cocoa), and on GTK+ or Motif on *NIX.</p>
<p>wxWidgets consists of several libraries, including extended implementations of things you might find in the STL. It also contains libraries to handle XML, networking, text rendering, etc. although all this is quite a bit more encapsulated than it is in, for example, GTK+.</p>
<p>For new projects written in C++ that target different platforms, including (for example) smart phones, wxWidgets may be a good choice. I have no experience whatsoever with it, however, so I can neither recommend it, nor recommend not using it. I would suggest, though, that you take a look at <a target="_blank" href="http://wiki.wxwidgets.org/WxWidgets_Compared_To_Other_Toolkits">wxWidgets compared to other toolkits</a> including its last seciont: &#8220;Why You Shouldn&#8217;t Use wxWidgets&#8221;.</p>
<p>Go to <a href="http://www.wxwidgets.org/download" target="_blank">the download page</a> to download and install.</p>
<h3>Qt</h3>
<p>Now owned by Nokia, Qt was originally the closed-source library on which KDE was based. Qt has grown out of its closed-source roots and is now available under LGPL. It is a complete GUI toolkit written in C++ and ported across several platforms, including embedded ones. It even comes with its own windowing system for embdedded platforms.</p>
<p>Qt consists of its own build system, its own IDE, its own internationalization system, its own GUI design system, a large number of ready-made widgets and a complete set of libraries that do anything from networking to XML parsing, filesystem access, etc. This has, of course, its drawbacks as well as its advantages, but these &#8220;own implementations&#8221; are generally well-written and generic enough for general use.</p>
<p>Qt pioneered the signals/slots view of the Observer pattern, and uses its meta-object compiler to generate the code necessary to to maintain the signals and slots. Though with modern C++ compilers this is no longer necessary (see the Boost.Signal implementation of signals and slots for proof if you need it) at the time it was a judicious choice and now is only a minor nuisance.</p>
<p>For new C++ projects that need a GUI, this is the GUI toolkit I would personally use: it contains everything you need to quickly develop a GUI around your existing code and can sometimes come in handle to put an app together quickly. Qt&#8217;s implementation of the model-view-controller pattern is one of the best I&#8217;ve encountered so far, and allows you to completely de-couple the core implementation of your work from the GUI which, to me, is an absolute requirement for creating testable, maintainable software.</p>
<p>You can get the latest version at <a href="http://qt.nokia.com">the Qt page</a>.</p>
<h2>Integrated Development Environments</h2>
<p>There are several FLOSS IDEs on Windows. Obviously, I won&#8217;t count Microsoft Visual Studio Express Edition: it may be free as in beer, but it&#8217;s not libre or open source software. It wouldn&#8217;t work with either of the two toolchains I mentioned above anyway, btw, unless you have a nac for writing Makefiles and not getting support from your IDE to keep them up-to-date&#8230;</p>
<p>The ones I will look at are <b>Code::Blocks</b>, <b>CodeLite</b>, <b>Anjuta</b>, <b>Qt Creator</b> and <b>Eclipse</b>.</p>
<h3>Code::Blocks and CodeLite</h3>
<p>Right off the bat, I should say I&#8217;ve never used either of these two IDEs. They seem to be the IDEs of choice for wxWidgets, though, so I feel I should at least mention them. If you have anything, good or bad, to say about either of these IDEs, leave a comment.</p>
<h3>Anjuta</h3>
<p>I&#8217;ve used Anjuta for GTK development, and for development in C, on Linux (under GNOME) and on Windows. As far as I can tell, there are no recent ports to Windows of this IDE, however. The port that existed a while ago had some stability issues and should not be used in production environments. Under Linux, its behavior is a lot better.</p>
<p>I would not recommend using Anjuta in a FLOSS development environment on Windows. On Linux, as indicated, it&#8217;s another story &#8211; but that is not the subject of this article.</p>
<h3>Qt Creator</h3>
<p>While Qt Creator comes with Qt and, as I stated before, Qt is my GUI framework/toolkit of choice for new GUI applications in C++, Qt Creator is by no means my IDE of choice for such applications: although its integration with Qt is, obviously, very good, it assumes (usually correctly) that you&#8217;re doing Qt programming and is therefore less well-adapted to general-purpose programming. This may or may not be a problem, depending on whether you want to use the Qt build system and framework for non-GUI applications as well. As I usually don&#8217;t do that, Qt Creator is not my IDE of choice for non-GUI applications in a FLOSS development environment.</p>
<h3>Eclipse</h3>
<p>Eclipse makes no assumptions about anything (or hardly any about hardly anything) and is therefore well-suited for &#8220;core&#8221; programming as well as GUI programming. Due to its modular architecture, it is possible to extend Eclipse well beyond its roots as an IDE for Java. I have so far seen it used as an IDE for several embedded platforms, as well as for things that didn&#8217;t exactly look like an IDE.</p>
<p>For C and C++ programming, there&#8217;s an Eclipse plugin called CDT, which you can download from <a target="_blank" href="http://www.eclipse.org/cdt/downloads.php">here</a>. It does not come with a toolchain, but detects the presence of both Cygwin and MinGW, if they&#8217;re installed in any of the usual locations.</p>
<p>For GUI programming with Qt, there&#8217;s an Eclipse plugin that you can get from <a href="http://qt.nokia.com/developer/eclipse-integration">the Qt website</a>. It looks like a similar plugin for GTK is dead in the water. For wxWidgets, there doesn&#8217;t seem to be a plugin, though there is <a target="_blank" href="http://wiki.wxwidgets.org/Eclipse">a page on their wiki</a> that explains how to use Eclipse (and suggests to use Code::Blocks in stead).</p>
<p>Personally, due to its completeness and the availability of many, many plugins, I&#8217;d go for Eclipse for an IDE in a FLOSS development environment.</p>
<h2>Installation</h2>
<p>I will consider the installation of two three toolchain/GUI toolkit/IDE combinations here: Cygwin with Eclipse, without a GUI; MinGW with Eclipse, without a GUI, MinGW with Eclipse and Qt, and QtCreator with Qt and MinGW. The installation procedure of each of these is described below.</p>
<h3>Cygwin/Eclipse</h3>
<p>In order to use Eclipse with Cygwin, you need the CDT plugin for Eclipse, and you need Cygwin to be installed. You can install Cygwin using <a target="_blank" href="http://cygwin.com/setup.exe">Cygwin Setup</a>. The installation process is pretty straight-forward. The toolchain is in the Devel category. Install at least <b>g++</b> and its dependencies. That should include <b>binutils</b> and <b>gcc</b>. You&#8217;ll need <b>gdb</b> as well.</p>
<p>Once you have Cygwin installed, you might want to try building a simple &#8220;Hello, World!&#8221; program to check that everything works. Should not be a problem, but you might as well try.</p>
<p>Eclipse assumes Java (JRE) to be installed. Just go to <a href="http://java.sun.com" target="_blank">java.sun.com</a> and git the &#8220;Get Java&#8221; button if you don&#8217;t already have it (which is unlikely, but ye never know). It doesn&#8217;t need anything other than downloading and unzipping to run: there&#8217;s no installer.</p>
<p>Eclipse works with &#8220;work spaces&#8221; under which you have &#8220;projects&#8221; which contain your source code, as mapped on the drive. There&#8217;s a plugin for integration with Git (EGit) that you can download and install through Eclipse&#8217;s integrated installer.</p>
<p>Eclipse will detect the presence of Cygwin if it&#8217;s installed in the standard location.</p>
<h3>MinGW/Eclipse</h3>
<p>To install MinGW, you can either use the <a href="http://sourceforge.net/projects/mingw/" target="_blank">automated installer</a> (hit the download button) or the <a href="http://mingw.org/wiki/InstallationHOWTOforMinGW" target="_blank">manual installation procedure</a>. The automated installer is easier to use but the manual installation procedure allows you to get more up-to-date tools. In either case, the tools in the toolchain are the same as for Cygwin.</p>
<p>The instructions for Eclipse are the same as well. You can install both toolchains on your computer and switch between the two if you like. Eclipse will detect them both of they are installed in the usual locations.</p>
<h3>MinGW/Qt/Eclipse</h3>
<p>Adding Qt to the MinGW/Eclipse mix is a question of installing Qt and installing the <a href="http://qt.nokia.com/developer/eclipse-integration">Qt plugin for Eclipse</a>. This shouldn&#8217;t pose any problems &#8211; especially once you have Eclipse and MinGW installed.</p>
<h3>MinGW/Qt/Qt Creator</h3>
<p>Qt Creator comes with its own copy of MinGW, so you don&#8217;t need to install it separately. Just download and install the Qt SDK.</p>
<h2>Conclusion</h2>
<p>I hope this article has been helpful in selecting the tools for your FLOSS projects. If I&#8217;ve missed anything, or if you have any other questions, answers, comments or suggestions, please leave a comment.</p>

<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F&amp;title=Setting+up+a+FLOSS+development+environment+on+Windows" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F&amp;title=Setting+up+a+FLOSS+development+environment+on+Windows" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F&amp;title=Setting+up+a+FLOSS+development+environment+on+Windows" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F&amp;headline=Setting+up+a+FLOSS+development+environment+on+Windows" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Setting+up+a+FLOSS+development+environment+on+Windows&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Setting+up+a+FLOSS+development+environment+on+Windows&amp;u=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Setting+up+a+FLOSS+development+environment+on+Windows&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Setting+up+a+FLOSS+development+environment+on+Windows&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Setting+up+a+FLOSS+development+environment+on+Windows&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F&amp;title=Setting+up+a+FLOSS+development+environment+on+Windows&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsetting-up-a-floss-development-environment-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://landheer-cieslak.com/wordpress/setting-up-a-floss-development-environment-on-windows/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Event handling in C and C++</title>
		<link>http://landheer-cieslak.com/wordpress/event-handling-in-c-and-c/</link>
		<comments>http://landheer-cieslak.com/wordpress/event-handling-in-c-and-c/#comments</comments>
		<pubDate>Wed, 25 Aug 2010 00:26:50 +0000</pubDate>
		<dc:creator>Ronald Landheer-Cieslak</dc:creator>
				<category><![CDATA[C & C++]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://landheer-cieslak.com/wordpress/?p=887</guid>
		<description><![CDATA[One of the most-occurring subpatterns I keep running into lately is an event-handling subpattern. I say subpattern because it is not a pattern in and of itself: it can be part of an observer pattern, a state machine, or of any other pattern in which objects that have neither an &#8220;is-a&#8221; nor an explicit &#8220;has-a&#8221; [...]]]></description>
			<content:encoded><![CDATA[
<p>One of the most-occurring subpatterns I keep running into lately is an event-handling subpattern. I say subpattern because it is not a pattern in and of itself: it can be part of an observer pattern, a state machine, or of any other pattern in which objects that have neither an &#8220;is-a&#8221; nor an explicit &#8220;has-a&#8221; relationship have to send messages to each other. I run into this when I&#8217;m doing C and when I&#8217;m doing C++, and the patterns that this is part of are pretty varied, but the way I handle this subpattern in both languages is almost identical. So I thought I&#8217;d write a post about it.<br />
<span id="more-887"></span><br />
	<div class='ArePayPalContent'>
	<p class='ArePayPalTextToShowIfNotLogedIn'>This is paid content - an experimental feature to try to get some income to support this site\'s maintenance. Please log in to access it.</p>
	<a class='ArePayPalLoginButton' href='http://landheer-cieslak.com/wordpress/wp-login.php?redirect_to=http://landheer-cieslak.com/wordpress/feed/'>Log in</a>
	</div></p>

<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F&amp;title=Event+handling+in+C+and+C%2B%2B" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F&amp;title=Event+handling+in+C+and+C%2B%2B" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F&amp;title=Event+handling+in+C+and+C%2B%2B" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F&amp;headline=Event+handling+in+C+and+C%2B%2B" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Event+handling+in+C+and+C%2B%2B&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Event+handling+in+C+and+C%2B%2B&amp;u=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Event+handling+in+C+and+C%2B%2B&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Event+handling+in+C+and+C%2B%2B&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Event+handling+in+C+and+C%2B%2B&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F&amp;title=Event+handling+in+C+and+C%2B%2B&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fevent-handling-in-c-and-c%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://landheer-cieslak.com/wordpress/event-handling-in-c-and-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The heap algorithm</title>
		<link>http://landheer-cieslak.com/wordpress/the-heap-algorithm/</link>
		<comments>http://landheer-cieslak.com/wordpress/the-heap-algorithm/#comments</comments>
		<pubDate>Mon, 16 Aug 2010 12:00:06 +0000</pubDate>
		<dc:creator>Ronald Landheer-Cieslak</dc:creator>
				<category><![CDATA[C++ for the self-taught]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://landheer-cieslak.com/wordpress/?p=874</guid>
		<description><![CDATA[Last night, I had an idea for a new lock-free algorithm: a single-producer, single-producer queue with a wait-free push and a lock-free pop. The algorithm in question, which is remarkably efficient for, e.g., logging (which is why I called the project HSL for High-Speed Logging) is prone to what I call &#8220;spurious popping&#8221; &#8211; i.e., [...]]]></description>
			<content:encoded><![CDATA[
<p>Last night, I had an idea for a new lock-free algorithm: a single-producer, single-producer queue with a wait-free push and a lock-free pop. The algorithm in question, which is remarkably efficient for, e.g., logging (which is why I called the project HSL for High-Speed Logging) is prone to what I call &#8220;spurious popping&#8221; &#8211; i.e., the queue can produce the same value more than once if it runs into a race condition, due to the wait-free nature of the push. The details of this are beyond the scope of the C++ for the self-taught column, but suffice it to say that I worked around this limitation (which is not a bug, by the way) by detecting it. An added peculiarity of my solution was that several queues had to be synchronized together by the consumer, to sort the values popped from the queues. Suffice it to say that I decided to kill two birds with one stone and used a heap.</p>
<p>This article will explain why: I&#8217;ll first explain what a heap is, how it works, show you the complete implementation of a heap in C and analyze its computational complexity. I will also discuss the alternatives I had and why I chose to use a heap in stead.<br />
<span id="more-874"></span></p>
<h2>What is a heap?</h2>
<p>A heap (in our case) is a binary tree of which each node&#8217;s invariant is determined by a strict weak ordering predicate. I&#8217;ll explain what that means by explaining each of the terms I just used: <em>invariant</em>, <em>predicate</em>,<em>strict weak ordering</em> and <em>binary tree</em>.</p>
<h3>What is an invariant?</h3>
<p>An invariant, in its largest definition, is something that must always be the same. In our case, it is an assertion, or a set of assertions, that must always be true in order for our abstract data type (ADT, the heap) to be in a consistent state. For example: a <em>trapezium</em> is a shape that has four corners, each of which is connected to the next by a straight line, and those lines cannot cross. The invariants of a trapezium are:
<ul>
<li>it has four corners</li>
<li>each corner is connected to two other corners by a straight line</li>
<li>none of the lines cross another line</li>
</ul>
<p>.</p>
<p>The more invariants you add, the more you know about the object you&#8217;re adding invariants to. For example: a parallelogram is a trapezium of which each side is parallel to another side, which implies that each corner has the same angle as the opposing corner. Hence, the assertions
<ul>
<li>each side is parallel to another side, and</li>
<li>each corner has the same angle as the opposing corner</li>
</ul>
<p> are both true, but are also mutually inclusive (if one is true, so is the other). Now, you can see that a parallelogram is really a special case of a trapezium &#8211; we&#8217;d model that in C++ as two classes, Trapezium and Parallelogram, which derive from each other (Parallelogram is derived from Trapezium). This implies that if you derive one class from another, the derived class must uphold all the invariants of the base class.</p>
<p>Let&#8217;s put this notion in pseudo-code:
<pre>class Trapezium
{
	void checkInvariants()
	{
		assert(this has four corners);
		assert(each corner is connected to two others by a straight line);
		assert(none of the lines cross any of the other lines);
		assert(at least one of the lines is parallel to another line);
	}
};

class Parallelogram : public Trapezium
{
	void checkInvariants()
	{
		Trapezium::checkInvariants();
		assert(each of the sides is parallel to another side);
		assert(each of the corners has the same angle as the opposing corner);
	}
};</pre>
<p>We can push this notion a bit further by considering lozenges and rectangles: lozenges are parallelograms of which all the sides have the same length; rectangles are parallelograms of which all corners have a 90 degree angle:</p>
<pre>class Lozenge : public Parallelogram
{
	void checkInvariants()
	{
		Parallelogram::checkInvariants();
		assert(all of the sides have the same length);
	}
};

class Rectangle : public Parallelogram
{
	void checkInvariants()
	{
		Parallelogram::checkInvariants();
		assert(all corners have a 90 degree angle);
	}
};</pre>
<p>Now, you can see that by combining sets of invariants, we end up creating classes that don&#8217;t have any invariants of their own, but are still very useful:
<pre>class Square : Rectangle, Lozenge
{
	void checkInvariants()
	{
		Rectangle::checkInvariants();
		Lozenge::checkInvariants();
	}
}</pre>
<p>In object-oriented design, invariants are very important, though sometimes they cannot be easily expressed in code. When they <em>can</em> be expressed in code, however, it is almost always useful to do so &#8211; though it is not always useful to check them during the execution of the code in production. When they are checked, there are a few caveats you should know about:</p>
<dl>
<dt>Invariants don&#8217;t only apply to the <em>visible</em> state of an object</dt>
<dd>Often, e.g. when implementing abstract data types such as heaps, the implementation can be wildly different from the visible state: the visible state of a heap, for example, is much the same as a stack, but sorted. Internally, unlike a stack, it is a tree which, unlike other trees, may be mapped into an array. In such a case, the invariants of an array apply, as do the invariants of our binary tree, but those of a &#8220;sorted stack&#8221; actually don&#8217;t apply, even though the ADT behaves as one.</p>
<p>Similarly, a circular buffer is usually implemented as an array and two pointers into the array and is often exposed as a contiguous space though an API. The buffer is mapped into the array using the two pointers, meaning the invariants of the buffer (such as the size of the writable space plus the size of the readable space is a constant) are different from the invariants of the implementation (such as both pointers always point within the array or one past the array).</dd>
<dt>Invariants may not hold at any moment, but should always hold after public operations have been performed</dt>
<dd>When implementing any non-trivial class that has invariants that can be expressed in code, those invariants invariably get broken while operations are in progress. Even externally visible invariants may be broken during such operations &#8211; and re-established afterwards. Take the circular buffer as an example (we&#8217;ll get to the heap when we start discussing its implementation): one of its invariants is that the total write space size plus the total read space size is a constant (i.e. if you have a circular buffer of N items, the number of items you can write when the buffer is empty is N, the number of items you can read when it is full is also N, and the if there are X items to read, you can still write N &#8211; X items). That constant is the capacity of the circular buffer. Now say you want to insert something into the buffer. Often, you&#8217;ll first &#8220;reserve a bucket&#8221; by advancing the write pointer. If at this moment you look at the write space, and there are X items already in the buffer, you get N &#8211; X &#8211; 1 because you can&#8217;t read from the bucket you&#8217;re writing to yet, but you can&#8217;t write to it from another write either. However, once you&#8217;re done with the bucket you were writing to, you release it and it becomes available for writing &#8211; thus re-establishing the invariant.</p>
<p>																																																																																															 In practice, this means that when you&#8217;re implementing a class with an invariant, private members of the class cannot count on the invariant of the class being valid when they are called, while public and protected methods can. Also, private members don&#8217;t always re-establish the invariant when done, while protected and public methods do.</p>
<p>																																																																																															 Similarly, when you&#8217;re working on an abstract data structure that uses locking internally to make it thread-safe, invariants should typically be re-established before a lock is released.</p>
<p>																																																																																															 Now, you may remember about the three guarantees: the <em>weak, strong and no-fail guarantee</em>. These guarantees, formulated in terms of invariants are:
<dl>
<dt>The weak guarantee:</dt>
<dd>the operation may fail, but will re-establish all invariants if it does so, such that the state of the object remains valid</dd>
<dt>the strong guarantee</dt>
<dd>the operation may fail, but in that case it has no effect (and therefore the object&#8217;s invariants still hold)</dd>
<dt>the no-fail guarantee</dt>
<dd>the operation cannot fail</dd>
</dl>
<p>You&#8217;ll remember that the weak guarantee is a minimum guarantee, so constructors must also obey it. I single out constructors because this means two-part construction (call a constructor, then call and initialization function) is generally a bad idea because the initialization function is typically used to establish the invariants for the first time.</dd>
</dl>
<h3>What is a predicate?</h3>
<p>A predicate is a function that returns a boolean. Usually, in C++, we use function objects (functors) for this:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">struct</span> Pred <span style="color: #008080;">:</span> unary_function<span style="color: #000080;">&lt;</span> C, <span style="color: #0000ff;">bool</span> <span style="color: #000080;">&gt;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #0000ff;">bool</span> operator<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#40;</span>C c<span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">const</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #0000ff;">return</span> <span style="color: #ff0000; font-style: italic;">/* something or other w.r.t. c */</span>
	<span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>Sorted ADTs usually use binary predicates (predicates that take two arguments) for their sorting &#8211; i.e. to compare two values to each other. Our heap will do that too.</p>
<h3>What is strict weak ordering?</h3>
<p>See <a href="http://www.sgi.com/tech/stl/StrictWeakOrdering.html">this explanation</a> for an exact definition. Basically, it means that a predicate that provides this ordering provides the same kind of behavior as less-than does on numbers.</p>
<h3>What is a binary tree?</h3>
<p><img src="http://landheer-cieslak.com/binary_tree.png" align="right" />A binary tree is a tree of which each node (except the leaf nodes) have (at most) two children. Trees like this are very common in computing because they are fairly easy to work with. Among other things, they can be stored in a contiguous array in an &#8220;Ahnentafel list&#8221;. This is a feature we will be using in our implementation as well. Another feature is that from any node, a direct path to the root is at most <img src='http://s.wordpress.com/latex.php?latex=%5Clog%5E2%28n%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\log^2(n)' title='\log^2(n)' class='latex' /> hops, where n is the number of nodes in the tree. This is called the <em>depth</em> of the tree. Due to these two advantages, the heap we are about to implement will have <img src='http://s.wordpress.com/latex.php?latex=O%28%5Clog%5E2%28n%29%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(\log^2(n))' title='O(\log^2(n))' class='latex' /> complexity for insertion and for removing an item from the heap, but, due to the invariants we will put in place, search will be <img src='http://s.wordpress.com/latex.php?latex=O%28n%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(n)' title='O(n)' class='latex' /> in the worst case.</p>
<h3>Putting it all together: the invariants of a heap&#8217;s binary tree</h3>
<p>In the binary tree we&#8217;ll be implementing, each node will hold a value and that value will be smaller than the values of each if the node&#8217;s child nodes. I.e., we might model this as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">template</span> <span style="color: #000080;">&lt;</span> <span style="color: #0000ff;">typename</span> T <span style="color: #000080;">&gt;</span>
<span style="color: #0000ff;">class</span> Node
<span style="color: #008000;">&#123;</span>
<span style="color: #0000ff;">public</span> <span style="color: #008080;">:</span>
	Node<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> T <span style="color: #000040;">&amp;</span> t<span style="color: #008000;">&#41;</span>
		<span style="color: #008080;">:</span> t_<span style="color: #008000;">&#40;</span>t<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span> <span style="color: #ff0000; font-style: italic;">/* no-op */</span> <span style="color: #008000;">&#125;</span>
&nbsp;
	<span style="color: #0000ff;">void</span> checkInvariants<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #0000dd;">assert</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">!</span>lhs_ <span style="color: #000040;">||</span> t_ <span style="color: #000080;">&lt;</span> lhs_<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>t_<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
		<span style="color: #0000dd;">assert</span><span style="color: #008000;">&#40;</span><span style="color: #000040;">!</span>rhs_ <span style="color: #000040;">||</span> t_ <span style="color: #000080;">&lt;</span> rhs_<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>t_<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
	<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0000ff;">private</span> <span style="color: #008080;">:</span>
	T t_<span style="color: #008080;">;</span>
	Node<span style="color: #000080;">&lt;</span> T <span style="color: #000080;">&gt;</span> <span style="color: #000040;">*</span> lhs_<span style="color: #008080;">;</span>
	Node<span style="color: #000080;">&lt;</span> T <span style="color: #000080;">&gt;</span> <span style="color: #000040;">*</span> rhs_<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span><span style="color: #008080;">;</span></pre></div></div>

<p>Another invariant is that if a node has a right-hand-side node, it also has a left-hand-side node:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">@@ -<span style="">10</span>,<span style="">6</span> +<span style="">10</span>,<span style="">7</span> @@
 	<span style="">&#123;</span>
 		assert<span style="">&#40;</span>!lhs_ || t_ &lt; lhs_-&gt;t_<span style="">&#41;</span>;
 		assert<span style="">&#40;</span>!rhs_ || t_ &lt; rhs_-&gt;t_<span style="">&#41;</span>;
<span style="color: #00b000;">+		assert<span style="">&#40;</span>!rhs_ || lhs_<span style="">&#41;</span>;</span>
 	<span style="">&#125;</span>
&nbsp;
 private :</pre></div></div>

<p>This latter invariant allows us to efficiently store the tree in an array &#8211; i.e. without losing any space. <code>T</code>, in the case of our first implementation, will be an integer.</p>
<h2>Implementing the Heap</h2>
<p>Like I mentioned above, the heap will be implemented as an array. We will need to know the number of elements in the array for almost any operation we might want to perform on the heap as well, so we will wrap the thing into a structure like this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> Heap_struct
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> values_<span style="color: #009900;">&#91;</span>HEAP_MAX_SIZE<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	<span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> end_<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> Heap<span style="color: #339933;">;</span></pre></div></div>

<p>As with anything in C, this structure will need to be initialized and, possibly, finalized, so the first two functions of our API are straight-forward:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> Heap_init<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	heap<span style="color: #339933;">-&gt;</span>end_ <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> HEAP_S_OK<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> Heap_fini<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span> <span style="color: #808080; font-style: italic;">/* no-op */</span> <span style="color: #009900;">&#125;</span></pre></div></div>

<p>Our API will consist of three other functions for now:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> Heap_push<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> Heap_pop<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> <span style="color: #339933;">*</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> Heap_find<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>We&#8217;ll add other functions later.</p>
<h3>Adding unit tests</h3>
<p>As we&#8217;re writing an abstract data type, we really need to start testing it right away, and make sure our tests both cover as much as possible of our code, and don&#8217;t fail when we add new features to the code. We&#8217;ll be using <a href="http://check.sf.net">Check</a> for this, as we&#8217;ll be programming in C. Here&#8217;s what those tests look like for now:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#ifdef USING_CHECK</span>
Suite <span style="color: #339933;">*</span> createTestSuite<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	Suite <span style="color: #339933;">*</span> s <span style="color: #339933;">=</span> suite_create<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Heap&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	TCase <span style="color: #339933;">*</span> tc <span style="color: #339933;">=</span> tcase_create<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Heap&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	suite_add_tcase<span style="color: #009900;">&#40;</span>s<span style="color: #339933;">,</span> tc<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> s<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> fail_count<span style="color: #339933;">;</span>
&nbsp;
	Suite <span style="color: #339933;">*</span> s <span style="color: #339933;">=</span> createTestSuite<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	SRunner <span style="color: #339933;">*</span> sr <span style="color: #339933;">=</span> srunner_create<span style="color: #009900;">&#40;</span>s<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	srunner_run_all<span style="color: #009900;">&#40;</span>sr<span style="color: #339933;">,</span> CK_NORMAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	fail_count <span style="color: #339933;">=</span> srunner_ntests_failed<span style="color: #009900;">&#40;</span>sr<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	srunner_free<span style="color: #009900;">&#40;</span>sr<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span>fail_count <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">?</span> EXIT_SUCCESS <span style="color: #339933;">:</span> EXIT_FAILURE<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #339933;">#endif</span></pre></div></div>

<h3>Navigating the tree</h3>
<p>Like I said before, we will be using an array to store our tree, which means that nodes are found as indices in the array. The root is at 0, and the left-hand-side child of any node <code>N</code> is found by <code>(N * 2) + 1</code>; the right hand side by <code>(N * 2) + 2</code>; the parent by <code>(N - 1) / 2</code>. Let&#8217;s take a look at the code that that gives:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#define Heap_nodeParent(h,n) (((n) - 1) / 2)</span>
<span style="color: #339933;">#define Heap_nodeLhs(h,n) (((n) * 2) + 1)</span>
<span style="color: #339933;">#define Heap_nodeRhs(h,n) (((n) * 2) + 2)</span>
<span style="color: #339933;">#define Heap_nodeSibling(h,n) (((n) % 2) ? ((n) + 1) : ((n) - 1))</span></pre></div></div>

<p>There are two things you&#8217;ll perhaps note here: one is that these are macros, the second is that they each take a parameter they won&#8217;t actually use. The reason for using macros is that there&#8217;s really no reason to use functions for this &#8211; at least not in C. In C++, these would have been private methods of a class. The reason for the first parameter is that by convention, I pass the object being worked on as the first parameter to any function or anything that looks like a function &#8211; which would include macros. There&#8217;s no cost to this (except perhaps a bit of typing) and the benefit is that coding becomes more predictable. For the same reason, anything that looks like a function follows the same naming convention as a function, so my macros are not necessary all in uppercase.</p>
<p>So, right now, heap.h looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* heap.h: a generic heap implementation in C
 * Copyright (C) 2010  Ronald Landheer-Cieslak
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see &lt;http://www.gnu.org/licenses/&gt;. */</span>
<span style="color: #339933;">#ifndef vlinder_heap_h</span>
<span style="color: #339933;">#define vlinder_heap_h</span>
&nbsp;
<span style="color: #339933;">#define HEAP_MAX_SIZE	64</span>
&nbsp;
<span style="color: #339933;">#define HEAP_S_OK		0x00000000</span>
<span style="color: #339933;">#define HEAP_E_FULL		0x80000000</span>
<span style="color: #339933;">#define HEAP_E_EMPTY	0x80000001</span>
&nbsp;
<span style="color: #339933;">#define HEAP_RESULT_IS_ERROR(s)	((s) &amp; 0x80000000)</span>
&nbsp;
<span style="color: #993333;">typedef</span> <span style="color: #993333;">struct</span> Heap_struct
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> values_<span style="color: #009900;">&#91;</span>HEAP_MAX_SIZE<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	<span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> end_<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> Heap<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> Heap_init<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> Heap_fini<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> Heap_push<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> Heap_pop<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> <span style="color: #339933;">*</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">int</span> Heap_find<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> value<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #339933;">#endif</span></pre></div></div>

<p>and heap.c looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">/* heap.c: a generic heap implementation in C
 * Copyright (C) 2010  Ronald Landheer-Cieslak
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see &lt;http://www.gnu.org/licenses/&gt;. */</span>
<span style="color: #339933;">#include &quot;heap.h&quot;</span>
<span style="color: #339933;">#ifdef USING_CHECK</span>
<span style="color: #339933;">#include &lt;check.h&gt;</span>
<span style="color: #339933;">#endif</span>
&nbsp;
<span style="color: #339933;">#define Heap_nodeParent(h,n) (((n) - 1) / 2)</span>
<span style="color: #339933;">#define Heap_nodeLhs(h,n) (((n) * 2) + 1)</span>
<span style="color: #339933;">#define Heap_nodeRhs(h,n) (((n) * 2) + 2)</span>
<span style="color: #339933;">#define Heap_nodeSibling(h,n) (((n) % 2) ? ((n) + 1) : ((n) - 1))</span>
&nbsp;
<span style="color: #993333;">int</span> Heap_init<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	heap<span style="color: #339933;">-&gt;</span>end_ <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> HEAP_S_OK<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> Heap_fini<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span> <span style="color: #808080; font-style: italic;">/* no-op */</span> <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #339933;">#ifdef USING_CHECK</span>
Suite <span style="color: #339933;">*</span> createTestSuite<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	Suite <span style="color: #339933;">*</span> s <span style="color: #339933;">=</span> suite_create<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Heap&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	TCase <span style="color: #339933;">*</span> tc <span style="color: #339933;">=</span> tcase_create<span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Heap&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	suite_add_tcase<span style="color: #009900;">&#40;</span>s<span style="color: #339933;">,</span> tc<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> s<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> fail_count<span style="color: #339933;">;</span>
&nbsp;
	Suite <span style="color: #339933;">*</span> s <span style="color: #339933;">=</span> createTestSuite<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	SRunner <span style="color: #339933;">*</span> sr <span style="color: #339933;">=</span> srunner_create<span style="color: #009900;">&#40;</span>s<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	srunner_run_all<span style="color: #009900;">&#40;</span>sr<span style="color: #339933;">,</span> CK_NORMAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	fail_count <span style="color: #339933;">=</span> srunner_ntests_failed<span style="color: #009900;">&#40;</span>sr<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	srunner_free<span style="color: #009900;">&#40;</span>sr<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span>fail_count <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">?</span> EXIT_SUCCESS <span style="color: #339933;">:</span> EXIT_FAILURE<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #339933;">#endif</span></pre></div></div>

<p>As you can see, push, pop and find aren&#8217;t implemented yet, so we will start with find, which is perhaps the easiest to understand, though also the most complex, of the three.</p>
<p>As of here, code will be presented as patches whenever that makes sense.</p>
<h3>Searching the heap</h3>
<p>In order to search in the heap, we have to implement Heap_find. We&#8217;ll walk through the code bit by bit:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">@@ -<span style="">14</span>,<span style="">14</span> +<span style="">14</span>,<span style="">30</span> @@
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see &lt;http://www.gnu.org/licenses/&gt;. */
 #include &quot;heap.h&quot;
<span style="color: #00b000;">+#include &lt;assert.h&gt;</span>
 #ifdef USING_CHECK
 #include &lt;check.h&gt;
<span style="color: #00b000;">+#include &lt;stdlib.h&gt;</span>
 #endif
&nbsp;
 #define Heap_nodeParent<span style="">&#40;</span>h,n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> - <span style="">1</span><span style="">&#41;</span> / <span style="">2</span><span style="">&#41;</span>
 #define Heap_nodeLhs<span style="">&#40;</span>h,n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> * <span style="">2</span><span style="">&#41;</span> + <span style="">1</span><span style="">&#41;</span>
 #define Heap_nodeRhs<span style="">&#40;</span>h,n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> * <span style="">2</span><span style="">&#41;</span> + <span style="">2</span><span style="">&#41;</span>
 #define Heap_nodeSibling<span style="">&#40;</span>h,n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> % <span style="">2</span><span style="">&#41;</span> ? <span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> + <span style="">1</span><span style="">&#41;</span> : <span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> - <span style="">1</span><span style="">&#41;</span><span style="">&#41;</span>
<span style="color: #00b000;">+#define Heap_nodeIsLeaf<span style="">&#40;</span>h, n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;end_ &lt;= Heap_nodeLhs<span style="">&#40;</span>h, n<span style="">&#41;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+#define Heap_nodeIsRhs<span style="">&#40;</span>h, n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> % <span style="">2</span><span style="">&#41;</span> == <span style="">0</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+#define Heap_nodeEq<span style="">&#40;</span>h,n,v<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n<span style="">&#93;</span> == v<span style="">&#41;</span></span>
<span style="color: #00b000;">+#define Heap_nodeLessV<span style="">&#40;</span>h,n,v<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n<span style="">&#93;</span> &lt; v<span style="">&#41;</span></span>
<span style="color: #00b000;">+#define Heap_capacity<span style="">&#40;</span>h<span style="">&#41;</span> <span style="">&#40;</span>sizeof<span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#41;</span> / sizeof<span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span><span style="">0</span><span style="">&#93;</span><span style="">&#41;</span><span style="">&#41;</span></span></pre></div></div>

<p>These macros allow us to query the heap and its nodes. As you can see, these are very dependent on the stored values being in an array of integers right now. We will revisit this later when the algorithmic parts are all set up.</p>
<p>The interesting part is this:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">+
<span style="color: #00b000;">+static unsigned char Heap_depth<span style="">&#40;</span>Heap * heap<span style="">&#41;</span></span>
<span style="color: #00b000;">+<span style="">&#123;</span></span>
<span style="color: #00b000;">+	unsigned int heap_size = Heap_capacity<span style="">&#40;</span>heap<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	unsigned char depth = <span style="">1</span>;</span>
<span style="color: #00b000;">+	while <span style="">&#40;</span>heap_size /= <span style="">2</span><span style="">&#41;</span> ++depth;</span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+	return depth;</span>
<span style="color: #00b000;">+<span style="">&#125;</span></span>
&nbsp;
 int Heap_init<span style="">&#40;</span>Heap * heap<span style="">&#41;</span>
 <span style="">&#123;</span></pre></div></div>

<p>This bit calculates the depth of the tree, which is <img src='http://s.wordpress.com/latex.php?latex=%5Clog%5E2%28n%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\log^2(n)' title='\log^2(n)' class='latex' /> where n is the number of nodes. We use this to check (in an assertion) that the stack we use to track our progress through the tree is large enough.</p>
<p>Now for the find function itself: I&#8217;ll put the whole code here first, then an annotated version.</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">@@ -<span style="">33</span>,<span style="">12</span> +<span style="">50</span>,<span style="">92</span> @@ int Heap_init<span style="">&#40;</span>Heap * heap<span style="">&#41;</span>
 void Heap_fini<span style="">&#40;</span>Heap * heap<span style="">&#41;</span>
 <span style="">&#123;</span> /* no-op */ <span style="">&#125;</span>
&nbsp;
<span style="color: #00b000;">+int Heap_find<span style="">&#40;</span>Heap * heap, int val<span style="">&#41;</span></span>
<span style="color: #00b000;">+<span style="">&#123;</span></span>
<span style="color: #00b000;">+	unsigned int root = <span style="">0</span>, done = <span style="">0</span>, retval = heap-&gt;end_;</span>
<span style="color: #00b000;">+	int stack<span style="">&#91;</span>HEAP_MAX_DEPTH<span style="">&#93;</span>, stackp = <span style="">0</span>;</span>
<span style="color: #00b000;">+	assert<span style="">&#40;</span>Heap_depth<span style="">&#40;</span>heap<span style="">&#41;</span> &lt;= <span style="">&#40;</span>sizeof<span style="">&#40;</span>stack<span style="">&#41;</span> / sizeof<span style="">&#40;</span>stack<span style="">&#91;</span><span style="">0</span><span style="">&#93;</span><span style="">&#41;</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+	if <span style="">&#40;</span>root != heap-&gt;end_<span style="">&#41;</span> while <span style="">&#40;</span>!done<span style="">&#41;</span></span>
<span style="color: #00b000;">+	<span style="">&#123;</span></span>
<span style="color: #00b000;">+		if <span style="">&#40;</span>Heap_nodeEq<span style="">&#40;</span>heap, root, val<span style="">&#41;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			done = <span style="">1</span>;</span>
<span style="color: #00b000;">+			retval = root;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+		else if <span style="">&#40;</span>!Heap_nodeIsLeaf<span style="">&#40;</span>heap, root<span style="">&#41;</span> &amp;&amp;</span>
<span style="color: #00b000;">+				  Heap_nodeEq<span style="">&#40;</span>heap, Heap_nodeLhs<span style="">&#40;</span>heap, root<span style="">&#41;</span>, val<span style="">&#41;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			retval = Heap_nodeLhs<span style="">&#40;</span>heap, root<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+			done = <span style="">1</span>;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+		else if <span style="">&#40;</span>!Heap_nodeIsLeaf<span style="">&#40;</span>heap, root<span style="">&#41;</span> &amp;&amp;</span>
<span style="color: #00b000;">+				  Heap_nodeLessV<span style="">&#40;</span>heap, Heap_nodeLhs<span style="">&#40;</span>heap, root<span style="">&#41;</span>, val<span style="">&#41;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			stack<span style="">&#91;</span>stackp++<span style="">&#93;</span> = root;</span>
<span style="color: #00b000;">+			root = Heap_nodeLhs<span style="">&#40;</span>heap, root<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+		else if <span style="">&#40;</span>!Heap_nodeIsRhs<span style="">&#40;</span>heap, root<span style="">&#41;</span> &amp;&amp;</span>
<span style="color: #00b000;">+				  Heap_nodeSibling<span style="">&#40;</span>heap, root<span style="">&#41;</span> &lt; heap-&gt;end_<span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span>	// we're in a leaf node, visit the sibling, if one is there</span>
<span style="color: #00b000;">+			root = Heap_nodeSibling<span style="">&#40;</span>heap, root<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+		else if <span style="">&#40;</span>stackp == <span style="">0</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			done = <span style="">1</span>;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+		else // go up the stack</span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			do</span>
<span style="color: #00b000;">+			<span style="">&#123;</span></span>
<span style="color: #00b000;">+				root = stack<span style="">&#91;</span>--stackp<span style="">&#93;</span>;</span>
<span style="color: #00b000;">+			<span style="">&#125;</span> while <span style="">&#40;</span>root != <span style="">0</span> &amp;&amp; <span style="">&#40;</span>Heap_nodeRhs<span style="">&#40;</span>heap, root<span style="">&#41;</span> &gt; heap-&gt;end_<span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+			root = Heap_nodeRhs<span style="">&#40;</span>heap, root<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+	<span style="">&#125;</span></span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+	return retval != heap-&gt;end_;</span>
<span style="color: #00b000;">+<span style="">&#125;</span></span>
<span style="color: #00b000;">+</span>
 #ifdef USING_CHECK
<span style="color: #00b000;">+START_TEST<span style="">&#40;</span>Test_Heap_find<span style="">&#41;</span></span>
<span style="color: #00b000;">+<span style="">&#123;</span></span>
<span style="color: #00b000;">+	int i, j;</span>
<span style="color: #00b000;">+	Heap * heap = calloc<span style="">&#40;</span><span style="">1</span>, sizeof<span style="">&#40;</span>Heap<span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	Heap_init<span style="">&#40;</span>heap<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; HEAP_MAX_SIZE; ++i<span style="">&#41;</span></span>
<span style="color: #00b000;">+	<span style="">&#123;</span>	// a linear sorted set of values is a valid heap, which is good</span>
<span style="color: #00b000;">+		// because that means we can test with that.</span>
<span style="color: #00b000;">+		heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span> = i + <span style="">1</span>;</span>
<span style="color: #00b000;">+	<span style="">&#125;</span></span>
<span style="color: #00b000;">+	// note we haven't changed end_ yet, so the heap is still empty</span>
<span style="color: #00b000;">+	// k = <span style="">0</span>;</span>
<span style="color: #00b000;">+	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; <span style="">&#40;</span>HEAP_MAX_SIZE + <span style="">1</span><span style="">&#41;</span>; ++i<span style="">&#41;</span></span>
<span style="color: #00b000;">+	<span style="">&#123;</span></span>
<span style="color: #00b000;">+		heap-&gt;end_ = i;</span>
<span style="color: #00b000;">+		for <span style="">&#40;</span>j = <span style="">0</span>; j &lt; HEAP_MAX_SIZE; ++j<span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			if <span style="">&#40;</span>j &lt; i<span style="">&#41;</span></span>
<span style="color: #00b000;">+			<span style="">&#123;</span></span>
<span style="color: #00b000;">+				fail_unless<span style="">&#40;</span>Heap_find<span style="">&#40;</span>heap, j + <span style="">1</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+			<span style="">&#125;</span></span>
<span style="color: #00b000;">+			else</span>
<span style="color: #00b000;">+			<span style="">&#123;</span></span>
<span style="color: #00b000;">+				fail_if<span style="">&#40;</span>Heap_find<span style="">&#40;</span>heap, j + <span style="">1</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+			<span style="">&#125;</span></span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+	<span style="">&#125;</span></span>
<span style="color: #00b000;">+	Heap_fini<span style="">&#40;</span>heap<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	free<span style="">&#40;</span>heap<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+<span style="">&#125;</span></span>
<span style="color: #00b000;">+END_TEST</span>
<span style="color: #00b000;">+</span>
 Suite * createTestSuite<span style="">&#40;</span><span style="">&#41;</span>
 <span style="">&#123;</span>
 	Suite * s = suite_create<span style="">&#40;</span>&quot;Heap&quot;<span style="">&#41;</span>;
&nbsp;
 	TCase * tc = tcase_create<span style="">&#40;</span>&quot;Heap&quot;<span style="">&#41;</span>;
<span style="color: #00b000;">+	tcase_add_test<span style="">&#40;</span>tc, Test_Heap_find<span style="">&#41;</span>;</span>
 	suite_add_tcase<span style="">&#40;</span>s, tc<span style="">&#41;</span>;
&nbsp;
 	return s;</pre></div></div>

<p>Of course, this chunk includes the unit test. The test basically creates a heap without using the insert function, which hasn&#8217;t been written yet, and loops over it to find all possible values.</p>
<p>Now let&#8217;s walk through the code. The function returns a boolean: non-zero if the value is found, 0 if it isn&#8217;t.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> Heap_find<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> val<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">unsigned</span> <span style="color: #993333;">int</span> root <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> done <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> retval <span style="color: #339933;">=</span> heap<span style="color: #339933;">-&gt;</span>end_<span style="color: #339933;">;</span>
	<span style="color: #993333;">int</span> stack<span style="color: #009900;">&#91;</span>HEAP_MAX_DEPTH<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> stackp <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
	assert<span style="color: #009900;">&#40;</span>Heap_depth<span style="color: #009900;">&#40;</span>heap<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;=</span> <span style="color: #009900;">&#40;</span><span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>stack<span style="color: #009900;">&#41;</span> <span style="color: #339933;">/</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span>stack<span style="color: #009900;">&#91;</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>We use the stack to track the parent we were in. Though we could do that b just calculating the parent of the current node, it also allows us to easily see when we&#8217;re done, and it provides information when debugging.</p>
<p>Stacks aren&#8217;t all that interesting w.r.t. the algorithms: pushing and popping are both <img src='http://s.wordpress.com/latex.php?latex=O%28c%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(c)' title='O(c)' class='latex' /> and they&#8217;re done in LIFO (last-in first-out) order. This particular implementation is just an array and a pointer (or rather: index) into it. Other algorithms are certainly possible, but the basic idea of a stack is that you can adapt almost any non-sorting linear container to become a stack, which is definitely useful.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>root <span style="color: #339933;">!=</span> heap<span style="color: #339933;">-&gt;</span>end_<span style="color: #009900;">&#41;</span></pre></div></div>

<p>Note this clause: we don&#8217;t start finding in an empty heap. If we would, the first thing we&#8217;d do would be to compare the value at the root with the one we&#8217;re looking for &#8211; which could result in unexpected behavior if the heap did not contain only integers.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>done<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>Heap_nodeEq<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #339933;">,</span> val<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span></pre></div></div>

<p>Right now, we check for equality. Later, we will check for equivalence in stead. If the value at the root of the current sub-tree is equal (or later: equivalent) to the one we&#8217;re looking for, we&#8217;re done.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">			done <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
			retval <span style="color: #339933;">=</span> root<span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>Heap_nodeIsLeaf<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span>
			  Heap_nodeEq<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> Heap_nodeLhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> val<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span></pre></div></div>

<p>We take a bit of a short-cut here: if the left-hand-side child node is equal (later: equivalent) to what we&#8217;re looking for, we return it immediately. The reason why this is a short cut is that otherwise, we&#8217;d have to descend into the left-hand-side subtree if the left hand side is not greater than the value we&#8217;re looking for. It comes at the potential cost of an extra comparison, though. We could code an alternate version with one less comparison, if less-than comparison were expensive. It isn&#8217;t for integers, and shouldn&#8217;t be for any valid key.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">			retval <span style="color: #339933;">=</span> Heap_nodeLhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			done <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>Heap_nodeIsLeaf<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span>
			  Heap_nodeLessV<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> Heap_nodeLhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> val<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span></pre></div></div>

<p>When we get this far, we already know that the left-hand-side leaf is not equal, but it might be less than the value we&#8217;re looking for, in which case the value we are looking for might be in one of its children. In that case, we push the current root onto the stack and &#8220;dive&#8221; into the subtree.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">			stack<span style="color: #009900;">&#91;</span>stackp<span style="color: #339933;">++</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> root<span style="color: #339933;">;</span>
			root <span style="color: #339933;">=</span> Heap_nodeLhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>Heap_nodeIsRhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span>
			  Heap_nodeSibling<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> heap<span style="color: #339933;">-&gt;</span>end_<span style="color: #009900;">&#41;</span></pre></div></div>

<p>From a left-hand-side leaf node we go to the right, to see if the value is there. Note that <code>Heap_nodeSibling</code> can move either way, so we need to know where we are before we call it, or we will get stuck here.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">		<span style="color: #009900;">&#123;</span>	<span style="color: #666666; font-style: italic;">// we're in a leaf node, visit the sibling, if one is there</span>
			root <span style="color: #339933;">=</span> Heap_nodeSibling<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>stackp <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span></pre></div></div>

<p>If we&#8217;ve gotten this far and we don&#8217;t have a stack to climb up in, we&#8217;re at the root of the tree. That means we&#8217;re done.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">			done <span style="color: #339933;">=</span> <span style="color: #0000dd;">1</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span> <span style="color: #666666; font-style: italic;">// go up the stack</span>
		<span style="color: #009900;">&#123;</span></pre></div></div>

<p>Otherwise, we start going up the stack and going right.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">			<span style="color: #b1b100;">do</span>
			<span style="color: #009900;">&#123;</span>
				root <span style="color: #339933;">=</span> stack<span style="color: #009900;">&#91;</span><span style="color: #339933;">--</span>stackp<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>root <span style="color: #339933;">!=</span> <span style="color: #0000dd;">0</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span>Heap_nodeRhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;</span> heap<span style="color: #339933;">-&gt;</span>end_<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			root <span style="color: #339933;">=</span> Heap_nodeRhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> retval <span style="color: #339933;">!=</span> heap<span style="color: #339933;">-&gt;</span>end_<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>There&#8217;s something missing in this code &#8211; something our unit test didn&#8217;t pick up. We&#8217;ll find it shortly, but don&#8217;t use this code as-is just yet!</p>
<p>Now, the tree we&#8217;ve created in the test looks like this (in ASCII art):
<pre>
                                                                   1
                                   2                                                               3
                   4                               5                               6                               7
           8               9              10              11              12              13              14              15
      16      17      18      19      20      21      22      23      24      25      26      27      28      29      30      31
    32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63
64
</pre>
<p>As you can see, the tree is balanced, but not complete. It would have been the result of multiple calls to insert if insert were written and called with these numbers in sorted order.</p>
<p>Now, let&#8217;s say we use ,code>Heap_find</code> to find number 35 in this heap. It would go over the following nodes, in this order: 1, 2, 4, 8, 16 32, 64, 33, 17, 34, 35. That's 11 steps - which is better than 35 steps which would have been a linear search. In fact, the works-cast scenario would be trying to find 63 in this heap, because it would actually be slightly worse than linear: in a linear search, it would have been found after 63 steps. In our case, it's found after 64 steps because it's the last leaf we look at - and 64 is one of the first leafs we look at.</p>
<p>You can also see that we've been a bit pessimistic when we allocated our stack: we will actually never have more than 5 roots on the stack (1, 2, 8, 16, 32) but we have seven spaces in the stack. There are two reasons for this: one is that the Heap_depth function is pessimistic: it returns the log2 of the power of two above the given value, so it will return one higher than necessary in our case (<img src='http://s.wordpress.com/latex.php?latex=64%20%3D%202%5E6&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='64 = 2^6' title='64 = 2^6' class='latex' /> but the function returns 7 because the power of two above 64 is 128). A simple patch can fix that:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">@@ -<span style="">34</span>,<span style="">7</span> +<span style="">34</span>,<span style="">7</span> @@
 static unsigned char Heap_depth<span style="">&#40;</span>Heap * heap<span style="">&#41;</span>
 <span style="">&#123;</span>
 	unsigned int heap_size = Heap_capacity<span style="">&#40;</span>heap<span style="">&#41;</span>;
<span style="color: #991111;">-	unsigned char depth = <span style="">1</span>;</span>
<span style="color: #00b000;">+	unsigned char depth = <span style="">0</span>;</span>
 	while <span style="">&#40;</span>heap_size /= <span style="">2</span><span style="">&#41;</span> ++depth;
&nbsp;
 	return depth;</pre></div></div>

<p>The second reason is that we never put the entire path on the stack: we only put the parent nodes on the stack when we've dived into the left-hand-side child of the node, so the current node is never on the stack. We don't want <code>Heap_depth</code> to reflect that, though, so if we want our stack to be less pessimistic, we have to fix the assertion:
<pre>@@ -54,7 +54,7 @@ int Heap_find(Heap * heap, int val)
 {
 	unsigned int root = 0, done = 0, retval = heap->end_;
 	int stack[HEAP_MAX_DEPTH], stackp = 0;
-	assert(Heap_depth(heap) <= (sizeof(stack) / sizeof(stack[0])));
+	assert(Heap_depth(heap) - 1 <= (sizeof(stack) / sizeof(stack[0])));

 	if (root != heap->end_) while (!done)
 	{
</pre>
<h3>Fixing the bug</h3>
<p>Like I said, there's a bug in the current version of the code that didn't get caught by our unit test - even though the coverage of the unit test couldn't be much better and it did perform 4160 iterations, which is a respectable amount of iterations for something like this. However, when describing the code (above), I left something out that may or may not have caught your attention. If it didn't, read the (annotated) code again before reading on.</p>
<p>The point of this little exercise is to show you that, though unit tests are good and will help you a lot when developing your own code, you should not forget to analyze your code thoroughly and think it through before putting it in production anywhere: you should put as much (relative) effort into your testing as you do in your development, if your testing is to be of the same quality as your development - otherwise, your development will turn out to be of the same quality as your testing.</p>
<p>Let's take a look at a test that will bring out the problem:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">@@ -<span style="">97</span>,<span style="">7</span> +<span style="">97</span>,<span style="">7</span> @@ int Heap_find<span style="">&#40;</span>Heap * heap, int val<span style="">&#41;</span>
 <span style="">&#125;</span>
&nbsp;
 #ifdef USING_CHECK
<span style="color: #991111;">-START_TEST<span style="">&#40;</span>Test_Heap_find<span style="">&#41;</span></span>
<span style="color: #00b000;">+START_TEST<span style="">&#40;</span>Test_Heap_find_01<span style="">&#41;</span></span>
 <span style="">&#123;</span>
 	int i, j;
 	Heap * heap = calloc<span style="">&#40;</span><span style="">1</span>, sizeof<span style="">&#40;</span>Heap<span style="">&#41;</span><span style="">&#41;</span>;
<span style="color: #440088;">@@ -<span style="">129</span>,<span style="">12</span> +<span style="">129</span>,<span style="">55</span> @@ START_TEST<span style="">&#40;</span>Test_Heap_find<span style="">&#41;</span></span>
 <span style="">&#125;</span>
 END_TEST
&nbsp;
<span style="color: #00b000;">+START_TEST<span style="">&#40;</span>Test_Heap_find_02<span style="">&#41;</span></span>
<span style="color: #00b000;">+<span style="">&#123;</span></span>
<span style="color: #00b000;">+	int i, j;</span>
<span style="color: #00b000;">+	static int heap_values<span style="">&#91;</span>HEAP_MAX_SIZE<span style="">&#93;</span> = <span style="">&#123;</span></span>
<span style="color: #00b000;">+                                                                 <span style="">1</span>,</span>
<span style="color: #00b000;">+                                 <span style="">3</span>,                                                              <span style="">2</span>,</span>
<span style="color: #00b000;">+	         <span style="">5</span>,                              <span style="">4</span>,                              <span style="">7</span>,                              <span style="">6</span>,</span>
<span style="color: #00b000;">+         <span style="">9</span>,              <span style="">8</span>,             <span style="">11</span>,             <span style="">10</span>,             <span style="">13</span>,             <span style="">12</span>,             <span style="">15</span>,             <span style="">14</span>,</span>
<span style="color: #00b000;">+    <span style="">17</span>,     <span style="">16</span>,     <span style="">19</span>,     <span style="">18</span>,     <span style="">21</span>,     <span style="">20</span>,     <span style="">23</span>,     <span style="">22</span>,     <span style="">25</span>,     <span style="">24</span>,     <span style="">27</span>,     <span style="">26</span>,     <span style="">29</span>,     <span style="">28</span>,     <span style="">31</span>,     <span style="">30</span>,</span>
<span style="color: #00b000;">+  <span style="">33</span>, <span style="">32</span>, <span style="">35</span>, <span style="">34</span>, <span style="">37</span>, <span style="">36</span>, <span style="">39</span>, <span style="">38</span>, <span style="">41</span>, <span style="">40</span>, <span style="">43</span>, <span style="">42</span>, <span style="">45</span>, <span style="">44</span>, <span style="">47</span>, <span style="">46</span>, <span style="">49</span>, <span style="">48</span>, <span style="">51</span>, <span style="">50</span>, <span style="">53</span>, <span style="">52</span>, <span style="">55</span>, <span style="">54</span>, <span style="">57</span>, <span style="">56</span>, <span style="">59</span>, <span style="">58</span>, <span style="">61</span>, <span style="">60</span>, <span style="">63</span>, <span style="">62</span>,</span>
<span style="color: #00b000;">+<span style="">64</span>,</span>
<span style="color: #00b000;">+	<span style="">&#125;</span>;</span>
<span style="color: #00b000;">+	Heap * heap = calloc<span style="">&#40;</span><span style="">1</span>, sizeof<span style="">&#40;</span>Heap<span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	Heap_init<span style="">&#40;</span>heap<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; HEAP_MAX_SIZE; ++i<span style="">&#41;</span></span>
<span style="color: #00b000;">+	<span style="">&#123;</span>	// a linear sorted set of values is a valid heap, which is good</span>
<span style="color: #00b000;">+		// because that means we can test with that.</span>
<span style="color: #00b000;">+		heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span> = heap_values<span style="">&#91;</span>i<span style="">&#93;</span>;</span>
<span style="color: #00b000;">+	<span style="">&#125;</span></span>
<span style="color: #00b000;">+	// note we haven't changed end_ yet, so the heap is still empty</span>
<span style="color: #00b000;">+	k = <span style="">0</span>;</span>
<span style="color: #00b000;">+	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; <span style="">&#40;</span>HEAP_MAX_SIZE + <span style="">1</span><span style="">&#41;</span>; ++i<span style="">&#41;</span></span>
<span style="color: #00b000;">+	<span style="">&#123;</span></span>
<span style="color: #00b000;">+		heap-&gt;end_ = i;</span>
<span style="color: #00b000;">+		for <span style="">&#40;</span>j = <span style="">0</span>; j &lt; HEAP_MAX_SIZE; ++j<span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			if <span style="">&#40;</span>j &lt; i<span style="">&#41;</span></span>
<span style="color: #00b000;">+			<span style="">&#123;</span></span>
<span style="color: #00b000;">+				int rv = Heap_find<span style="">&#40;</span>heap, heap_values<span style="">&#91;</span>j<span style="">&#93;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+				fail_unless<span style="">&#40;</span>rv<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+			<span style="">&#125;</span></span>
<span style="color: #00b000;">+			else</span>
<span style="color: #00b000;">+			<span style="">&#123;</span></span>
<span style="color: #00b000;">+				fail_if<span style="">&#40;</span>Heap_find<span style="">&#40;</span>heap, heap_values<span style="">&#91;</span>j<span style="">&#93;</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+			<span style="">&#125;</span></span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+	<span style="">&#125;</span></span>
<span style="color: #00b000;">+	Heap_fini<span style="">&#40;</span>heap<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	free<span style="">&#40;</span>heap<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+<span style="">&#125;</span></span>
<span style="color: #00b000;">+END_TEST</span>
<span style="color: #00b000;">+</span>
 Suite * createTestSuite<span style="">&#40;</span><span style="">&#41;</span>
 <span style="">&#123;</span>
 	Suite * s = suite_create<span style="">&#40;</span>&quot;Heap&quot;<span style="">&#41;</span>;
&nbsp;
 	TCase * tc = tcase_create<span style="">&#40;</span>&quot;Heap&quot;<span style="">&#41;</span>;
<span style="color: #991111;">-	tcase_add_test<span style="">&#40;</span>tc, Test_Heap_find<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	tcase_add_test<span style="">&#40;</span>tc, Test_Heap_find_01<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	tcase_add_test<span style="">&#40;</span>tc, Test_Heap_find_02<span style="">&#41;</span>;</span>
 	suite_add_tcase<span style="">&#40;</span>s, tc<span style="">&#41;</span>;
&nbsp;
 	return s;</pre></div></div>

<p>As you can see, this test implements a heap that is designed to bring out the error: if you were to run the code with this test, the test would fail when trying to find the value 2 in the tree. The reason for that is that the find algorithm is missing a crucial step:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">@@ -<span style="">25</span>,<span style="">6</span> +<span style="">25</span>,<span style="">7</span> @@
 #define Heap_nodeRhs<span style="">&#40;</span>h,n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> * <span style="">2</span><span style="">&#41;</span> + <span style="">2</span><span style="">&#41;</span>
 #define Heap_nodeSibling<span style="">&#40;</span>h,n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> % <span style="">2</span><span style="">&#41;</span> ? <span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> + <span style="">1</span><span style="">&#41;</span> : <span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> - <span style="">1</span><span style="">&#41;</span><span style="">&#41;</span>
 #define Heap_nodeIsLeaf<span style="">&#40;</span>h, n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;end_ &lt;= Heap_nodeLhs<span style="">&#40;</span>h, n<span style="">&#41;</span><span style="">&#41;</span>
<span style="color: #00b000;">+#define Heap_nodeHasRhs<span style="">&#40;</span>h, n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;end_ &lt;= Heap_nodeRhs<span style="">&#40;</span>h, n<span style="">&#41;</span><span style="">&#41;</span></span>
 #define Heap_nodeIsRhs<span style="">&#40;</span>h, n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> % <span style="">2</span><span style="">&#41;</span> == <span style="">0</span><span style="">&#41;</span>
 #define Heap_nodeEq<span style="">&#40;</span>h,n,v<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n<span style="">&#93;</span> == v<span style="">&#41;</span>
 #define Heap_nodeLessV<span style="">&#40;</span>h,n,v<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n<span style="">&#93;</span> &lt; v<span style="">&#41;</span>
<span style="color: #440088;">@@ -<span style="">74</span>,<span style="">6</span> +<span style="">76</span>,<span style="">17</span> @@ int Heap_find<span style="">&#40;</span>Heap * heap, int val<span style="">&#41;</span></span>
 			stack<span style="">&#91;</span>stackp++<span style="">&#93;</span> = root;
 			root = Heap_nodeLhs<span style="">&#40;</span>heap, root<span style="">&#41;</span>;
 		<span style="">&#125;</span>
<span style="color: #00b000;">+		else if <span style="">&#40;</span>!Heap_nodeHasRhs<span style="">&#40;</span>heap, root<span style="">&#41;</span> &amp;&amp;</span>
<span style="color: #00b000;">+				  Heap_nodeEq<span style="">&#40;</span>heap, Heap_nodeRhs<span style="">&#40;</span>heap, root<span style="">&#41;</span>, val<span style="">&#41;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			retval = Heap_nodeRhs<span style="">&#40;</span>heap, root<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+			done = <span style="">1</span>;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+		else if <span style="">&#40;</span>!Heap_nodeHasRhs<span style="">&#40;</span>heap, root<span style="">&#41;</span> &amp;&amp;</span>
<span style="color: #00b000;">+				  Heap_nodeLessV<span style="">&#40;</span>heap, Heap_nodeRhs<span style="">&#40;</span>heap, root<span style="">&#41;</span>, val<span style="">&#41;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			root = Heap_nodeRhs<span style="">&#40;</span>heap, root<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
 		else if <span style="">&#40;</span>!Heap_nodeIsRhs<span style="">&#40;</span>heap, root<span style="">&#41;</span> &amp;&amp;
 				  Heap_nodeSibling<span style="">&#40;</span>heap, root<span style="">&#41;</span> &lt; heap-&gt;end_<span style="">&#41;</span>
 		<span style="">&#123;</span>	// we're in a leaf node, visit the sibling, if one is there</pre></div></div>

<p>This chunk of code checks the right-hand-side child node of the current node and handles the case where the value on the left-hand side of the node is greater than the one we're looking for, but the value on the right-hand side isn't.</p>
<p>If we take a close look at our invariants, we can see why this is important; the node invariant says that any given node's value should be smaller than the values of each of its children (if it has children). It <em>doesn't</em> say that the left-hand-side child should also be smaller than the right-hand-side child. The tree in our new test is a valid one, and inverts each of the values of adjacent children w.r.t. the tree in the first test. It brings this bug to light.</p>
<h3>Pushing onto the heap</h3>
<p>The algorithm to push a value onto the heap is pretty straight-forward: we use what's called a "sift-up" method in that we place the new value at a leaf in the tree and move it up (by swapping it with its parent) until the node invariant holds for the node it is in. An alternative method would have been to find a place to put it by "trickling down" from the root but because of the way we store our heap - in an array - we already know where the left-most leaf node is (it's at the end of the array: <code>heap->values_[hea->end_]</code>), which makes the sift-up method a lot easier to implement.</p>
<p>Let's take a look at the code:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> Heap_push<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> value<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> retval <span style="color: #339933;">=</span> HEAP_S_OK<span style="color: #339933;">;</span>
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">-&gt;</span>end_ <span style="color: #339933;">==</span> Heap_capacity<span style="color: #009900;">&#40;</span>heap<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		retval <span style="color: #339933;">=</span> HEAP_E_FULL<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #b1b100;">else</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #993333;">int</span> curr <span style="color: #339933;">=</span> heap<span style="color: #339933;">-&gt;</span>end_<span style="color: #339933;">++;</span>
		heap<span style="color: #339933;">-&gt;</span>values_<span style="color: #009900;">&#91;</span>curr<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> value<span style="color: #339933;">;</span>
		<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>curr <span style="color: #339933;">!=</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>Heap_nodeLess<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> curr<span style="color: #339933;">,</span> Heap_nodeParent<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> curr<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
			<span style="color: #009900;">&#123;</span>
				Heap_nodeSwap<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> curr<span style="color: #339933;">,</span> Heap_nodeParent<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> curr<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				curr <span style="color: #339933;">=</span> Heap_nodeParent<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> curr<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
			<span style="color: #b1b100;">else</span>
			<span style="color: #009900;">&#123;</span>
				<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #339933;">#ifndef NDEBUG</span>
	Heap_checkInvariants<span style="color: #009900;">&#40;</span>heap<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">#endif</span>
	<span style="color: #b1b100;">return</span> retval<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">&lt;</span>pre<span style="color: #339933;">&gt;</span>Of course<span style="color: #339933;">,</span> the very first thing the <span style="color: #000000; font-weight: bold;">function</span> checks is whether it<span style="color: #ff0000;">'s actually possible to push anything on the heap - which it isn'</span>t <span style="color: #b1b100;">if</span> the heap is full. <span style="color: #202020;">If</span> it is full<span style="color: #339933;">,</span> it will <span style="color: #b1b100;">return</span> a valuye indicating that it is and <span style="color: #b1b100;">do</span> nothing more. <span style="color: #202020;">Otherwise</span><span style="color: #339933;">,</span> it will put the new value at the end of the heap <span style="color: #009900;">&#40;</span>which is the left<span style="color: #339933;">-</span>most available leaf node<span style="color: #009900;">&#41;</span> and swap it up until it is either at the root<span style="color: #339933;">,</span> or its parent is smaller than it is.
&nbsp;
<span style="color: #202020;">Simple</span> though this algorithm may be<span style="color: #339933;">,</span> it is useful to add unit tests <span style="color: #b1b100;">for</span> it. <span style="color: #202020;">One</span> test <span style="color: #339933;">-</span> a <span style="color: #ff0000;">&quot;smoke test&quot;</span> <span style="color: #b1b100;">if</span> you will <span style="color: #339933;">-</span> is to push random values onto the heap and make sure all of them can be found in the heap when done. <span style="color: #202020;">It</span> can be rather tedious to write such a smoke test<span style="color: #339933;">,</span> especially <span style="color: #b1b100;">if</span> you want more than one to be run <span style="color: #009900;">&#40;</span>otherwise<span style="color: #339933;">,</span> how <span style="color: #b1b100;">do</span> you know that it<span style="color: #ff0000;">'s not just the random set of values you chose that happened to work?) but writing a script that generates the test case is easy enough: the following script generates 64 test cases, each with random values to put in the heap. &lt;pre lang=&quot;sh&quot;&gt;#! /bin/bash
rm -f heap.val.in heap.val.tcase.in
for ((i = 0; i &lt; 64; ++i)); do
	echo &quot;#include <span style="color: #000099; font-weight: bold;">\&quot;</span>heap.val.${i}.in<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot; &gt;&gt; heap.val.in
	echo &quot;		tcase_add_test(tc, Test_Heap_push_rnd${i});&quot; &gt;&gt; heap.val.tcase.in
	cat &gt; heap.val.${i}.in &lt;&lt;EOF
START_TEST(Test_Heap_push_rnd${i})
{
	Heap * heap = calloc(1, sizeof(*heap));
	int i;
	int heap_values[HEAP_MAX_SIZE] = {
EOF
	dd bs=4 count=64 if=/dev/random of=tt
	od -A n -t x4 tt | sed -e '</span>s<span style="color: #339933;">/^</span> <span style="color: #339933;">/</span>		0x<span style="color: #339933;">/</span><span style="color: #ff0000;">' | sed -e '</span>s<span style="color: #339933;">/</span> <span style="color: #339933;">/,</span> 0x<span style="color: #339933;">/</span>g<span style="color: #ff0000;">' | sed -e '</span>s<span style="color: #339933;">/</span>$<span style="color: #339933;">/,/</span>g<span style="color: #ff0000;">' &gt;&gt; heap.val.${i}.in
	cat &gt;&gt; heap.val.${i}.in &lt;&lt;EOF
	};
&nbsp;
	Heap_init(heap);
	for (i = 0; i &lt; HEAP_MAX_SIZE; ++i)
	{
		fail_unless(Heap_push(heap, heap_values[i]) == HEAP_S_OK);
	}
	// pushing anything in here now should fail
	fail_unless(Heap_push(heap, 0) == HEAP_E_FULL);
	for (i = 0; i &lt; HEAP_MAX_SIZE; ++i)
	{
		fail_unless(Heap_find(heap, heap_values[i]));
	}
//	Heap_dump(heap, stdout);
	Heap_fini(heap);
	free(heap);
}
END_TEST
EOF
&nbsp;
done</span></pre></div></div>

<p>This is what one of those tests looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">START_TEST<span style="color: #009900;">&#40;</span>Test_Heap_push_rnd54<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	Heap <span style="color: #339933;">*</span> heap <span style="color: #339933;">=</span> calloc<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>heap<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
	<span style="color: #993333;">int</span> heap_values<span style="color: #009900;">&#91;</span>HEAP_MAX_SIZE<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #208080;">0x3196a3b8</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xa53e4989</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x23b36d80</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xd324e8a7</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0x73d71b10</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xd5dea692</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x2faf7ef1</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x06515cb3</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0xbd8affd4</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x0eada2a5</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xf068d6da</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x5d720625</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0x8077b60c</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xdbd1fffd</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x9f357c8c</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x38ef64eb</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0x4a1e1513</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x891a7be9</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xd738d651</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xa715584c</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0x223a4a78</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xd02354a7</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x503c4a3d</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x5c5deb30</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0xdff69472</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xa5effd60</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x2584ef20</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x41f7f45b</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0x846633f2</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xf7bce84f</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x70f1f224</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xbc10b2ff</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0xc1229e66</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x67f83a40</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xa7ef445c</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xa25d9b97</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0x2b86dea3</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xb2b37e57</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x450305ad</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x3e194d93</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0xe1422d07</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xaa3c37f6</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x92540227</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x849b216a</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0x18958218</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xea89e7b1</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x94b2a9e8</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x7a244559</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0x450879bd</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x029059c9</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xc121cb75</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x73c21ced</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0x09bba9f5</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xdc1b66fc</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xb8381cc8</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xb7484b98</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0xcc60b798</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xc18653ef</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x758ad5cc</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x6c8e7d1d</span><span style="color: #339933;">,</span>
		<span style="color: #208080;">0x54378939</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x1562c20b</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xe6c64b6d</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xeb86a57b</span><span style="color: #339933;">,</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
	Heap_init<span style="color: #009900;">&#40;</span>heap<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> HEAP_MAX_SIZE<span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		fail_unless<span style="color: #009900;">&#40;</span>Heap_push<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> heap_values<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> HEAP_S_OK<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">// pushing anything in here now should fail</span>
	fail_unless<span style="color: #009900;">&#40;</span>Heap_push<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> HEAP_E_FULL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> HEAP_MAX_SIZE<span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		fail_unless<span style="color: #009900;">&#40;</span>Heap_find<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> heap_values<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #666666; font-style: italic;">//	Heap_dump(heap, stdout);</span>
	Heap_fini<span style="color: #009900;">&#40;</span>heap<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	free<span style="color: #009900;">&#40;</span>heap<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
END_TEST</pre></div></div>

<p>These tests are generated by the Makefile if they don't exist.</p>
<p>Like I said, these are smoke tests. We also want to know whether the layout of the tree is as expected, which is why I wrote a function called <code>Heap_dump</code> to manually inspect the contents of a tree (I won't put the code of that here - it's a simple for loop). Also, at the end of each execution of the push function, the invariants of the nodes are checked to make sure the heap is still valid. The <code>Heap_checkInvariants</code> function looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">static</span> <span style="color: #993333;">void</span> Heap_checkInvariants<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> curr<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>curr <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> curr <span style="color: #339933;">&lt;</span> heap<span style="color: #339933;">-&gt;</span>end_<span style="color: #339933;">;</span> <span style="color: #339933;">++</span>curr<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		assert<span style="color: #009900;">&#40;</span>Heap_nodeIsLeaf<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> curr<span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> Heap_nodeLess<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> curr<span style="color: #339933;">,</span> Heap_nodeLhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> curr<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		assert<span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>Heap_nodeHasRhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> curr<span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> Heap_nodeLess<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> curr<span style="color: #339933;">,</span> Heap_nodeRhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> curr<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Of course, there is no need to follow the tree to check the invariants, as we already know where all the nodes are.</p>
<h3>Popping from the heap</h3>
<p>The algorithm we use for popping from the heap is a trickle-down algorithm: we swap the value at the root of the heap with the left-most leaf (which, again, is easy to find when you're storing the tree in an array as wel are) and trickle what was in the leaf down the tree until we find its final resting place. Here's the code:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> Heap_pop<span style="color: #009900;">&#40;</span>Heap <span style="color: #339933;">*</span> heap<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> <span style="color: #339933;">*</span> value<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">int</span> root<span style="color: #339933;">,</span> child<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">-&gt;</span>end_ <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">return</span> HEAP_E_EMPTY<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #b1b100;">else</span>
	<span style="color: #009900;">&#123;</span> <span style="color: #808080; font-style: italic;">/* heap is not empty */</span> <span style="color: #009900;">&#125;</span>
&nbsp;
	Heap_nodeSwap<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> heap<span style="color: #339933;">-&gt;</span>end_ <span style="color: #339933;">-</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #339933;">--</span>heap<span style="color: #339933;">-&gt;</span>end_<span style="color: #339933;">;</span>
&nbsp;
	root <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span>Heap_nodeLhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> heap<span style="color: #339933;">-&gt;</span>end_<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		child <span style="color: #339933;">=</span> Heap_nodeLhs<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>Heap_nodeSibling<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> child<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> heap<span style="color: #339933;">-&gt;</span>end_<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> 
			Heap_nodeLess<span style="color: #009900;">&#40;</span>
				heap<span style="color: #339933;">,</span>
				Heap_nodeSibling<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> child<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
				child<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			child <span style="color: #339933;">=</span> Heap_nodeSibling<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> child<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span>
		<span style="color: #009900;">&#123;</span> <span style="color: #808080; font-style: italic;">/* go left */</span> <span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>Heap_nodeLess<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> child<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			Heap_nodeSwap<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> child<span style="color: #339933;">,</span> root<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			root <span style="color: #339933;">=</span> child<span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #339933;">*</span>value <span style="color: #339933;">=</span> heap<span style="color: #339933;">-&gt;</span>values_<span style="color: #009900;">&#91;</span>heap<span style="color: #339933;">-&gt;</span>end_<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">return</span> HEAP_S_OK<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Of course, this code comes with its own tests. Those tests are generated like the others. There's no real need for hand-written tests as we'd just be testing the same thing: regardless of the order in which items are put in the heap, we want them to come out in ascending order. The generating script now looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="sh" style="font-family:monospace;">#! /bin/bash
rm -f heap.val.in heap.val.tcase.in
for ((i = 0; i &lt; 64; ++i)); do
	echo &quot;#include \&quot;heap.val.${i}.in\&quot;&quot; &gt;&gt; heap.val.in
	echo &quot;		tcase_add_test(tc, Test_Heap_push_rnd${i});&quot; &gt;&gt; heap.val.tcase.in
	echo &quot;		tcase_add_test(tc, Test_Heap_pop_rnd${i});&quot; &gt;&gt; heap.val.tcase.in
	cat &gt; heap.val.${i}.in &lt;&lt;EOF
#line 9 &quot;mkvals.sh&quot;
START_TEST(Test_Heap_push_rnd${i})
{
	Heap * heap = calloc(1, sizeof(*heap));
	int i;
	int heap_values[HEAP_MAX_SIZE] = {
EOF
	dd bs=4 count=64 if=/dev/random of=tt
	od -A n -t x4 tt | sed -e 's/^ /		0x/' | sed -e 's/ /, 0x/g' | sed -e 's/$/,/g' &gt;&gt; heap.val.${i}.in
	cat &gt;&gt; heap.val.${i}.in &lt;&lt;EOF
#line 19 &quot;mkvals.sh&quot;
	};
&nbsp;
	Heap_init(heap);
	for (i = 0; i &lt; HEAP_MAX_SIZE; ++i)
	{
		fail_unless(Heap_push(heap, heap_values[i]) == HEAP_S_OK);
	}
	// pushing anything in here now should fail
	fail_unless(Heap_push(heap, 0) == HEAP_E_FULL);
	for (i = 0; i &lt; HEAP_MAX_SIZE; ++i)
	{
		fail_unless(Heap_find(heap, heap_values[i]));
	}
//	Heap_dump(heap, stdout);
	Heap_fini(heap);
	free(heap);
}
END_TEST
EOF
&nbsp;
	cat &gt;&gt; heap.val.${i}.in &lt;&lt;EOF
#line 41 &quot;mkvals.sh&quot;
START_TEST(Test_Heap_pop_rnd${i})
{
	Heap * heap = calloc(1, sizeof(*heap));
	int i, prev, curr;
	int heap_values[HEAP_MAX_SIZE] = {
EOF
	dd bs=4 count=64 if=/dev/random of=tt
	od -A n -t x4 tt | sed -e 's/^ /		0x/' | sed -e 's/ /, 0x/g' | sed -e 's/$/,/g' &gt;&gt; heap.val.${i}.in
	cat &gt;&gt; heap.val.${i}.in &lt;&lt;EOF
#line 51 &quot;mkvals.sh&quot;
	};
&nbsp;
	Heap_init(heap);
	for (i = 0; i &lt; HEAP_MAX_SIZE; ++i)
	{
		fail_unless(Heap_push(heap, heap_values[i]) == HEAP_S_OK);
	}
	// pushing anything in here now should fail
	fail_unless(Heap_push(heap, 0) == HEAP_E_FULL);
	for (i = 0; i &lt; HEAP_MAX_SIZE; ++i)
	{
		fail_unless(Heap_find(heap, heap_values[i]));
	}
	fail_unless(Heap_pop(heap, &amp;prev) == HEAP_S_OK);
	for (i = 1; i &lt; HEAP_MAX_SIZE; ++i)
	{
		fail_unless(Heap_pop(heap, &amp;curr) == HEAP_S_OK);
		fail_unless(prev &lt;= curr);
		prev = curr;
	}
	fail_unless(Heap_pop(heap, &amp;curr) == HEAP_E_EMPTY);
//	Heap_dump(heap, stdout);
	Heap_fini(heap);
	free(heap);
}
END_TEST
EOF
&nbsp;
done</pre></div></div>

<h2>Continuing from here: Predicates</h2>
<p>With the tests and the heap in its current state, we have 132 tests (128 of which are automatically generated), all of which pass:
<pre>Running suite(s): Heap
100%: Checks: 132, Failures: 0, Errors: 0</pre>
<p>This version is available <a href="http://landheer-cieslak.com/heap-1.0.00.tar.gz">here</a>, but we're not quite done yet: we have that little thing called a predicate to handle.</p>
<p>Up to now, we've used three predicates without really naming them: the macros <code>Heap_nodeEq</code>, <code>Heap_nodeLess</code> and <code>Heap_nodeLessV</code> are all predicates. This really tells us only one thing, though: what our predicate should look like. I.e., it should be a function that takes two pointers to otherwise unknown objects (after all: this is C, we don't have templates to make the type known at compile-time) and return a boolean (nonzero for true, zero for false).</p>
<p>The changes to our code and test cases are really - perhaps surprisingly - limited:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">@@ -<span style="">29</span>,<span style="">12</span> +<span style="">29</span>,<span style="">14</span> @@
 #define Heap_nodeHasLhs<span style="">&#40;</span>h,n<span style="">&#41;</span> !Heap_nodeIsLeaf<span style="">&#40;</span>h,n<span style="">&#41;</span>
 #define Heap_nodeHasRhs<span style="">&#40;</span>h, n<span style="">&#41;</span> <span style="">&#40;</span>Heap_nodeRhs<span style="">&#40;</span>h, n<span style="">&#41;</span> &lt; <span style="">&#40;</span>h<span style="">&#41;</span>-&gt;end_<span style="">&#41;</span>
 #define Heap_nodeIsRhs<span style="">&#40;</span>h, n<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span><span style="">&#40;</span>n<span style="">&#41;</span> % <span style="">2</span><span style="">&#41;</span> == <span style="">0</span><span style="">&#41;</span>
<span style="color: #991111;">-#define Heap_nodeEq<span style="">&#40;</span>h,n,v<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n<span style="">&#93;</span> == v<span style="">&#41;</span></span>
<span style="color: #991111;">-#define Heap_nodeLess<span style="">&#40;</span>h,n1,n2<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n1<span style="">&#93;</span> &lt; <span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n2<span style="">&#93;</span><span style="">&#41;</span></span>
<span style="color: #991111;">-#define Heap_nodeLessV<span style="">&#40;</span>h,n,v<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n<span style="">&#93;</span> &lt; v<span style="">&#41;</span></span>
<span style="color: #00b000;">+#define Heap_nodeEq<span style="">&#40;</span>h,n,v<span style="">&#41;</span>													\</span>
<span style="color: #00b000;">+	<span style="">&#40;</span><span style="">&#40;</span>!<span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;pred_<span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n<span style="">&#93;</span>, v<span style="">&#41;</span><span style="">&#41;</span><span style="">&#41;</span> &amp;&amp; <span style="">&#40;</span>!<span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;pred_<span style="">&#40;</span>v, <span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n<span style="">&#93;</span><span style="">&#41;</span><span style="">&#41;</span><span style="">&#41;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+#define Heap_nodeLess<span style="">&#40;</span>h,n1,n2<span style="">&#41;</span> 												\</span>
<span style="color: #00b000;">+	<span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;pred_<span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n1<span style="">&#93;</span>, <span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n2<span style="">&#93;</span><span style="">&#41;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+#define Heap_nodeLessV<span style="">&#40;</span>h,n,v<span style="">&#41;</span> <span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;pred_<span style="">&#40;</span><span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n<span style="">&#93;</span>, v<span style="">&#41;</span><span style="">&#41;</span></span>
 #define Heap_nodeSwap<span style="">&#40;</span>h,n1,n2<span style="">&#41;</span>												\
 <span style="">&#123;</span>																			\
<span style="color: #991111;">-	int temp = <span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n1<span style="">&#93;</span>;											\</span>
<span style="color: #00b000;">+	void * temp = <span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n1<span style="">&#93;</span>;											\</span>
 	<span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n1<span style="">&#93;</span> = <span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n2<span style="">&#93;</span>;									\
 	<span style="">&#40;</span>h<span style="">&#41;</span>-&gt;values_<span style="">&#91;</span>n2<span style="">&#93;</span> = temp;												\
 <span style="">&#125;</span>
<span style="color: #440088;">@@ -<span style="">47</span>,<span style="">7</span> +<span style="">49</span>,<span style="">7</span> @@ void Heap_dump<span style="">&#40;</span>Heap * heap, FILE * out<span style="">&#41;</span></span>
 	fprintf<span style="">&#40;</span>out, &quot;<span style="">&#123;</span> &quot;<span style="">&#41;</span>;
 	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; heap-&gt;end_; ++i<span style="">&#41;</span>
 	<span style="">&#123;</span>
<span style="color: #991111;">-		fprintf<span style="">&#40;</span>out, <span style="">&#40;</span>i == <span style="">&#40;</span>heap-&gt;end_ - <span style="">1</span><span style="">&#41;</span> ? &quot;%d &quot; : &quot;%d, &quot;<span style="">&#41;</span>, heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		fprintf<span style="">&#40;</span>out, <span style="">&#40;</span>i == <span style="">&#40;</span>heap-&gt;end_ - <span style="">1</span><span style="">&#41;</span> ? &quot;%p &quot; : &quot;%p, &quot;<span style="">&#41;</span>, heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span><span style="">&#41;</span>;</span>
 	<span style="">&#125;</span>
 	fprintf<span style="">&#40;</span>out, &quot;<span style="">&#125;</span>\n&quot;<span style="">&#41;</span>;
 <span style="">&#125;</span>
<span style="color: #440088;">@@ -<span style="">59</span>,<span style="">8</span> +<span style="">61</span>,<span style="">12</span> @@ static void Heap_checkInvariants<span style="">&#40;</span>Heap *</span>
&nbsp;
 	for <span style="">&#40;</span>curr = <span style="">0</span>; curr &lt; heap-&gt;end_; ++curr<span style="">&#41;</span>
 	<span style="">&#123;</span>
<span style="color: #991111;">-		assert<span style="">&#40;</span>Heap_nodeIsLeaf<span style="">&#40;</span>heap, curr<span style="">&#41;</span> || Heap_nodeLess<span style="">&#40;</span>heap, curr, Heap_nodeLhs<span style="">&#40;</span>heap, curr<span style="">&#41;</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #991111;">-		assert<span style="">&#40;</span>!Heap_nodeHasRhs<span style="">&#40;</span>heap, curr<span style="">&#41;</span> || Heap_nodeLess<span style="">&#40;</span>heap, curr, Heap_nodeRhs<span style="">&#40;</span>heap, curr<span style="">&#41;</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		assert<span style="">&#40;</span></span>
<span style="color: #00b000;">+			Heap_nodeIsLeaf<span style="">&#40;</span>heap, curr<span style="">&#41;</span> ||</span>
<span style="color: #00b000;">+			Heap_nodeLess<span style="">&#40;</span>heap, curr, Heap_nodeLhs<span style="">&#40;</span>heap, curr<span style="">&#41;</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		assert<span style="">&#40;</span></span>
<span style="color: #00b000;">+			!Heap_nodeHasRhs<span style="">&#40;</span>heap, curr<span style="">&#41;</span> ||</span>
<span style="color: #00b000;">+			Heap_nodeLess<span style="">&#40;</span>heap, curr, Heap_nodeRhs<span style="">&#40;</span>heap, curr<span style="">&#41;</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
 	<span style="">&#125;</span>
 <span style="">&#125;</span>
&nbsp;
<span style="color: #440088;">@@ -<span style="">74</span>,<span style="">9</span> +<span style="">80</span>,<span style="">10</span> @@ static unsigned char Heap_depth<span style="">&#40;</span>Heap * h</span>
 <span style="">&#125;</span>
 #endif
&nbsp;
<span style="color: #991111;">-int Heap_init<span style="">&#40;</span>Heap * heap<span style="">&#41;</span></span>
<span style="color: #00b000;">+int Heap_init<span style="">&#40;</span>Heap * heap, Heap_pred pred<span style="">&#41;</span></span>
 <span style="">&#123;</span>
 	heap-&gt;end_ = <span style="">0</span>;
<span style="color: #00b000;">+	heap-&gt;pred_ = pred;</span>
&nbsp;
 	return HEAP_S_OK;
 <span style="">&#125;</span>
<span style="color: #440088;">@@ -<span style="">84</span>,<span style="">7</span> +<span style="">91</span>,<span style="">7</span> @@ int Heap_init<span style="">&#40;</span>Heap * heap<span style="">&#41;</span></span>
 void Heap_fini<span style="">&#40;</span>Heap * heap<span style="">&#41;</span>
 <span style="">&#123;</span> /* no-op */ <span style="">&#125;</span>
&nbsp;
<span style="color: #991111;">-int Heap_push<span style="">&#40;</span>Heap * heap, int value<span style="">&#41;</span></span>
<span style="color: #00b000;">+int Heap_push<span style="">&#40;</span>Heap * heap, void * value<span style="">&#41;</span></span>
 <span style="">&#123;</span>
 	int retval = HEAP_S_OK;
 	if <span style="">&#40;</span>heap-&gt;end_ == Heap_capacity<span style="">&#40;</span>heap<span style="">&#41;</span><span style="">&#41;</span>
<span style="color: #440088;">@@ -<span style="">114</span>,<span style="">7</span> +<span style="">121</span>,<span style="">7</span> @@ int Heap_push<span style="">&#40;</span>Heap * heap, int value<span style="">&#41;</span></span>
 	return retval;
 <span style="">&#125;</span>
&nbsp;
<span style="color: #991111;">-int Heap_pop<span style="">&#40;</span>Heap * heap, int * value<span style="">&#41;</span></span>
<span style="color: #00b000;">+int Heap_pop<span style="">&#40;</span>Heap * heap, void ** value<span style="">&#41;</span></span>
 <span style="">&#123;</span>
 	int root, child;
&nbsp;
<span style="color: #440088;">@@ -<span style="">157</span>,<span style="">7</span> +<span style="">164</span>,<span style="">7</span> @@ int Heap_pop<span style="">&#40;</span>Heap * heap, int * value<span style="">&#41;</span></span>
 	return HEAP_S_OK;
 <span style="">&#125;</span>
&nbsp;
<span style="color: #991111;">-int Heap_find<span style="">&#40;</span>Heap * heap, int val<span style="">&#41;</span></span>
<span style="color: #00b000;">+int Heap_find<span style="">&#40;</span>Heap * heap, void * val<span style="">&#41;</span></span>
 <span style="">&#123;</span>
 	unsigned int root = <span style="">0</span>, done = <span style="">0</span>, retval = heap-&gt;end_;
 	int stack<span style="">&#91;</span>HEAP_MAX_DEPTH<span style="">&#93;</span>, stackp = <span style="">0</span>;
<span style="color: #440088;">@@ -<span style="">216</span>,<span style="">15</span> +<span style="">223</span>,<span style="">19</span> @@ int Heap_find<span style="">&#40;</span>Heap * heap, int val<span style="">&#41;</span></span>
 <span style="">&#125;</span>
&nbsp;
 #ifdef USING_CHECK
<span style="color: #00b000;">+static int Test_less<span style="">&#40;</span>void * lhs, void * rhs<span style="">&#41;</span></span>
<span style="color: #00b000;">+<span style="">&#123;</span></span>
<span style="color: #00b000;">+	return <span style="">&#40;</span>lhs &lt; rhs<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+<span style="">&#125;</span></span>
 START_TEST<span style="">&#40;</span>Test_Heap_find_01<span style="">&#41;</span>
 <span style="">&#123;</span>
 	int i, j;
 	Heap * heap = calloc<span style="">&#40;</span><span style="">1</span>, sizeof<span style="">&#40;</span>Heap<span style="">&#41;</span><span style="">&#41;</span>;
<span style="color: #991111;">-	Heap_init<span style="">&#40;</span>heap<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	Heap_init<span style="">&#40;</span>heap, Test_less<span style="">&#41;</span>;</span>
 	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; HEAP_MAX_SIZE; ++i<span style="">&#41;</span>
 	<span style="">&#123;</span>	// a linear sorted set of values is a valid heap, which is good
 		// because that means we can test with that.
<span style="color: #991111;">-		heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span> = i + <span style="">1</span>;</span>
<span style="color: #00b000;">+		heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span> = <span style="">&#40;</span>void*<span style="">&#41;</span><span style="">&#40;</span>i + <span style="">1</span><span style="">&#41;</span>;</span>
 	<span style="">&#125;</span>
 	// note we haven't changed end_ yet, so the heap is still empty
 	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; <span style="">&#40;</span>HEAP_MAX_SIZE + <span style="">1</span><span style="">&#41;</span>; ++i<span style="">&#41;</span>
<span style="color: #440088;">@@ -<span style="">234</span>,<span style="">11</span> +<span style="">245</span>,<span style="">11</span> @@ START_TEST<span style="">&#40;</span>Test_Heap_find_01<span style="">&#41;</span></span>
 		<span style="">&#123;</span>
 			if <span style="">&#40;</span>j &lt; i<span style="">&#41;</span>
 			<span style="">&#123;</span>
<span style="color: #991111;">-				fail_unless<span style="">&#40;</span>Heap_find<span style="">&#40;</span>heap, j + <span style="">1</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+				fail_unless<span style="">&#40;</span>Heap_find<span style="">&#40;</span>heap, <span style="">&#40;</span>void*<span style="">&#41;</span><span style="">&#40;</span>j + <span style="">1</span><span style="">&#41;</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
 			<span style="">&#125;</span>
 			else
 			<span style="">&#123;</span>
<span style="color: #991111;">-				fail_if<span style="">&#40;</span>Heap_find<span style="">&#40;</span>heap, j + <span style="">1</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+				fail_if<span style="">&#40;</span>Heap_find<span style="">&#40;</span>heap, <span style="">&#40;</span>void*<span style="">&#41;</span><span style="">&#40;</span>j + <span style="">1</span><span style="">&#41;</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
 			<span style="">&#125;</span>
 		<span style="">&#125;</span>
 	<span style="">&#125;</span>
<span style="color: #440088;">@@ -<span style="">260</span>,<span style="">11</span> +<span style="">271</span>,<span style="">11</span> @@ START_TEST<span style="">&#40;</span>Test_Heap_find_02<span style="">&#41;</span></span>
 <span style="">64</span>,
 	<span style="">&#125;</span>;
 	Heap * heap = calloc<span style="">&#40;</span><span style="">1</span>, sizeof<span style="">&#40;</span>Heap<span style="">&#41;</span><span style="">&#41;</span>;
<span style="color: #991111;">-	Heap_init<span style="">&#40;</span>heap<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	Heap_init<span style="">&#40;</span>heap, Test_less<span style="">&#41;</span>;</span>
 	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; HEAP_MAX_SIZE; ++i<span style="">&#41;</span>
 	<span style="">&#123;</span>	// a linear sorted set of values is a valid heap, which is good
 		// because that means we can test with that.
<span style="color: #991111;">-		heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span> = heap_values<span style="">&#91;</span>i<span style="">&#93;</span>;</span>
<span style="color: #00b000;">+		heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span> = <span style="">&#40;</span>void*<span style="">&#41;</span>heap_values<span style="">&#91;</span>i<span style="">&#93;</span>;</span>
 	<span style="">&#125;</span>
 	// note we haven't changed end_ yet, so the heap is still empty
 	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; <span style="">&#40;</span>HEAP_MAX_SIZE + <span style="">1</span><span style="">&#41;</span>; ++i<span style="">&#41;</span>
<span style="color: #440088;">@@ -<span style="">274</span>,<span style="">12</span> +<span style="">285</span>,<span style="">12</span> @@ START_TEST<span style="">&#40;</span>Test_Heap_find_02<span style="">&#41;</span></span>
 		<span style="">&#123;</span>
 			if <span style="">&#40;</span>j &lt; i<span style="">&#41;</span>
 			<span style="">&#123;</span>
<span style="color: #991111;">-				int rv = Heap_find<span style="">&#40;</span>heap, heap_values<span style="">&#91;</span>j<span style="">&#93;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+				int rv = Heap_find<span style="">&#40;</span>heap, <span style="">&#40;</span>void*<span style="">&#41;</span>heap_values<span style="">&#91;</span>j<span style="">&#93;</span><span style="">&#41;</span>;</span>
 				fail_unless<span style="">&#40;</span>rv<span style="">&#41;</span>;
 			<span style="">&#125;</span>
 			else
 			<span style="">&#123;</span>
<span style="color: #991111;">-				fail_if<span style="">&#40;</span>Heap_find<span style="">&#40;</span>heap, heap_values<span style="">&#91;</span>j<span style="">&#93;</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+				fail_if<span style="">&#40;</span>Heap_find<span style="">&#40;</span>heap, <span style="">&#40;</span>void*<span style="">&#41;</span>heap_values<span style="">&#91;</span>j<span style="">&#93;</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
 			<span style="">&#125;</span>
 		<span style="">&#125;</span>
 	<span style="">&#125;</span>
<span style="color: #440088;">@@ -<span style="">294</span>,<span style="">16</span> +<span style="">305</span>,<span style="">16</span> @@ START_TEST<span style="">&#40;</span>Test_Heap_push_01<span style="">&#41;</span></span>
 	Heap * heap = calloc<span style="">&#40;</span><span style="">1</span>, sizeof<span style="">&#40;</span>*heap<span style="">&#41;</span><span style="">&#41;</span>;
 	int i;
&nbsp;
<span style="color: #991111;">-	Heap_init<span style="">&#40;</span>heap<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	Heap_init<span style="">&#40;</span>heap, Test_less<span style="">&#41;</span>;</span>
 	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; HEAP_MAX_SIZE; ++i<span style="">&#41;</span>
 	<span style="">&#123;</span>
<span style="color: #991111;">-		fail_unless<span style="">&#40;</span>Heap_push<span style="">&#40;</span>heap, i + <span style="">1</span><span style="">&#41;</span> == HEAP_S_OK<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		fail_unless<span style="">&#40;</span>Heap_push<span style="">&#40;</span>heap, <span style="">&#40;</span>void*<span style="">&#41;</span><span style="">&#40;</span>i + <span style="">1</span><span style="">&#41;</span><span style="">&#41;</span> == HEAP_S_OK<span style="">&#41;</span>;</span>
 	<span style="">&#125;</span>
 	// pushing anything in here now should fail
 	fail_unless<span style="">&#40;</span>Heap_push<span style="">&#40;</span>heap, <span style="">0</span><span style="">&#41;</span> == HEAP_E_FULL<span style="">&#41;</span>;
 	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; HEAP_MAX_SIZE; ++i<span style="">&#41;</span>
 	<span style="">&#123;</span>
<span style="color: #991111;">-		fail_unless<span style="">&#40;</span>heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span> == i + <span style="">1</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		fail_unless<span style="">&#40;</span>heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span> == <span style="">&#40;</span>void*<span style="">&#41;</span><span style="">&#40;</span>i + <span style="">1</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
 	<span style="">&#125;</span>
 	Heap_fini<span style="">&#40;</span>heap<span style="">&#41;</span>;
 	free<span style="">&#40;</span>heap<span style="">&#41;</span>;
<span style="color: #440088;">@@ -<span style="">325</span>,<span style="">16</span> +<span style="">336</span>,<span style="">16</span> @@ START_TEST<span style="">&#40;</span>Test_Heap_push_02<span style="">&#41;</span></span>
 <span style="">64</span>
 	<span style="">&#125;</span>;
&nbsp;
<span style="color: #991111;">-	Heap_init<span style="">&#40;</span>heap<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+	Heap_init<span style="">&#40;</span>heap, Test_less<span style="">&#41;</span>;</span>
 	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; HEAP_MAX_SIZE; ++i<span style="">&#41;</span>
 	<span style="">&#123;</span>
<span style="color: #991111;">-		fail_unless<span style="">&#40;</span>Heap_push<span style="">&#40;</span>heap, HEAP_MAX_SIZE - i<span style="">&#41;</span> == HEAP_S_OK<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		fail_unless<span style="">&#40;</span>Heap_push<span style="">&#40;</span>heap, <span style="">&#40;</span>void*<span style="">&#41;</span><span style="">&#40;</span>HEAP_MAX_SIZE - i<span style="">&#41;</span><span style="">&#41;</span> == HEAP_S_OK<span style="">&#41;</span>;</span>
 	<span style="">&#125;</span>
 	// pushing anything in here now should fail
 	fail_unless<span style="">&#40;</span>Heap_push<span style="">&#40;</span>heap, <span style="">0</span><span style="">&#41;</span> == HEAP_E_FULL<span style="">&#41;</span>;
 	for <span style="">&#40;</span>i = <span style="">0</span>; i &lt; HEAP_MAX_SIZE; ++i<span style="">&#41;</span>
 	<span style="">&#123;</span>
<span style="color: #991111;">-		fail_unless<span style="">&#40;</span>heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span> == heap_values<span style="">&#91;</span>i<span style="">&#93;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		fail_unless<span style="">&#40;</span>heap-&gt;values_<span style="">&#91;</span>i<span style="">&#93;</span> == <span style="">&#40;</span>void*<span style="">&#41;</span>heap_values<span style="">&#91;</span>i<span style="">&#93;</span><span style="">&#41;</span>;</span>
 	<span style="">&#125;</span>
 	Heap_fini<span style="">&#40;</span>heap<span style="">&#41;</span>;
 	free<span style="">&#40;</span>heap<span style="">&#41;</span>;</pre></div></div>

<p>Our predicate-wielding macros have become a bit more complicated because they call functions now, and the "equals" macro has become an "equivalent" macro (predicate fails on the two values in both directions), but that's really all there is to it.</p>
<h2>Final details: duplicate values</h2>
<p>There is one thing we haven't explicitly tested yet, but we should: we haven't tried putting two or more equivalent values on the heap. Our random tests could conceivably run into the case from time to time, but if the system's random number generator (in /dev/random) is any good, the likelihood of that happening is pretty slim (one in about sixty-eight million). So, what happens if we do this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">START_TEST<span style="color: #009900;">&#40;</span>Test_heapPush_duplicates<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	Heap <span style="color: #339933;">*</span> heap <span style="color: #339933;">=</span> calloc<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #339933;">,</span> <span style="color: #993333;">sizeof</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">*</span>heap<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #993333;">int</span> i<span style="color: #339933;">;</span>
&nbsp;
	Heap_init<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> Test_less<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> HEAP_MAX_SIZE<span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		fail_unless<span style="color: #009900;">&#40;</span>Heap_push<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> HEAP_S_OK<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">// pushing anything in here now should fail</span>
	fail_unless<span style="color: #009900;">&#40;</span>Heap_push<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> HEAP_E_FULL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> HEAP_MAX_SIZE<span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		fail_unless<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">-&gt;</span>values_<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> HEAP_MAX_SIZE<span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #993333;">void</span> <span style="color: #339933;">*</span> val<span style="color: #339933;">;</span>
		fail_unless<span style="color: #009900;">&#40;</span>Heap_pop<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> <span style="color: #339933;">&amp;</span>val<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> HEAP_S_OK<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		fail_unless<span style="color: #009900;">&#40;</span>val <span style="color: #339933;">==</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	fail_unless<span style="color: #009900;">&#40;</span>Heap_pop<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> HEAP_E_EMPTY<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	Heap_fini<span style="color: #009900;">&#40;</span>heap<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	free<span style="color: #009900;">&#40;</span>heap<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
END_TEST</pre></div></div>

<p>The answer is this:
<pre>Running suite(s): Heap
assertion "Heap_nodeIsLeaf(heap, curr) || Heap_nodeLess(heap, curr, Heap_nodeLhs(heap, curr))" failed: file "heap.c", line 66, function: Heap_checkInvariants
99%: Checks: 133, Failures: 0, Errors: 1
heap.c:365:E:Heap:Test_heapPush_duplicates:0: (after this point) Received signal 6 (Aborted)</pre>
<p>meaning one of the invariants failed.</p>
<p>There are two ways to handle this: either we change the invariant to allow duplicate values, in which case the invariant becomes "the parent is smaller than <em>or equivalent to</em> each of its children", or we detect the duplicate value when it's inserted into the heap and fail at that point, with an error. In order to decide which one we'll do, we'll consider three things: the requirements our heap has to meet, the risk of not meeting those requirements in either implementation, and the consequences of both implementations if executed correctly.</p>
<p>In terms of requirements, the basic requirements for our heap are pretty straight-forward: we want a push onto the heap, and a pop from the heap, to have <img src='http://s.wordpress.com/latex.php?latex=O%28%5Clog%5E2%28n%29%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(\log^2(n))' title='O(\log^2(n))' class='latex' /> complexity, and a search in the heap to have <img src='http://s.wordpress.com/latex.php?latex=O%28%5Clog%5E2%28n%29%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(\log^2(n))' title='O(\log^2(n))' class='latex' /> complexity on average, and <img src='http://s.wordpress.com/latex.php?latex=O%28n%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(n)' title='O(n)' class='latex' /> complexity in the worst case. In our current implementation, pops are slightly more expensive that pushes because pushes only perform one comparison per node encountered, and <img src='http://s.wordpress.com/latex.php?latex=%5Clog%5E2%28n%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='\log^2(n)' title='\log^2(n)' class='latex' /> comparisons in the worst case. The pop performs two comparisons per node (one with the right-hand-side child, one with the left-hand-side child) and <img src='http://s.wordpress.com/latex.php?latex=2%5Clog%5E2%28n%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='2\log^2(n)' title='2\log^2(n)' class='latex' /> comparisons in the worst case. The find algorithm does three comparisons in the worst case, but may go through the whole tree before it gives up, so it's <img src='http://s.wordpress.com/latex.php?latex=3n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='3n' title='3n' class='latex' /> in the worst case. This is still within our complexity requirements, but we should avoid making it any more expensive if we can.</p>
<p>In terms of guarantees, we need both push and pop to give the strong guarantee: neither should break the invariants and neither should have any effect on the visible state of the heap if they fail: a pop should always either remove a single object from the heap - and that object should be the smallest object on the heap - or fail if the heap is empty; and a push should always either put a single object on the heap or fail if the heap is full. Find should never fail, nor change the state of the heap (nor break any invariants).</p>
<p>Let's consider the way the push algorithm works: it puts the new value in the left-most vacant leaf and propagates it up the tree toward to root. In doing so, it only considers the nodes on the path from the left-most vacant leaf to the root, disregarding any other nodes. This is why the complexity of push is <img src='http://s.wordpress.com/latex.php?latex=O%28%5Clog%5E2%28n%29%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(\log^2(n))' title='O(\log^2(n))' class='latex' />. The most naive implementation of push that would attempt to detect duplicate values would simply detect a duplicate value on that path an report an error if one is found, rolling back the changes it made up to that point. Such an implementation would retain its <img src='http://s.wordpress.com/latex.php?latex=O%28%5Clog%5E2%28n%29%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(\log^2(n))' title='O(\log^2(n))' class='latex' /> complexity - but would it reliably detect duplicates? Let's consider the following bit of code (and imagine that we're using <code>int</code>s in stead of <code>void*</code>s again):</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">Heap_push<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Heap_push<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Heap_push<span style="color: #009900;">&#40;</span>heap<span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This would construct a tree with three nodes: zero at the root, one in each of its children. More importantly, this would not fail because the second time we insert 1, the left-most vacant leaf is the right-hand-side leaf of the root node, so the algorithm would only compare with the root. If we'd want it to compare with the other node containing 1, we'd have to compare with the new node's sibling as well. This is all fine and dandy, until the tree becomes a bit more complex, e.g. by inserting the following values in an empty heap:
<pre>Heap_push(heap, 0);
Heap_push(heap, 10);
Heap_push(heap, 12);
Heap_push(heap, 20);
Heap_push(heap, 15);
Heap_push(heap, 17);
Heap_push(heap, 15);</pre>
<p>This results in the following tree:
<pre>
       0
  10      12
20  15  17  15
</pre>
<p>Note that this tree is still perfectly valid according to the current invariants, but would cease to be so at the first pop, which would result in the following tree:
<pre>
      10
  15      12
20  15  17
</pre>
<p>According to our current invariants, this tree is not valid, because the upper node with value 15 has a child that is not greater than itself (i.e. it is not less than both of its children). That means that, in this case, <em>pop</em> would break the invariant - not push.</p>
<p>The only way to reliably avoid this would be to search the heap before inserting the new value but, as we've seen, searching the heap is costlier than inserting a value into it: this would make insertion <img src='http://s.wordpress.com/latex.php?latex=O%28n%5Clog%5E2%28n%29%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(n\log^2(n))' title='O(n\log^2(n))' class='latex' />. Another option that would work for integers is to detect duplicate values at the moment they are popped, by keeping the latest popped value and comparing with it before giving the value back. That won't work for real objects, though, for two reasons: first of all, our implementation doesn't own the objects in the heap but only has pointers to them. This could be handled by having the heap own its contents, but that would bring all sorts of problems with it, which I won't go into right now. The second reason is that for real objects we don't check equality, but equivalence. As the heap does not provide FIFO order for equivalent values (even in our current implementation) there is really no way to predict the order in which two equivalent values would come out of the heap, so <em>which</em> pop would be quenched by this approach would also be unpredictable - and we would still have to alter the invariants to allow for such an approach.</p>
<p>Suffice it to say that remaining within our performance requirements, this feature cannot be implemented reliably.</p>
<p>Simply not implementing the feature and leaving the state as-is is not really an option: any self-respecting implementation of an abstract data type should not delegate the responsibility of its own integrity - the validity of its internal invariants - to its users. Not changing the current state of affairs and keeping the invariants as they are would allow the client code to break the invariants simply by inserting the same value into the heap twice. Forcing the client code to detect that before they push a value onto the heap would mean forcing them to perform a find before each push, effectively creating a situation in which pushing is both error-prone and <img src='http://s.wordpress.com/latex.php?latex=O%28n%5Clog%5E2%28n%29%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='O(n\log^2(n))' title='O(n\log^2(n))' class='latex' />.</p>
<p>So, our only remaining option is to change the invariant of the heap, allowing duplicate values and, therefore, allowing equivalence as well as the less-than relationship between parent and child. This patch will do that:</p>
<pre>@@ -63,10 +63,14 @@ static void Heap_checkInvariants(Heap *
 	{
 		assert(
 			Heap_nodeIsLeaf(heap, curr) ||
-			Heap_nodeLess(heap, curr, Heap_nodeLhs(heap, curr)));
+			Heap_nodeLess(heap, curr, Heap_nodeLhs(heap, curr)) ||
+			(!Heap_nodeLess(heap, curr, Heap_nodeLhs(heap, curr)) &#038;&#038;
+			 !Heap_nodeLess(heap, Heap_nodeLhs(heap, curr), curr)));
 		assert(
 			!Heap_nodeHasRhs(heap, curr) ||
-			Heap_nodeLess(heap, curr, Heap_nodeRhs(heap, curr)));
+			Heap_nodeLess(heap, curr, Heap_nodeRhs(heap, curr)) ||
+			(!Heap_nodeLess(heap, curr, Heap_nodeRhs(heap, curr)) &#038;&#038;
+			 !Heap_nodeLess(heap, Heap_nodeRhs(heap, curr), curr)));
 	}
 }
 </pre>
<p>Now, if the client code does not want to allow duplicate values, it will have to perform a find on the heap before inserting but if it <em>does</em> want to allow duplicate values, it can simply insert them. If wants to go for the cheaper option of having duplicate values filtered at the pop-end of the heap, it can do that with full knowledge of what equivalence means (as the client code provides the predicate) and of how element life-time is handled (as that is also handled by the client code). Our heap makes no assumptions on either.</p>
<h2>Conclusion</h2>
<p>We've created a monster!</p>
<p>Actually, no. We've created a fairly efficient implementation of a heap with all the bells and whistles, that also happens to be fairly generic. It's written in C, but the same thing would certainly have been possible in C++ (and I might be tempted to write a version in C++ at some point). We've seen invariants in action, analyzed the computational complexity of our algorithm and solved a few problems along the way.</p>
<p>The generic version of the heap implementation is available as version 1.1.00, <a href="http://landheer-cieslak.com/heap-1.1.00.tar.gz">here</a>.</p>

<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F&amp;title=The+heap+algorithm" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F&amp;title=The+heap+algorithm" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F&amp;title=The+heap+algorithm" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F&amp;headline=The+heap+algorithm" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=The+heap+algorithm&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=The+heap+algorithm&amp;u=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=The+heap+algorithm&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=The+heap+algorithm&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=The+heap+algorithm&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F&amp;title=The+heap+algorithm&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fthe-heap-algorithm%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://landheer-cieslak.com/wordpress/the-heap-algorithm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Women in computing</title>
		<link>http://landheer-cieslak.com/wordpress/women-in-computing/</link>
		<comments>http://landheer-cieslak.com/wordpress/women-in-computing/#comments</comments>
		<pubDate>Fri, 13 Aug 2010 02:18:06 +0000</pubDate>
		<dc:creator>Ronald Landheer-Cieslak</dc:creator>
				<category><![CDATA[Opinions]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[anecdotes]]></category>

		<guid isPermaLink="false">http://landheer-cieslak.com/wordpress/?p=872</guid>
		<description><![CDATA[When I ran a team of R&#038;D programmers, a while ago, at one point, we had one person from a visible minority, one person with a slight handicap, two women, two immigrants (one of which was one of the two women, the other was me) and at least one phytopathologist (me). We beat most of [...]]]></description>
			<content:encoded><![CDATA[
<p>When I ran a team of R&#038;D programmers, a while ago, at one point, we had one person from a visible minority, one person with a slight handicap, two women, two immigrants (one of which was one of the two women, the other was me) and at least one phytopathologist (me). We beat most of the statistics with that team, because there were about ten of us at the time. One of the members of my team remarked that it was the first time he&#8217;d worked in a team with two women in it &#8211; and he had worked in larger teams before.<br />
<span id="more-872"></span><br />
I find it rather strange that women are so rare in computing in these parts of the world &#8211; and I am not aware of any part of the world where they form a majority. I think this is strange because in the history of computing, women have played, and are still playing, a very important role. After all: the first programmer ever was a woman (Ada Lovelace), compilers were invented by a woman (Grace Hopper), technologies like Bluetooth and WiFi would not be possible without spread spectrum broadcasting, co-invented by Hedy Lamarr. The first person to use a computer in a private home was a woman (Mary Allen Wilkes) who also developed the first OS for the first minicomputer. Adele Goldberg helped invent object-oriented programming with her work on Smalltalk; Sally Floyd helped make the Internet possible with her work on TCP; etc.</p>
<p>In fact, come to think of it, most of the technologies I work with on a daily basis have a woman&#8217;s influence in its history. Women have traditionally played an important role in anything ranging from the esthetic to the very, very technical. One of the women in the team I referred to earlier was in charge of quality assurance for the team while the other worked on a firmware, written in C.</p>
<p>So why is it that computing tends to be such a masculin environment (in that there are a lot of men working in this field)? Maybe it&#8217;s just because women are smarter than men..? They&#8217;ve moved on to greener pastures where their superior intellect is more needed, leaving us to do the footwork. The few women remaining in the field are just there to keep an eye on us&#8230;</p>
<p>Nah.., that can&#8217;t be it, can it..?</p>

<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F&amp;title=Women+in+computing" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F&amp;title=Women+in+computing" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F&amp;title=Women+in+computing" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F&amp;headline=Women+in+computing" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Women+in+computing&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Women+in+computing&amp;u=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Women+in+computing&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Women+in+computing&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Women+in+computing&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F&amp;title=Women+in+computing&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fwomen-in-computing%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://landheer-cieslak.com/wordpress/women-in-computing/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Tell me twice</title>
		<link>http://landheer-cieslak.com/wordpress/tell-me-twice/</link>
		<comments>http://landheer-cieslak.com/wordpress/tell-me-twice/#comments</comments>
		<pubDate>Fri, 06 Aug 2010 02:09:49 +0000</pubDate>
		<dc:creator>Ronald Landheer-Cieslak</dc:creator>
				<category><![CDATA[Reasons]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Software Design]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://landheer-cieslak.com/wordpress/?p=865</guid>
		<description><![CDATA[A few days ago, I explained to a colleague why certain communications protocols have a &#8220;tell me twice&#8221; policy &#8211; i.e. to allow for any command to have any effect, the same command &#8211; or a command to the same effect &#8211; has to be received twice (from the same master). In human parlance, this [...]]]></description>
			<content:encoded><![CDATA[
<p>A few days ago, I explained to a colleague why certain communications protocols have a &#8220;tell me twice&#8221; policy &#8211; i.e. to allow for any command to have any effect, the same command &#8211; or a command to the same effect &#8211; has to be received twice (from the same master). In human parlance, this would be the equivalent of Jean-Luc Picard saying &#8220;ensign, I&#8217;m about to tell you to lower the shields&#8221; &#8230; &#8220;ensign, shields down!&#8221; in which the ensign (Wesley Crusher?) wouldn&#8217;t be allowed to obey the second command unless he had heard, understood and acknowledged (HUA!) the first. Now for the math..<br />
<span id="more-865"></span><br />
This kind of &#8220;tell me twice&#8221; policy is usually found in serial protocols and is based on the idea that if a bit flips in a message, the chance of the same bit flipping in two consecutive messages is far lower. Bit flipping is a common error in serial communications &#8211; which is why parity bits exist, for example &#8211; and even if the chance for any given bit flipping is relatively low, the chance of <em>a</em> bit flipping somewhere in any message is relatively high. I&#8217;ll show you how that works:</p>
<p>Say the chance of any given bit flipping is <img src='http://s.wordpress.com/latex.php?latex=p&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='p' title='p' class='latex' />, the number of bits in a byte is <img src='http://s.wordpress.com/latex.php?latex=b&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='b' title='b' class='latex' /> and the number of bytes in a message is <img src='http://s.wordpress.com/latex.php?latex=n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='n' title='n' class='latex' />. This means that the chance of a bit <em>not</em> flipping is <img src='http://s.wordpress.com/latex.php?latex=1-p&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='1-p' title='1-p' class='latex' /> and the chance of getting a message through without any flipped bits is <img src='http://s.wordpress.com/latex.php?latex=%281-p%29%5E%7Bbn%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='(1-p)^{bn}' title='(1-p)^{bn}' class='latex' />, which, depending on the values of <img src='http://s.wordpress.com/latex.php?latex=p&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='p' title='p' class='latex' /> <img src='http://s.wordpress.com/latex.php?latex=b&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='b' title='b' class='latex' /> and <img src='http://s.wordpress.com/latex.php?latex=n&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='n' title='n' class='latex' /> can either be very high, or very low, so let&#8217;s fill in a few values to get an idea of what this means. Let&#8217;s say that the chances of a bit flipping are about one in a million, we have eight bits per byte and our messages are 256 bytes in length. The message may be a bit larger than what you&#8217;d usually find on a serial connection, but we&#8217;re going for a case in which there&#8217;s an actual payload to send, so I think it&#8217;s reasonable. With these numbers, our little formula, <img src='http://s.wordpress.com/latex.php?latex=P%20%3D%20%281-p%29%5E%7Bbn%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='P = (1-p)^{bn}' title='P = (1-p)^{bn}' class='latex' /> works out to a value for <img src='http://s.wordpress.com/latex.php?latex=P&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='P' title='P' class='latex' /> of 0.997954. That is: with a one-in-a-million chance of any bit flipping, one message out of ever 500 is corrupt. If that one message was &#8220;shields down&#8221; and, due to the bit flip, becomes &#8220;eject the warp core&#8221;, and the <i>Enterprise</i> is dead in space.</p>
<p>So, the idea of &#8220;tell me twice&#8221; is to reduce the chances of such errors happening by reducing the chance that a bit flip would have any effect. This is based on the idea that the chances of the <em>same</em> bit flipping in two consecutive chances are far lower than the one-in-five-hundred we just came up with, even it the chances of <em>a</em> bit flipping are still the same. To understand this, we need to know what the chances are that a <em>specific</em> bit in a message is flipped. That chance is <img src='http://s.wordpress.com/latex.php?latex=P%20%3D%20p%281-p%29%5E%7Bbn-1%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='P = p(1-p)^{bn-1}' title='P = p(1-p)^{bn-1}' class='latex' />, which is <em>smaller</em> that the chance of any individual bit flipping (because all the other bits have to not flip). In our case, this works out to <img src='http://s.wordpress.com/latex.php?latex=9.980%20%2A%2010%5E%7B-7%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='9.980 * 10^{-7}' title='9.980 * 10^{-7}' class='latex' /> which is about one in 1,002,049.</p>
<p>Now, the probability that a message is followed by another message that has the same bit flipped is the product of the probability that a message has a flipped bit (one in 500) and the probability that a message has <em>a given</em> bit flipped (one in a little over a million): <img src='http://s.wordpress.com/latex.php?latex=P%20%3D%20%281%20-%20%28%281-p%29%5E%7Bbn%7D%29%29%28p%28%281-p%29%5E%7Bbn-1%7D%29%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='P = (1 - ((1-p)^{bn}))(p((1-p)^{bn-1}))' title='P = (1 - ((1-p)^{bn}))(p((1-p)^{bn-1}))' class='latex' />, which in our case works out to <img src='http://s.wordpress.com/latex.php?latex=2.03963%20%2A%2010%5E%7B-9%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='2.03963 * 10^{-9}' title='2.03963 * 10^{-9}' class='latex' /> which is about one in a half billion.</p>
<p>Of course, added to this is the fact that most serial protocols also have some kind of CRC checking, there&#8217;s usually a parity bit in there somewhere, etc. All these individually rather weak methods, together, make it nearly impossible for a corrupt message to come through undetected &#8211; because for any broken message to come through undetected, <em>all</em> of the error detection features have to fail, so as long as they don&#8217;t all check the same thing the same way, the chances of that happening is the product of the chances of each individual method failing (i.e. checking the parity five times doesn&#8217;t make your chances of finding an undetected error any better, but checking the parity and four other things does).</p>

<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F&amp;title=Tell+me+twice" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F&amp;title=Tell+me+twice" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F&amp;title=Tell+me+twice" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F&amp;headline=Tell+me+twice" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Tell+me+twice&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Tell+me+twice&amp;u=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Tell+me+twice&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Tell+me+twice&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Tell+me+twice&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F&amp;title=Tell+me+twice&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Ftell-me-twice%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://landheer-cieslak.com/wordpress/tell-me-twice/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Once burned, twice shy</title>
		<link>http://landheer-cieslak.com/wordpress/once-burned-twice-shy/</link>
		<comments>http://landheer-cieslak.com/wordpress/once-burned-twice-shy/#comments</comments>
		<pubDate>Tue, 03 Aug 2010 02:08:40 +0000</pubDate>
		<dc:creator>Ronald Landheer-Cieslak</dc:creator>
				<category><![CDATA[Business]]></category>
		<category><![CDATA[Opinions]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[anecdotes]]></category>

		<guid isPermaLink="false">http://landheer-cieslak.com/wordpress/?p=863</guid>
		<description><![CDATA[&#34;Is Good Code Possible?&#34; John Blanco asks on his blog. He goes on to tell a harrowing story on how he had to develop an iPhone app for a big retailer (&#8220;Gorilla Mart&#8221;) in less than two weeks. Why he even accepted the contract is beyond me but then, he may not have had a [...]]]></description>
			<content:encoded><![CDATA[
<p>&quot;<a href="http://raptureinvenice.com/?p=63" target="_blank">Is Good Code Possible?</a>&quot; John Blanco asks on his blog. He goes on to tell a harrowing story on how he had to develop an iPhone app for a big retailer (&#8220;Gorilla Mart&#8221;) in less than two weeks. Why he even accepted the contract is beyond me but then, he may not have had a choice.</p>
<p>In the scenario he described, there&#8217;s really little chance of creating quality code, unless&#8230;<br />
<span id="more-863"></span><br />
I avoid contracts like the one John described like the plague: if the client doesn&#8217;t know what they want, there&#8217;s little chance for me to come up with a satisfactory solution. Then again, I am in a slightly different business than John is: I don&#8217;t make applications for end-user devices. In stead, I make the software that runs under or behind it &#8211; embedded software, firmware and server software (either I work on the very small, or I work on the very big). In the last decade, I&#8217;ve written code for servers and code for embedded devices, but of that code, almost nothing has been visible to the end-user. Some has been visible to an operator on a packaging line, but that is just a small minority of the code I&#8217;ve written. However, I&#8217;ve worked with many of the same technologies as John apparently has: web services to get data, databases, etc. are among the things I&#8217;ve worked with, as he has. So, how do I go about avoiding contracts as the one John described?</p>
<p>The one thing in short-term contracts is to avoid surprises: you have to work with a third part, you have to know it from the outset. Nothing should be assumed: in any application, data has to come from somewhere (a source) and go somewhere (a sink); events need to be triggered and those triggers also need to come from somewhere; relations between all datasets need to be established from the outset, etc. Like I said: I don&#8217;t usually work on end-user applications, but from my point of view, there are a few lessons to be learned from John&#8217;s experience:<br />
questions that needed to be asked, weren&#8217;t. The feeling the execs wanted to have come across that the app was going to be &#8220;simple&#8221; was accepted at face value. I can understand that John didn&#8217;t want to seem uncomfortable with that assertion, but seeing as <em>he</em> was the specialist in the room, it was clearly up to <em>him</em> to decide whether the app was simple or not &#8211; and it was up to him to show that such was not the case.</p>
<blockquote><p>&#8220;But it&#8217;s OK,&#8221; Gorilla Mart Executive #1 says. &#8220;The app is simple.&#8221;</p></blockquote>
<p>This, of course, is the cue for &#8220;I&#8217;ll be the judge of that!&#8221; or something in that order. The point is that there can be only one judge of the simplicity of an app, and that judge is the specialist. I&#8217;m always happy to explain how I intend to solve a given problem, and I am always happy to accept suggestions as to the solution. To go from there to accepting a solution from an exec, who may well have an MBA, is a step I am not willing to take without good arguments.</p>
<p>Now, I don&#8217;t want to come over as a know-it-all, nor do I want to judge the way other people handle their contracts, so I&#8217;ll propose a few anecdotes of my own.</p>
<h2>Anecdote #1: Purdy Please?!</h2>
<blockquote><p>
This was about a year ago. I&#8217;d put a notice up on this site that I was available for a new contract and got a phone call a few days later, if I would accept a two-week contract to interface an existing system to a brand-new web service for it to obtain geo-location data. The contract was to be done post-haste, so the person searching for a developer was in a hurry.</p>
<p>I have a list of developers that I can call if I have a contract that is too big for me to handle by myself, or if I don&#8217;t have time to do the contract myself. These are all people I&#8217;ve worked with before and for whom I can vouch in terms of their being good programmers. When I had put the notice up on my site that I was available, I didn&#8217;t expect to get calls quite that quickly, so with the deadline as close as it was, there was no way I could accept the contract myself. When pushed a bit (the guy was 300 km away from his client and needed to get a developer <em>right now</em>) I took out my list and made a few calls. I found a suitable developer, and earned a commission for the referral.</p>
<p>Crisis averted, and everybody happy: the programmer that got to do the job, the HR person looking for a programmer, the client and me all got what we wanted, and three out of four were a bit richer after the deal &#8211; the fourth had his product, so will be a bit richer by now as well.</p></blockquote>
<h2>Anecdote #2: What do you mean: &#8220;what do you need?&#8221;?</h2>
<blockquote><p>A few months ago, I got a call asking me to develop the firmware for a new product. The call lasted about thirty minutes and ended with me asking for some material to at least give me a feel of what was needed &#8211; something I could base a draft architecture on.</p>
<p>They didn&#8217;t have any such documentation &#8211; actually wanted me to come up with some. Naturally, I can&#8217;t do that: I don&#8217;t know the market for the device, nor do I know enough about marketing to come up with that kind of material. All I could do is give them a few pointers, and tell them to come back to me when they had some more information.</p>
<p>Now, this is a case in which no money exchanged hands and the amount of work on my part was really minimal: they basically got an expert opinion on a few questions they had and were happy with the answers they got. They also knew they had a bit more homework to do. Me accepting the contract without that homework being done first would be a waste of my time and theirs &#8211; and as my time is their money, they understood that I was saving them money with my questions.</p>
<p>When their homework is done and they do come back to me, the time I spent will have been a good investment on my part. If they don&#8217;t do their home work or they don&#8217;t come back to me, it will still have been a good investment on my part, but it will not have had the hoped-for return.</p></blockquote>
<h2>Anecdote #3: Questions, questions&#8230;</h2>
<blockquote><p>There are few clients that like your work enough to pay you in advance for time they might not even use &#8211; just so they can call you any time during the day and ask a few questions. One such client wanted me to write a specification from a set of PowerPoint slides. Happy to oblige, I went through the PowerPoint slides and came up with a long list of questions. My continuing the work on the specification depends on getting the answers to those questions.</p>
<p>Now, these questions aren&#8217;t technical in nature, but PowerPoint slides have a tendency to be vague and technical specifications can&#8217;t really have that luxury, so choices have to be made at some point. E.g., when defining a security profile of a new device, do you want to emphasize confidentiality, integrity, authentication or non-repudiation? In embedded devices, you usually don&#8217;t have enough space to have them all and I can&#8217;t make such decisions on behalf of my clients &#8211; nor can I describe all options and have the development team make the choices (although I can describe and explain alternatives).</p></blockquote>
<p>Now, does this mean that every time a client comes up with a vague question, I tell them to do their homework and go on my merry way? No. I am not <em>that</em> financially independent. It does mean, though, that creating software-intensive systems requires real input from the system&#8217;s stakeholders. I&#8217;m happy to work with stakeholders and think different scenarios through with them, and I&#8217;m very happy to explain alternatives to them, to analyse possible repercussions of different choices, etc. but I cannot, and will not, take their decisions for them.</p>
<p>Of course, all three of these anecdotes didn&#8217;t actually result in me investing any significant amounts of time (except for the third one, in which I spent the better part of three days analysing the presentation and the repercussions for the existing architecture) and therefore didn&#8217;t come at great cost to the client. In each case, the customer was helped along the way to the end-result they were going for, and in the first case, the project was eventually executed while the other two are still pending.</p>
<p>So, how is this approach different from the one described by John? Well, aside from none of these cases being particularly frustrating for me or for the client, I don&#8217;t get &#8220;pumped&#8221; &#8211; I hardly ever get excited &#8211; for a job: getting too excited about anything usually ends up in disappointments for everyone involved. Now, that doesn&#8217;t mean I haven&#8217;t made my share of mistakes: committing to deadlines I couldn&#8217;t live up to, working nights, etc. to &#8220;get the job done&#8221; and producing code that would have smelled the way it looked if code had any smell to it at all, but &#8211; knock on wood &#8211; those days are (hopefully) over&#8230; almost.</p>

<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F&amp;title=Once+burned%2C+twice+shy" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F&amp;title=Once+burned%2C+twice+shy" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F&amp;title=Once+burned%2C+twice+shy" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F&amp;headline=Once+burned%2C+twice+shy" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Once+burned%2C+twice+shy&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Once+burned%2C+twice+shy&amp;u=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Once+burned%2C+twice+shy&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Once+burned%2C+twice+shy&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Once+burned%2C+twice+shy&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F&amp;title=Once+burned%2C+twice+shy&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fonce-burned-twice-shy%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://landheer-cieslak.com/wordpress/once-burned-twice-shy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Socks 5: Credentials on Windows</title>
		<link>http://landheer-cieslak.com/wordpress/socks-5-credentials-on-windows/</link>
		<comments>http://landheer-cieslak.com/wordpress/socks-5-credentials-on-windows/#comments</comments>
		<pubDate>Sun, 01 Aug 2010 23:31:26 +0000</pubDate>
		<dc:creator>Ronald Landheer-Cieslak</dc:creator>
				<category><![CDATA[C++ for the self-taught]]></category>

		<guid isPermaLink="false">http://landheer-cieslak.com/wordpress/?p=847</guid>
		<description><![CDATA[In this installment, we will continue our implementation of GSSAPI/SSPI, this time on Windows, where we&#8217;ll try to get some credentials. We will look at two topics this time: first, we&#8217;ll look at data encapsulation, after which we&#8217;ll look at when RAII is a bit too much, and how to handle that. Data encapsulation One [...]]]></description>
			<content:encoded><![CDATA[
<div style="width: 200px; height: 100px; float:right"><iframe src="http://vlinder.ca/podcasts/play.php?file=21-credentials" width="200" height="70" scrolling="no"></iframe><form class='donate' method='post' action='https://www.paypal.com/cgi-bin/webscr'>		<input type='hidden' value='2.50' name='amount'/>		<input type='hidden' value='_xclick' name='cmd'/>		<input type='hidden' value='ronald@landheer-cieslak.com' name='business'/>		<input type='hidden' value='Donate for the C++ for the self-taught podcast' name='item_name'/>		<input type='hidden' value='1' name='no_shipping'/>		<input type='hidden' value='ttp://landheer-cieslak.com/wordpress/thanks/' name='return'/>		<input type='hidden' value='http://landheer-cieslak.com' name='cancel_return'/>		<input type='hidden' value='CAD' name='currency_code'/>		<input type='hidden' value='' name='page_style'/>		<input type='hidden' value='0' name='tax'/>		<input type='image' alt='PayPal - The safer, easier way to pay online' name='submit' style='border: 0pt none ;' src='http://landheer-cieslak.com/donate.png'/></form></div>
<p>In this installment, we will continue our implementation of GSSAPI/SSPI, this time on Windows, where we&#8217;ll try to get some credentials.</p>
<p>We will look at two topics this time: first, we&#8217;ll look at data encapsulation, after which we&#8217;ll look at when RAII is a bit too much, and how to handle that.</p>
<p><span id="more-847"></span></p>
<h2>Data encapsulation</h2>
<p>One of the main reasons we&#8217;re going to the trouble of creating an abstract factory is because we want the users of our code to be pretty close to impervious to the way security is implemented. Most notably, we don&#8217;t want the user to be obliged to know anything about SSPI or GSSAPI and we don&#8217;t want them to have to include any of the associated headers &#8211; or even necessarily have those headers around. This comes at a cost, though: we need to hide our implementation so far that we need to allow the user to not even know about the types we are using. In our first patch today, we&#8217;ll see how to do that.</p>
<p>Let&#8217;s first take a look at the changes we make to the Mechanism.h file, in the sspi library:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">diff --git a/lib/sspi/Mechanism.h b/lib/sspi/Mechanism.h
index 804fef5..<span style="color: #440088;">456c233</span> <span style="">100644</span>
<span style="color: #888822;">--- a/lib/sspi/Mechanism.h</span>
<span style="color: #888822;">+++ b/lib/sspi/Mechanism.h</span>
<span style="color: #440088;">@@ -<span style="">3</span>,<span style="">19</span> +<span style="">3</span>,<span style="">25</span> @@</span>
&nbsp;
 #include &quot;../security/Mechanism.h&quot;
 #include &quot;Details/prologue.h&quot;
<span style="color: #00b000;">+#include &lt;string&gt;</span>
&nbsp;
 namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace SSPI <span style="">&#123;</span> 
 	class VLINDER_CHAUSETTE_SSPI_API Mechanism
 		: public Security::Mechanism
 	<span style="">&#123;</span>
 	public :
<span style="color: #991111;">-		Mechanism<span style="">&#40;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		Mechanism<span style="">&#40;</span>const std::string &amp; package_name<span style="">&#41;</span>;</span>
 		virtual ~Mechanism<span style="">&#40;</span><span style="">&#41;</span>;
&nbsp;
 	private :
 		// neither CopyConstructible nor Assignable
 		Mechanism<span style="">&#40;</span>const Mechanism &amp;<span style="">&#41;</span>;
 		Mechanism &amp; operator=<span style="">&#40;</span>const Mechanism &amp;<span style="">&#41;</span>;
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+	private :</span>
<span style="color: #00b000;">+		struct Data_;</span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+		Data_ * data_;</span>
 	<span style="">&#125;</span>;
 <span style="">&#125;</span><span style="">&#125;</span><span style="">&#125;</span></pre></div></div>

<p>Like I said in a previous installment, there&#8217;s not much point in trying to hide the standard library implementation, as whoever uses our code will be using it anyway. There&#8217;s not much point, either, in trying to hide that an instance of <code>Mechanism</code> needs a package name to be created under SSPI: the <code>MechanismFactory</code> will do the creating for us, so if all goes well, the client code won&#8217;t even include this file. There is a chance, however, that they will, in which case we don&#8217;t want the user to be dependent on the Windows headers. That&#8217;s why I&#8217;ve created a forward-declaration to a private member structure called <code>Data_</code>. The structure itself is not here, but is defined in the .cpp file. It contains the package information we will need for later use, and it is conveniently hidden from view.</p>
<p>You might be wondering by now why the <code>Data_</code> structure doesn&#8217;t have to be visible here &#8211; after all, I do have a pointer to an instance of it in my class. The thing is, though, that there are only a few reasons why the compiler needs to know the definition of a structure: it needs to know how to create an instance of it when one is defined or explicitly allocated with <code>new</code>; it needs to know how to destroy it when one goes out of scope or is explicitly destroyed with <code>delete</code>, and it needs to know how big it is when one is used as a member of something else. You might think that our use in this header would fall in that last category, but it doesn&#8217;t: our member is a <em>pointer to</em> an instance of <code>Data_</code>. It is not an instance of <code>Data_</code> by itself. Pointers usually have the same size regardless of what they point to  and, in any case, the compiler can figure out what that size is without knowing what it points to, so there&#8217;s no need, here, to know the definition of <code>Data_</code> in order to use it.</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">diff --git a/lib/sspi/Mechanism.cpp b/lib/sspi/Mechanism.cpp
index 34fa65a..b4e7149 <span style="">100644</span>
<span style="color: #888822;">--- a/lib/sspi/Mechanism.cpp</span>
<span style="color: #888822;">+++ b/lib/sspi/Mechanism.cpp</span>
<span style="color: #440088;">@@ -<span style="">1</span>,<span style="">10</span> +<span style="">1</span>,<span style="">40</span> @@</span>
 #include &quot;Mechanism.h&quot;
<span style="color: #00b000;">+#include &lt;windows.h&gt;</span>
<span style="color: #00b000;">+#include &lt;security.h&gt;</span>
&nbsp;
 namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace SSPI <span style="">&#123;</span> 
<span style="color: #991111;">-	Mechanism::Mechanism<span style="">&#40;</span><span style="">&#41;</span></span>
<span style="color: #991111;">-	<span style="">&#123;</span> /* no-op */ <span style="">&#125;</span></span>
<span style="color: #00b000;">+	struct Mechanism::Data_</span>
<span style="color: #00b000;">+	<span style="">&#123;</span></span>
<span style="color: #00b000;">+		Data_<span style="">&#40;</span>const std::string &amp; package_name<span style="">&#41;</span></span>
<span style="color: #00b000;">+			: package_name_<span style="">&#40;</span>package_name<span style="">&#41;</span></span>
<span style="color: #00b000;">+			, package_info_<span style="">&#40;</span><span style="">0</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span> /* no-op */ <span style="">&#125;</span></span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+		~Data_<span style="">&#40;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			FreeContextBuffer<span style="">&#40;</span>package_info_<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+		std::string package_name_;</span>
<span style="color: #00b000;">+		PSecPkgInfo package_info_;</span>
<span style="color: #00b000;">+	<span style="">&#125;</span>;</span>
<span style="color: #00b000;">+	</span>
<span style="color: #00b000;">+	Mechanism::Mechanism<span style="">&#40;</span>const std::string &amp; package_name/* = std::string<span style="">&#40;</span><span style="">&#41;</span>*/<span style="">&#41;</span></span>
<span style="color: #00b000;">+		: data_<span style="">&#40;</span>new Data_<span style="">&#40;</span>package_name<span style="">&#41;</span><span style="">&#41;</span></span>
<span style="color: #00b000;">+	<span style="">&#123;</span></span>
<span style="color: #00b000;">+		if <span style="">&#40;</span>QuerySecurityPackageInfo<span style="">&#40;</span><span style="">&#40;</span>LPSTR<span style="">&#41;</span>package_name.c_str<span style="">&#40;</span><span style="">&#41;</span>, &amp;data_-&gt;package_info_<span style="">&#41;</span> != SEC_E_OK<span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			delete data_;</span>
<span style="color: #00b000;">+			data_ = <span style="">0</span>;</span>
<span style="color: #00b000;">+			throw std::runtime_error<span style="">&#40;</span>&quot;Failed to query package info&quot;<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+		else</span>
<span style="color: #00b000;">+		<span style="">&#123;</span> /* all is well */ <span style="">&#125;</span></span>
<span style="color: #00b000;">+	<span style="">&#125;</span></span>
&nbsp;
 	/*virtual */Mechanism::~Mechanism<span style="">&#40;</span><span style="">&#41;</span>
<span style="color: #991111;">-	<span style="">&#123;</span> /* no-op */ <span style="">&#125;</span></span>
<span style="color: #00b000;">+	<span style="">&#123;</span></span>
<span style="color: #00b000;">+		delete data_;</span>
<span style="color: #00b000;">+	<span style="">&#125;</span></span>
 <span style="">&#125;</span><span style="">&#125;</span><span style="">&#125;</span></pre></div></div>

<p>As you can see in this chunk, <code>Data_</code> doesn&#8217;t <em>do</em> much of anything: it will free the <code>PSecPkgInfo</code> instance when it&#8217;s done, but that&#8217;s about all. All of the logic is still in the <code>Mechanism</code> class, where it belongs.</p>
<p>Now for the factory:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">diff --git a/lib/sspi/MechanismFactory.cpp b/lib/sspi/MechanismFactory.cpp
index 8ffd315..<span style="color: #440088;">3565a9</span>c <span style="">100644</span>
<span style="color: #888822;">--- a/lib/sspi/MechanismFactory.cpp</span>
<span style="color: #888822;">+++ b/lib/sspi/MechanismFactory.cpp</span>
<span style="color: #440088;">@@ -<span style="">1</span>,<span style="">6</span> +<span style="">1</span>,<span style="">5</span> @@</span>
 #include &quot;MechanismFactory.h&quot;
 #include &quot;Mechanism.h&quot;
<span style="color: #991111;">-#define SECURITY_WIN32</span>
 #include &lt;windows.h&gt;
 #include &lt;security.h&gt;
&nbsp;
<span style="color: #440088;">@@ -<span style="">52</span>,<span style="">7</span> +<span style="">51</span>,<span style="">7</span> @@ namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace SSPI <span style="">&#123;</span></span>
&nbsp;
 	/*virtual */Mechanism * MechanismFactory::getDefaultMechanism<span style="">&#40;</span><span style="">&#41;</span> const/* = <span style="">0</span>*/
 	<span style="">&#123;</span>
<span style="color: #991111;">-		return new Mechanism;</span>
<span style="color: #00b000;">+		return new Mechanism<span style="">&#40;</span>getAvailableMechanisms<span style="">&#40;</span><span style="">&#41;</span><span style="">&#91;</span><span style="">0</span><span style="">&#93;</span><span style="">&#41;</span>;</span>
 	<span style="">&#125;</span>
&nbsp;
 	/*virtual */void MechanismFactory::releaseMechanism<span style="">&#40;</span>Security::Mechanism * mechanism<span style="">&#41;</span>/* = <span style="">0</span>*/</pre></div></div>

<p>As you can see, we assume that on Windows, the default package is whichever is listed first in the available packages &#8211; or &#8220;mechanisms&#8221; as we call them. This holds true for Windows and, as long as we don&#8217;t start sorting those packages, will hold true when we care for it to hold true.</p>
<p>Now a final little chunk:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">diff --git a/tests/RFC1961/main.cpp b/tests/RFC1961/main.cpp
index <span style="color: #440088;">3d9540</span>c..396f6ab <span style="">100644</span>
<span style="color: #888822;">--- a/tests/RFC1961/main.cpp</span>
<span style="color: #888822;">+++ b/tests/RFC1961/main.cpp</span>
<span style="color: #440088;">@@ -<span style="">31</span>,<span style="">6</span> +<span style="">31</span>,<span style="">7</span> @@ int main<span style="">&#40;</span><span style="">&#41;</span></span>
 	std::auto_ptr&lt; Vlinder::Chausette::GSSAPI::MechanismFactory &gt; mechanism_factory<span style="">&#40;</span>new Vlinder::Chausette::GSSAPI::MechanismFactory<span style="">&#41;</span>;
 #endif
 	std::vector&lt; std::string &gt; mechanisms<span style="">&#40;</span>Vlinder::Chausette::Security::MechanismFactory::getInstance<span style="">&#40;</span><span style="">&#41;</span>.getAvailableMechanisms<span style="">&#40;</span><span style="">&#41;</span><span style="">&#41;</span>;
<span style="color: #00b000;">+	std::auto_ptr&lt; Vlinder::Chausette::Security::Mechanism &gt; mechanism<span style="">&#40;</span>mechanism_factory-&gt;getDefaultMechanism<span style="">&#40;</span><span style="">&#41;</span><span style="">&#41;</span>;</span>
&nbsp;
 #ifdef _MSC_VER
 	WSADATA wsa_data;</pre></div></div>

<p>in which we get the default mechanism in our test. Of course, we should really think of creating an actual unit test, but that&#8217;s beyond the scope of this installment.</p>
<p>So, data encapsulation works because we don&#8217;t need to know the definition of the data in order to be able to work with it, and it&#8217;s useful because it hides the nitty-gritty from those who don&#8217;t need to know it.</p>
<h2>When RAII is too much</h2>
<p>I&#8217;ve been going on about RAII in practically every installment of this podcast now &#8211; at least since I introduced the concept a while ago. You must either think that I am stark raving mad, or that I&#8217;m addicted to RAII. You might actually be right &#8211; whichever option you opt for &#8211; but you should also know that I can go without RAII for a few (albeit very few) lines of code. Sometimes, RAII is more trouble than it&#8217;s worth.</p>
<p>Look at the following chunk of code:</p>

<div class="wp_syntax"><div class="code"><pre class="diff" style="font-family:monospace;">diff --git a/lib/sspi/Mechanism.cpp b/lib/sspi/Mechanism.cpp
index b4e7149..e801e14 <span style="">100644</span>
<span style="color: #888822;">--- a/lib/sspi/Mechanism.cpp</span>
<span style="color: #888822;">+++ b/lib/sspi/Mechanism.cpp</span>
<span style="color: #440088;">@@ -<span style="">1</span>,<span style="">6</span> +<span style="">1</span>,<span style="">7</span> @@</span>
 #include &quot;Mechanism.h&quot;
 #include &lt;windows.h&gt;
 #include &lt;security.h&gt;
<span style="color: #00b000;">+#include &quot;Credentials.h&quot;</span>
&nbsp;
 namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace SSPI <span style="">&#123;</span> 
 	struct Mechanism::Data_
<span style="color: #440088;">@@ -<span style="">36</span>,<span style="">5</span> +<span style="">37</span>,<span style="">35</span> @@ namespace Vlinder <span style="">&#123;</span> namespace Chausette <span style="">&#123;</span> namespace SSPI <span style="">&#123;</span></span>
 	<span style="">&#123;</span>
 		delete data_;
 	<span style="">&#125;</span>
<span style="color: #00b000;">+</span>
<span style="color: #00b000;">+	/*virtual */std::auto_ptr&lt; Security::Credentials &gt; Mechanism::getCredentials<span style="">&#40;</span>const std::string &amp; principal, int flags<span style="">&#41;</span>/* = <span style="">0</span>*/</span>
<span style="color: #00b000;">+	<span style="">&#123;</span></span>
<span style="color: #00b000;">+		CredHandle cred_handle;</span>
<span style="color: #00b000;">+		TimeStamp expiry;</span>
<span style="color: #00b000;">+		if <span style="">&#40;</span>AcquireCredentialsHandle<span style="">&#40;</span></span>
<span style="color: #00b000;">+			<span style="">&#40;</span>LPSTR<span style="">&#41;</span>principal.c_str<span style="">&#40;</span><span style="">&#41;</span>,</span>
<span style="color: #00b000;">+			data_-&gt;package_info_-&gt;Name, </span>
<span style="color: #00b000;">+			flags,</span>
<span style="color: #00b000;">+			<span style="">0</span> /* no LUID */,</span>
<span style="color: #00b000;">+			<span style="">0</span> /* no auth data */,</span>
<span style="color: #00b000;">+			<span style="">0</span> /* unused */,</span>
<span style="color: #00b000;">+			<span style="">0</span> /* unused */,</span>
<span style="color: #00b000;">+			&amp;cred_handle,</span>
<span style="color: #00b000;">+			&amp;expiry<span style="">&#41;</span> != SEC_E_OK<span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			throw std::runtime_error<span style="">&#40;</span>&quot;acquire credentials failed&quot;<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+		else</span>
<span style="color: #00b000;">+		<span style="">&#123;</span> /* all is well */ <span style="">&#125;</span></span>
<span style="color: #00b000;">+		try</span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			return std::auto_ptr&lt; Security::Credentials &gt;<span style="">&#40;</span>new Credentials<span style="">&#40;</span>cred_handle<span style="">&#41;</span><span style="">&#41;</span>;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+		catch <span style="">&#40;</span>...<span style="">&#41;</span></span>
<span style="color: #00b000;">+		<span style="">&#123;</span></span>
<span style="color: #00b000;">+			FreeCredentialsHandle<span style="">&#40;</span>&amp;cred_handle<span style="">&#41;</span>;</span>
<span style="color: #00b000;">+			throw;</span>
<span style="color: #00b000;">+		<span style="">&#125;</span></span>
<span style="color: #00b000;">+	<span style="">&#125;</span></span>
 <span style="">&#125;</span><span style="">&#125;</span><span style="">&#125;</span></pre></div></div>

<p>This is where I obtain a handle on the credentials of a given principal and, if that works, pass it on to a new instance of <code>Credentials</code>, which will manage its lifetime and whose lifetime is managed by an <code>auto_ptr</code>. Now, the important bit here is that there are two things that can go wrong between the <code>try</code> and the <code>catch</code>: the allocation might fail, in which case we&#8217;d be in big trouble but, more importantly, the constructor of the <code>Credentials</code> class would never be called, and construction of the <code>Credentials</code> instance might fail. If I were to define <code>Credentials</code> such that anything that is passed to its constructor will be taken over by the <code>Credentials</code> class, even if its construction fails &#8211; a popular and often worthy option &#8211; I&#8217;d have a problem in that I&#8217;d need to know which step went wrong. It is the option <code>auto_ptr</code> implements, though, and that is a Good Thing, though it would also complicate matters if construction of <code>auto_ptr</code> actually <em>could</em> fail.</p>
<p>Now, what would have happened had I used RAII for this task? There are two options: either I&#8217;d have created a scoped handle on the credentials handle, which I would have dismissed after the construction of the <code>Credentials</code> instance, but that would have left the same problem as I have now: determining which construction failed in order to know whether or not to dismiss the guard. An option that doesn&#8217;t actually make the code any cleaner is not really an option.</p>
<p>The alternative would have been to create a class that would explicitly hand ownership of the credentials handle to the new instance of the <code>Credentials</code> class, much like <code>auto_ptr</code> does with pointers. If it goes out of scope while still holding the reference, it will call the proper clean-up function.</p>
<p>Implementing that option can be fun &#8211; I would invite you to do it and contribute your result. It can also be far more work than writing a <code>try</code>-<code>catch</code> block with as its only benefit to make the code marginally cleaner. I say marginally because, although the clarity of the semantics would be a lot better, this piece of code isn&#8217;t repeated anywhere else. As such, weighing the benefits of implementing the &#8220;right&#8221; RAII solution (automatic ownership transfer) vs. the use of a <code>try</code>-<code>catch</code> block, the <code>try</code>-<code>catch</code> block wins because it is that much less work. Implementing the wrong RAII solution simply doesn&#8217;t make any sense.</p>
<p>So, I may be off my rocker and/or addicted to RAII, but apparently I still have a wee bit of common sense. I&#8217;ll try applying that again in four weeks &#8211; I&#8217;m taking the next two weeks off from the podcast, so there will be no mid-August installment.</p>

<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F&amp;title=Socks+5%3A+Credentials+on+Windows" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F&amp;title=Socks+5%3A+Credentials+on+Windows" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F&amp;title=Socks+5%3A+Credentials+on+Windows" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F&amp;headline=Socks+5%3A+Credentials+on+Windows" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Socks+5%3A+Credentials+on+Windows&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Socks+5%3A+Credentials+on+Windows&amp;u=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Socks+5%3A+Credentials+on+Windows&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Socks+5%3A+Credentials+on+Windows&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Socks+5%3A+Credentials+on+Windows&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F&amp;title=Socks+5%3A+Credentials+on+Windows&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Flandheer-cieslak.com%2Fwordpress%2Fsocks-5-credentials-on-windows%2F" ><img class="lightsocial_img" src="http://landheer-cieslak.com/wordpress/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://landheer-cieslak.com/wordpress/socks-5-credentials-on-windows/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
