Add encoder

I know I've broken PR etiquette here by combining a lot of changes AND reformatting the code, but I thought I'd raise it anyway to see what you think. This adds basic encoding functionality, a lot more tests, fixes a bug or two and speeds up the VINT encoding (at least according to the times reported by the tests).