Tuesday, March 27, 2012

C++ then and now

A long while ago (turn of the century) I wrote a little Win32 utility to drag and drop files to get their MD5 and SHA-1 hashes -- useful for verifying downloads. And when I composed the hex-string hashes into a std::string, it looked almost 'C' like, thus (repeated once per hash):

for(k=0; k<SHAHASHSIZE; ++k)
{
x += sprintf(buff+x, "%02x", sha[k]);
if(k%2) x += sprintf(buff+x, " ");
}
view raw gistfile1.cpp hosted with ❤ by GitHub

with <string> being the only bit of C++ in sight, in fact

After the recent Going Native C++11 bash I decided to dust it off and revise it using Boost and the TR1 features in VC++ 2010 (which has most of the C++11 goodness all by itself). So now that section looks like:

static void format_hex_string(std::vector<BYTE> & buffer, std::wstring & sink)
{
boost::wformat hex(L"%02x");
boost::for_each(buffer, [&hex, &sink] (BYTE x) {
static int count = 1;
hex % x;
sink += hex.str();
if ((++count)%2) sink += L" ";
});
}
view raw gistfile1.cpp hosted with ❤ by GitHub

which gets called in another lambda that is for_eaching over a vector of tuples containing hash contexts.

The code size has gone up (down if you count discarding hand-written MD5 and SHA1 for the CryptoAPI -- which adds its own error-handling bloat); but the increase includes half a dozen little RAII classes, and code to discover a better monospace font than SYSTEM_FIXED_FONT, albeit from a hard-coded list of Inconsolata, Consolas, Lucida Console and finally Courier New.

My immediate reaction is that the provision of lambdas now makes the standard algorithms actually usable -- no more functor classes remote from the point of use -- and I can program it in the more functional style that I'm now used to.

No comments :