Friday, 28 November 2008

The Last Man Standing

You may recall that my company has decided to shut down our Cambridge office and scale back its development operation significantly. Since that announcement I've been busily looking for other gainful employment, and have been pleasantly surprised that the job market is not entirely stagnant. I've had a number interesting leads that I'm still following up.

However, in a dramatic turnaround I have now secured a safe position in my existing organisation, which is a huge weight off my mind. (That doesn't necessarily mean I'll stop looking for other work, but it means I'm secure in the meantime). I am The Last Man Standing.

I was a little disappointed that we didn't have an Apprentice-style face-off for the position, with the CEO saying you're fired to team members in turn. In the end the selection process was little more than a job proposal, some phone calls to the states, and a little negotiation. No pistols at dawn.

This new role is going to be somewhat taxing. Solely responsible for the future of the codebase we've developed, reporting to the US, without the safety net of on-site QA or hardware support, working on my own (in a location yet to be determined). I'm genuinely unsure of how well I'll be able to work on my own; I've never done that before. It's going to be a bumpy ride...

And, I'm not entirely sure how I'm going to structure my development process. Let's be honest, it's hard to do XP in a team of one. Pair programming will be somewhat tricky, and code reviews hard to elicit. I'm going to need to build in something to replace the accountability in our existing development process. All comments and suggestions welcomed...

It's been a great three years working with a team of talented and motivated people, and a real shame to get to the end of the era at this early stage. There was a lot more potential in the team that we hadn't yet exploited.

Wednesday, 26 November 2008

C++: An STL-like circular buffer (Part 9)

Here's a little extra method we can easily add: back(). In a similar way to std::vector, std::deque, and std::list, the circular_buffer can support a back method, which returns a reference to the item at the end of the container.

Remember, m_back refers to the next unused item, so if we have anything in the buffer, it will be stored in the previous element.
// In declaration
reference back();
const_reference back() const;

template <typename T, typename A>
inline
typename circular_buffer<T,A>::reference circular_buffer<T,A>::back()
{
assert(m_front);
return *wrap(m_back-1);
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::const_reference circular_buffer<T,A>::back() const
{
assert(m_front);
return *wrap(m_back-1);
}

C++: An STL-like circular buffer (Part 8)

The circular_buffer is looking in pretty good shape now. We've squashed bugs and introduced an allocator. And, to be fair, we could stop here and have a perfectly usable class.

However, let's add some more methods to the container to learn a bit more about writing STL-like containers. The story can't end here after all, there's been no dramatic climax.

operator[] and at

These two methods aren't strictly required of a circular buffer. Section 23.1.1 of the standard claims these operations are only provided when they take constant time. We can achieve constant time indexing with our class, so let's write them.
    // In declaration
reference operator[](size_type n);
const_reference operator[](size_type n) const;
reference at(size_type n);
const_reference at(size_type n) const;
at() is an index operator that performs bounds checking, throwing a std::out_of_range error if the index is invalid. operator[] itself need perform no bounds checking. Given our wrap() method, the implementations are simple:
template <typename T, typename A>
inline
typename circular_buffer<T,A>::reference circular_buffer<T,A>::operator[]
(size_type n)
{
return *wrap(m_front+n);
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::const_reference circular_buffer<T,A>::operator[]
(size_type n) const
{
return *wrap(m_front+n);
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::reference circular_buffer<T,A>::at(size_type n)
{
if (n >= size()) throw std::out_of_range("Parameter out of range");
return (*this)[n];
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::const_reference circular_buffer<T,A>::at
(size_type n) const
{
if (n >= size()) throw std::out_of_range("Parameter out of range");
return (*this)[n];
}
We implement at() in terms of operator[]. To use std::out_of_range, you'll need to include <stdexcept>

We should write some more tests for test these new methods. In showing you this, I'll reproduce the entire class so far.
#include <algorithm>
#include <stdexcept>

template <typename T, typename A = std::allocator<T> >
class circular_buffer
{
public:
typedef T value_type;
typedef A allocator_type;
typedef typename allocator_type::size_type size_type;
typedef typename allocator_type::difference_type difference_type;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;

explicit circular_buffer(size_type capacity,
const allocator_type &a = allocator_type());
~circular_buffer();
allocator_type get_allocator() const;

size_type size() const;
size_type max_size() const;
bool empty() const;

size_type capacity() const;

reference front();
const_reference front() const;

bool push_back(const value_type &);
void pop_front();
void clear();

reference operator[](size_type n);
const_reference operator[](size_type n) const;
reference at(size_type n);
const_reference at(size_type n) const;

private:
size_type m_capacity;
allocator_type m_allocator;
pointer m_buffer;
pointer m_front;
pointer m_back; // points to next unused item

typedef circular_buffer<T> class_type;

circular_buffer(const class_type &);
class_type &operator=(const class_type &);

value_type *wrap(value_type *ptr) const
{
assert(ptr < m_buffer + m_capacity*2);
if (ptr >= m_buffer+m_capacity)
return ptr-m_capacity;
else
return ptr;
}
};

template <typename T, typename A>
inline
circular_buffer<T,A>::circular_buffer
(size_type capacity, const allocator_type &allocator)
: m_capacity(capacity),
m_allocator(allocator),
m_buffer(m_allocator.allocate(capacity)),
m_front(0),
m_back(m_buffer)
{
assert(capacity > 0);
}

template <typename T, typename A>
inline
circular_buffer<T,A>::~circular_buffer()
{
clear(); // deallocates all objects
m_allocator.deallocate(m_buffer, m_capacity);
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::allocator_type
circular_buffer<T,A>::get_allocator() const
{
return m_allocator;
}


template <typename T, typename A>
inline
typename circular_buffer<T,A>::size_type circular_buffer<T,A>::capacity() const
{
return m_capacity;
}

template <typename T, typename A>
inline
bool circular_buffer<T,A>::empty() const
{
return !m_front;
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::size_type circular_buffer<T,A>::size() const
{
return !m_front ? 0
: (m_back > m_front ? m_back : m_back+m_capacity) - m_front;
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::size_type circular_buffer<T,A>::max_size() const
{
return m_allocator.max_size();
}

template <typename T, typename A>
inline
bool circular_buffer<T,A>::push_back(const value_type &value)
{
if (m_front && m_front == m_back)
m_allocator.destroy(m_back);

m_allocator.construct(m_back, value);

value_type *const next = wrap(m_back+1);
if (!m_front)
{
// first entry in the buffer
m_front = m_back;
m_back = next;
return true;
}
else if (m_front == m_back)
{
// buffer is full already, throw something away
m_front = m_back = next;
return false;
}
else
{
m_back = next;
return true;
}
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::reference circular_buffer<T,A>::front()
{
assert(m_front);
return *m_front;
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::const_reference circular_buffer<T,A>::front() const
{
assert(m_front);
return *m_front;
}

template <typename T, typename A>
inline
void circular_buffer<T,A>::pop_front()
{
assert(m_front);

m_allocator.destroy(m_front);
value_type *const next = wrap(m_front+1);
if (next == m_back)
m_front = 0;
else
m_front = next;
}

template <typename T, typename A>
inline
void circular_buffer<T,A>::clear()
{
if (m_front)
{
do
{
m_allocator.destroy(m_front);
m_front = wrap(m_front+1);
}
while (m_front != m_back);
}
m_front = 0;
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::reference circular_buffer<T,A>::operator[]
(size_type n)
{
return *wrap(m_front+n);
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::const_reference circular_buffer<T,A>::operator[]
(size_type n) const
{
return *wrap(m_front+n);
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::reference circular_buffer<T,A>::at(size_type n)
{
if (n >= size()) throw std::out_of_range("Parameter out of range");
return (*this)[n];
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::const_reference circular_buffer<T,A>::at
(size_type n) const
{
if (n >= size()) throw std::out_of_range("Parameter out of range");
return (*this)[n];
}

namespace tests
{
void pushing_and_popping()
{
circular_buffer<int> cb(5);

assert(cb.size() == 0);
assert(cb.capacity() == 5);
assert(cb.empty());
assert(cb.max_size() > 0);

assert(cb.push_back(1));
assert(cb.size() == 1);
assert(cb.capacity() == 5);
assert(!cb.empty());
assert(cb.front() == 1);

assert(cb.push_back(2));
assert(cb.size() == 2);
assert(cb.capacity() == 5);
assert(!cb.empty());
assert(cb.front() == 1);

assert(cb.push_back(3));
assert(cb.push_back(4));
assert(cb.push_back(5));
assert(cb.size() == 5);
assert(cb.capacity() == 5);
assert(!cb.empty());
assert(cb.front() == 1);

assert(!cb.push_back(6));
assert(cb.size() == 5);
assert(cb.capacity() == 5);
assert(!cb.empty());
assert(cb.front() == 2);

cb.pop_front();
assert(cb.size() == 4);
assert(cb.capacity() == 5);
assert(!cb.empty());
assert(cb.front() == 3);

cb.pop_front();
assert(cb.size() == 3);
assert(cb.front() == 4);

cb.pop_front();
assert(cb.size() == 2);
assert(cb.front() == 5);

cb.pop_front();
assert(cb.size() == 1);
assert(cb.front() == 6);

cb.pop_front();
assert(cb.size() == 0);
assert(cb.capacity() == 5);
assert(cb.empty());

// empty again

assert(cb.push_back(7));
assert(cb.size() == 1);
assert(cb.capacity() == 5);
assert(!cb.empty());
assert(cb.front() == 7);

assert(cb.push_back(8));
assert(cb.push_back(9));
assert(cb.size() == 3);
assert(!cb.empty());
assert(cb.front() == 7);

cb.clear();
assert(cb.size() == 0);
assert(cb.capacity() == 5);
assert(cb.empty());
}

void indexing()
{
circular_buffer<int> cb(5);

// A helper - like asssert, but checks for an exception
#define assert_throws(a,b) \
{\
try { a; throw "Failed to throw"; } \
catch (const b&) { /*OK*/ } \
catch (...) { throw "Threw wrong thing"; } \
}

// We loop round this test several times so our data wraps around the
// internal m_buffer array a few times.
for (size_t n = 0; n < 10; ++n)
{
assert(cb.empty());

const circular_buffer<int> &const_cb(cb);

assert_throws(cb.at(0), std::out_of_range);
assert_throws(cb.at(1), std::out_of_range);
assert_throws(const_cb.at(0), std::out_of_range);
assert_throws(const_cb.at(0), std::out_of_range);
// we could check that operator[] explodes, but there's little point!

assert(cb.push_back(0));
assert(cb.push_back(1));
assert(cb.push_back(2));
assert(cb.at(0) == 0); assert(const_cb.at(0) == 0);
assert(cb.at(1) == 1); assert(const_cb.at(1) == 1);
assert(cb.at(2) == 2); assert(const_cb.at(2) == 2);
assert(cb[0] == 0); assert(const_cb[0] == 0);
assert(cb[1] == 1); assert(const_cb[1] == 1);
assert(cb[2] == 2); assert(const_cb[2] == 2);

assert(cb.front() == 0);
cb[0] = 3;
assert(cb.front() == 3);
assert(cb.at(0) == 3); assert(const_cb.at(0) == 3);
assert(cb.at(1) == 1); assert(const_cb.at(1) == 1);
assert(cb.at(2) == 2); assert(const_cb.at(2) == 2);
assert(cb[0] == 3); assert(const_cb[0] == 3);
assert(cb[1] == 1); assert(const_cb[1] == 1);
assert(cb[2] == 2); assert(const_cb[2] == 2);

cb[1] = 4;
assert(cb.at(0) == 3); assert(const_cb.at(0) == 3);
assert(cb.at(1) == 4); assert(const_cb.at(1) == 4);
assert(cb.at(2) == 2); assert(const_cb.at(2) == 2);
assert(cb[0] == 3); assert(const_cb[0] == 3);
assert(cb[1] == 4); assert(const_cb[1] == 4);
assert(cb[2] == 2); assert(const_cb[2] == 2);

cb.pop_front();
assert(cb[0] == 4); assert(const_cb[0] == 4);
assert(cb[1] == 2); assert(const_cb[1] == 2);

cb.pop_front();
assert(cb[0] == 2); assert(const_cb[0] == 2);

cb.pop_front();
}

}
}

int main()
{
tests::pushing_and_popping();
tests::indexing();
return 0;
}


(Another) MacBook Pro hard drive upgrade (17" model)

In October I performed surgery on my 15" MacBook Pro, to upgrade the hard drive. Today I've been repeating the performance, but on a 17" MacBook Pro.

A few observations on the different models:
  • Upgrading the 17" model was easier. (Partly because I've done it once before, and partly because it's generally a more accessible machine.)
  • The screw patterns are identical. However, the Phillips screws inside the battery cover are far more accessible than on the 15" model; they're angled so you can get a screwdriver to them without contorting your hand.
  • The lid seems to crack off of a 17" model with greater ease - less fiddly plastic interlocking.
  • There's more use of sticky tape inside a 17" machine!
  • The nubs that hold the drive in the laptop chassis are different on the 17", asymmetrical in design. I wonder why the two models differ like this?

Monday, 24 November 2008

C++: An STL-like circular buffer (Part 7)

Time to air the dirty laundry, and — since every good metaphor must run to the bitter end — to ask a pantomime washer woman to save the day. Or something like that.

In part 6 we identified some serious object management issues with the existing circular_buffer design. Now we understand them, we'll learn how to fix them, and how to use a C++ allocator. This whole sordid tale will show us exactly how useful allocators are.

What is an allocator?

All STL containers take an allocator as a template parameter. The allocator is an abstraction used to allocate and free memory for items held in the container. The allocator interface is described in section 20.1.5 of the C++ standard.

An allocator is itself templated over the type of object it can allocate space for. Every STL container defaults the allocator template parameter to std::allocator, the standard C++ allocator which employs new and delete. You'll rarely specify an allocator by hand in day-to-day C++ code. The std::allocator class is described in section 20.4.1 of the standard.

The allocator interface is pretty straightforward. An allocator provides a number of typedefs, identical to those required of a container:
  • value_type
  • pointer
  • const_pointer
  • reference
  • const_reference
  • size_type
  • difference_type
It provides a number of methods, including:
size_type max_size(); // Same as a container

// Allocate memory. The second parameter is an optional "hint"
// to the allocator, the address of the object allocated prior to
// this allocation.
pointer allocate(size_type,
typename std::allocator<void>::const_pointer = 0);

// Relinquish allocated memory
void deallocate(pointer p, size_type);

// Construct an object at this (allocated) memory location
void construct(pointer p, const T &t);

// Destruct the object that was constructed in this memory location
void destroy(pointer p);
allocate and deallocate, as their names suggest, service requests for memory allocation or deallocation. More interestingly, construct and destroy are used to vivify an object in already-allocated memory (the memory must have originally come from this allocator). The default implementations employ placement new and invoke the object's destructor in place, as below:
void construct(pointer p, const T &t) { new(p) T(t); }
void destroy(pointer p) { p->~T(); }
That's the kind of C++ you'll very, very rarely write, but that is worth understanding all the same.

Adding the allocator to circular_buffer

So let's thread an allocator through our circular_buffer. The first step, naturally, is to add a new template parameter to the class. We'll default this to std::allocator, which will suit 99% of all users.
template <typename T, typename A = std::allocator<T> >
class circular_buffer
{
// ...
Since the allocator provides a host of useful typedefs related to the object it allocates, we can refine our class' definitions accordingly:
 typedef T                                        value_type;
typedef A allocator_type;
typedef circular_buffer<T,A> self_type;
typedef typename allocator_type::difference_type difference_type;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;
We also extend the constructor to take an explicit allocator object (and supply a sensible default), and add get_allocator to retrieve it.
explicit circular_buffer(size_type capacity,
const allocator_type &a = allocator_type());
allocator_type get_allocator() const;
We'll need to hold a copy of the allocator alongside the other private data members. But more importantly, we must use the it to allocate the memory for m_buffer and to delete it again afterwards. The boost::scoped_array (which seemed like such a good idea at the time) goes, and we must therefore add a corresponding custom destructor, too.
public:
~circular_buffer();

private:
size_type m_capacity;
allocator_type m_allocator;
pointer m_buffer;
pointer m_front;
pointer m_back;
The updated method implementations look like this:
template <typename T, typename A>
inline
circular_buffer<T,A>::circular_buffer
(size_type capacity, const allocator_type &allocator)
: m_capacity(capacity),
m_allocator(allocator),
m_buffer(m_allocator.allocate(capacity)),
m_front(0),
m_back(m_buffer)
{
}

template <typename T, typename A>
inline
circular_buffer<T,A>::~circular_buffer()
{
clear(); // Delete all objects before deallocating the buffer
m_allocator.deallocate(m_buffer, m_capacity);
}

template <typename T, typename A>
typename circular_buffer<T,A>::allocator_type
inline
circular_buffer<T,A>::get_allocator() const
{
return m_allocator;
}

template <typename T, typename A>
inline
typename circular_buffer<T,A>::size_type circular_buffer<T,A>::max_size() const
{
// This is clearly more elegant than the previous implementation!
return m_allocator.max_size();
}

// This version of push_back must constuct and detroy objects in m_buffer
// using m_allocators methods, rather than traditional construction, copying,
// assignment.
template <typename T, typename A>
inline
bool circular_buffer<T,A>::push_back(const value_type &value)
{
// If the buffer is full, and data will fall off the back of the
// buffer - so we must destroy the stale object first.
// This is an implementation choice, we could instead use operator= on
// the value_type to replace the item. However, that would require
// value_type to provide a copy assignment operator.
if (m_front && m_front == m_back)
m_allocator.destroy(m_back);

m_allocator.construct(m_back, value);

// The rest of push_back is as it was before
value_type *const next = wrap(m_back+1);
if (!m_front)
{
// first entry in the buffer
m_front = m_back;
m_back = next;
return true;
}
else if (m_front == m_back)
{
// buffer is full already, throw something away
m_front = m_back = next;
return false;
}
else
{
m_back = next;
return true;
}
}

template <typename T, typename A>
inline
void circular_buffer<T,A>::pop_front()
{
assert(m_front);

m_allocator.destroy(m_front);
value_type *const next = wrap(m_front+1);
if (next == m_back)
m_front = 0;
else
m_front = next;
}

template <typename T, typename A>
inline
void circular_buffer<T,A>::clear()
{
if (m_front)
{
do
{
m_allocator.destroy(m_front);
m_front = wrap(m_front+1);
}
while (m_front != m_back);
}
m_front = 0;
}
That's everything that needs substantial change. Every other existing method definition gains an additional template parameter (but ignores it). Oh, and wrap() needs the ".get()"s striped from the m_buffer address lookups.

That's it.

We've fixed some nasty, subtle bugs and taken one step closer to STL perfection.

Next time: We begin to iterate. And then we iterate. And then we iterate. And then we...

Saturday, 22 November 2008

C++: An STL-like circular buffer (Part 6)

We now have a circular_buffer that you can add data to, read data from, remove data from, and that seems superficially correct. Let's add one extra method, clear(), and then start fretting.

Clear

We can quite easily add clear(), a method that removes all the data from the buffer. (This is what many programmers initially confuse the empty() method for. Obviously empty is a question, and clear is a command. Go figure)
template <typename T>
void circular_buffer<T>::clear()
{
m_front = 0;
}
That's simple enough, isn't it? We can make the buffer think it is empty again by simply resetting the m_front pointer. Let's test...
  circular_buffer<int> cb(5);

assert(cb.push_back(7));
assert(cb.push_back(8));
assert(cb.push_back(9));
assert(cb.size() == 3);
assert(cb.capacity() == 5);
assert(!cb.empty());
assert(cb.front() == 7);

cb.clear();
assert(cb.size() == 0);
assert(cb.capacity() == 5);
assert(cb.empty());
Success. Hurray.

Falling from grace

However, we've ignored the elephant for long enough. This method is the straw that broke the elephant's back. What happened to all the data that was in the buffer? So far, we've only tested with ints, so nothing interesting has happened at all.

But what if you want a circular_buffer of a large user-defined class, Foo? This is what is going to happen:
  • The constructor will allocate an array of m_capacity default-constructed Foos. If there isn't a default constructor then constructing the circular_buffer will not compile. An empty buffer should not have constructed anything.
  • push_back replaces Foo objects in the array with Foo's assignment operator
  • pop_back does not destruct the Foo being removed
  • empty does not destruct the Foos that have been put in the buffer
That's not ideal. In fact, it's downright incorrect. Here's a little illustration to prove the point; at the end of IllustrateTheProblem you would have expected no TheProblem objects to have been constructed.
  struct TheProblem
{
static size_t constructed;
TheProblem() { ++constructed; }
};

size_t TheProblem::constructed = 0;

void IllustrateTheProblem()
{
assert(TheProblem::constructed == 0);
circular_buffer<TheProblem> bufer(5);
assert(TheProblem::constructed == 0); // this fails
}
There, we've said it. It's out in the open. We'll address this problem when we add allocators to the class design.

Intermission: Posting code on Blogger

The series I'm posting on circular buffers in C++ is a bit of a personal experiment in article writing; attempting to form an article on-line in pieces that can eventually be assembled into a cohesive whole.

Thanks for the feedback you're giving me, in comments and by email. The encouragement is great.

The experience has been an interesting one so far. In fact, it's also been a quite frustrating one. The Blogger editor is supremely unhelpful when you try to enter preformatted text (like C++ code).
  • Code with angle brackets (e.g. < and >) is hard to get into Blogger without accidental butchering during editing or display, since you fall into all sorts of complex HTML problems.
  • The Blogger editor continually reformats my pre-formatted code, stripping spaces, inserting spaces, realigning things. Every time you open the editor to fix one mistake, it breaks everything you fixed last time. Very frustrating.
  • The editor window is far too small for anything except the smallest pieces of writing.
  • I've attempted using external blog editing software, Quama to sidestep these issues. It's a beta version, and so somewhat buggy. It also has it's own ideas of how to butcher and reformat my code.
  • The Blogger layout themes don't really help to make code readable at all.
If anyone has any cunning solutions to this problem, I would really love to hear them! Otherwise, I'll soldier on fiddling with code by hand and losing what's left of my hair. Please do point out layout issues to me, and I'll do my best to fix them.