mapbox/pbf — pull request #11 by mourner (2014-12-24 22:04:21+00:00)
Title: Convenient methods for easier reading

Adds two simple convenience methods, `read` and `readMessage`, two make the following possible:

```js
var result = pbf.read(readData);

function readData(tag) {
var result = {};
if (tag === 1) result.name = pbf.readString();
else if (tag === 2) result.version = pbf.readVarint();
else if (tag === 3) result.layer = this.readMessage(readLayer);
return result;
}
function readLayer(tag) {
if (tag === 1) ...
}
```

Compare that with the explicit approach:

```js
var result = {};

while (pbf.pos < pbf.length) {
var val = pbf.readVarint(),
tag = val >> 3,
startPos = buf.pos;

if (tag === 1) result.name = pbf.readString();
else if (tag === 2) result.version = pbf.readVarint();
else if (tag === 3) {
result.layer = {};

var bytes = this.readVarint();
while (this.pos < end) {
var val = this.readVarint(),
tag = val >> 3,
startPos = this.pos;
if (tag === 1) ...
else this.skip(val);
}
}
else this.skip(val);
}
```

Both methods accept a function for reading a field which get tag as an argument. Skipping tags is done automatically — if position didn't change after calling a function (which means there were no reads), we skip it. You can add explicit skipping though and it'll still work. cc @tmcw @springmeyer @kkaefer