Saturday, 22 November 2008

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

So far we have created a fairly inert husk of a circular_buffer class. The few methods we've written allow you to easily discover that it doesn't have anything in it. And that's about it. We need to get data in and we need to get data out.

Refining the data representation


But first, let's consider the internal data representation. We originally decided that the buffer is empty when m_front == m_back, and full when 'm_front+1' (modulo m_buffer size) == m_back.

If you're observant you'll notice that this means the m_buffer array will never get completely filled. The circular_buffer will be considered full when there is one space left in m_buffer. Certainly, for a buffer of ints this might be acceptable, but a circular_buffer of a large custom data type might be consuming a lot of memory unnecessarily.

So what can be done about this? A simple mechanism that will work well is to set the m_front pointer to 0 when the buffer is empty. This simple change means the following methods change:
template <typename T>
circular_buffer<T>::circular_buffer(size_t capacity)
: m_capacity(capacity),
buffer(new value_type[capacity]),
m_front(0), //< initialisation change here
m_back(buffer.get())
{
}

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

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

Following STL traditions, we'll provide a push_back method to push an item onto the back of the circular_buffer. At this point, we must decide what to do when the buffer is full. The options are:

  • throw an exception
  • return an error code
  • silently ignore the data and leave the circular_buffer unchanged
  • accept the data and consume the oldest peice of data at the back of the buffer
We'll choose the latter option. It would be perfectly possible provide several options in the future, either by a template traits parameter, a parameter to the push_back method, or a set of overloaded functions. This is left as an excercise for the reader.

Traditionally, a push_back method returns void, but we'll return a boolean value: true normally, or false if the new data has pushed old stale data from the back of the buffer. The signature is in the class declaration is therefore:
bool push_back(const value_type &);
It's basic template-code good practice to pass the parameter as a const reference. We'll not go into the reasons here, but make sure you know why.

Here's our first go at the implementation of push_back...
template <typename T>
bool circular_buffer<T>::push_back(const value_type &value)
{
*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;
}
}
You'll notice that I have incanted a new method, wrap. This is a little internal helper that takes a pointer and wraps it around into m_buffer if it falls of m_buffer's bounds. We're going to be doing this quite a lot.
private:
value_type *wrap(value_type *ptr)
{
assert(ptr < buffer.get() + m_capacity*2);
if (ptr >= buffer.get()+m_capacity)
return ptr-m_capacity;
else
return ptr;
}
Now let's check that it all works correctly:
int main()
{
circular_buffer<int> cb(5);

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

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

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.push_back(6));
assert(cb.size() == 5);
assert(cb.capacity() == 5);
assert(!cb.empty());
}

Getting data out

We got it in there, now we need a way to get it out again. To read the contents we implement front(), which returns the item at the head of the buffer. We need two overloads, a const and non-const version:
// In declaration
reference front();
const_reference front() const;
We can return a reference (or const_reference) to the data inside m_buffer to avoid unnecessary data copying.

What should the behaviour be when the circular_buffer is empty? Following the model set by existing STL containers, the result is undefined. The user Should Not do this, and if you do the class might just explode in a shower of bright purple sparks.

Of course, we'll be a bit more polite than that.
template <typename T>
typename circular_buffer<T>::reference circular_buffer<T>::front()
{
assert(m_front);
return *m_front;
}

template <typename T>
typename circular_buffer<T>::const_reference circular_buffer<T>::front() const
{
assert(m_front);
return *m_front;
}
Once we've read the item at the front, we need to remove it so we can get at the next item. The candidate for that is called called pop_front. Again, the user should not call pop_front if there is no data in the circular_buffer so we are quite at liberty to produce exciting purple sparks, or boring assertion failures.

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

value_type *const next = wrap(m_front+1);
if (next == m_back)
m_front = 0;
else
m_front = next;
}
If you're paying attention, you should by now be feeling very uncomfortable. There's an elephant lurking in the corner of this room. Clue: it's related to object lifetimes. We'll address this in the next installment.

Until then, we need to compose some reasonable tests for front() and pop_front(). To do this, I'll provide the entire code so far so you can see how it looks.
#include <boost/scoped_array.hpp>
#include <algorithm>

template <typename T>
class circular_buffer
{
public:
typedef T value_type;
typedef size_t size_type;
typedef value_type &reference;
typedef const value_type &const_reference;

circular_buffer(size_t capacity);

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();

private:
const size_type m_capacity;
boost::scoped_array<value_type> m_buffer;
value_type *m_front;
value_type *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)
{
assert(ptr < m_buffer.get() + m_capacity*2);
if (ptr >= m_buffer.get()+m_capacity)
return ptr-m_capacity;
else
return ptr;
}
};

template <typename T>
circular_buffer<T>::circular_buffer(size_t capacity)
: m_capacity(capacity),
m_buffer(new value_type[capacity]),
m_front(0),
m_back(m_buffer.get())
{
}

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

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

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

template <typename T>
typename circular_buffer<T>::size_type circular_buffer<T>::max_size() const
{
const size_type count = size_type(-1) / sizeof(value_type);
return std::max(count, size_type(1));
}

template <typename T>
bool circular_buffer<T>::push_back(const value_type &value)
{
*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 circular_buffer<T>::reference circular_buffer<T>::front()
{
assert(m_front);
return *m_front;
}

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

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

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

int main()
{
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);

return 0;
}

Friday, 21 November 2008

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

Now it's time to think about the gory internal details of our circular_buffer.

Obviously, we need a data store for the buffer. A good old-fashioned array will do nicely, thank you. We'll need to remember the capacity of the array so we don't overrun it. And we must maintain a record of the front and the back of the data stored in the array. We could store these as indexes into the array, or as a pointer to the data. Let's go with the latter. There will be no need to separately store the number of items held in the buffer as it can be derived easily from the front/back pointers.

We want to play the C++ game nicely and make sure that we never leak resources, so we'll store the buffer in a boost::scoped_array (see here). So, here's a first stab at the data members for our class:
private:
const size_type m_capacity;
boost::scoped_array<value_type> m_buffer;
value_type *m_front;
value_type *m_back; // points to next unused item
Stylistic note #1: I really don't usually like m_ prefixes for member variables. However, since we will shortly need to create a public method called capacity(), we can't use that as a variable name. I don't want to instead use a bizarre variable name for "capacity", so I'll adopt this naming scheme.

Here's the plan:
  • We insert new data at m_back.
  • We read data from m_front.
  • When m_front == m_back (as it will after construction), the buffer is empty.
  • If the item after m_front is m_back, then the buffer is full.
Having established this, we can get on with some serious implementation:

The constructor

The constructor sets everything up as you'd expect. Note that we make it explicit so you can't write the nonsensical line: circular_buffer cb = 20;
// In declaration
explicit circular_buffer(size_t capacity);


template <typename T>
circular_buffer<T>::circular_buffer(size_t capacity)
: m_capacity(capacity),
m_buffer(new value_type[capacity]),
m_front(buffer.get()),
m_back(buffer.get())
{
}
Stylistic note #2: I'm writing the definitions of all methods out-of-line underneath the class declaration. This makes the class declaration far easier to read, at the expense of more typing are the definition.

If you're paying attention then you'll already realise that there may be some problems with this design. We'll get to this in Part 6.

Some easy questions

Now we can implement some of the simpler methods required by section 23.1 of the C++ standard. size() returns the number of items held in the buffer. empty() tells you if the container is empty (rather than emptying all the items out of it, which is a common newbie misunderstanding!) capacity() tells you how many items the container can hold. max_size() returns the size() of the largest possible container.
// In declaration
size_type size() const;
size_type max_size() const;
bool empty() const;
size_type capacity() const;

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

template <typename T>
bool circular_buffer<T>::empty() const
{
return m_front == m_back;
}

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

template <typename T>
typename circular_buffer<T>::size_type circular_buffer<T>::max_size() const
{
// Yes, this is a rather nasty trick. We could pull the maximum value for
// size_type from std::numeric_limits instead of using -1.
// But we'll do something even nicer shortly.
const size_type count = size_type(-1) / sizeof(value_type);
return std::max(count, size_type(1));
}
The only reasonably complex function is size() and it's clear what's going on in there, isn't it?

Note the use of typename in the function implementations above. That is required to help the compiler deduce that
circular_buffer<T>::size_type is the name of a type; the poor thing can't work this out for itself.

Notable by their absense

The circular_buffer is notionally a sequence container (as defined by section 23.1.1 of the standard), by its very nature it does not support insertion or removal of items in the middle of the sequence. So we will not provide a version of insert() or erase(). We'll also chose not to support reserve(); unlike a growing container (e.g. std::vector), the circular buffer size must be supplied on construction. There is little point in providing an interface to change this capacity. (If you want to do this, I will leave it as an exercise for the reader).

Prohibit the prohibitable

Our choice of data storage means that it is not safe to copy or assign to a circular_buffer. Until we deign to fix this, we'll make sure that a user of the code can't shoot themselves in the foot:
// In declaration
private: // Not to be implemented
typedef circular_buffer class_type;
circular_buffer(const class_type &);
class_type &operator=(const class_type &);
This is a standard c++ technique: we declare the copy constructor and assignment operator in the private section and don't implement them.

Testing

Before we bring part 4 to rest, we'd best check that those methods work. I usually use Aeryn, a great unit test framework for C++. But rather than indoctrinate you into the cult Aeryn right now, we'll write some simple tests using nothing more that the standard C assert macro.
int main()
{
circular_buffer<int> cb(5);

assert(cb.size() == 0);
assert(cb.capacity() == 5);
assert(cb.empty());
assert(cb.max_size() > 0);
}
Right now, there's not much more we can do to the buffer. But that's all set to change...

Thursday, 20 November 2008

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


Now it's time flesh out the class, and consider the interface we'd like to give it.

First, STL containers have a number of requirements, laid down in the C++ standard in section 23.1. This includes definitions for these nested type definitions:
  • value_type - type of the items help in the container
  • reference - type of a reference to an item in the container
  • const_reference - type of a reference to a constant item in the container
  • iterator - type of container iterator
  • const_iterator - type of container const interator
  • difference_type - type expressing the distance between two iterators (or const_iterators)
  • size_type - type that represents any non-negative value of difference_type
As a first step, we'll add to our class the following typedefs, remembering that T is the template parameter name for the container item type:
typedef T value_type;
typedef size_t size_type;
typedef int difference_type;
typedef value_type &reference;
typedef const value_type &const_reference;
This is a starting point. We'll define the iterator types later, and some of these definitions can be made a little more elegant, too.

Next time: we'll decide the mechanics of the class and how to manage resources.

Wednesday, 19 November 2008

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

In part 1 we looked at what a circular buffer is, and why you'd want to use (or write) an STL-compliant circular buffer. Now let's start to write one.

First, a few preliminaries:
  • How will we ensure it is thread safe? This is a real issue, as most circular buffer applications are in producer/consumer applications where the consumer and producer are running on different threads. The answer: for an STL container, this is not an issue - we will ignore threading issues, as current STL container implementations do. It is up to the client of the circular_buffer class to use it in a thread safe manner.
  • Do we want to write a container adaptor? Some standard C++ containers are actually container adaptors - data types that wrap and adapt existing container types and give them a more specialised interface. For example, std::priority_queue is an adaptor that, by default, wraps a std::vector. In this instance, it is not particularly beneficial to wrap any other container type, and so we will not make the circular_buffer an adaptor type.
Every journey has a start

So let's kick off the data type by writing a simple starting scaffold:
template <typename T> //< See note below
class circular_buffer
{
public:
circular_buffer(size_t capacity);
};
This defines the class, circular_buffer, that will store items of type T.

There is already one issue apparent that we will shelve for a while: allocators. STL containers all take an additional template parameter that describes how the container should allocate and free internal memory resources. We'll come back to that later. (Honest)

The constructor takes the fixed size of the internal data store of the circular buffer. We could chose to provide a default implementation to make using the class 'easier', but I don't see any advantage to doing so. Each use of a circular buffer is individual, and the storage requirements depend on the situation. Providing a default value could lead to problems in practice, so I'd like to force the programmer to consider the size of storage needed each time they instantiate a circular_buffer.

Although this is a very simple scaffold, let's write a unit test to i) prove that the code compiles OK, and to ii) check that it works.
int main()
{
circular_buffer cb1(10);
circular_buffer cb1(100);
}
Naturally, this compiles cleanly. However, it won't link or run, since we've not written the body of the constuctor yet. All this fun, and more, is yet to come.

Next time: the next step is to set up the basic typedefs required of an STL-compliant container.

On programming: You gotta care about the code

The following article is excerpted from a forthcoming book project.

It doesn't take Sherlock Holmes to work out that good programmers write good code. Bad programmers... don't. They produce monstrosities that the rest of us have to clean up. You want to write the good stuff, right? You want to be a good programmer.

Good code doesn't pop out of thin air. It isn't something that happens by luck when the planets align. To get good code, you have to work at it. Hard. And you'll only get good code if you actually care about good code.

Good programming is not borne from mere technical competence. I've seen highly intellectual programmers who can produce intense and impressive algorithms, who know their language standard by heart, but who write the most awful code. It's painful to read, painful to use, and painful to modify. I've seen more humble programmers who stick to very simple code, but who write elegant and expressive programs that are a joy to work with.

Based on my years of experience in the software factory, I've concluded that the real difference between adequate programmers and great programmers is this: their attitude. Good programming lies in taking a professional approach, and wanting to write the best software you can, within the Real World constrains and pressures of the software factory.

The code to hell is paved with good intentions. To be an excellent programmer you have to rise above good intentions, and actually care about the code - to foster positive perspectives and develop healthy attitudes. Great code is carefully crafted by master artisans, not thoughtlessly hacked out by sloppy programmers, or erected mysteriously by self-professed coding gurus.

You want to write good code. You want to be a good programmer. So, you care about the code:
  • In any coding situation, you refuse to hack something that seems to work. You strive to craft elegant code that is clearly correct (and has good tests to show that it is correct).
  • You write code that is discoverable (that other programmers can easily pick up and understand), that is maintainable (that you, or other programmers, will be easily able to modify in the future), and that is correct (you take all steps possible to determine that you have solved the problem, not just made it look like the program works).
  • You work well alongside other programmers. No programmer is an island. Few programmers work alone; most work in a team of programmers, either in a company environment, or in open source project. You consider programmers, and construct code that other people can read. You want the team to write the best software possible, rather than to make yourself look clever.
  • Any time you touch a piece of code you strive to leave it better than you found it (either better structured, better tested, more understandable...).
  • You care about code and about programming, so you are constantly learning new languages, idioms, and techniques. But you only apply them when appropriate.
Fortunately, you're reading this because you do care about code. It interests you. It's your passion. Have fun programming. Enjoy cutting code to solve tricky problems. Produce software that makes you proud.

Tuesday, 18 November 2008

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

This is the first in a series of postings that will walk through the process of writing a C++ STL-like container. Specifically, we're going to look at the implementation of a circular buffer in C++.

In this first part we'll cover a little introductory ground.

What is a circular buffer?

A circular buffer is a fixed size data structure that presents its storage space as one long continuous buffer. The internal store effectively wraps around itself internally (circularly, hence the name).

Because of the internal data storage scheme, a circular buffer only lends itself to pushing a block of data onto the front of the buffer, and pulling a block of data from the back of buffer. It specifically will not support insertion in the middle of the data, and needn't support random access, either. Typically, circular buffers are FIFO.

Once the internal data store is full, a circular buffer implementation could either choose to:
  • not accept any more data until the buffer is emptied, or to
  • accept any amount of data, silently overwriting the older data with the new data.
Like a fixed-size array, you always know how much space a circular buffer will occupy - a useful property in many applications, and an possible advantage over a std::vector. It also has fixed performance characteristics.

A circular buffer is often employed in producer-consumer scenarios, where one component supplies data and another asynchronously consumes that data. We commonly see this pattern in multimedia and communications applications.

Why would you want an STL-like circular buffer?

So why would you specifically write an STL-like implementation of a circular buffer in C++?
  1. Interoperability. Any container that subscribes to the STL's interface can be used seamlessly with existing C++ algorithms (either those in the std namespace supplied in the C++ standard library, or other third-party STL-like algorithms, like those in the Boost library).
  2. Discoverability. If your container has an STL-like interface then C++ programmers will be easily able to pick it up and work with it. Sure, they'll have to understand its specific performance characteristics, and to which situations it is particularly suited (as you do with any C++ container). But an STL-like container will be easy to learn, and also easy to understand in order to modify.
  3. Good taste. The STL is the benchmark for good C++ library design. Sure, there are a few oddnesses and warts in there. No library is perfect. But it's a generally well thought out, and carefully constructed beast. There's a lot to be said for fitting into its world view.
  4. Reusability. Resuse is often a shadow that programmers chase unnecessarily. However, in most cases giving a simple container an STL-like interface, rather than a very application-specific interface will allow you to use it in more than one situation; a small sliver of a silver bullet, if ever there was one.
  5. Learn the inner workings of the STL. And if you're really bored, here's another great reason to write your own STL-like container: If you want to understand how the STL really works, how to extend it, and how to use it like a master then there's nothing better than writing your own STL code.
Hopefully that's a compelling list of reasons.

In the next posting, I'll launch into some C++. Buckle your std::seatbelts!

Closing down. Everything must go.

Anyone want to buy a small, cute software development team? One previous careful owner. House-trained (mostly).

There's a direct connection between bankers in the US having a little private disaster party and the job security of the rest of the world. The ripples are moving gradually further out, and sadly the writing's now one the wall for my development team in Cambridge, UK. It's a real shame, but largely unavoidable: when you make consumer products, and distributers are not buying any stock at Christmas time, or can't get credit to do so, then you have a problem. And there aren't many solutions.

So our office will almost certainly close its doors for the last time in a few days.

Personally, it's a shame. It's not often you get to work on something you are genuinely passionate about. It's not often you are able to construct something truly excellent from scratch, to work on an excellent codebase, fully unit tested from the start, and to do so with a team of excellent programmers who you're happy to meet in the pub as much as the work place. It's a shame that the economic conditions will consign our codebase and products to a very small chapter of history. Plans for world domination have been put on hold.

Still, onwards. To new challenges. The first of which will be finding a job. I'm going to have to buy some shoes...