Compare commits

..
3 Commits
Author SHA1 Message Date
Erica Fischer af1a7ed7ae Once features can't possibly fit in a tile, stop trying (#9)
* Stop adding features to a tile if it can't possibly work

* Add --integer and --fraction options to tippecanoe-decode

* Carry the strategies field from tileset metadata through tile-join

* Update changelog

* Assign different codes to different kinds of error exits
2022-09-23 20:01:13 -04:00
Vincent Sarago ed31b9ac84 Update README.md (#13)
protomaps -> felt
2022-09-23 19:54:57 -04:00
Erica Fischer 8e46650da7 Upgrade to protozero 1.7.1 (#5)
* Upgrade to protozero 1.7.1

* Bump version number
2022-09-13 11:24:01 -07:00
61 changed files with 3431 additions and 1874 deletions
+10
View File
@@ -1,3 +1,13 @@
## 2.6.2
* Stop adding features to a tile if it can't possibly work, to limit memory use
* Add --integer and --fraction options to tippecanoe-decode
* Carry `strategies` field from tileset metadata through tile-join
## 2.6.1
* Upgrade protozero to version 1.7.1
## 2.6.0
* Add another drop rate guessing options, from the same metrics -zg uses
+4
View File
@@ -160,10 +160,14 @@ decode-test:
mkdir -p tests/muni/decode
./tippecanoe -q -z11 -Z11 -f -o tests/muni/decode/multi.mbtiles tests/muni/*.json
./tippecanoe-decode -x generator -l subway tests/muni/decode/multi.mbtiles > tests/muni/decode/multi.mbtiles.json.check
./tippecanoe-decode -x generator -l subway --integer tests/muni/decode/multi.mbtiles > tests/muni/decode/multi.mbtiles.integer.json.check
./tippecanoe-decode -x generator -l subway --fraction tests/muni/decode/multi.mbtiles > tests/muni/decode/multi.mbtiles.fraction.json.check
./tippecanoe-decode -x generator -c tests/muni/decode/multi.mbtiles > tests/muni/decode/multi.mbtiles.pipeline.json.check
./tippecanoe-decode -x generator tests/muni/decode/multi.mbtiles 11 327 791 > tests/muni/decode/multi.mbtiles.onetile.json.check
./tippecanoe-decode -x generator --stats tests/muni/decode/multi.mbtiles > tests/muni/decode/multi.mbtiles.stats.json.check
cmp tests/muni/decode/multi.mbtiles.json.check tests/muni/decode/multi.mbtiles.json
cmp tests/muni/decode/multi.mbtiles.integer.json.check tests/muni/decode/multi.mbtiles.integer.json
cmp tests/muni/decode/multi.mbtiles.fraction.json.check tests/muni/decode/multi.mbtiles.fraction.json
cmp tests/muni/decode/multi.mbtiles.pipeline.json.check tests/muni/decode/multi.mbtiles.pipeline.json
cmp tests/muni/decode/multi.mbtiles.onetile.json.check tests/muni/decode/multi.mbtiles.onetile.json
cmp tests/muni/decode/multi.mbtiles.stats.json.check tests/muni/decode/multi.mbtiles.stats.json
+3 -1
View File
@@ -38,7 +38,7 @@ Installation
For this fork you will need to build from the source repository:
```sh
$ git clone https://github.com/protomaps/tippecanoe.git
$ git clone https://github.com/felt/tippecanoe.git
$ cd tippecanoe
$ make -j
$ make install
@@ -880,6 +880,8 @@ resolutions.
* `-c` or `--tag-layer-and-zoom`: Include each feature's layer and zoom level as part of its `tippecanoe` object rather than as a FeatureCollection wrapper
* `-S` or `--stats`: Just report statistics about each tile's size and the number of features in it, as a JSON structure.
* `-f` or `--force`: Decode tiles even if polygon ring order or closure problems are detected
* `-I` or `--integer`: Report coordinates in integer tile coordinates
* `-F` or `--fraction`: Report coordinates as a fraction of the tile extent
tippecanoe-json-tool
====================
+5 -4
View File
@@ -1,5 +1,6 @@
#include "csv.hpp"
#include "text.hpp"
#include "errors.hpp"
std::vector<std::string> csv_split(const char *s) {
std::vector<std::string> ret;
@@ -68,7 +69,7 @@ void readcsv(const char *fn, std::vector<std::string> &header, std::map<std::str
FILE *f = fopen(fn, "r");
if (f == NULL) {
perror(fn);
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
std::string s;
@@ -76,7 +77,7 @@ void readcsv(const char *fn, std::vector<std::string> &header, std::map<std::str
std::string err = check_utf8(s);
if (err != "") {
fprintf(stderr, "%s: %s\n", fn, err.c_str());
exit(EXIT_FAILURE);
exit(EXIT_UTF8);
}
header = csv_split(s.c_str());
@@ -89,7 +90,7 @@ void readcsv(const char *fn, std::vector<std::string> &header, std::map<std::str
std::string err = check_utf8(s);
if (err != "") {
fprintf(stderr, "%s: %s\n", fn, err.c_str());
exit(EXIT_FAILURE);
exit(EXIT_UTF8);
}
std::vector<std::string> line = csv_split(s.c_str());
@@ -105,7 +106,7 @@ void readcsv(const char *fn, std::vector<std::string> &header, std::map<std::str
if (fclose(f) != 0) {
perror("fclose");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
+45 -27
View File
@@ -22,6 +22,7 @@
#include "write_json.hpp"
#include "jsonpull/jsonpull.h"
#include "dirtiles.hpp"
#include "errors.hpp"
int minzoom = 0;
int maxzoom = 32;
@@ -85,18 +86,18 @@ void do_stats(mvt_tile &tile, size_t size, bool compressed, int z, unsigned x, u
state.json_write_newline();
}
void handle(std::string message, int z, unsigned x, unsigned y, std::set<std::string> const &to_decode, bool pipeline, bool stats, json_writer &state) {
void handle(std::string message, int z, unsigned x, unsigned y, std::set<std::string> const &to_decode, bool pipeline, bool stats, json_writer &state, int coordinate_mode) {
mvt_tile tile;
bool was_compressed;
try {
if (!tile.decode(message, was_compressed)) {
fprintf(stderr, "Couldn't parse tile %d/%u/%u\n", z, x, y);
exit(EXIT_FAILURE);
exit(EXIT_MVT);
}
} catch (std::exception const &e) {
fprintf(stderr, "PBF decoding error in tile %d/%u/%u\n", z, x, y);
exit(EXIT_FAILURE);
exit(EXIT_PROTOBUF);
}
if (stats) {
@@ -159,7 +160,7 @@ void handle(std::string message, int z, unsigned x, unsigned y, std::set<std::st
if (layer.extent <= 0) {
fprintf(stderr, "Impossible layer extent %lld in mbtiles\n", layer.extent);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
if (to_decode.size() != 0 && !to_decode.count(layer.name)) {
@@ -202,10 +203,16 @@ void handle(std::string message, int z, unsigned x, unsigned y, std::set<std::st
// X and Y are unsigned, so no need to check <0
if (x > (1ULL << z) || y > (1ULL << z)) {
fprintf(stderr, "Impossible tile %d/%u/%u\n", z, x, y);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
layer_to_geojson(layer, z, x, y, !pipeline, pipeline, pipeline, false, 0, 0, 0, !force, state);
double scale = 0;
if (coordinate_mode == 1) { // fraction
scale = layer.extent;
} else if (coordinate_mode == 2) { // integer
scale = 1;
}
layer_to_geojson(layer, z, x, y, !pipeline, pipeline, pipeline, false, 0, 0, 0, !force, state, scale);
if (!pipeline) {
if (true) {
@@ -223,7 +230,7 @@ void handle(std::string message, int z, unsigned x, unsigned y, std::set<std::st
}
}
void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> const &to_decode, bool pipeline, bool stats, std::set<std::string> const &exclude_meta) {
void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> const &to_decode, bool pipeline, bool stats, std::set<std::string> const &exclude_meta, int coordinate_mode) {
sqlite3 *db = NULL;
bool isdir = false;
int oz = z;
@@ -240,12 +247,12 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
if (strcmp(map, "SQLite format 3") != 0) {
if (z >= 0) {
std::string s = std::string(map, st.st_size);
handle(s, z, x, y, to_decode, pipeline, stats, state);
handle(s, z, x, y, to_decode, pipeline, stats, state, coordinate_mode);
munmap(map, st.st_size);
return;
} else {
fprintf(stderr, "Must specify zoom/x/y to decode a single pbf file\n");
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
}
}
@@ -256,7 +263,7 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
}
if (close(fd) != 0) {
perror("close");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
} else {
perror(fname);
@@ -272,13 +279,13 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
} else {
if (sqlite3_open(fname, &db) != SQLITE_OK) {
fprintf(stderr, "%s: %s\n", fname, sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
char *err = NULL;
if (sqlite3_exec(db, "PRAGMA integrity_check;", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: integrity_check: %s\n", fname, err);
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
@@ -299,7 +306,7 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
sqlite3_stmt *stmt2;
if (sqlite3_prepare_v2(db, sql2, -1, &stmt2, NULL) != SQLITE_OK) {
fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
while (sqlite3_step(stmt2) == SQLITE_ROW) {
@@ -308,7 +315,7 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
if (name == NULL || value == NULL) {
fprintf(stderr, "Corrupt mbtiles file: null metadata\n");
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
if (exclude_meta.count((char *) name) == 0) {
@@ -361,7 +368,7 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
FILE *f = fopen(fn.c_str(), "rb");
if (f == NULL) {
perror(fn.c_str());
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
std::string s;
@@ -372,14 +379,14 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
}
fclose(f);
handle(s, tiles[i].z, tiles[i].x, tiles[i].y, to_decode, pipeline, stats, state);
handle(s, tiles[i].z, tiles[i].x, tiles[i].y, to_decode, pipeline, stats, state, coordinate_mode);
}
} else {
const char *sql = "SELECT tile_data, zoom_level, tile_column, tile_row from tiles where zoom_level between ? and ? order by zoom_level, tile_column, tile_row;";
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
sqlite3_bind_int(stmt, 1, minzoom);
@@ -407,7 +414,7 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
if (tz < 0 || tz >= 32) {
fprintf(stderr, "Impossible zoom level %d in mbtiles\n", tz);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
ty = (1LL << tz) - 1 - ty;
@@ -415,10 +422,10 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
if (s == NULL) {
fprintf(stderr, "Corrupt mbtiles file: null entry in tiles table\n");
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
handle(std::string(s, len), tz, tx, ty, to_decode, pipeline, stats, state);
handle(std::string(s, len), tz, tx, ty, to_decode, pipeline, stats, state, coordinate_mode);
}
sqlite3_finalize(stmt);
@@ -443,7 +450,7 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
sqlite3_bind_int(stmt, 1, z);
@@ -456,14 +463,14 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
if (s == NULL) {
fprintf(stderr, "Corrupt mbtiles file: null entry in tiles table\n");
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
if (z != oz) {
fprintf(stderr, "%s: Warning: using tile %d/%u/%u instead of %d/%u/%u\n", fname, z, x, y, oz, ox, oy);
}
handle(std::string(s, len), z, x, y, to_decode, pipeline, stats, state);
handle(std::string(s, len), z, x, y, to_decode, pipeline, stats, state, coordinate_mode);
handled = 1;
}
@@ -477,13 +484,13 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
if (sqlite3_close(db) != SQLITE_OK) {
fprintf(stderr, "%s: could not close database: %s\n", fname, sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
void usage(char **argv) {
fprintf(stderr, "Usage: %s [-s projection] [-Z minzoom] [-z maxzoom] [-l layer ...] file.mbtiles [zoom x y]\n", argv[0]);
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
int main(int argc, char **argv) {
@@ -494,9 +501,12 @@ int main(int argc, char **argv) {
bool pipeline = false;
bool stats = false;
std::set<std::string> exclude_meta;
int coordinate_mode = 0;
struct option long_options[] = {
{"projection", required_argument, 0, 's'},
{"fractional-coordinates", no_argument, 0, 'F'},
{"integer-coordinates", no_argument, 0, 'I'},
{"maximum-zoom", required_argument, 0, 'z'},
{"minimum-zoom", required_argument, 0, 'Z'},
{"layer", required_argument, 0, 'l'},
@@ -527,6 +537,14 @@ int main(int argc, char **argv) {
set_projection_or_exit(optarg);
break;
case 'F':
coordinate_mode = 1;
break;
case 'I':
coordinate_mode = 2;
break;
case 'z':
maxzoom = atoi(optarg);
break;
@@ -561,9 +579,9 @@ int main(int argc, char **argv) {
}
if (argc == optind + 4) {
decode(argv[optind], atoi(argv[optind + 1]), atoi(argv[optind + 2]), atoi(argv[optind + 3]), to_decode, pipeline, stats, exclude_meta);
decode(argv[optind], atoi(argv[optind + 1]), atoi(argv[optind + 2]), atoi(argv[optind + 3]), to_decode, pipeline, stats, exclude_meta, coordinate_mode);
} else if (argc == optind + 1) {
decode(argv[optind], -1, -1, -1, to_decode, pipeline, stats, exclude_meta);
decode(argv[optind], -1, -1, -1, to_decode, pipeline, stats, exclude_meta, coordinate_mode);
} else {
usage(argv);
}
+11 -10
View File
@@ -12,6 +12,7 @@
#include <sqlite3.h>
#include "jsonpull/jsonpull.h"
#include "dirtiles.hpp"
#include "errors.hpp"
std::string dir_read_tile(std::string base, struct zxy tile) {
std::ifstream pbfFile(base + "/" + tile.path(), std::ios::in | std::ios::binary);
@@ -35,7 +36,7 @@ void dir_write_tile(const char *outdir, int z, int tx, int ty, std::string const
struct stat st;
if (stat(newdir.c_str(), &st) == 0) {
fprintf(stderr, "Can't write tile to already existing %s\n", newdir.c_str());
exit(EXIT_FAILURE);
exit(EXIT_EXISTS);
}
std::ofstream pbfFile(newdir, std::ios::out | std::ios::binary);
@@ -75,7 +76,7 @@ void check_dir(const char *dir, char **argv, bool force, bool forcetable) {
fprintf(stderr, "%s: Tileset \"%s\" already exists. You can use --force if you want to delete the old tileset.\n", argv[0], dir);
fprintf(stderr, "%s: %s: file exists\n", argv[0], meta.c_str());
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_EXISTS);
}
}
}
@@ -93,11 +94,11 @@ void check_dir(const char *dir, char **argv, bool force, bool forcetable) {
if (force) {
if (unlink(fn.c_str()) != 0) {
perror(fn.c_str());
exit(EXIT_FAILURE);
exit(EXIT_UNLINK);
}
} else {
fprintf(stderr, "%s: file exists\n", fn.c_str());
exit(EXIT_FAILURE);
exit(EXIT_EXISTS);
}
}
}
@@ -116,7 +117,7 @@ std::vector<zxy> enumerate_dirtiles(const char *fname, int minzoom, int maxzoom)
DIR *d2 = opendir(z.c_str());
if (d2 == NULL) {
perror(z.c_str());
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
struct dirent *dp2;
@@ -128,7 +129,7 @@ std::vector<zxy> enumerate_dirtiles(const char *fname, int minzoom, int maxzoom)
DIR *d3 = opendir(x.c_str());
if (d3 == NULL) {
perror(x.c_str());
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
struct dirent *dp3;
@@ -165,11 +166,11 @@ sqlite3 *dirmeta2tmp(const char *fname) {
if (sqlite3_open("", &db) != SQLITE_OK) {
fprintf(stderr, "Temporary db: %s\n", sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
if (sqlite3_exec(db, "CREATE TABLE metadata (name text, value text);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "Create metadata table: %s\n", err);
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
std::string name = fname;
@@ -183,12 +184,12 @@ sqlite3 *dirmeta2tmp(const char *fname) {
json_object *o = json_read_tree(jp);
if (o == NULL) {
fprintf(stderr, "%s: metadata parsing error: %s\n", name.c_str(), jp->error);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
if (o->type != JSON_HASH) {
fprintf(stderr, "%s: bad metadata format\n", name.c_str());
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
for (size_t i = 0; i < o->value.object.length; i++) {
+7 -6
View File
@@ -2,19 +2,20 @@
#include <stdlib.h>
#include <unistd.h>
#include <sqlite3.h>
#include "errors.hpp"
void enumerate(char *fname) {
sqlite3 *db;
if (sqlite3_open(fname, &db) != SQLITE_OK) {
fprintf(stderr, "%s: %s\n", fname, sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
char *err = NULL;
if (sqlite3_exec(db, "PRAGMA integrity_check;", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: integrity_check: %s\n", fname, err);
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
const char *sql = "SELECT zoom_level, tile_column, tile_row from tiles order by zoom_level, tile_column, tile_row;";
@@ -22,7 +23,7 @@ void enumerate(char *fname) {
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
while (sqlite3_step(stmt) == SQLITE_ROW) {
@@ -32,7 +33,7 @@ void enumerate(char *fname) {
if (zoom < 0 || zoom > 31) {
fprintf(stderr, "Corrupt mbtiles file: impossible zoom level %lld\n", zoom);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
y = (1LL << zoom) - 1 - y;
@@ -43,13 +44,13 @@ void enumerate(char *fname) {
if (sqlite3_close(db) != SQLITE_OK) {
fprintf(stderr, "%s: could not close database: %s\n", fname, sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
void usage(char **argv) {
fprintf(stderr, "Usage: %s file.mbtiles ...\n", argv[0]);
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
int main(int argc, char **argv) {
+21
View File
@@ -0,0 +1,21 @@
#define EXIT_INCOMPLETE 100
#define EXIT_ARGS 101
#define EXIT_CLOSE 102
#define EXIT_CSV 103
#define EXIT_EXISTS 104
#define EXIT_FILTER 105
#define EXIT_IMPOSSIBLE 106
#define EXIT_JSON 107
#define EXIT_MEMORY 108
#define EXIT_MVT 109
#define EXIT_NODATA 110
#define EXIT_OPEN 111
#define EXIT_PROTOBUF 112
#define EXIT_PTHREAD 113
#define EXIT_READ 114
#define EXIT_SEEK 115
#define EXIT_SQLITE 116
#define EXIT_STAT 117
#define EXIT_UNLINK 118
#define EXIT_UTF8 119
#define EXIT_WRITE 120
+23 -22
View File
@@ -4,6 +4,7 @@
#include <map>
#include "mvt.hpp"
#include "evaluator.hpp"
#include "errors.hpp"
int compare(mvt_value one, json_object *two, bool &fail) {
if (one.type == mvt_string) {
@@ -34,7 +35,7 @@ int compare(mvt_value one, json_object *two, bool &fail) {
v = one.numeric_value.sint_value;
} else {
fprintf(stderr, "Internal error: bad mvt type %d\n", one.type);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
if (v < two->value.number.number) {
@@ -66,36 +67,36 @@ int compare(mvt_value one, json_object *two, bool &fail) {
}
fprintf(stderr, "Internal error: bad mvt type %d\n", one.type);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
bool eval(std::map<std::string, mvt_value> const &feature, json_object *f, std::set<std::string> &exclude_attributes) {
if (f == NULL || f->type != JSON_ARRAY) {
fprintf(stderr, "Filter is not an array: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_FILTER);
}
if (f->value.array.length < 1) {
fprintf(stderr, "Array too small in filter: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_FILTER);
}
if (f->value.array.array[0]->type != JSON_STRING) {
fprintf(stderr, "Filter operation is not a string: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_FILTER);
}
if (strcmp(f->value.array.array[0]->value.string.string, "has") == 0 ||
strcmp(f->value.array.array[0]->value.string.string, "!has") == 0) {
if (f->value.array.length != 2) {
fprintf(stderr, "Wrong number of array elements in filter: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_FILTER);
}
if (strcmp(f->value.array.array[0]->value.string.string, "has") == 0) {
if (f->value.array.array[1]->type != JSON_STRING) {
fprintf(stderr, "\"has\" key is not a string: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_FILTER);
}
return feature.count(std::string(f->value.array.array[1]->value.string.string)) != 0;
}
@@ -103,7 +104,7 @@ bool eval(std::map<std::string, mvt_value> const &feature, json_object *f, std::
if (strcmp(f->value.array.array[0]->value.string.string, "!has") == 0) {
if (f->value.array.array[1]->type != JSON_STRING) {
fprintf(stderr, "\"!has\" key is not a string: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_FILTER);
}
return feature.count(std::string(f->value.array.array[1]->value.string.string)) == 0;
}
@@ -117,11 +118,11 @@ bool eval(std::map<std::string, mvt_value> const &feature, json_object *f, std::
strcmp(f->value.array.array[0]->value.string.string, "<=") == 0) {
if (f->value.array.length != 3) {
fprintf(stderr, "Wrong number of array elements in filter: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_FILTER);
}
if (f->value.array.array[1]->type != JSON_STRING) {
fprintf(stderr, "\"!has\" key is not a string: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
fprintf(stderr, "comparison key is not a string: %s\n", json_stringify(f));
exit(EXIT_FILTER);
}
auto ff = feature.find(std::string(f->value.array.array[1]->value.string.string));
@@ -176,7 +177,7 @@ bool eval(std::map<std::string, mvt_value> const &feature, json_object *f, std::
}
fprintf(stderr, "Internal error: can't happen: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
if (strcmp(f->value.array.array[0]->value.string.string, "all") == 0 ||
@@ -217,12 +218,12 @@ bool eval(std::map<std::string, mvt_value> const &feature, json_object *f, std::
strcmp(f->value.array.array[0]->value.string.string, "!in") == 0) {
if (f->value.array.length < 2) {
fprintf(stderr, "Array too small in filter: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_FILTER);
}
if (f->value.array.array[1]->type != JSON_STRING) {
fprintf(stderr, "\"!has\" key is not a string: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
fprintf(stderr, "\"!in\" key is not a string: %s\n", json_stringify(f));
exit(EXIT_FILTER);
}
auto ff = feature.find(std::string(f->value.array.array[1]->value.string.string));
@@ -272,12 +273,12 @@ bool eval(std::map<std::string, mvt_value> const &feature, json_object *f, std::
if (strcmp(f->value.array.array[0]->value.string.string, "attribute-filter") == 0) {
if (f->value.array.length != 3) {
fprintf(stderr, "Wrong number of array elements in filter: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_FILTER);
}
if (f->value.array.array[1]->type != JSON_STRING) {
fprintf(stderr, "\"attribute-filter\" key is not a string: %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_FILTER);
}
bool ok = eval(feature, f->value.array.array[2], exclude_attributes);
@@ -289,13 +290,13 @@ bool eval(std::map<std::string, mvt_value> const &feature, json_object *f, std::
}
fprintf(stderr, "Unknown filter %s\n", json_stringify(f));
exit(EXIT_FAILURE);
exit(EXIT_FILTER);
}
bool evaluate(std::map<std::string, mvt_value> const &feature, std::string const &layer, json_object *filter, std::set<std::string> &exclude_attributes) {
if (filter == NULL || filter->type != JSON_HASH) {
fprintf(stderr, "Error: filter is not a hash: %s\n", json_stringify(filter));
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
bool ok = true;
@@ -318,14 +319,14 @@ json_object *read_filter(const char *fname) {
FILE *fp = fopen(fname, "r");
if (fp == NULL) {
perror(fname);
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
json_pull *jp = json_begin_file(fp);
json_object *filter = json_read_tree(jp);
if (filter == NULL) {
fprintf(stderr, "%s: %s\n", fname, jp->error);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_disconnect(filter);
json_end(jp);
@@ -339,7 +340,7 @@ json_object *parse_filter(const char *s) {
if (filter == NULL) {
fprintf(stderr, "Could not parse filter %s\n", s);
fprintf(stderr, "%s\n", jp->error);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_disconnect(filter);
json_end(jp);
+8 -7
View File
@@ -6,6 +6,7 @@
#include "flatgeobuf/header_generated.h"
#include "milo/dtoa_milo.h"
#include "main.hpp"
#include "errors.hpp"
static constexpr uint8_t magicbytes[8] = { 0x66, 0x67, 0x62, 0x03, 0x66, 0x67, 0x62, 0x01 };
@@ -95,7 +96,7 @@ drawvec readGeometry(const FlatGeobuf::Geometry *geometry, FlatGeobuf::GeometryT
return dv;
} else {
fprintf(stderr, "flatgeobuf has unsupported geometry type %u\n", (unsigned int)h_geometry_type);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
}
@@ -124,7 +125,7 @@ void readFeature(const FlatGeobuf::Feature *feature, long long feature_sequence_
case FlatGeobuf::GeometryType::GeometryCollection :
default:
fprintf(stderr, "flatgeobuf has unsupported geometry type %u\n", (unsigned int)h_geometry_type);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
serial_feature sf;
@@ -236,7 +237,7 @@ void readFeature(const FlatGeobuf::Feature *feature, long long feature_sequence_
} else {
// Binary is not representable in MVT
fprintf(stderr, "flatgeobuf has unsupported column type %u\n", (unsigned int)col_type);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
full_keys.push_back(h_column_names[col_idx]);
full_values.push_back(sv);
@@ -304,7 +305,7 @@ void fgbRunQueue() {
for (size_t i = 0; i < CPUS; i++) {
if (pthread_create(&pthreads[i], NULL, fgb_run_parse_feature, &qra[i]) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
}
@@ -347,7 +348,7 @@ void parse_flatgeobuf(std::vector<struct serialization_state> *sst, const char *
const auto ok = FlatGeobuf::VerifySizePrefixedHeaderBuffer(v);
if (!ok) {
fprintf(stderr, "flatgeobuf header verification failed\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
auto header = FlatGeobuf::GetSizePrefixedHeader(src + sizeof(magicbytes));
@@ -384,7 +385,7 @@ void parse_flatgeobuf(std::vector<struct serialization_state> *sst, const char *
const auto ok2 = FlatGeobuf::VerifySizePrefixedFeatureBuffer(v2);
if (!ok2) {
fprintf(stderr, "flatgeobuf feature buffer verification failed\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
auto feature = FlatGeobuf::GetSizePrefixedFeature(start);
@@ -396,4 +397,4 @@ void parse_flatgeobuf(std::vector<struct serialization_state> *sst, const char *
}
fgbRunQueue();
}
}
+8 -7
View File
@@ -14,6 +14,7 @@
#include "milo/dtoa_milo.h"
#include "jsonpull/jsonpull.h"
#include "text.hpp"
#include "errors.hpp"
#define POINT 0
#define MULTIPOINT 1
@@ -37,7 +38,7 @@ static std::vector<queued_feature> feature_queue;
void ensureDim(size_t dim) {
if (dim < 2) {
fprintf(stderr, "Geometry has fewer than 2 dimensions: %zu\n", dim);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
}
@@ -117,7 +118,7 @@ drawvec readLinePart(std::vector<long long> &coords, size_t dim, double e, size_
for (size_t i = start; i + dim - 1 < end; i += dim) {
if (i + dim - 1 >= coords.size()) {
fprintf(stderr, "Internal error: line segment %zu vs %zu\n", i + dim - 1, coords.size());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
for (size_t d = 0; d < dim; d++) {
@@ -328,12 +329,12 @@ void readFeature(protozero::pbf_reader &pbf, size_t dim, double e, std::vector<s
for (size_t i = 0; i + 1 < properties.size(); i += 2) {
if (properties[i] >= keys.size()) {
fprintf(stderr, "Out of bounds key: %zu in %zu\n", properties[i], keys.size());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
if (properties[i + 1] >= values.size()) {
fprintf(stderr, "Out of bounds value: %zu in %zu\n", properties[i + 1], values.size());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
full_keys.push_back(keys[properties[i]]);
@@ -354,12 +355,12 @@ void readFeature(protozero::pbf_reader &pbf, size_t dim, double e, std::vector<s
for (size_t i = 0; i + 1 < misc.size(); i += 2) {
if (misc[i] >= keys.size()) {
fprintf(stderr, "Out of bounds key: %zu in %zu\n", misc[i], keys.size());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
if (misc[i + 1] >= values.size()) {
fprintf(stderr, "Out of bounds value: %zu in %zu\n", misc[i + 1], values.size());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
other.insert(std::pair<std::string, serial_val>(keys[misc[i]], values[misc[i + 1]]));
@@ -466,7 +467,7 @@ void runQueue() {
for (size_t i = 0; i < CPUS; i++) {
if (pthread_create(&pthreads[i], NULL, run_parse_feature, &qra[i]) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
}
+7 -6
View File
@@ -9,6 +9,7 @@
#include "csv.hpp"
#include "milo/dtoa_milo.h"
#include "options.hpp"
#include "errors.hpp"
void parse_geocsv(std::vector<struct serialization_state> &sst, std::string fname, int layer, std::string layername) {
FILE *f;
@@ -19,7 +20,7 @@ void parse_geocsv(std::vector<struct serialization_state> &sst, std::string fnam
f = fopen(fname.c_str(), "r");
if (f == NULL) {
perror(fname.c_str());
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
}
@@ -31,7 +32,7 @@ void parse_geocsv(std::vector<struct serialization_state> &sst, std::string fnam
std::string err = check_utf8(s);
if (err != "") {
fprintf(stderr, "%s: %s\n", fname.c_str(), err.c_str());
exit(EXIT_FAILURE);
exit(EXIT_UTF8);
}
header = csv_split(s.c_str());
@@ -53,7 +54,7 @@ void parse_geocsv(std::vector<struct serialization_state> &sst, std::string fnam
if (latcol < 0 || loncol < 0) {
fprintf(stderr, "%s: Can't find \"lat\" and \"lon\" columns\n", fname.c_str());
exit(EXIT_FAILURE);
exit(EXIT_CSV);
}
size_t seq = 0;
@@ -61,7 +62,7 @@ void parse_geocsv(std::vector<struct serialization_state> &sst, std::string fnam
std::string err = check_utf8(s);
if (err != "") {
fprintf(stderr, "%s: %s\n", fname.c_str(), err.c_str());
exit(EXIT_FAILURE);
exit(EXIT_UTF8);
}
seq++;
@@ -69,7 +70,7 @@ void parse_geocsv(std::vector<struct serialization_state> &sst, std::string fnam
if (line.size() != header.size()) {
fprintf(stderr, "%s:%zu: Mismatched column count: %zu in line, %zu in header\n", fname.c_str(), seq + 1, line.size(), header.size());
exit(EXIT_FAILURE);
exit(EXIT_CSV);
}
if (line[loncol].empty() || line[latcol].empty()) {
@@ -133,7 +134,7 @@ void parse_geocsv(std::vector<struct serialization_state> &sst, std::string fnam
if (fname.size() != 0) {
if (fclose(f) != 0) {
perror("fclose");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
}
+2 -1
View File
@@ -39,6 +39,7 @@
#include "mvt.hpp"
#include "geojson-loop.hpp"
#include "milo/dtoa_milo.h"
#include "errors.hpp"
int serialize_geojson_feature(struct serialization_state *sst, json_object *geometry, json_object *properties, json_object *id, int layer, json_object *tippecanoe, json_object *feature, std::string layername) {
json_object *geometry_type = json_hash_get(geometry, "type");
@@ -332,7 +333,7 @@ struct json_pull *json_begin_map(char *map, long long len) {
struct jsonmap *jm = new jsonmap;
if (jm == NULL) {
perror("Out of memory");
exit(EXIT_FAILURE);
exit(EXIT_MEMORY);
}
jm->map = map;
+7 -6
View File
@@ -20,6 +20,7 @@
#include "serial.hpp"
#include "main.hpp"
#include "options.hpp"
#include "errors.hpp"
static int pnpoly(drawvec &vert, size_t start, size_t nvert, long long testx, long long testy);
static int clip(double *x0, double *y0, double *x1, double *y1, double xmin, double ymin, double xmax, double ymax);
@@ -39,7 +40,7 @@ drawvec decode_geometry(FILE *meta, std::atomic<long long> *geompos, int z, unsi
if (!deserialize_byte_io(meta, &d.op, geompos)) {
fprintf(stderr, "Internal error: Unexpected end of file in geometry\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
if (d.op == VT_END) {
break;
@@ -210,7 +211,7 @@ static void decode_clipped(mapbox::geometry::multi_polygon<long long> &t, drawve
if ((j == 0 && area < 0) || (j != 0 && area > 0)) {
fprintf(stderr, "Ring area has wrong sign: %f for %zu\n", area, j);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
for (size_t k = 0; k < ring.size(); k++) {
@@ -316,7 +317,7 @@ drawvec clean_or_clip_poly(drawvec &geom, int z, int buffer, bool clip) {
fclose(f);
fprintf(stderr, "Internal error: Polygon cleaning failed. Log in /tmp/wagyu.log\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
drawvec ret;
@@ -501,7 +502,7 @@ drawvec simple_clip_poly(drawvec &geom, long long minx, long long miny, long lon
i = j - 1;
} else {
fprintf(stderr, "Unexpected operation in polygon %d\n", (int) geom[i].op);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
}
@@ -1023,7 +1024,7 @@ drawvec fix_polygon(drawvec &geom) {
outer = 0;
} else {
fprintf(stderr, "Internal error: polygon ring begins with %d, not moveto\n", geom[i].op);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
}
@@ -1266,7 +1267,7 @@ drawvec stairstep(drawvec &geom, int z, int detail) {
// out.push_back(draw(VT_LINETO, xx, yy));
} else {
fprintf(stderr, "Can't happen: stairstepping lineto with no moveto\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
}
+18 -17
View File
@@ -12,6 +12,7 @@
#include "text.hpp"
#include "geojson-loop.hpp"
#include "milo/dtoa_milo.h"
#include "errors.hpp"
int fail = EXIT_SUCCESS;
bool wrap = false;
@@ -198,7 +199,7 @@ void out(std::string const &s, int type, json_object *properties) {
if (type != buffered_type) {
fprintf(stderr, "Error: mix of bare geometries and features\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
}
@@ -209,13 +210,13 @@ void join_csv(json_object *j) {
std::string s = csv_getline(csvfile);
if (s.size() == 0) {
fprintf(stderr, "Couldn't get column header from CSV file\n");
exit(EXIT_FAILURE);
exit(EXIT_CSV);
}
std::string err = check_utf8(s);
if (err != "") {
fprintf(stderr, "%s\n", err.c_str());
exit(EXIT_FAILURE);
exit(EXIT_UTF8);
}
header = csv_split(s.c_str());
@@ -226,7 +227,7 @@ void join_csv(json_object *j) {
if (header.size() == 0) {
fprintf(stderr, "No columns in CSV header \"%s\"\n", s.c_str());
exit(EXIT_FAILURE);
exit(EXIT_CSV);
}
}
@@ -259,7 +260,7 @@ void join_csv(json_object *j) {
if (joinkey < prev_joinkey) {
fprintf(stderr, "GeoJSON file is out of sort: \"%s\" follows \"%s\"\n", joinkey.c_str(), prev_joinkey.c_str());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
prev_joinkey = joinkey;
@@ -279,7 +280,7 @@ void join_csv(json_object *j) {
std::string err = check_utf8(s);
if (err != "") {
fprintf(stderr, "%s\n", err.c_str());
exit(EXIT_FAILURE);
exit(EXIT_UTF8);
}
fields = csv_split(s.c_str());
@@ -290,7 +291,7 @@ void join_csv(json_object *j) {
if (fields.size() > 0 && fields[0] < prevkey) {
fprintf(stderr, "CSV file is out of sort: \"%s\" follows \"%s\"\n", fields[0].c_str(), prevkey.c_str());
exit(EXIT_FAILURE);
exit(EXIT_CSV);
}
if (fields.size() > 0 && fields[0] >= joinkey) {
@@ -310,7 +311,7 @@ void join_csv(json_object *j) {
properties->value.object.values = (json_object **) realloc((void *) properties->value.object.values, (properties->value.object.length + 8 + fields.size()) * sizeof(json_object *));
if (properties->value.object.keys == NULL || properties->value.object.values == NULL) {
perror("realloc");
exit(EXIT_FAILURE);
exit(EXIT_MEMORY);
}
for (size_t i = 1; i < fields.size(); i++) {
@@ -335,7 +336,7 @@ void join_csv(json_object *j) {
json_object *vo = (json_object *) malloc(sizeof(json_object));
if (ko == NULL || vo == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
exit(EXIT_MEMORY);
}
ko->type = JSON_STRING;
@@ -345,7 +346,7 @@ void join_csv(json_object *j) {
ko->value.string.string = strdup(k.c_str());
if (ko->value.string.string == NULL) {
perror("strdup");
exit(EXIT_FAILURE);
exit(EXIT_MEMORY);
}
vo->type = attr_type;
@@ -356,7 +357,7 @@ void join_csv(json_object *j) {
vo->value.string.string = strdup(v.c_str());
if (vo->value.string.string == NULL) {
perror("strdup");
exit(EXIT_FAILURE);
exit(EXIT_MEMORY);
}
} else if (attr_type == JSON_NUMBER) {
vo->value.number.number = atof(v.c_str());
@@ -455,26 +456,26 @@ int main(int argc, char **argv) {
pe = true;
} else {
fprintf(stderr, "%s: Unknown option for -p%s\n", argv[0], optarg);
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
break;
default:
fprintf(stderr, "Unexpected option -%c\n", i);
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
}
if (extract != NULL && wrap) {
fprintf(stderr, "%s: --wrap and --extract not supported together\n", argv[0]);
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
if (csv != NULL) {
csvfile = fopen(csv, "r");
if (csvfile == NULL) {
perror(csv);
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
}
@@ -485,7 +486,7 @@ int main(int argc, char **argv) {
FILE *f = fopen(argv[i], "r");
if (f == NULL) {
perror(argv[i]);
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
process(f, argv[i]);
@@ -502,7 +503,7 @@ int main(int argc, char **argv) {
if (csvfile != NULL) {
if (fclose(csvfile) != 0) {
perror("close");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
+156 -155
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -1110,6 +1110,10 @@ resolutions.
\fB\fC\-S\fR or \fB\fC\-\-stats\fR: Just report statistics about each tile's size and the number of features in it, as a JSON structure.
.IP \(bu 2
\fB\fC\-f\fR or \fB\fC\-\-force\fR: Decode tiles even if polygon ring order or closure problems are detected
.IP \(bu 2
\fB\fC\-I\fR or \fB\fC\-\-integer\fR: Report coordinates in integer tile coordinates
.IP \(bu 2
\fB\fC\-F\fR or \fB\fC\-\-fraction\fR: Report coordinates as a fraction of the tile extent
.RE
.SH tippecanoe\-json\-tool
.PP
+33 -32
View File
@@ -18,6 +18,7 @@
#include "milo/dtoa_milo.h"
#include "write_json.hpp"
#include "version.hpp"
#include "errors.hpp"
size_t max_tilestats_attributes = 1000;
size_t max_tilestats_sample_values = 1000;
@@ -28,45 +29,45 @@ sqlite3 *mbtiles_open(char *dbname, char **argv, int forcetable) {
if (sqlite3_open(dbname, &outdb) != SQLITE_OK) {
fprintf(stderr, "%s: %s: %s\n", argv[0], dbname, sqlite3_errmsg(outdb));
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
char *err = NULL;
if (sqlite3_exec(outdb, "PRAGMA synchronous=0", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: async: %s\n", argv[0], err);
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
if (sqlite3_exec(outdb, "PRAGMA locking_mode=EXCLUSIVE", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: async: %s\n", argv[0], err);
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
if (sqlite3_exec(outdb, "PRAGMA journal_mode=DELETE", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: async: %s\n", argv[0], err);
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
if (sqlite3_exec(outdb, "CREATE TABLE metadata (name text, value text);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: Tileset \"%s\" already exists. You can use --force if you want to delete the old tileset.\n", argv[0], dbname);
fprintf(stderr, "%s: %s\n", argv[0], err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_EXISTS);
}
}
if (sqlite3_exec(outdb, "CREATE TABLE tiles (zoom_level integer, tile_column integer, tile_row integer, tile_data blob);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: create tiles table: %s\n", argv[0], err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_EXISTS);
}
}
if (sqlite3_exec(outdb, "create unique index name on metadata (name);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: index metadata: %s\n", argv[0], err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_EXISTS);
}
}
if (sqlite3_exec(outdb, "create unique index tile_index on tiles (zoom_level, tile_column, tile_row);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: index tiles: %s\n", argv[0], err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_EXISTS);
}
}
@@ -78,7 +79,7 @@ void mbtiles_write_tile(sqlite3 *outdb, int z, int tx, int ty, const char *data,
const char *query = "insert into tiles (zoom_level, tile_column, tile_row, tile_data) values (?, ?, ?, ?)";
if (sqlite3_prepare_v2(outdb, query, -1, &stmt, NULL) != SQLITE_OK) {
fprintf(stderr, "sqlite3 insert prep failed\n");
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
sqlite3_bind_int(stmt, 1, z);
@@ -336,11 +337,11 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (outdb == NULL) {
if (sqlite3_open("", &db) != SQLITE_OK) {
fprintf(stderr, "Temporary db: %s\n", sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
if (sqlite3_exec(db, "CREATE TABLE metadata (name text, value text);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "Create metadata table: %s\n", err);
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
@@ -348,7 +349,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set name in metadata: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -357,7 +358,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set description in metadata: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -366,7 +367,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set version : %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -375,7 +376,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set minzoom: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -384,7 +385,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set maxzoom: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -393,7 +394,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set center: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -402,7 +403,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set bounds: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -411,7 +412,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set type: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -421,7 +422,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set type: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -431,7 +432,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set format: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -441,7 +442,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set version: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -450,7 +451,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set commandline: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -461,7 +462,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set strategies: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -561,7 +562,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set json: %s\n", err);
if (!forcetable) {
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
}
sqlite3_free(sql);
@@ -577,7 +578,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
FILE *fp = fopen(metadata.c_str(), "w");
if (fp == NULL) {
perror(metadata.c_str());
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
json_writer state(fp);
@@ -594,7 +595,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
const char *v = (const char *) sqlite3_column_text(stmt, 1);
if (k == NULL || v == NULL) {
fprintf(stderr, "Corrupt mbtiles file: null metadata\n");
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
state.json_comma_newline();
@@ -614,7 +615,7 @@ void mbtiles_write_metadata(sqlite3 *outdb, const char *outdir, const char *fnam
if (outdb == NULL) {
if (sqlite3_close(db) != SQLITE_OK) {
fprintf(stderr, "Could not close temp database: %s\n", sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
}
@@ -624,11 +625,11 @@ void mbtiles_close(sqlite3 *outdb, const char *pgm) {
if (sqlite3_exec(outdb, "ANALYZE;", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: ANALYZE failed: %s\n", pgm, err);
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
if (sqlite3_close(outdb) != SQLITE_OK) {
fprintf(stderr, "%s: could not close database: %s\n", pgm, sqlite3_errmsg(outdb));
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
@@ -661,7 +662,7 @@ std::map<std::string, layermap_entry> merge_layermaps(std::vector<std::map<std::
auto out_entry = out.find(layername);
if (out_entry == out.end()) {
fprintf(stderr, "Internal error merging layers\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
for (auto fk = map->second.file_keys.begin(); fk != map->second.file_keys.end(); ++fk) {
@@ -726,7 +727,7 @@ void add_to_file_keys(std::map<std::string, type_and_string_stats> &file_keys, s
if (fka == file_keys.end()) {
fprintf(stderr, "Can't happen (tilestats)\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
if (val.type == mvt_double) {
+6 -5
View File
@@ -13,6 +13,7 @@
#include "protozero/pbf_reader.hpp"
#include "protozero/pbf_writer.hpp"
#include "milo/dtoa_milo.h"
#include "errors.hpp"
mvt_geometry::mvt_geometry(int nop, long long nx, long long ny) {
this->op = nop;
@@ -115,7 +116,7 @@ bool mvt_tile::decode(std::string &message, bool &was_compressed) {
if (is_compressed(message)) {
std::string uncompressed;
if (decompress(message, uncompressed) == 0) {
exit(EXIT_FAILURE);
exit(EXIT_MVT);
}
src = uncompressed;
was_compressed = true;
@@ -349,10 +350,10 @@ std::string mvt_tile::encode() {
value_writer.add_bool(7, pbv.numeric_value.bool_value);
} else if (pbv.type == mvt_null) {
fprintf(stderr, "Internal error: trying to write null attribute to tile\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
} else {
fprintf(stderr, "Internal error: trying to write undefined attribute type to tile\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
sorted_value sv;
@@ -418,7 +419,7 @@ std::string mvt_tile::encode() {
if (dx < INT_MIN || dx > INT_MAX || dy < INT_MIN || dy > INT_MAX) {
fprintf(stderr, "Internal error: Geometry delta is too big: %lld,%lld\n", dx, dy);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
geometry.push_back(protozero::encode_zigzag32(dx));
@@ -431,7 +432,7 @@ std::string mvt_tile::encode() {
length++;
} else {
fprintf(stderr, "\nInternal error: corrupted geometry\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
}
+41 -40
View File
@@ -24,6 +24,7 @@
#include "projection.hpp"
#include "geometry.hpp"
#include "serial.hpp"
#include "errors.hpp"
extern "C" {
#include "jsonpull/jsonpull.h"
@@ -48,12 +49,12 @@ void *run_writer(void *a) {
FILE *fp = fdopen(wa->write_to, "w");
if (fp == NULL) {
perror("fdopen (pipe writer)");
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
json_writer state(fp);
for (size_t i = 0; i < wa->layers->size(); i++) {
layer_to_geojson((*(wa->layers))[i], wa->z, wa->x, wa->y, false, true, false, true, 0, 0, 0, true, state);
layer_to_geojson((*(wa->layers))[i], wa->z, wa->x, wa->y, false, true, false, true, 0, 0, 0, true, state, 0);
}
if (fclose(fp) != 0) {
@@ -65,7 +66,7 @@ void *run_writer(void *a) {
}
} else {
perror("fclose output to filter");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
@@ -90,7 +91,7 @@ std::vector<mvt_layer> parse_layers(int fd, int z, unsigned x, unsigned y, std::
FILE *f = fdopen(fd, "r");
if (f == NULL) {
perror("fdopen filter output");
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
json_pull *jp = json_begin_file(f);
@@ -102,7 +103,7 @@ std::vector<mvt_layer> parse_layers(int fd, int z, unsigned x, unsigned y, std::
if (jp->root != NULL) {
json_context(jp->root);
}
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_free(jp->root);
@@ -122,7 +123,7 @@ std::vector<mvt_layer> parse_layers(int fd, int z, unsigned x, unsigned y, std::
fprintf(stderr, "Filter output:%d: filtered feature with no geometry\n", jp->line);
json_context(j);
json_free(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_object *properties = json_hash_get(j, "properties");
@@ -130,27 +131,27 @@ std::vector<mvt_layer> parse_layers(int fd, int z, unsigned x, unsigned y, std::
fprintf(stderr, "Filter output:%d: feature without properties hash\n", jp->line);
json_context(j);
json_free(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_object *geometry_type = json_hash_get(geometry, "type");
if (geometry_type == NULL) {
fprintf(stderr, "Filter output:%d: null geometry (additional not reported)\n", jp->line);
json_context(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
if (geometry_type->type != JSON_STRING) {
fprintf(stderr, "Filter output:%d: geometry type is not a string\n", jp->line);
json_context(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_object *coordinates = json_hash_get(geometry, "coordinates");
if (coordinates == NULL || coordinates->type != JSON_ARRAY) {
fprintf(stderr, "Filter output:%d: feature without coordinates array\n", jp->line);
json_context(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
int t;
@@ -162,7 +163,7 @@ std::vector<mvt_layer> parse_layers(int fd, int z, unsigned x, unsigned y, std::
if (t >= GEOM_TYPES) {
fprintf(stderr, "Filter output:%d: Can't handle geometry type %s\n", jp->line, geometry_type->value.string.string);
json_context(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
std::string layername = "unknown";
@@ -240,7 +241,7 @@ std::vector<mvt_layer> parse_layers(int fd, int z, unsigned x, unsigned y, std::
auto fk = layermap.find(layername);
if (fk == layermap.end()) {
fprintf(stderr, "Internal error: layer %s not found\n", layername.c_str());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
if (z < fk->second.minzoom) {
fk->second.minzoom = z;
@@ -287,7 +288,7 @@ std::vector<mvt_layer> parse_layers(int fd, int z, unsigned x, unsigned y, std::
json_end(jp);
if (fclose(f) != 0) {
perror("fclose postfilter output");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
std::vector<mvt_layer> final;
@@ -309,7 +310,7 @@ serial_feature parse_feature(json_pull *jp, int z, unsigned x, unsigned y, std::
if (jp->root != NULL) {
json_context(jp->root);
}
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_free(jp->root);
@@ -330,7 +331,7 @@ serial_feature parse_feature(json_pull *jp, int z, unsigned x, unsigned y, std::
fprintf(stderr, "Filter output:%d: filtered feature with no geometry\n", jp->line);
json_context(j);
json_free(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_object *properties = json_hash_get(j, "properties");
@@ -338,27 +339,27 @@ serial_feature parse_feature(json_pull *jp, int z, unsigned x, unsigned y, std::
fprintf(stderr, "Filter output:%d: feature without properties hash\n", jp->line);
json_context(j);
json_free(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_object *geometry_type = json_hash_get(geometry, "type");
if (geometry_type == NULL) {
fprintf(stderr, "Filter output:%d: null geometry (additional not reported)\n", jp->line);
json_context(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
if (geometry_type->type != JSON_STRING) {
fprintf(stderr, "Filter output:%d: geometry type is not a string\n", jp->line);
json_context(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_object *coordinates = json_hash_get(geometry, "coordinates");
if (coordinates == NULL || coordinates->type != JSON_ARRAY) {
fprintf(stderr, "Filter output:%d: feature without coordinates array\n", jp->line);
json_context(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
int t;
@@ -370,7 +371,7 @@ serial_feature parse_feature(json_pull *jp, int z, unsigned x, unsigned y, std::
if (t >= GEOM_TYPES) {
fprintf(stderr, "Filter output:%d: Can't handle geometry type %s\n", jp->line, geometry_type->value.string.string);
json_context(j);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
drawvec dv;
@@ -476,7 +477,7 @@ serial_feature parse_feature(json_pull *jp, int z, unsigned x, unsigned y, std::
auto fk = layermap.find(layername);
if (fk == layermap.end()) {
fprintf(stderr, "Internal error: layer %s not found\n", layername.c_str());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
sf.layer = fk->second.id;
@@ -539,17 +540,17 @@ void setup_filter(const char *filter, int *write_to, int *read_from, pid_t *pid,
if (pthread_mutex_lock(&pipe_lock) != 0) {
perror("pthread_mutex_lock (pipe)");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
int pipe_orig[2], pipe_filtered[2];
if (pipe(pipe_orig) < 0) {
perror("pipe (original features)");
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
if (pipe(pipe_filtered) < 0) {
perror("pipe (filtered features)");
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
std::string z_str = std::to_string(z);
@@ -559,64 +560,64 @@ void setup_filter(const char *filter, int *write_to, int *read_from, pid_t *pid,
*pid = fork();
if (*pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
} else if (*pid == 0) {
// child
if (dup2(pipe_orig[0], 0) < 0) {
perror("dup child stdin");
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
if (dup2(pipe_filtered[1], 1) < 0) {
perror("dup child stdout");
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
if (close(pipe_orig[1]) != 0) {
perror("close output to filter");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
if (close(pipe_filtered[0]) != 0) {
perror("close input from filter");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
if (close(pipe_orig[0]) != 0) {
perror("close dup input of filter");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
if (close(pipe_filtered[1]) != 0) {
perror("close dup output of filter");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
// XXX close other fds?
if (execlp("sh", "sh", "-c", filter, "sh", z_str.c_str(), x_str.c_str(), y_str.c_str(), NULL) != 0) {
perror("exec");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
} else {
// parent
if (close(pipe_orig[0]) != 0) {
perror("close filter-side reader");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
if (close(pipe_filtered[1]) != 0) {
perror("close filter-side writer");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
if (fcntl(pipe_orig[1], F_SETFD, FD_CLOEXEC) != 0) {
perror("cloxec output to filter");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
if (fcntl(pipe_filtered[0], F_SETFD, FD_CLOEXEC) != 0) {
perror("cloxec input from filter");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
if (pthread_mutex_unlock(&pipe_lock) != 0) {
perror("pthread_mutex_unlock (pipe_lock)");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
*write_to = pipe_orig[1];
@@ -640,7 +641,7 @@ std::vector<mvt_layer> filter_layers(const char *filter, std::vector<mvt_layer>
pthread_t writer;
if (pthread_create(&writer, NULL, run_writer, &wa) != 0) {
perror("pthread_create (filter writer)");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
std::vector<mvt_layer> nlayers = parse_layers(read_from, z, x, y, layermaps, tiling_seg, layer_unmaps, extent);
@@ -649,7 +650,7 @@ std::vector<mvt_layer> filter_layers(const char *filter, std::vector<mvt_layer>
int stat_loc;
if (waitpid(pid, &stat_loc, 0) < 0) {
perror("waitpid for filter\n");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
if (WIFEXITED(stat_loc) || WIFSIGNALED(stat_loc)) {
break;
@@ -659,7 +660,7 @@ std::vector<mvt_layer> filter_layers(const char *filter, std::vector<mvt_layer>
void *ret;
if (pthread_join(writer, &ret) != 0) {
perror("pthread_join filter writer");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
return nlayers;
+6 -5
View File
@@ -5,6 +5,7 @@
#include <math.h>
#include "memfile.hpp"
#include "pool.hpp"
#include "errors.hpp"
int swizzlecmp(const char *a, const char *b) {
ssize_t alen = strlen(a);
@@ -63,11 +64,11 @@ long long addpool(struct memfile *poolfile, struct memfile *treefile, const char
long long off = poolfile->off;
if (memfile_write(poolfile, &type, 1) < 0) {
perror("memfile write");
exit(EXIT_FAILURE);
exit(EXIT_WRITE);
}
if (memfile_write(poolfile, (void *) s, strlen(s) + 1) < 0) {
perror("memfile write");
exit(EXIT_FAILURE);
exit(EXIT_WRITE);
}
return off;
}
@@ -84,11 +85,11 @@ long long addpool(struct memfile *poolfile, struct memfile *treefile, const char
long long off = poolfile->off;
if (memfile_write(poolfile, &type, 1) < 0) {
perror("memfile write");
exit(EXIT_FAILURE);
exit(EXIT_WRITE);
}
if (memfile_write(poolfile, (void *) s, strlen(s) + 1) < 0) {
perror("memfile write");
exit(EXIT_FAILURE);
exit(EXIT_WRITE);
}
if (off >= LONG_MAX || treefile->off >= LONG_MAX) {
@@ -109,7 +110,7 @@ long long addpool(struct memfile *poolfile, struct memfile *treefile, const char
long long p = treefile->off;
if (memfile_write(treefile, &tsp, sizeof(struct stringpool)) < 0) {
perror("memfile write");
exit(EXIT_FAILURE);
exit(EXIT_WRITE);
}
if (ssp == -1) {
+2 -1
View File
@@ -4,6 +4,7 @@
#include <math.h>
#include <atomic>
#include "projection.hpp"
#include "errors.hpp"
unsigned long long (*encode_index)(unsigned int wx, unsigned int wy) = NULL;
void (*decode_index)(unsigned long long index, unsigned *wx, unsigned *wy) = NULL;
@@ -212,6 +213,6 @@ void set_projection_or_exit(const char *optarg) {
}
if (p->name == NULL) {
fprintf(stderr, "Unknown projection (-s): %s\n", optarg);
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
}
+266
View File
@@ -0,0 +1,266 @@
#ifndef PROTOZERO_BASIC_PBF_BUILDER_HPP
#define PROTOZERO_BASIC_PBF_BUILDER_HPP
/*****************************************************************************
protozero - Minimalistic protocol buffer decoder and encoder in C++.
This file is from https://github.com/mapbox/protozero where you can find more
documentation.
*****************************************************************************/
/**
* @file basic_pbf_builder.hpp
*
* @brief Contains the basic_pbf_builder template class.
*/
#include "basic_pbf_writer.hpp"
#include "types.hpp"
#include <type_traits>
namespace protozero {
/**
* The basic_pbf_builder is used to write PBF formatted messages into a buffer.
* It is based on the basic_pbf_writer class and has all the same methods. The
* difference is that while the pbf_writer class takes an integer tag,
* this template class takes a tag of the template type T. The idea is that
* T will be an enumeration value and this helps reduce the possibility of
* programming errors.
*
* Almost all methods in this class can throw an std::bad_alloc exception if
* the underlying buffer class wants to resize.
*
* Read the tutorial to understand how this class is used. In most cases you
* want to use the pbf_builder class which uses a std::string as buffer type.
*/
template <typename TBuffer, typename T>
class basic_pbf_builder : public basic_pbf_writer<TBuffer> {
static_assert(std::is_same<pbf_tag_type, typename std::underlying_type<T>::type>::value,
"T must be enum with underlying type protozero::pbf_tag_type");
public:
/// The type of messages this class will build.
using enum_type = T;
basic_pbf_builder() = default;
/**
* Create a builder using the given string as a data store. The object
* stores a reference to that string and adds all data to it. The string
* doesn't have to be empty. The pbf_message object will just append data.
*/
explicit basic_pbf_builder(TBuffer& data) noexcept :
basic_pbf_writer<TBuffer>{data} {
}
/**
* Construct a pbf_builder for a submessage from the pbf_message or
* pbf_writer of the parent message.
*
* @param parent_writer The parent pbf_message or pbf_writer
* @param tag Tag of the field that will be written
*/
template <typename P>
basic_pbf_builder(basic_pbf_writer<TBuffer>& parent_writer, P tag) noexcept :
basic_pbf_writer<TBuffer>{parent_writer, pbf_tag_type(tag)} {
}
/// @cond INTERNAL
#define PROTOZERO_WRITER_WRAP_ADD_SCALAR(name, type) \
void add_##name(T tag, type value) { \
basic_pbf_writer<TBuffer>::add_##name(pbf_tag_type(tag), value); \
}
PROTOZERO_WRITER_WRAP_ADD_SCALAR(bool, bool)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(enum, int32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(int32, int32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(sint32, int32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(uint32, uint32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(int64, int64_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(sint64, int64_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(uint64, uint64_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(fixed32, uint32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(sfixed32, int32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(fixed64, uint64_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(sfixed64, int64_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(float, float)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(double, double)
#undef PROTOZERO_WRITER_WRAP_ADD_SCALAR
/// @endcond
/**
* Add "bytes" field to data.
*
* @param tag Tag of the field
* @param value Pointer to value to be written
* @param size Number of bytes to be written
*/
void add_bytes(T tag, const char* value, std::size_t size) {
basic_pbf_writer<TBuffer>::add_bytes(pbf_tag_type(tag), value, size);
}
/**
* Add "bytes" field to data.
*
* @param tag Tag of the field
* @param value Value to be written
*/
void add_bytes(T tag, const data_view& value) {
basic_pbf_writer<TBuffer>::add_bytes(pbf_tag_type(tag), value);
}
/**
* Add "bytes" field to data.
*
* @param tag Tag of the field
* @param value Value to be written
*/
void add_bytes(T tag, const std::string& value) {
basic_pbf_writer<TBuffer>::add_bytes(pbf_tag_type(tag), value);
}
/**
* Add "bytes" field to data. Bytes from the value are written until
* a null byte is encountered. The null byte is not added.
*
* @param tag Tag of the field
* @param value Pointer to zero-delimited value to be written
*/
void add_bytes(T tag, const char* value) {
basic_pbf_writer<TBuffer>::add_bytes(pbf_tag_type(tag), value);
}
/**
* Add "bytes" field to data using vectored input. All the data in the
* 2nd and further arguments is "concatenated" with only a single copy
* into the final buffer.
*
* This will work with objects of any type supporting the data() and
* size() methods like std::string or protozero::data_view.
*
* Example:
* @code
* std::string data1 = "abc";
* std::string data2 = "xyz";
* builder.add_bytes_vectored(1, data1, data2);
* @endcode
*
* @tparam Ts List of types supporting data() and size() methods.
* @param tag Tag of the field
* @param values List of objects of types Ts with data to be appended.
*/
template <typename... Ts>
void add_bytes_vectored(T tag, Ts&&... values) {
basic_pbf_writer<TBuffer>::add_bytes_vectored(pbf_tag_type(tag), std::forward<Ts>(values)...);
}
/**
* Add "string" field to data.
*
* @param tag Tag of the field
* @param value Pointer to value to be written
* @param size Number of bytes to be written
*/
void add_string(T tag, const char* value, std::size_t size) {
basic_pbf_writer<TBuffer>::add_string(pbf_tag_type(tag), value, size);
}
/**
* Add "string" field to data.
*
* @param tag Tag of the field
* @param value Value to be written
*/
void add_string(T tag, const data_view& value) {
basic_pbf_writer<TBuffer>::add_string(pbf_tag_type(tag), value);
}
/**
* Add "string" field to data.
*
* @param tag Tag of the field
* @param value Value to be written
*/
void add_string(T tag, const std::string& value) {
basic_pbf_writer<TBuffer>::add_string(pbf_tag_type(tag), value);
}
/**
* Add "string" field to data. Bytes from the value are written until
* a null byte is encountered. The null byte is not added.
*
* @param tag Tag of the field
* @param value Pointer to value to be written
*/
void add_string(T tag, const char* value) {
basic_pbf_writer<TBuffer>::add_string(pbf_tag_type(tag), value);
}
/**
* Add "message" field to data.
*
* @param tag Tag of the field
* @param value Pointer to message to be written
* @param size Length of the message
*/
void add_message(T tag, const char* value, std::size_t size) {
basic_pbf_writer<TBuffer>::add_message(pbf_tag_type(tag), value, size);
}
/**
* Add "message" field to data.
*
* @param tag Tag of the field
* @param value Value to be written. The value must be a complete message.
*/
void add_message(T tag, const data_view& value) {
basic_pbf_writer<TBuffer>::add_message(pbf_tag_type(tag), value);
}
/**
* Add "message" field to data.
*
* @param tag Tag of the field
* @param value Value to be written. The value must be a complete message.
*/
void add_message(T tag, const std::string& value) {
basic_pbf_writer<TBuffer>::add_message(pbf_tag_type(tag), value);
}
/// @cond INTERNAL
#define PROTOZERO_WRITER_WRAP_ADD_PACKED(name) \
template <typename InputIterator> \
void add_packed_##name(T tag, InputIterator first, InputIterator last) { \
basic_pbf_writer<TBuffer>::add_packed_##name(pbf_tag_type(tag), first, last); \
}
PROTOZERO_WRITER_WRAP_ADD_PACKED(bool)
PROTOZERO_WRITER_WRAP_ADD_PACKED(enum)
PROTOZERO_WRITER_WRAP_ADD_PACKED(int32)
PROTOZERO_WRITER_WRAP_ADD_PACKED(sint32)
PROTOZERO_WRITER_WRAP_ADD_PACKED(uint32)
PROTOZERO_WRITER_WRAP_ADD_PACKED(int64)
PROTOZERO_WRITER_WRAP_ADD_PACKED(sint64)
PROTOZERO_WRITER_WRAP_ADD_PACKED(uint64)
PROTOZERO_WRITER_WRAP_ADD_PACKED(fixed32)
PROTOZERO_WRITER_WRAP_ADD_PACKED(sfixed32)
PROTOZERO_WRITER_WRAP_ADD_PACKED(fixed64)
PROTOZERO_WRITER_WRAP_ADD_PACKED(sfixed64)
PROTOZERO_WRITER_WRAP_ADD_PACKED(float)
PROTOZERO_WRITER_WRAP_ADD_PACKED(double)
#undef PROTOZERO_WRITER_WRAP_ADD_PACKED
/// @endcond
}; // class basic_pbf_builder
} // end namespace protozero
#endif // PROTOZERO_BASIC_PBF_BUILDER_HPP
File diff suppressed because it is too large Load Diff
+222
View File
@@ -0,0 +1,222 @@
#ifndef PROTOZERO_BUFFER_FIXED_HPP
#define PROTOZERO_BUFFER_FIXED_HPP
/*****************************************************************************
protozero - Minimalistic protocol buffer decoder and encoder in C++.
This file is from https://github.com/mapbox/protozero where you can find more
documentation.
*****************************************************************************/
/**
* @file buffer_fixed.hpp
*
* @brief Contains the fixed_size_buffer_adaptor class.
*/
#include "buffer_tmpl.hpp"
#include "config.hpp"
#include <algorithm>
#include <cstddef>
#include <iterator>
#include <stdexcept>
namespace protozero {
/**
* This class can be used instead of std::string if you want to create a
* vector tile in a fixed-size buffer. Any operation that needs more space
* than is available will fail with a std::length_error exception.
*/
class fixed_size_buffer_adaptor {
char* m_data;
std::size_t m_capacity;
std::size_t m_size = 0;
public:
/// @cond usual container typedefs not documented
using size_type = std::size_t;
using value_type = char;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = value_type*;
using const_pointer = const value_type*;
using iterator = pointer;
using const_iterator = const_pointer;
/// @endcond
/**
* Constructor.
*
* @param data Pointer to some memory allocated for the buffer.
* @param capacity Number of bytes available.
*/
fixed_size_buffer_adaptor(char* data, std::size_t capacity) noexcept :
m_data(data),
m_capacity(capacity) {
}
/**
* Constructor.
*
* @param container Some container class supporting the member functions
* data() and size().
*/
template <typename T>
explicit fixed_size_buffer_adaptor(T& container) :
m_data(container.data()),
m_capacity(container.size()) {
}
/// Returns a pointer to the data in the buffer.
const char* data() const noexcept {
return m_data;
}
/// Returns a pointer to the data in the buffer.
char* data() noexcept {
return m_data;
}
/// The capacity this buffer was created with.
std::size_t capacity() const noexcept {
return m_capacity;
}
/// The number of bytes used in the buffer. Always <= capacity().
std::size_t size() const noexcept {
return m_size;
}
/// Return iterator to beginning of data.
char* begin() noexcept {
return m_data;
}
/// Return iterator to beginning of data.
const char* begin() const noexcept {
return m_data;
}
/// Return iterator to beginning of data.
const char* cbegin() const noexcept {
return m_data;
}
/// Return iterator to end of data.
char* end() noexcept {
return m_data + m_size;
}
/// Return iterator to end of data.
const char* end() const noexcept {
return m_data + m_size;
}
/// Return iterator to end of data.
const char* cend() const noexcept {
return m_data + m_size;
}
/// @cond INTERNAL
// Do not rely on anything beyond this point
void append(const char* data, std::size_t count) {
if (m_size + count > m_capacity) {
throw std::length_error{"fixed size data store exhausted"};
}
std::copy_n(data, count, m_data + m_size);
m_size += count;
}
void append_zeros(std::size_t count) {
if (m_size + count > m_capacity) {
throw std::length_error{"fixed size data store exhausted"};
}
std::fill_n(m_data + m_size, count, '\0');
m_size += count;
}
void resize(std::size_t size) {
protozero_assert(size < m_size);
if (size > m_capacity) {
throw std::length_error{"fixed size data store exhausted"};
}
m_size = size;
}
void erase_range(std::size_t from, std::size_t to) {
protozero_assert(from <= m_size);
protozero_assert(to <= m_size);
protozero_assert(from < to);
std::copy(m_data + to, m_data + m_size, m_data + from);
m_size -= (to - from);
}
char* at_pos(std::size_t pos) {
protozero_assert(pos <= m_size);
return m_data + pos;
}
void push_back(char ch) {
if (m_size >= m_capacity) {
throw std::length_error{"fixed size data store exhausted"};
}
m_data[m_size++] = ch;
}
/// @endcond
}; // class fixed_size_buffer_adaptor
/// @cond INTERNAL
template <>
struct buffer_customization<fixed_size_buffer_adaptor> {
static std::size_t size(const fixed_size_buffer_adaptor* buffer) noexcept {
return buffer->size();
}
static void append(fixed_size_buffer_adaptor* buffer, const char* data, std::size_t count) {
buffer->append(data, count);
}
static void append_zeros(fixed_size_buffer_adaptor* buffer, std::size_t count) {
buffer->append_zeros(count);
}
static void resize(fixed_size_buffer_adaptor* buffer, std::size_t size) {
buffer->resize(size);
}
static void reserve_additional(fixed_size_buffer_adaptor* /*buffer*/, std::size_t /*size*/) {
/* nothing to be done for fixed-size buffers */
}
static void erase_range(fixed_size_buffer_adaptor* buffer, std::size_t from, std::size_t to) {
buffer->erase_range(from, to);
}
static char* at_pos(fixed_size_buffer_adaptor* buffer, std::size_t pos) {
return buffer->at_pos(pos);
}
static void push_back(fixed_size_buffer_adaptor* buffer, char ch) {
buffer->push_back(ch);
}
};
/// @endcond
} // namespace protozero
#endif // PROTOZERO_BUFFER_FIXED_HPP
+78
View File
@@ -0,0 +1,78 @@
#ifndef PROTOZERO_BUFFER_STRING_HPP
#define PROTOZERO_BUFFER_STRING_HPP
/*****************************************************************************
protozero - Minimalistic protocol buffer decoder and encoder in C++.
This file is from https://github.com/mapbox/protozero where you can find more
documentation.
*****************************************************************************/
/**
* @file buffer_string.hpp
*
* @brief Contains the customization points for buffer implementation based
* on std::string
*/
#include "buffer_tmpl.hpp"
#include "config.hpp"
#include <cstddef>
#include <iterator>
#include <string>
namespace protozero {
// Implementation of buffer customizations points for std::string
/// @cond INTERNAL
template <>
struct buffer_customization<std::string> {
static std::size_t size(const std::string* buffer) noexcept {
return buffer->size();
}
static void append(std::string* buffer, const char* data, std::size_t count) {
buffer->append(data, count);
}
static void append_zeros(std::string* buffer, std::size_t count) {
buffer->append(count, '\0');
}
static void resize(std::string* buffer, std::size_t size) {
protozero_assert(size < buffer->size());
buffer->resize(size);
}
static void reserve_additional(std::string* buffer, std::size_t size) {
buffer->reserve(buffer->size() + size);
}
static void erase_range(std::string* buffer, std::size_t from, std::size_t to) {
protozero_assert(from <= buffer->size());
protozero_assert(to <= buffer->size());
protozero_assert(from <= to);
buffer->erase(std::next(buffer->begin(), static_cast<std::string::iterator::difference_type>(from)),
std::next(buffer->begin(), static_cast<std::string::iterator::difference_type>(to)));
}
static char* at_pos(std::string* buffer, std::size_t pos) {
protozero_assert(pos <= buffer->size());
return (&*buffer->begin()) + pos;
}
static void push_back(std::string* buffer, char ch) {
buffer->push_back(ch);
}
};
/// @endcond
} // namespace protozero
#endif // PROTOZERO_BUFFER_STRING_HPP
+113
View File
@@ -0,0 +1,113 @@
#ifndef PROTOZERO_BUFFER_TMPL_HPP
#define PROTOZERO_BUFFER_TMPL_HPP
/*****************************************************************************
protozero - Minimalistic protocol buffer decoder and encoder in C++.
This file is from https://github.com/mapbox/protozero where you can find more
documentation.
*****************************************************************************/
/**
* @file buffer_tmpl.hpp
*
* @brief Contains the customization points for buffer implementations.
*/
#include <cstddef>
#include <iterator>
#include <string>
namespace protozero {
// Implementation of buffer customizations points for std::string
/// @cond INTERNAL
template <typename T>
struct buffer_customization {
/**
* Get the number of bytes currently used in the buffer.
*
* @param buffer Pointer to the buffer.
* @returns number of bytes used in the buffer.
*/
static std::size_t size(const std::string* buffer);
/**
* Append count bytes from data to the buffer.
*
* @param buffer Pointer to the buffer.
* @param data Pointer to the data.
* @param count Number of bytes to be added to the buffer.
*/
static void append(std::string* buffer, const char* data, std::size_t count);
/**
* Append count zero bytes to the buffer.
*
* @param buffer Pointer to the buffer.
* @param count Number of bytes to be added to the buffer.
*/
static void append_zeros(std::string* buffer, std::size_t count);
/**
* Shrink the buffer to the specified size. The new size will always be
* smaller than the current size.
*
* @param buffer Pointer to the buffer.
* @param size New size of the buffer.
*
* @pre size < current size of buffer
*/
static void resize(std::string* buffer, std::size_t size);
/**
* Reserve an additional size bytes for use in the buffer. This is used for
* variable-sized buffers to tell the buffer implementation that soon more
* memory will be used. The implementation can ignore this.
*
* @param buffer Pointer to the buffer.
* @param size Number of bytes to reserve.
*/
static void reserve_additional(std::string* buffer, std::size_t size);
/**
* Delete data from the buffer. This must move back the data after the
* part being deleted and resize the buffer accordingly.
*
* @param buffer Pointer to the buffer.
* @param from Offset into the buffer where we want to erase from.
* @param to Offset into the buffer one past the last byte we want to erase.
*
* @pre from, to <= size of the buffer, from < to
*/
static void erase_range(std::string* buffer, std::size_t from, std::size_t to);
/**
* Return a pointer to the memory at the specified position in the buffer.
*
* @param buffer Pointer to the buffer.
* @param pos The position in the buffer.
* @returns pointer to the memory in the buffer at the specified position.
*
* @pre pos <= size of the buffer
*/
static char* at_pos(std::string* buffer, std::size_t pos);
/**
* Add a char to the buffer incrementing the number of chars in the buffer.
*
* @param buffer Pointer to the buffer.
* @param ch The character to add.
*/
static void push_back(std::string* buffer, char ch);
};
/// @endcond
} // namespace protozero
#endif // PROTOZERO_BUFFER_TMPL_HPP
+78
View File
@@ -0,0 +1,78 @@
#ifndef PROTOZERO_BUFFER_VECTOR_HPP
#define PROTOZERO_BUFFER_VECTOR_HPP
/*****************************************************************************
protozero - Minimalistic protocol buffer decoder and encoder in C++.
This file is from https://github.com/mapbox/protozero where you can find more
documentation.
*****************************************************************************/
/**
* @file buffer_vector.hpp
*
* @brief Contains the customization points for buffer implementation based
* on std::vector<char>
*/
#include "buffer_tmpl.hpp"
#include "config.hpp"
#include <cstddef>
#include <iterator>
#include <vector>
namespace protozero {
// Implementation of buffer customizations points for std::vector<char>
/// @cond INTERNAL
template <>
struct buffer_customization<std::vector<char>> {
static std::size_t size(const std::vector<char>* buffer) noexcept {
return buffer->size();
}
static void append(std::vector<char>* buffer, const char* data, std::size_t count) {
buffer->insert(buffer->end(), data, data + count);
}
static void append_zeros(std::vector<char>* buffer, std::size_t count) {
buffer->insert(buffer->end(), count, '\0');
}
static void resize(std::vector<char>* buffer, std::size_t size) {
protozero_assert(size < buffer->size());
buffer->resize(size);
}
static void reserve_additional(std::vector<char>* buffer, std::size_t size) {
buffer->reserve(buffer->size() + size);
}
static void erase_range(std::vector<char>* buffer, std::size_t from, std::size_t to) {
protozero_assert(from <= buffer->size());
protozero_assert(to <= buffer->size());
protozero_assert(from <= to);
buffer->erase(std::next(buffer->begin(), static_cast<std::string::iterator::difference_type>(from)),
std::next(buffer->begin(), static_cast<std::string::iterator::difference_type>(to)));
}
static char* at_pos(std::vector<char>* buffer, std::size_t pos) {
protozero_assert(pos <= buffer->size());
return (&*buffer->begin()) + pos;
}
static void push_back(std::vector<char>* buffer, char ch) {
buffer->push_back(ch);
}
};
/// @endcond
} // namespace protozero
#endif // PROTOZERO_BUFFER_VECTOR_HPP
+49 -25
View File
@@ -16,10 +16,10 @@ documentation.
* @brief Contains functions to swap bytes in values (for different endianness).
*/
#include <cassert>
#include <cstdint>
#include "config.hpp"
#include <protozero/config.hpp>
#include <cstdint>
#include <cstring>
namespace protozero {
namespace detail {
@@ -28,10 +28,10 @@ inline uint32_t byteswap_impl(uint32_t value) noexcept {
#ifdef PROTOZERO_USE_BUILTIN_BSWAP
return __builtin_bswap32(value);
#else
return ((value & 0xff000000) >> 24) |
((value & 0x00ff0000) >> 8) |
((value & 0x0000ff00) << 8) |
((value & 0x000000ff) << 24);
return ((value & 0xff000000U) >> 24U) |
((value & 0x00ff0000U) >> 8U) |
((value & 0x0000ff00U) << 8U) |
((value & 0x000000ffU) << 24U);
#endif
}
@@ -39,46 +39,70 @@ inline uint64_t byteswap_impl(uint64_t value) noexcept {
#ifdef PROTOZERO_USE_BUILTIN_BSWAP
return __builtin_bswap64(value);
#else
return ((value & 0xff00000000000000ULL) >> 56) |
((value & 0x00ff000000000000ULL) >> 40) |
((value & 0x0000ff0000000000ULL) >> 24) |
((value & 0x000000ff00000000ULL) >> 8) |
((value & 0x00000000ff000000ULL) << 8) |
((value & 0x0000000000ff0000ULL) << 24) |
((value & 0x000000000000ff00ULL) << 40) |
((value & 0x00000000000000ffULL) << 56);
return ((value & 0xff00000000000000ULL) >> 56U) |
((value & 0x00ff000000000000ULL) >> 40U) |
((value & 0x0000ff0000000000ULL) >> 24U) |
((value & 0x000000ff00000000ULL) >> 8U) |
((value & 0x00000000ff000000ULL) << 8U) |
((value & 0x0000000000ff0000ULL) << 24U) |
((value & 0x000000000000ff00ULL) << 40U) |
((value & 0x00000000000000ffULL) << 56U);
#endif
}
} // end namespace detail
/// byteswap the data pointed to by ptr in-place.
inline void byteswap_inplace(uint32_t* ptr) noexcept {
*ptr = byteswap_impl(*ptr);
*ptr = detail::byteswap_impl(*ptr);
}
/// byteswap the data pointed to by ptr in-place.
inline void byteswap_inplace(uint64_t* ptr) noexcept {
*ptr = byteswap_impl(*ptr);
*ptr = detail::byteswap_impl(*ptr);
}
/// byteswap the data pointed to by ptr in-place.
inline void byteswap_inplace(int32_t* ptr) noexcept {
auto bptr = reinterpret_cast<uint32_t*>(ptr);
*bptr = byteswap_impl(*bptr);
auto* bptr = reinterpret_cast<uint32_t*>(ptr);
*bptr = detail::byteswap_impl(*bptr);
}
/// byteswap the data pointed to by ptr in-place.
inline void byteswap_inplace(int64_t* ptr) noexcept {
auto bptr = reinterpret_cast<uint64_t*>(ptr);
*bptr = byteswap_impl(*bptr);
auto* bptr = reinterpret_cast<uint64_t*>(ptr);
*bptr = detail::byteswap_impl(*bptr);
}
/// byteswap the data pointed to by ptr in-place.
inline void byteswap_inplace(float* ptr) noexcept {
auto bptr = reinterpret_cast<uint32_t*>(ptr);
*bptr = byteswap_impl(*bptr);
static_assert(sizeof(float) == 4, "Expecting four byte float");
uint32_t tmp = 0;
std::memcpy(&tmp, ptr, 4);
tmp = detail::byteswap_impl(tmp); // uint32 overload
std::memcpy(ptr, &tmp, 4);
}
/// byteswap the data pointed to by ptr in-place.
inline void byteswap_inplace(double* ptr) noexcept {
auto bptr = reinterpret_cast<uint64_t*>(ptr);
*bptr = byteswap_impl(*bptr);
static_assert(sizeof(double) == 8, "Expecting eight byte double");
uint64_t tmp = 0;
std::memcpy(&tmp, ptr, 8);
tmp = detail::byteswap_impl(tmp); // uint64 overload
std::memcpy(ptr, &tmp, 8);
}
namespace detail {
// Added for backwards compatibility with any code that might use this
// function (even if it shouldn't have). Will be removed in a later
// version of protozero.
using ::protozero::byteswap_inplace;
} // end namespace detail
} // end namespace protozero
#endif // PROTOZERO_BYTESWAP_HPP
+236
View File
@@ -0,0 +1,236 @@
#ifndef PROTOZERO_DATA_VIEW_HPP
#define PROTOZERO_DATA_VIEW_HPP
/*****************************************************************************
protozero - Minimalistic protocol buffer decoder and encoder in C++.
This file is from https://github.com/mapbox/protozero where you can find more
documentation.
*****************************************************************************/
/**
* @file data_view.hpp
*
* @brief Contains the implementation of the data_view class.
*/
#include "config.hpp"
#include <algorithm>
#include <cstddef>
#include <cstring>
#include <string>
#include <utility>
namespace protozero {
#ifdef PROTOZERO_USE_VIEW
using data_view = PROTOZERO_USE_VIEW;
#else
/**
* Holds a pointer to some data and a length.
*
* This class is supposed to be compatible with the std::string_view
* that will be available in C++17.
*/
class data_view {
const char* m_data = nullptr;
std::size_t m_size = 0;
public:
/**
* Default constructor. Construct an empty data_view.
*/
constexpr data_view() noexcept = default;
/**
* Create data_view from pointer and size.
*
* @param ptr Pointer to the data.
* @param length Length of the data.
*/
constexpr data_view(const char* ptr, std::size_t length) noexcept
: m_data{ptr},
m_size{length} {
}
/**
* Create data_view from string.
*
* @param str String with the data.
*/
data_view(const std::string& str) noexcept // NOLINT(google-explicit-constructor, hicpp-explicit-conversions)
: m_data{str.data()},
m_size{str.size()} {
}
/**
* Create data_view from zero-terminated string.
*
* @param ptr Pointer to the data.
*/
data_view(const char* ptr) noexcept // NOLINT(google-explicit-constructor, hicpp-explicit-conversions)
: m_data{ptr},
m_size{std::strlen(ptr)} {
}
/**
* Swap the contents of this object with the other.
*
* @param other Other object to swap data with.
*/
void swap(data_view& other) noexcept {
using std::swap;
swap(m_data, other.m_data);
swap(m_size, other.m_size);
}
/// Return pointer to data.
constexpr const char* data() const noexcept {
return m_data;
}
/// Return length of data in bytes.
constexpr std::size_t size() const noexcept {
return m_size;
}
/// Returns true if size is 0.
constexpr bool empty() const noexcept {
return m_size == 0;
}
#ifndef PROTOZERO_STRICT_API
/**
* Convert data view to string.
*
* @pre Must not be default constructed data_view.
*
* @deprecated to_string() is not available in C++17 string_view so it
* should not be used to make conversion to that class easier
* in the future.
*/
std::string to_string() const {
protozero_assert(m_data);
return {m_data, m_size};
}
#endif
/**
* Convert data view to string.
*
* @pre Must not be default constructed data_view.
*/
explicit operator std::string() const {
protozero_assert(m_data);
return {m_data, m_size};
}
/**
* Compares the contents of this object with the given other object.
*
* @returns 0 if they are the same, <0 if this object is smaller than
* the other or >0 if it is larger. If both objects have the
* same size returns <0 if this object is lexicographically
* before the other, >0 otherwise.
*
* @pre Must not be default constructed data_view.
*/
int compare(data_view other) const noexcept {
assert(m_data && other.m_data);
const int cmp = std::memcmp(data(), other.data(),
std::min(size(), other.size()));
if (cmp == 0) {
if (size() == other.size()) {
return 0;
}
return size() < other.size() ? -1 : 1;
}
return cmp;
}
}; // class data_view
/**
* Swap two data_view objects.
*
* @param lhs First object.
* @param rhs Second object.
*/
inline void swap(data_view& lhs, data_view& rhs) noexcept {
lhs.swap(rhs);
}
/**
* Two data_view instances are equal if they have the same size and the
* same content.
*
* @param lhs First object.
* @param rhs Second object.
*/
inline constexpr bool operator==(const data_view lhs, const data_view rhs) noexcept {
return lhs.size() == rhs.size() &&
std::equal(lhs.data(), lhs.data() + lhs.size(), rhs.data());
}
/**
* Two data_view instances are not equal if they have different sizes or the
* content differs.
*
* @param lhs First object.
* @param rhs Second object.
*/
inline constexpr bool operator!=(const data_view lhs, const data_view rhs) noexcept {
return !(lhs == rhs);
}
/**
* Returns true if lhs.compare(rhs) < 0.
*
* @param lhs First object.
* @param rhs Second object.
*/
inline bool operator<(const data_view lhs, const data_view rhs) noexcept {
return lhs.compare(rhs) < 0;
}
/**
* Returns true if lhs.compare(rhs) <= 0.
*
* @param lhs First object.
* @param rhs Second object.
*/
inline bool operator<=(const data_view lhs, const data_view rhs) noexcept {
return lhs.compare(rhs) <= 0;
}
/**
* Returns true if lhs.compare(rhs) > 0.
*
* @param lhs First object.
* @param rhs Second object.
*/
inline bool operator>(const data_view lhs, const data_view rhs) noexcept {
return lhs.compare(rhs) > 0;
}
/**
* Returns true if lhs.compare(rhs) >= 0.
*
* @param lhs First object.
* @param rhs Second object.
*/
inline bool operator>=(const data_view lhs, const data_view rhs) noexcept {
return lhs.compare(rhs) >= 0;
}
#endif
} // end namespace protozero
#endif // PROTOZERO_DATA_VIEW_HPP
+37 -4
View File
@@ -29,7 +29,9 @@ namespace protozero {
*/
struct exception : std::exception {
/// Returns the explanatory string.
const char* what() const noexcept override { return "pbf exception"; }
const char* what() const noexcept override {
return "pbf exception";
}
};
/**
@@ -38,7 +40,9 @@ struct exception : std::exception {
*/
struct varint_too_long_exception : exception {
/// Returns the explanatory string.
const char* what() const noexcept override { return "varint too long exception"; }
const char* what() const noexcept override {
return "varint too long exception";
}
};
/**
@@ -47,7 +51,9 @@ struct varint_too_long_exception : exception {
*/
struct unknown_pbf_wire_type_exception : exception {
/// Returns the explanatory string.
const char* what() const noexcept override { return "unknown pbf field type exception"; }
const char* what() const noexcept override {
return "unknown pbf field type exception";
}
};
/**
@@ -60,7 +66,34 @@ struct unknown_pbf_wire_type_exception : exception {
*/
struct end_of_buffer_exception : exception {
/// Returns the explanatory string.
const char* what() const noexcept override { return "end of buffer exception"; }
const char* what() const noexcept override {
return "end of buffer exception";
}
};
/**
* This exception is thrown when a tag has an invalid value. Tags must be
* unsigned integers between 1 and 2^29-1. Tags between 19000 and 19999 are
* not allowed. See
* https://developers.google.com/protocol-buffers/docs/proto#assigning-tags
*/
struct invalid_tag_exception : exception {
/// Returns the explanatory string.
const char* what() const noexcept override {
return "invalid tag exception";
}
};
/**
* This exception is thrown when a length field of a packed repeated field is
* invalid. For fixed size types the length must be a multiple of the size of
* the type.
*/
struct invalid_length_exception : exception {
/// Returns the explanatory string.
const char* what() const noexcept override {
return "invalid length exception";
}
};
} // end namespace protozero
+200 -47
View File
@@ -16,17 +16,18 @@ documentation.
* @brief Contains the iterators for access to packed repeated fields.
*/
#include <cstring>
#include <iterator>
#include <utility>
#include <protozero/config.hpp>
#include <protozero/varint.hpp>
#include "config.hpp"
#include "varint.hpp"
#if PROTOZERO_BYTE_ORDER != PROTOZERO_LITTLE_ENDIAN
# include <protozero/byteswap.hpp>
#endif
#include <algorithm>
#include <cstring>
#include <iterator>
#include <utility>
namespace protozero {
/**
@@ -55,18 +56,18 @@ public:
* Default constructor. Create empty iterator_range.
*/
constexpr iterator_range() :
P(iterator{}, iterator{}) {
P{iterator{}, iterator{}} {
}
/**
* Create iterator range from two iterators.
*
* @param first_iterator Iterator to beginning or range.
* @param last_iterator Iterator to end or range.
* @param first_iterator Iterator to beginning of range.
* @param last_iterator Iterator to end of range.
*/
constexpr iterator_range(iterator&& first_iterator, iterator&& last_iterator) :
P(std::forward<iterator>(first_iterator),
std::forward<iterator>(last_iterator)) {
P{std::forward<iterator>(first_iterator),
std::forward<iterator>(last_iterator)} {
}
/// Return iterator to beginning of range.
@@ -89,11 +90,24 @@ public:
return this->second;
}
/// Return true if this range is empty.
constexpr std::size_t empty() const noexcept {
/**
* Return true if this range is empty.
*
* Complexity: Constant.
*/
constexpr bool empty() const noexcept {
return begin() == end();
}
/**
* Get the size of the range, ie the number of elements it contains.
*
* Complexity: Constant or linear depending on the underlaying iterator.
*/
std::size_t size() const noexcept {
return static_cast<size_t>(std::distance(begin(), end()));
}
/**
* Get element at the beginning of the range.
*
@@ -146,27 +160,22 @@ template <typename T>
class const_fixed_iterator {
/// Pointer to current iterator position
const char* m_data;
/// Pointer to end iterator position
const char* m_end;
const char* m_data = nullptr;
public:
using iterator_category = std::forward_iterator_tag;
/// @cond usual iterator functions not documented
using iterator_category = std::random_access_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
const_fixed_iterator() noexcept :
m_data(nullptr),
m_end(nullptr) {
}
const_fixed_iterator() noexcept = default;
const_fixed_iterator(const char* data, const char* end) noexcept :
m_data(data),
m_end(end) {
explicit const_fixed_iterator(const char* data) noexcept :
m_data{data} {
}
const_fixed_iterator(const const_fixed_iterator&) noexcept = default;
@@ -177,34 +186,99 @@ public:
~const_fixed_iterator() noexcept = default;
value_type operator*() const {
value_type operator*() const noexcept {
value_type result;
std::memcpy(&result, m_data, sizeof(value_type));
#if PROTOZERO_BYTE_ORDER != PROTOZERO_LITTLE_ENDIAN
detail::byteswap_inplace(&result);
byteswap_inplace(&result);
#endif
return result;
}
const_fixed_iterator& operator++() {
const_fixed_iterator& operator++() noexcept {
m_data += sizeof(value_type);
return *this;
}
const_fixed_iterator operator++(int) {
const const_fixed_iterator tmp(*this);
const_fixed_iterator operator++(int) noexcept {
const const_fixed_iterator tmp{*this};
++(*this);
return tmp;
}
bool operator==(const const_fixed_iterator& rhs) const noexcept {
return m_data == rhs.m_data && m_end == rhs.m_end;
const_fixed_iterator& operator--() noexcept {
m_data -= sizeof(value_type);
return *this;
}
bool operator!=(const const_fixed_iterator& rhs) const noexcept {
return !(*this == rhs);
const_fixed_iterator operator--(int) noexcept {
const const_fixed_iterator tmp{*this};
--(*this);
return tmp;
}
friend bool operator==(const_fixed_iterator lhs, const_fixed_iterator rhs) noexcept {
return lhs.m_data == rhs.m_data;
}
friend bool operator!=(const_fixed_iterator lhs, const_fixed_iterator rhs) noexcept {
return !(lhs == rhs);
}
friend bool operator<(const_fixed_iterator lhs, const_fixed_iterator rhs) noexcept {
return lhs.m_data < rhs.m_data;
}
friend bool operator>(const_fixed_iterator lhs, const_fixed_iterator rhs) noexcept {
return rhs < lhs;
}
friend bool operator<=(const_fixed_iterator lhs, const_fixed_iterator rhs) noexcept {
return !(lhs > rhs);
}
friend bool operator>=(const_fixed_iterator lhs, const_fixed_iterator rhs) noexcept {
return !(lhs < rhs);
}
const_fixed_iterator& operator+=(difference_type val) noexcept {
m_data += (sizeof(value_type) * val);
return *this;
}
friend const_fixed_iterator operator+(const_fixed_iterator lhs, difference_type rhs) noexcept {
const_fixed_iterator tmp{lhs};
tmp.m_data += (sizeof(value_type) * rhs);
return tmp;
}
friend const_fixed_iterator operator+(difference_type lhs, const_fixed_iterator rhs) noexcept {
const_fixed_iterator tmp{rhs};
tmp.m_data += (sizeof(value_type) * lhs);
return tmp;
}
const_fixed_iterator& operator-=(difference_type val) noexcept {
m_data -= (sizeof(value_type) * val);
return *this;
}
friend const_fixed_iterator operator-(const_fixed_iterator lhs, difference_type rhs) noexcept {
const_fixed_iterator tmp{lhs};
tmp.m_data -= (sizeof(value_type) * rhs);
return tmp;
}
friend difference_type operator-(const_fixed_iterator lhs, const_fixed_iterator rhs) noexcept {
return static_cast<difference_type>(lhs.m_data - rhs.m_data) / static_cast<difference_type>(sizeof(T));
}
value_type operator[](difference_type n) const noexcept {
return *(*this + n);
}
/// @endcond
}; // class const_fixed_iterator
/**
@@ -217,27 +291,40 @@ class const_varint_iterator {
protected:
/// Pointer to current iterator position
const char* m_data;
const char* m_data = nullptr; // NOLINT(misc-non-private-member-variables-in-classes, cppcoreguidelines-non-private-member-variables-in-classes,-warnings-as-errors)
/// Pointer to end iterator position
const char* m_end;
const char* m_end = nullptr; // NOLINT(misc-non-private-member-variables-in-classes, cppcoreguidelines-non-private-member-variables-in-classes,-warnings-as-errors)
public:
/// @cond usual iterator functions not documented
using iterator_category = std::forward_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
const_varint_iterator() noexcept :
m_data(nullptr),
m_end(nullptr) {
static difference_type distance(const_varint_iterator begin, const_varint_iterator end) noexcept {
// The "distance" between default initialized const_varint_iterator's
// is always 0.
if (!begin.m_data) {
return 0;
}
// We know that each varint contains exactly one byte with the most
// significant bit not set. We can use this to quickly figure out
// how many varints there are without actually decoding the varints.
return std::count_if(begin.m_data, end.m_data, [](char c) noexcept {
return (static_cast<unsigned char>(c) & 0x80U) == 0;
});
}
const_varint_iterator() noexcept = default;
const_varint_iterator(const char* data, const char* end) noexcept :
m_data(data),
m_end(end) {
m_data{data},
m_end{end} {
}
const_varint_iterator(const const_varint_iterator&) noexcept = default;
@@ -249,17 +336,20 @@ public:
~const_varint_iterator() noexcept = default;
value_type operator*() const {
protozero_assert(m_data);
const char* d = m_data; // will be thrown away
return static_cast<value_type>(decode_varint(&d, m_end));
}
const_varint_iterator& operator++() {
protozero_assert(m_data);
skip_varint(&m_data, m_end);
return *this;
}
const_varint_iterator operator++(int) {
const const_varint_iterator tmp(*this);
protozero_assert(m_data);
const const_varint_iterator tmp{*this};
++(*this);
return tmp;
}
@@ -272,6 +362,8 @@ public:
return !(*this == rhs);
}
/// @endcond
}; // class const_varint_iterator
/**
@@ -283,6 +375,8 @@ class const_svarint_iterator : public const_varint_iterator<T> {
public:
/// @cond usual iterator functions not documented
using iterator_category = std::forward_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
@@ -290,39 +384,98 @@ public:
using reference = value_type&;
const_svarint_iterator() noexcept :
const_varint_iterator<T>() {
const_varint_iterator<T>{} {
}
const_svarint_iterator(const char* data, const char* end) noexcept :
const_varint_iterator<T>(data, end) {
const_varint_iterator<T>{data, end} {
}
const_svarint_iterator(const const_svarint_iterator&) = default;
const_svarint_iterator(const_svarint_iterator&&) = default;
const_svarint_iterator(const_svarint_iterator&&) noexcept = default;
const_svarint_iterator& operator=(const const_svarint_iterator&) = default;
const_svarint_iterator& operator=(const_svarint_iterator&&) = default;
const_svarint_iterator& operator=(const_svarint_iterator&&) noexcept = default;
~const_svarint_iterator() = default;
value_type operator*() const {
protozero_assert(this->m_data);
const char* d = this->m_data; // will be thrown away
return static_cast<value_type>(decode_zigzag64(decode_varint(&d, this->m_end)));
}
const_svarint_iterator& operator++() {
protozero_assert(this->m_data);
skip_varint(&this->m_data, this->m_end);
return *this;
}
const_svarint_iterator operator++(int) {
const const_svarint_iterator tmp(*this);
protozero_assert(this->m_data);
const const_svarint_iterator tmp{*this};
++(*this);
return tmp;
}
/// @endcond
}; // class const_svarint_iterator
} // end namespace protozero
namespace std {
// Specialize std::distance for all the protozero iterators. Because
// functions can't be partially specialized, we have to do this for
// every value_type we are using.
/// @cond individual overloads do not need to be documented
template <>
inline typename protozero::const_varint_iterator<int32_t>::difference_type
distance<protozero::const_varint_iterator<int32_t>>(protozero::const_varint_iterator<int32_t> first, // NOLINT(readability-inconsistent-declaration-parameter-name)
protozero::const_varint_iterator<int32_t> last) {
return protozero::const_varint_iterator<int32_t>::distance(first, last);
}
template <>
inline typename protozero::const_varint_iterator<int64_t>::difference_type
distance<protozero::const_varint_iterator<int64_t>>(protozero::const_varint_iterator<int64_t> first, // NOLINT(readability-inconsistent-declaration-parameter-name)
protozero::const_varint_iterator<int64_t> last) {
return protozero::const_varint_iterator<int64_t>::distance(first, last);
}
template <>
inline typename protozero::const_varint_iterator<uint32_t>::difference_type
distance<protozero::const_varint_iterator<uint32_t>>(protozero::const_varint_iterator<uint32_t> first, // NOLINT(readability-inconsistent-declaration-parameter-name)
protozero::const_varint_iterator<uint32_t> last) {
return protozero::const_varint_iterator<uint32_t>::distance(first, last);
}
template <>
inline typename protozero::const_varint_iterator<uint64_t>::difference_type
distance<protozero::const_varint_iterator<uint64_t>>(protozero::const_varint_iterator<uint64_t> first, // NOLINT(readability-inconsistent-declaration-parameter-name)
protozero::const_varint_iterator<uint64_t> last) {
return protozero::const_varint_iterator<uint64_t>::distance(first, last);
}
template <>
inline typename protozero::const_svarint_iterator<int32_t>::difference_type
distance<protozero::const_svarint_iterator<int32_t>>(protozero::const_svarint_iterator<int32_t> first, // NOLINT(readability-inconsistent-declaration-parameter-name)
protozero::const_svarint_iterator<int32_t> last) {
return protozero::const_svarint_iterator<int32_t>::distance(first, last);
}
template <>
inline typename protozero::const_svarint_iterator<int64_t>::difference_type
distance<protozero::const_svarint_iterator<int64_t>>(protozero::const_svarint_iterator<int64_t> first, // NOLINT(readability-inconsistent-declaration-parameter-name)
protozero::const_svarint_iterator<int64_t> last) {
return protozero::const_svarint_iterator<int64_t>::distance(first, last);
}
/// @endcond
} // end namespace std
#endif // PROTOZERO_ITERATORS_HPP
+5 -133
View File
@@ -16,144 +16,16 @@ documentation.
* @brief Contains the pbf_builder template class.
*/
#include <type_traits>
#include "basic_pbf_builder.hpp"
#include "pbf_writer.hpp"
#include <protozero/pbf_writer.hpp>
#include <protozero/types.hpp>
#include <string>
namespace protozero {
/**
* The pbf_builder is used to write PBF formatted messages into a buffer. It
* is based on the pbf_writer class and has all the same methods. The
* difference is that while the pbf_writer class takes an integer tag,
* this template class takes a tag of the template type T. The idea is that
* T will be an enumeration value and this helps reduce the possibility of
* programming errors.
*
* Almost all methods in this class can throw an std::bad_alloc exception if
* the std::string used as a buffer wants to resize.
*
* Read the tutorial to understand how this class is used.
*/
/// Specialization of basic_pbf_builder using std::string as buffer type.
template <typename T>
class pbf_builder : public pbf_writer {
static_assert(std::is_same<pbf_tag_type, typename std::underlying_type<T>::type>::value,
"T must be enum with underlying type protozero::pbf_tag_type");
public:
using enum_type = T;
explicit pbf_builder(std::string& data) noexcept :
pbf_writer(data) {
}
template <typename P>
pbf_builder(pbf_writer& parent_writer, P tag) noexcept :
pbf_writer(parent_writer, pbf_tag_type(tag)) {
}
/// @cond INTERNAL
#define PROTOZERO_WRITER_WRAP_ADD_SCALAR(name, type) \
void add_##name(T tag, type value) { \
pbf_writer::add_##name(pbf_tag_type(tag), value); \
}
PROTOZERO_WRITER_WRAP_ADD_SCALAR(bool, bool)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(enum, int32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(int32, int32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(sint32, int32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(uint32, uint32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(int64, int64_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(sint64, int64_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(uint64, uint64_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(fixed32, uint32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(sfixed32, int32_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(fixed64, uint64_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(sfixed64, int64_t)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(float, float)
PROTOZERO_WRITER_WRAP_ADD_SCALAR(double, double)
#undef PROTOZERO_WRITER_WRAP_ADD_SCALAR
/// @endcond
void add_bytes(T tag, const char* value, std::size_t size) {
pbf_writer::add_bytes(pbf_tag_type(tag), value, size);
}
void add_bytes(T tag, const data_view& value) {
pbf_writer::add_bytes(pbf_tag_type(tag), value);
}
void add_bytes(T tag, const std::string& value) {
pbf_writer::add_bytes(pbf_tag_type(tag), value);
}
void add_bytes(T tag, const char* value) {
pbf_writer::add_bytes(pbf_tag_type(tag), value);
}
template <typename... Ts>
void add_bytes_vectored(T tag, Ts&&... values) {
pbf_writer::add_bytes_vectored(pbf_tag_type(tag), std::forward<Ts>(values)...);
}
void add_string(T tag, const char* value, std::size_t size) {
pbf_writer::add_string(pbf_tag_type(tag), value, size);
}
void add_string(T tag, const data_view& value) {
pbf_writer::add_string(pbf_tag_type(tag), value);
}
void add_string(T tag, const std::string& value) {
pbf_writer::add_string(pbf_tag_type(tag), value);
}
void add_string(T tag, const char* value) {
pbf_writer::add_string(pbf_tag_type(tag), value);
}
void add_message(T tag, const char* value, std::size_t size) {
pbf_writer::add_message(pbf_tag_type(tag), value, size);
}
void add_message(T tag, const data_view& value) {
pbf_writer::add_message(pbf_tag_type(tag), value);
}
void add_message(T tag, const std::string& value) {
pbf_writer::add_message(pbf_tag_type(tag), value);
}
/// @cond INTERNAL
#define PROTOZERO_WRITER_WRAP_ADD_PACKED(name) \
template <typename InputIterator> \
void add_packed_##name(T tag, InputIterator first, InputIterator last) { \
pbf_writer::add_packed_##name(pbf_tag_type(tag), first, last); \
}
PROTOZERO_WRITER_WRAP_ADD_PACKED(bool)
PROTOZERO_WRITER_WRAP_ADD_PACKED(enum)
PROTOZERO_WRITER_WRAP_ADD_PACKED(int32)
PROTOZERO_WRITER_WRAP_ADD_PACKED(sint32)
PROTOZERO_WRITER_WRAP_ADD_PACKED(uint32)
PROTOZERO_WRITER_WRAP_ADD_PACKED(int64)
PROTOZERO_WRITER_WRAP_ADD_PACKED(sint64)
PROTOZERO_WRITER_WRAP_ADD_PACKED(uint64)
PROTOZERO_WRITER_WRAP_ADD_PACKED(fixed32)
PROTOZERO_WRITER_WRAP_ADD_PACKED(sfixed32)
PROTOZERO_WRITER_WRAP_ADD_PACKED(fixed64)
PROTOZERO_WRITER_WRAP_ADD_PACKED(sfixed64)
PROTOZERO_WRITER_WRAP_ADD_PACKED(float)
PROTOZERO_WRITER_WRAP_ADD_PACKED(double)
#undef PROTOZERO_WRITER_WRAP_ADD_PACKED
/// @endcond
}; // class pbf_builder
using pbf_builder = basic_pbf_builder<std::string, T>;
} // end namespace protozero
+94 -8
View File
@@ -16,10 +16,10 @@ documentation.
* @brief Contains the pbf_message template class.
*/
#include <type_traits>
#include "pbf_reader.hpp"
#include "types.hpp"
#include <protozero/pbf_reader.hpp>
#include <protozero/types.hpp>
#include <type_traits>
namespace protozero {
@@ -35,7 +35,7 @@ namespace protozero {
*
* std::string buffer;
* // fill buffer...
* pbf_message<Message> message(buffer.data(), buffer.size());
* pbf_message<Message> message{buffer.data(), buffer.size()};
* @endcode
*
* Sub-messages are created using get_message():
@@ -45,7 +45,7 @@ namespace protozero {
* ...
* };
*
* pbf_message<Message> message(...);
* pbf_message<Message> message{...};
* message.next();
* pbf_message<SubMessage> submessage = message.get_message();
* @endcode
@@ -64,29 +64,115 @@ namespace protozero {
template <typename T>
class pbf_message : public pbf_reader {
static_assert(std::is_same<pbf_tag_type, typename std::underlying_type<T>::type>::value, "T must be enum with underlying type protozero::pbf_tag_type");
static_assert(std::is_same<pbf_tag_type, typename std::underlying_type<T>::type>::value,
"T must be enum with underlying type protozero::pbf_tag_type");
public:
/// The type of messages this class will read.
using enum_type = T;
/**
* Construct a pbf_message. All arguments are forwarded to the pbf_reader
* parent class.
*/
template <typename... Args>
pbf_message(Args&&... args) noexcept :
pbf_reader(std::forward<Args>(args)...) {
pbf_message(Args&&... args) noexcept : // NOLINT(google-explicit-constructor, hicpp-explicit-conversions)
pbf_reader{std::forward<Args>(args)...} {
}
/**
* Set next field in the message as the current field. This is usually
* called in a while loop:
*
* @code
* pbf_message<...> message(...);
* while (message.next()) {
* // handle field
* }
* @endcode
*
* @returns `true` if there is a next field, `false` if not.
* @pre There must be no current field.
* @post If it returns `true` there is a current field now.
*/
bool next() {
return pbf_reader::next();
}
/**
* Set next field with given tag in the message as the current field.
* Fields with other tags are skipped. This is usually called in a while
* loop for repeated fields:
*
* @code
* pbf_message<Example1> message{...};
* while (message.next(Example1::repeated_fixed64_r)) {
* // handle field
* }
* @endcode
*
* or you can call it just once to get the one field with this tag:
*
* @code
* pbf_message<Example1> message{...};
* if (message.next(Example1::required_uint32_x)) {
* // handle field
* }
* @endcode
*
* Note that this will not check the wire type. The two-argument version
* of this function will also check the wire type.
*
* @returns `true` if there is a next field with this tag.
* @pre There must be no current field.
* @post If it returns `true` there is a current field now with the given tag.
*/
bool next(T next_tag) {
return pbf_reader::next(pbf_tag_type(next_tag));
}
/**
* Set next field with given tag and wire type in the message as the
* current field. Fields with other tags are skipped. This is usually
* called in a while loop for repeated fields:
*
* @code
* pbf_message<Example1> message{...};
* while (message.next(Example1::repeated_fixed64_r, pbf_wire_type::varint)) {
* // handle field
* }
* @endcode
*
* or you can call it just once to get the one field with this tag:
*
* @code
* pbf_message<Example1> message{...};
* if (message.next(Example1::required_uint32_x, pbf_wire_type::varint)) {
* // handle field
* }
* @endcode
*
* Note that this will also check the wire type. The one-argument version
* of this function will not check the wire type.
*
* @returns `true` if there is a next field with this tag.
* @pre There must be no current field.
* @post If it returns `true` there is a current field now with the given tag.
*/
bool next(T next_tag, pbf_wire_type type) {
return pbf_reader::next(pbf_tag_type(next_tag), type);
}
/**
* The tag of the current field. The tag is the enum value for the field
* number from the description in the .proto file.
*
* Call next() before calling this function to set the current field.
*
* @returns tag of the current field.
* @pre There must be a current field (ie. next() must have returned `true`).
*/
T tag() const noexcept {
return T(pbf_reader::tag());
}
+95 -70
View File
@@ -16,21 +16,23 @@ documentation.
* @brief Contains the pbf_reader class.
*/
#include <cstddef>
#include <cstdint>
#include <string>
#include <utility>
#include <protozero/config.hpp>
#include <protozero/exception.hpp>
#include <protozero/iterators.hpp>
#include <protozero/types.hpp>
#include <protozero/varint.hpp>
#include "config.hpp"
#include "data_view.hpp"
#include "exception.hpp"
#include "iterators.hpp"
#include "types.hpp"
#include "varint.hpp"
#if PROTOZERO_BYTE_ORDER != PROTOZERO_LITTLE_ENDIAN
# include <protozero/byteswap.hpp>
#endif
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
#include <utility>
namespace protozero {
/**
@@ -41,13 +43,13 @@ namespace protozero {
* @code
* std::string buffer;
* // fill buffer...
* pbf_reader message(buffer.data(), buffer.size());
* pbf_reader message{buffer.data(), buffer.size()};
* @endcode
*
* Sub-messages are created using get_message():
*
* @code
* pbf_reader message(...);
* pbf_reader message{...};
* message.next();
* pbf_reader submessage = message.get_message();
* @endcode
@@ -74,10 +76,11 @@ class pbf_reader {
template <typename T>
T get_fixed() {
T result;
const char* data = m_data;
skip_bytes(sizeof(T));
std::memcpy(&result, m_data - sizeof(T), sizeof(T));
std::memcpy(&result, data, sizeof(T));
#if PROTOZERO_BYTE_ORDER != PROTOZERO_LITTLE_ENDIAN
detail::byteswap_inplace(&result);
byteswap_inplace(&result);
#endif
return result;
}
@@ -86,14 +89,17 @@ class pbf_reader {
iterator_range<const_fixed_iterator<T>> packed_fixed() {
protozero_assert(tag() != 0 && "call next() before accessing field value");
const auto len = get_len_and_skip();
protozero_assert(len % sizeof(T) == 0);
return iterator_range<const_fixed_iterator<T>>{const_fixed_iterator<T>(m_data - len, m_data),
const_fixed_iterator<T>(m_data, m_data)};
if (len % sizeof(T) != 0) {
throw invalid_length_exception{};
}
return {const_fixed_iterator<T>(m_data - len),
const_fixed_iterator<T>(m_data)};
}
template <typename T>
T get_varint() {
return static_cast<T>(decode_varint(&m_data, m_end));
const auto val = static_cast<T>(decode_varint(&m_data, m_end));
return val;
}
template <typename T>
@@ -107,14 +113,14 @@ class pbf_reader {
}
void skip_bytes(pbf_length_type len) {
if (m_data + len > m_end) {
throw end_of_buffer_exception();
if (m_end - m_data < static_cast<ptrdiff_t>(len)) {
throw end_of_buffer_exception{};
}
m_data += len;
// In debug builds reset the tag to zero so that we can detect (some)
// wrong code.
#ifndef NDEBUG
// In debug builds reset the tag to zero so that we can detect (some)
// wrong code.
m_tag = 0;
#endif
}
@@ -129,8 +135,8 @@ class pbf_reader {
iterator_range<T> get_packed() {
protozero_assert(tag() != 0 && "call next() before accessing field value");
const auto len = get_len_and_skip();
return iterator_range<T>{T{m_data - len, m_data},
T{m_data, m_data}};
return {T{m_data - len, m_data},
T{m_data, m_data}};
}
public:
@@ -146,10 +152,8 @@ public:
* @post There is no current field.
*/
explicit pbf_reader(const data_view& view) noexcept
: m_data(view.data()),
m_end(view.data() + view.size()),
m_wire_type(pbf_wire_type::unknown),
m_tag(0) {
: m_data{view.data()},
m_end{view.data() + view.size()} {
}
/**
@@ -163,12 +167,11 @@ public:
* @post There is no current field.
*/
pbf_reader(const char* data, std::size_t size) noexcept
: m_data(data),
m_end(data + size),
m_wire_type(pbf_wire_type::unknown),
m_tag(0) {
: m_data{data},
m_end{data + size} {
}
#ifndef PROTOZERO_STRICT_API
/**
* Construct a pbf_reader message from a data pointer and a length. The
* pointer will be stored inside the pbf_reader object, no data is copied.
@@ -178,13 +181,13 @@ public:
* The buffer must contain a complete protobuf message.
*
* @post There is no current field.
* @deprecated Use one of the other constructors.
*/
explicit pbf_reader(const std::pair<const char*, std::size_t>& data) noexcept
: m_data(data.first),
m_end(data.first + data.second),
m_wire_type(pbf_wire_type::unknown),
m_tag(0) {
: m_data{data.first},
m_end{data.first + data.second} {
}
#endif
/**
* Construct a pbf_reader message from a std::string. A pointer to the
@@ -197,10 +200,8 @@ public:
* @post There is no current field.
*/
explicit pbf_reader(const std::string& data) noexcept
: m_data(data.data()),
m_end(data.data() + data.size()),
m_wire_type(pbf_wire_type::unknown),
m_tag(0) {
: m_data{data.data()},
m_end{data.data() + data.size()} {
}
/**
@@ -241,8 +242,15 @@ public:
* are still fields available and to `false` if the last field has been
* read.
*/
operator bool() const noexcept {
return m_data < m_end;
operator bool() const noexcept { // NOLINT(google-explicit-constructor, hicpp-explicit-conversions)
return m_data != m_end;
}
/**
* Get a view of the not yet read data.
*/
data_view data() const noexcept {
return {m_data, static_cast<std::size_t>(m_end - m_data)};
}
/**
@@ -279,14 +287,15 @@ public:
}
const auto value = get_varint<uint32_t>();
m_tag = pbf_tag_type(value >> 3);
m_tag = pbf_tag_type(value >> 3U);
// tags 0 and 19000 to 19999 are not allowed as per
// https://developers.google.com/protocol-buffers/docs/proto
protozero_assert(((m_tag > 0 && m_tag < 19000) ||
(m_tag > 19999 && m_tag <= ((1 << 29) - 1))) && "tag out of range");
// https://developers.google.com/protocol-buffers/docs/proto#assigning-tags
if (m_tag == 0 || (m_tag >= 19000 && m_tag <= 19999)) {
throw invalid_tag_exception{};
}
m_wire_type = pbf_wire_type(value & 0x07);
m_wire_type = pbf_wire_type(value & 0x07U);
switch (m_wire_type) {
case pbf_wire_type::varint:
case pbf_wire_type::fixed64:
@@ -294,7 +303,7 @@ public:
case pbf_wire_type::fixed32:
break;
default:
throw unknown_pbf_wire_type_exception();
throw unknown_pbf_wire_type_exception{};
}
return true;
@@ -306,7 +315,7 @@ public:
* loop for repeated fields:
*
* @code
* pbf_reader message(...);
* pbf_reader message{...};
* while (message.next(17)) {
* // handle field
* }
@@ -315,7 +324,7 @@ public:
* or you can call it just once to get the one field with this tag:
*
* @code
* pbf_reader message(...);
* pbf_reader message{...};
* if (message.next(17)) {
* // handle field
* }
@@ -332,9 +341,8 @@ public:
while (next()) {
if (m_tag == next_tag) {
return true;
} else {
skip();
}
skip();
}
return false;
}
@@ -345,7 +353,7 @@ public:
* called in a while loop for repeated fields:
*
* @code
* pbf_reader message(...);
* pbf_reader message{...};
* while (message.next(17, pbf_wire_type::varint)) {
* // handle field
* }
@@ -354,7 +362,7 @@ public:
* or you can call it just once to get the one field with this tag:
*
* @code
* pbf_reader message(...);
* pbf_reader message{...};
* if (message.next(17, pbf_wire_type::varint)) {
* // handle field
* }
@@ -371,9 +379,8 @@ public:
while (next()) {
if (m_tag == next_tag && m_wire_type == type) {
return true;
} else {
skip();
}
skip();
}
return false;
}
@@ -417,7 +424,7 @@ public:
* Use it like this:
*
* @code
* pbf_reader message(...);
* pbf_reader message{...};
* while (message.next()) {
* switch (message.tag_and_type()) {
* case tag_and_type(17, pbf_wire_type::length_delimited):
@@ -468,7 +475,7 @@ public:
skip_bytes(4);
break;
default:
protozero_assert(false && "can not be here because next() should have thrown already");
break;
}
}
@@ -487,9 +494,9 @@ public:
bool get_bool() {
protozero_assert(tag() != 0 && "call next() before accessing field value");
protozero_assert(has_wire_type(pbf_wire_type::varint) && "not a varint");
protozero_assert((*m_data & 0x80) == 0 && "not a 1 byte varint");
skip_bytes(1);
return m_data[-1] != 0; // -1 okay because we incremented m_data the line before
const bool result = m_data[0] != 0;
skip_varint(&m_data, m_end);
return result;
}
/**
@@ -667,7 +674,7 @@ public:
protozero_assert(tag() != 0 && "call next() before accessing field value");
protozero_assert(has_wire_type(pbf_wire_type::length_delimited) && "not of type string, bytes or message");
const auto len = get_len_and_skip();
return data_view{m_data - len, len};
return {m_data - len, len};
}
#ifndef PROTOZERO_STRICT_API
@@ -683,7 +690,7 @@ public:
protozero_assert(tag() != 0 && "call next() before accessing field value");
protozero_assert(has_wire_type(pbf_wire_type::length_delimited) && "not of type string, bytes or message");
const auto len = get_len_and_skip();
return std::make_pair(m_data - len, len);
return {m_data - len, len};
}
#endif
@@ -717,7 +724,7 @@ public:
* @post The current field was consumed and there is no current field now.
*/
pbf_reader get_message() {
return pbf_reader(get_view());
return pbf_reader{get_view()};
}
///@}
@@ -746,6 +753,24 @@ public:
/// Forward iterator for iterating over uint64 (varint) values.
using const_uint64_iterator = const_varint_iterator<uint64_t>;
/// Forward iterator for iterating over fixed32 values.
using const_fixed32_iterator = const_fixed_iterator<uint32_t>;
/// Forward iterator for iterating over sfixed32 values.
using const_sfixed32_iterator = const_fixed_iterator<int32_t>;
/// Forward iterator for iterating over fixed64 values.
using const_fixed64_iterator = const_fixed_iterator<uint64_t>;
/// Forward iterator for iterating over sfixed64 values.
using const_sfixed64_iterator = const_fixed_iterator<int64_t>;
/// Forward iterator for iterating over float values.
using const_float_iterator = const_fixed_iterator<float>;
/// Forward iterator for iterating over double values.
using const_double_iterator = const_fixed_iterator<double>;
///@{
/**
* @name Repeated packed field accessor functions
@@ -864,7 +889,7 @@ public:
* @pre The current field must be of type "repeated packed fixed32".
* @post The current field was consumed and there is no current field now.
*/
auto get_packed_fixed32() -> decltype(packed_fixed<uint32_t>()) {
iterator_range<pbf_reader::const_fixed32_iterator> get_packed_fixed32() {
return packed_fixed<uint32_t>();
}
@@ -877,7 +902,7 @@ public:
* @pre The current field must be of type "repeated packed sfixed32".
* @post The current field was consumed and there is no current field now.
*/
auto get_packed_sfixed32() -> decltype(packed_fixed<int32_t>()) {
iterator_range<pbf_reader::const_sfixed32_iterator> get_packed_sfixed32() {
return packed_fixed<int32_t>();
}
@@ -890,7 +915,7 @@ public:
* @pre The current field must be of type "repeated packed fixed64".
* @post The current field was consumed and there is no current field now.
*/
auto get_packed_fixed64() -> decltype(packed_fixed<uint64_t>()) {
iterator_range<pbf_reader::const_fixed64_iterator> get_packed_fixed64() {
return packed_fixed<uint64_t>();
}
@@ -903,7 +928,7 @@ public:
* @pre The current field must be of type "repeated packed sfixed64".
* @post The current field was consumed and there is no current field now.
*/
auto get_packed_sfixed64() -> decltype(packed_fixed<int64_t>()) {
iterator_range<pbf_reader::const_sfixed64_iterator> get_packed_sfixed64() {
return packed_fixed<int64_t>();
}
@@ -916,7 +941,7 @@ public:
* @pre The current field must be of type "repeated packed float".
* @post The current field was consumed and there is no current field now.
*/
auto get_packed_float() -> decltype(packed_fixed<float>()) {
iterator_range<pbf_reader::const_float_iterator> get_packed_float() {
return packed_fixed<float>();
}
@@ -929,7 +954,7 @@ public:
* @pre The current field must be of type "repeated packed double".
* @post The current field was consumed and there is no current field now.
*/
auto get_packed_double() -> decltype(packed_fixed<double>()) {
iterator_range<pbf_reader::const_double_iterator> get_packed_double() {
return packed_fixed<double>();
}
+19 -918
View File
@@ -16,959 +16,60 @@ documentation.
* @brief Contains the pbf_writer class.
*/
#include <cstddef>
#include "basic_pbf_writer.hpp"
#include "buffer_string.hpp"
#include <cstdint>
#include <cstring>
#include <iterator>
#include <limits>
#include <string>
#include <utility>
#include <protozero/config.hpp>
#include <protozero/types.hpp>
#include <protozero/varint.hpp>
#if PROTOZERO_BYTE_ORDER != PROTOZERO_LITTLE_ENDIAN
# include <protozero/byteswap.hpp>
#endif
namespace protozero {
namespace detail {
template <typename T> class packed_field_varint;
template <typename T> class packed_field_svarint;
template <typename T> class packed_field_fixed;
} // end namespace detail
/**
* The pbf_writer is used to write PBF formatted messages into a buffer.
*
* Almost all methods in this class can throw an std::bad_alloc exception if
* the std::string used as a buffer wants to resize.
* Specialization of basic_pbf_writer using std::string as buffer type.
*/
class pbf_writer {
// A pointer to a string buffer holding the data already written to the
// PBF message. For default constructed writers or writers that have been
// rolled back, this is a nullptr.
std::string* m_data;
// A pointer to a parent writer object if this is a submessage. If this
// is a top-level writer, it is a nullptr.
pbf_writer* m_parent_writer;
// This is usually 0. If there is an open submessage, this is set in the
// parent to the rollback position, ie. the last position before the
// submessage was started. This is the position where the header of the
// submessage starts.
std::size_t m_rollback_pos = 0;
// This is usually 0. If there is an open submessage, this is set in the
// parent to the position where the data of the submessage is written to.
std::size_t m_pos = 0;
void add_varint(uint64_t value) {
protozero_assert(m_pos == 0 && "you can't add fields to a parent pbf_writer if there is an existing pbf_writer for a submessage");
protozero_assert(m_data);
write_varint(std::back_inserter(*m_data), value);
}
void add_field(pbf_tag_type tag, pbf_wire_type type) {
protozero_assert(((tag > 0 && tag < 19000) || (tag > 19999 && tag <= ((1 << 29) - 1))) && "tag out of range");
const uint32_t b = (tag << 3) | uint32_t(type);
add_varint(b);
}
void add_tagged_varint(pbf_tag_type tag, uint64_t value) {
add_field(tag, pbf_wire_type::varint);
add_varint(value);
}
template <typename T>
void add_fixed(T value) {
protozero_assert(m_pos == 0 && "you can't add fields to a parent pbf_writer if there is an existing pbf_writer for a submessage");
protozero_assert(m_data);
#if PROTOZERO_BYTE_ORDER != PROTOZERO_LITTLE_ENDIAN
detail::byteswap_inplace(&value);
#endif
m_data->append(reinterpret_cast<const char*>(&value), sizeof(T));
}
template <typename T, typename It>
void add_packed_fixed(pbf_tag_type tag, It first, It last, std::input_iterator_tag) {
if (first == last) {
return;
}
pbf_writer sw(*this, tag);
while (first != last) {
sw.add_fixed<T>(*first++);
}
}
template <typename T, typename It>
void add_packed_fixed(pbf_tag_type tag, It first, It last, std::forward_iterator_tag) {
if (first == last) {
return;
}
const auto length = std::distance(first, last);
add_length_varint(tag, sizeof(T) * pbf_length_type(length));
reserve(sizeof(T) * std::size_t(length));
while (first != last) {
add_fixed<T>(*first++);
}
}
template <typename It>
void add_packed_varint(pbf_tag_type tag, It first, It last) {
if (first == last) {
return;
}
pbf_writer sw(*this, tag);
while (first != last) {
sw.add_varint(uint64_t(*first++));
}
}
template <typename It>
void add_packed_svarint(pbf_tag_type tag, It first, It last) {
if (first == last) {
return;
}
pbf_writer sw(*this, tag);
while (first != last) {
sw.add_varint(encode_zigzag64(*first++));
}
}
// The number of bytes to reserve for the varint holding the length of
// a length-delimited field. The length has to fit into pbf_length_type,
// and a varint needs 8 bit for every 7 bit.
enum constant_reserve_bytes : int {
reserve_bytes = sizeof(pbf_length_type) * 8 / 7 + 1
};
// If m_rollpack_pos is set to this special value, it means that when
// the submessage is closed, nothing needs to be done, because the length
// of the submessage has already been written correctly.
enum constant_size_is_known : std::size_t {
size_is_known = std::numeric_limits<std::size_t>::max()
};
void open_submessage(pbf_tag_type tag, std::size_t size) {
protozero_assert(m_pos == 0);
protozero_assert(m_data);
if (size == 0) {
m_rollback_pos = m_data->size();
add_field(tag, pbf_wire_type::length_delimited);
m_data->append(std::size_t(reserve_bytes), '\0');
} else {
m_rollback_pos = size_is_known;
add_length_varint(tag, pbf_length_type(size));
reserve(size);
}
m_pos = m_data->size();
}
void rollback_submessage() {
protozero_assert(m_pos != 0);
protozero_assert(m_rollback_pos != size_is_known);
protozero_assert(m_data);
m_data->resize(m_rollback_pos);
m_pos = 0;
}
void commit_submessage() {
protozero_assert(m_pos != 0);
protozero_assert(m_rollback_pos != size_is_known);
protozero_assert(m_data);
const auto length = pbf_length_type(m_data->size() - m_pos);
protozero_assert(m_data->size() >= m_pos - reserve_bytes);
const auto n = write_varint(m_data->begin() + long(m_pos) - reserve_bytes, length);
m_data->erase(m_data->begin() + long(m_pos) - reserve_bytes + n, m_data->begin() + long(m_pos));
m_pos = 0;
}
void close_submessage() {
protozero_assert(m_data);
if (m_pos == 0 || m_rollback_pos == size_is_known) {
return;
}
if (m_data->size() - m_pos == 0) {
rollback_submessage();
} else {
commit_submessage();
}
}
void add_length_varint(pbf_tag_type tag, pbf_length_type length) {
add_field(tag, pbf_wire_type::length_delimited);
add_varint(length);
}
public:
/**
* Create a writer using the given string as a data store. The pbf_writer
* stores a reference to that string and adds all data to it. The string
* doesn't have to be empty. The pbf_writer will just append data.
*/
explicit pbf_writer(std::string& data) noexcept :
m_data(&data),
m_parent_writer(nullptr) {
}
/**
* Create a writer without a data store. In this form the writer can not
* be used!
*/
pbf_writer() noexcept :
m_data(nullptr),
m_parent_writer(nullptr) {
}
/**
* Construct a pbf_writer for a submessage from the pbf_writer of the
* parent message.
*
* @param parent_writer The pbf_writer
* @param tag Tag (field number) of the field that will be written
* @param size Optional size of the submessage in bytes (use 0 for unknown).
* Setting this allows some optimizations but is only possible in
* a few very specific cases.
*/
pbf_writer(pbf_writer& parent_writer, pbf_tag_type tag, std::size_t size=0) :
m_data(parent_writer.m_data),
m_parent_writer(&parent_writer) {
m_parent_writer->open_submessage(tag, size);
}
/// A pbf_writer object can be copied
pbf_writer(const pbf_writer&) noexcept = default;
/// A pbf_writer object can be copied
pbf_writer& operator=(const pbf_writer&) noexcept = default;
/// A pbf_writer object can be moved
pbf_writer(pbf_writer&&) noexcept = default;
/// A pbf_writer object can be moved
pbf_writer& operator=(pbf_writer&&) noexcept = default;
~pbf_writer() {
if (m_parent_writer) {
m_parent_writer->close_submessage();
}
}
/**
* Swap the contents of this object with the other.
*
* @param other Other object to swap data with.
*/
void swap(pbf_writer& other) noexcept {
using std::swap;
swap(m_data, other.m_data);
swap(m_parent_writer, other.m_parent_writer);
swap(m_rollback_pos, other.m_rollback_pos);
swap(m_pos, other.m_pos);
}
/**
* Reserve size bytes in the underlying message store in addition to
* whatever the message store already holds. So unlike
* the `std::string::reserve()` method this is not an absolute size,
* but additional memory that should be reserved.
*
* @param size Number of bytes to reserve in underlying message store.
*/
void reserve(std::size_t size) {
protozero_assert(m_data);
m_data->reserve(m_data->size() + size);
}
/**
* Cancel writing of this submessage. The complete submessage will be
* removed as if it was never created and no fields were added.
*
* @pre Must be a pbf_writer of a submessage, ie one opened with the
* pbf_writer constructor taking a parent message.
*/
void rollback() {
protozero_assert(m_parent_writer && "you can't call rollback() on a pbf_writer without a parent");
protozero_assert(m_pos == 0 && "you can't call rollback() on a pbf_writer that has an open nested submessage");
m_parent_writer->rollback_submessage();
m_data = nullptr;
}
///@{
/**
* @name Scalar field writer functions
*/
/**
* Add "bool" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_bool(pbf_tag_type tag, bool value) {
add_field(tag, pbf_wire_type::varint);
protozero_assert(m_pos == 0 && "you can't add fields to a parent pbf_writer if there is an existing pbf_writer for a submessage");
protozero_assert(m_data);
m_data->append(1, value);
}
/**
* Add "enum" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_enum(pbf_tag_type tag, int32_t value) {
add_tagged_varint(tag, uint64_t(value));
}
/**
* Add "int32" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_int32(pbf_tag_type tag, int32_t value) {
add_tagged_varint(tag, uint64_t(value));
}
/**
* Add "sint32" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_sint32(pbf_tag_type tag, int32_t value) {
add_tagged_varint(tag, encode_zigzag32(value));
}
/**
* Add "uint32" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_uint32(pbf_tag_type tag, uint32_t value) {
add_tagged_varint(tag, value);
}
/**
* Add "int64" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_int64(pbf_tag_type tag, int64_t value) {
add_tagged_varint(tag, uint64_t(value));
}
/**
* Add "sint64" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_sint64(pbf_tag_type tag, int64_t value) {
add_tagged_varint(tag, encode_zigzag64(value));
}
/**
* Add "uint64" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_uint64(pbf_tag_type tag, uint64_t value) {
add_tagged_varint(tag, value);
}
/**
* Add "fixed32" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_fixed32(pbf_tag_type tag, uint32_t value) {
add_field(tag, pbf_wire_type::fixed32);
add_fixed<uint32_t>(value);
}
/**
* Add "sfixed32" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_sfixed32(pbf_tag_type tag, int32_t value) {
add_field(tag, pbf_wire_type::fixed32);
add_fixed<int32_t>(value);
}
/**
* Add "fixed64" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_fixed64(pbf_tag_type tag, uint64_t value) {
add_field(tag, pbf_wire_type::fixed64);
add_fixed<uint64_t>(value);
}
/**
* Add "sfixed64" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_sfixed64(pbf_tag_type tag, int64_t value) {
add_field(tag, pbf_wire_type::fixed64);
add_fixed<int64_t>(value);
}
/**
* Add "float" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_float(pbf_tag_type tag, float value) {
add_field(tag, pbf_wire_type::fixed32);
add_fixed<float>(value);
}
/**
* Add "double" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_double(pbf_tag_type tag, double value) {
add_field(tag, pbf_wire_type::fixed64);
add_fixed<double>(value);
}
/**
* Add "bytes" field to data.
*
* @param tag Tag (field number) of the field
* @param value Pointer to value to be written
* @param size Number of bytes to be written
*/
void add_bytes(pbf_tag_type tag, const char* value, std::size_t size) {
protozero_assert(m_pos == 0 && "you can't add fields to a parent pbf_writer if there is an existing pbf_writer for a submessage");
protozero_assert(m_data);
protozero_assert(size <= std::numeric_limits<pbf_length_type>::max());
add_length_varint(tag, pbf_length_type(size));
m_data->append(value, size);
}
/**
* Add "bytes" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_bytes(pbf_tag_type tag, const data_view& value) {
add_bytes(tag, value.data(), value.size());
}
/**
* Add "bytes" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_bytes(pbf_tag_type tag, const std::string& value) {
add_bytes(tag, value.data(), value.size());
}
/**
* Add "bytes" field to data. Bytes from the value are written until
* a null byte is encountered. The null byte is not added.
*
* @param tag Tag (field number) of the field
* @param value Pointer to zero-delimited value to be written
*/
void add_bytes(pbf_tag_type tag, const char* value) {
add_bytes(tag, value, std::strlen(value));
}
/**
* Add "bytes" field to data using vectored input. All the data in the
* 2nd and further arguments is "concatenated" with only a single copy
* into the final buffer.
*
* This will work with objects of any type supporting the data() and
* size() methods like std::string or protozero::data_view.
*
* Example:
* @code
* std::string data1 = "abc";
* std::string data2 = "xyz";
* writer.add_bytes_vectored(1, data1, data2);
* @endcode
*
* @tparam Ts List of types supporting data() and size() methods.
* @param tag Tag (field number) of the field
* @param values List of objects of types Ts with data to be appended.
*/
template <typename... Ts>
void add_bytes_vectored(pbf_tag_type tag, Ts&&... values) {
protozero_assert(m_pos == 0 && "you can't add fields to a parent pbf_writer if there is an existing pbf_writer for a submessage");
protozero_assert(m_data);
size_t sum_size = 0;
(void)std::initializer_list<size_t>{sum_size += values.size()...};
protozero_assert(sum_size <= std::numeric_limits<pbf_length_type>::max());
add_length_varint(tag, pbf_length_type(sum_size));
m_data->reserve(m_data->size() + sum_size);
(void)std::initializer_list<int>{(m_data->append(values.data(), values.size()), 0)...};
}
/**
* Add "string" field to data.
*
* @param tag Tag (field number) of the field
* @param value Pointer to value to be written
* @param size Number of bytes to be written
*/
void add_string(pbf_tag_type tag, const char* value, std::size_t size) {
add_bytes(tag, value, size);
}
/**
* Add "string" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_string(pbf_tag_type tag, const data_view& value) {
add_bytes(tag, value.data(), value.size());
}
/**
* Add "string" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written
*/
void add_string(pbf_tag_type tag, const std::string& value) {
add_bytes(tag, value.data(), value.size());
}
/**
* Add "string" field to data. Bytes from the value are written until
* a null byte is encountered. The null byte is not added.
*
* @param tag Tag (field number) of the field
* @param value Pointer to value to be written
*/
void add_string(pbf_tag_type tag, const char* value) {
add_bytes(tag, value, std::strlen(value));
}
/**
* Add "message" field to data.
*
* @param tag Tag (field number) of the field
* @param value Pointer to message to be written
* @param size Length of the message
*/
void add_message(pbf_tag_type tag, const char* value, std::size_t size) {
add_bytes(tag, value, size);
}
/**
* Add "message" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written. The value must be a complete message.
*/
void add_message(pbf_tag_type tag, const data_view& value) {
add_bytes(tag, value.data(), value.size());
}
/**
* Add "message" field to data.
*
* @param tag Tag (field number) of the field
* @param value Value to be written. The value must be a complete message.
*/
void add_message(pbf_tag_type tag, const std::string& value) {
add_bytes(tag, value.data(), value.size());
}
///@}
///@{
/**
* @name Repeated packed field writer functions
*/
/**
* Add "repeated packed bool" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to bool.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_bool(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_varint(tag, first, last);
}
/**
* Add "repeated packed enum" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to int32_t.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_enum(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_varint(tag, first, last);
}
/**
* Add "repeated packed int32" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to int32_t.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_int32(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_varint(tag, first, last);
}
/**
* Add "repeated packed sint32" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to int32_t.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_sint32(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_svarint(tag, first, last);
}
/**
* Add "repeated packed uint32" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to uint32_t.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_uint32(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_varint(tag, first, last);
}
/**
* Add "repeated packed int64" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to int64_t.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_int64(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_varint(tag, first, last);
}
/**
* Add "repeated packed sint64" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to int64_t.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_sint64(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_svarint(tag, first, last);
}
/**
* Add "repeated packed uint64" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to uint64_t.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_uint64(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_varint(tag, first, last);
}
/**
* Add "repeated packed fixed32" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to uint32_t.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_fixed32(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_fixed<uint32_t, InputIterator>(tag, first, last,
typename std::iterator_traits<InputIterator>::iterator_category());
}
/**
* Add "repeated packed sfixed32" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to int32_t.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_sfixed32(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_fixed<int32_t, InputIterator>(tag, first, last,
typename std::iterator_traits<InputIterator>::iterator_category());
}
/**
* Add "repeated packed fixed64" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to uint64_t.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_fixed64(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_fixed<uint64_t, InputIterator>(tag, first, last,
typename std::iterator_traits<InputIterator>::iterator_category());
}
/**
* Add "repeated packed sfixed64" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to int64_t.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_sfixed64(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_fixed<int64_t, InputIterator>(tag, first, last,
typename std::iterator_traits<InputIterator>::iterator_category());
}
/**
* Add "repeated packed float" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to float.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_float(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_fixed<float, InputIterator>(tag, first, last,
typename std::iterator_traits<InputIterator>::iterator_category());
}
/**
* Add "repeated packed double" field to data.
*
* @tparam InputIterator A type satisfying the InputIterator concept.
* Dereferencing the iterator must yield a type assignable to double.
* @param tag Tag (field number) of the field
* @param first Iterator pointing to the beginning of the data
* @param last Iterator pointing one past the end of data
*/
template <typename InputIterator>
void add_packed_double(pbf_tag_type tag, InputIterator first, InputIterator last) {
add_packed_fixed<double, InputIterator>(tag, first, last,
typename std::iterator_traits<InputIterator>::iterator_category());
}
///@}
template <typename T> friend class detail::packed_field_varint;
template <typename T> friend class detail::packed_field_svarint;
template <typename T> friend class detail::packed_field_fixed;
}; // class pbf_writer
/**
* Swap two pbf_writer objects.
*
* @param lhs First object.
* @param rhs Second object.
*/
inline void swap(pbf_writer& lhs, pbf_writer& rhs) noexcept {
lhs.swap(rhs);
}
namespace detail {
class packed_field {
protected:
pbf_writer m_writer;
public:
packed_field(const packed_field&) = delete;
packed_field& operator=(const packed_field&) = delete;
packed_field(packed_field&&) = default;
packed_field& operator=(packed_field&&) = default;
packed_field(pbf_writer& parent_writer, pbf_tag_type tag) :
m_writer(parent_writer, tag) {
}
packed_field(pbf_writer& parent_writer, pbf_tag_type tag, std::size_t size) :
m_writer(parent_writer, tag, size) {
}
void rollback() {
m_writer.rollback();
}
}; // class packed_field
template <typename T>
class packed_field_fixed : public packed_field {
public:
template <typename P>
packed_field_fixed(pbf_writer& parent_writer, P tag) :
packed_field(parent_writer, static_cast<pbf_tag_type>(tag)) {
}
template <typename P>
packed_field_fixed(pbf_writer& parent_writer, P tag, std::size_t size) :
packed_field(parent_writer, static_cast<pbf_tag_type>(tag), size * sizeof(T)) {
}
void add_element(T value) {
m_writer.add_fixed<T>(value);
}
}; // class packed_field_fixed
template <typename T>
class packed_field_varint : public packed_field {
public:
template <typename P>
packed_field_varint(pbf_writer& parent_writer, P tag) :
packed_field(parent_writer, static_cast<pbf_tag_type>(tag)) {
}
void add_element(T value) {
m_writer.add_varint(uint64_t(value));
}
}; // class packed_field_varint
template <typename T>
class packed_field_svarint : public packed_field {
public:
template <typename P>
packed_field_svarint(pbf_writer& parent_writer, P tag) :
packed_field(parent_writer, static_cast<pbf_tag_type>(tag)) {
}
void add_element(T value) {
m_writer.add_varint(encode_zigzag64(value));
}
}; // class packed_field_svarint
} // end namespace detail
using pbf_writer = basic_pbf_writer<std::string>;
/// Class for generating packed repeated bool fields.
using packed_field_bool = detail::packed_field_varint<bool>;
using packed_field_bool = detail::packed_field_varint<std::string, bool>;
/// Class for generating packed repeated enum fields.
using packed_field_enum = detail::packed_field_varint<int32_t>;
using packed_field_enum = detail::packed_field_varint<std::string, int32_t>;
/// Class for generating packed repeated int32 fields.
using packed_field_int32 = detail::packed_field_varint<int32_t>;
using packed_field_int32 = detail::packed_field_varint<std::string, int32_t>;
/// Class for generating packed repeated sint32 fields.
using packed_field_sint32 = detail::packed_field_svarint<int32_t>;
using packed_field_sint32 = detail::packed_field_svarint<std::string, int32_t>;
/// Class for generating packed repeated uint32 fields.
using packed_field_uint32 = detail::packed_field_varint<uint32_t>;
using packed_field_uint32 = detail::packed_field_varint<std::string, uint32_t>;
/// Class for generating packed repeated int64 fields.
using packed_field_int64 = detail::packed_field_varint<int64_t>;
using packed_field_int64 = detail::packed_field_varint<std::string, int64_t>;
/// Class for generating packed repeated sint64 fields.
using packed_field_sint64 = detail::packed_field_svarint<int64_t>;
using packed_field_sint64 = detail::packed_field_svarint<std::string, int64_t>;
/// Class for generating packed repeated uint64 fields.
using packed_field_uint64 = detail::packed_field_varint<uint64_t>;
using packed_field_uint64 = detail::packed_field_varint<std::string, uint64_t>;
/// Class for generating packed repeated fixed32 fields.
using packed_field_fixed32 = detail::packed_field_fixed<uint32_t>;
using packed_field_fixed32 = detail::packed_field_fixed<std::string, uint32_t>;
/// Class for generating packed repeated sfixed32 fields.
using packed_field_sfixed32 = detail::packed_field_fixed<int32_t>;
using packed_field_sfixed32 = detail::packed_field_fixed<std::string, int32_t>;
/// Class for generating packed repeated fixed64 fields.
using packed_field_fixed64 = detail::packed_field_fixed<uint64_t>;
using packed_field_fixed64 = detail::packed_field_fixed<std::string, uint64_t>;
/// Class for generating packed repeated sfixed64 fields.
using packed_field_sfixed64 = detail::packed_field_fixed<int64_t>;
using packed_field_sfixed64 = detail::packed_field_fixed<std::string, int64_t>;
/// Class for generating packed repeated float fields.
using packed_field_float = detail::packed_field_fixed<float>;
using packed_field_float = detail::packed_field_fixed<std::string, float>;
/// Class for generating packed repeated double fields.
using packed_field_double = detail::packed_field_fixed<double>;
using packed_field_double = detail::packed_field_fixed<std::string, double>;
} // end namespace protozero
+4 -144
View File
@@ -16,6 +16,8 @@ documentation.
* @brief Contains the declaration of low-level types used in the pbf format.
*/
#include "config.hpp"
#include <algorithm>
#include <cstddef>
#include <cstdint>
@@ -23,8 +25,6 @@ documentation.
#include <string>
#include <utility>
#include <protozero/config.hpp>
namespace protozero {
/**
@@ -40,8 +40,7 @@ using pbf_tag_type = uint32_t;
enum class pbf_wire_type : uint32_t {
varint = 0, // int32/64, uint32/64, sint32/64, bool, enum
fixed64 = 1, // fixed64, sfixed64, double
length_delimited = 2, // string, bytes, embedded messages,
// packed repeated fields
length_delimited = 2, // string, bytes, nested messages, packed repeated fields
fixed32 = 5, // fixed32, sfixed32, float
unknown = 99 // used for default setting in this library
};
@@ -54,7 +53,7 @@ enum class pbf_wire_type : uint32_t {
*/
template <typename T>
constexpr inline uint32_t tag_and_type(T tag, pbf_wire_type wire_type) noexcept {
return (static_cast<uint32_t>(static_cast<pbf_tag_type>(tag)) << 3) | static_cast<uint32_t>(wire_type);
return (static_cast<uint32_t>(static_cast<pbf_tag_type>(tag)) << 3U) | static_cast<uint32_t>(wire_type);
}
/**
@@ -62,145 +61,6 @@ constexpr inline uint32_t tag_and_type(T tag, pbf_wire_type wire_type) noexcept
*/
using pbf_length_type = uint32_t;
#ifdef PROTOZERO_USE_VIEW
using data_view = PROTOZERO_USE_VIEW;
#else
/**
* Holds a pointer to some data and a length.
*
* This class is supposed to be compatible with the std::string_view
* that will be available in C++17.
*/
class data_view {
const char* m_data;
std::size_t m_size;
public:
/**
* Default constructor. Construct an empty data_view.
*/
constexpr data_view() noexcept
: m_data(nullptr),
m_size(0) {
}
/**
* Create data_view from pointer and size.
*
* @param ptr Pointer to the data.
* @param length Length of the data.
*/
constexpr data_view(const char* ptr, std::size_t length) noexcept
: m_data(ptr),
m_size(length) {
}
/**
* Create data_view from string.
*
* @param str String with the data.
*/
data_view(const std::string& str) noexcept
: m_data(str.data()),
m_size(str.size()) {
}
/**
* Create data_view from zero-terminated string.
*
* @param ptr Pointer to the data.
*/
data_view(const char* ptr) noexcept
: m_data(ptr),
m_size(std::strlen(ptr)) {
}
/**
* Swap the contents of this object with the other.
*
* @param other Other object to swap data with.
*/
void swap(data_view& other) noexcept {
using std::swap;
swap(m_data, other.m_data);
swap(m_size, other.m_size);
}
/// Return pointer to data.
constexpr const char* data() const noexcept {
return m_data;
}
/// Return length of data in bytes.
constexpr std::size_t size() const noexcept {
return m_size;
}
/// Returns true if size is 0.
constexpr bool empty() const noexcept {
return m_size == 0;
}
/**
* Convert data view to string.
*
* @pre Must not be default constructed data_view.
*/
std::string to_string() const {
protozero_assert(m_data);
return std::string{m_data, m_size};
}
/**
* Convert data view to string.
*
* @pre Must not be default constructed data_view.
*/
explicit operator std::string() const {
protozero_assert(m_data);
return std::string{m_data, m_size};
}
}; // class data_view
/**
* Swap two data_view objects.
*
* @param lhs First object.
* @param rhs Second object.
*/
inline void swap(data_view& lhs, data_view& rhs) noexcept {
lhs.swap(rhs);
}
/**
* Two data_view instances are equal if they have the same size and the
* same content.
*
* @param lhs First object.
* @param rhs Second object.
*/
inline bool operator==(const data_view& lhs, const data_view& rhs) noexcept {
return lhs.size() == rhs.size() && std::equal(lhs.data(), lhs.data() + lhs.size(), rhs.data());
}
/**
* Two data_view instances are not equal if they have different sizes or the
* content differs.
*
* @param lhs First object.
* @param rhs Second object.
*/
inline bool operator!=(const data_view& lhs, const data_view& rhs) noexcept {
return !(lhs == rhs);
}
#endif
} // end namespace protozero
#endif // PROTOZERO_TYPES_HPP
+92 -34
View File
@@ -16,9 +16,10 @@ documentation.
* @brief Contains low-level varint and zigzag encoding and decoding functions.
*/
#include <cstdint>
#include "buffer_tmpl.hpp"
#include "exception.hpp"
#include <protozero/exception.hpp>
#include <cstdint>
namespace protozero {
@@ -31,34 +32,34 @@ namespace detail {
// from https://github.com/facebook/folly/blob/master/folly/Varint.h
inline uint64_t decode_varint_impl(const char** data, const char* end) {
const int8_t* begin = reinterpret_cast<const int8_t*>(*data);
const int8_t* iend = reinterpret_cast<const int8_t*>(end);
const auto* begin = reinterpret_cast<const int8_t*>(*data);
const auto* iend = reinterpret_cast<const int8_t*>(end);
const int8_t* p = begin;
uint64_t val = 0;
if (iend - begin >= max_varint_length) { // fast path
do {
int64_t b;
b = *p++; val = uint64_t((b & 0x7f) ); if (b >= 0) break;
b = *p++; val |= uint64_t((b & 0x7f) << 7); if (b >= 0) break;
b = *p++; val |= uint64_t((b & 0x7f) << 14); if (b >= 0) break;
b = *p++; val |= uint64_t((b & 0x7f) << 21); if (b >= 0) break;
b = *p++; val |= uint64_t((b & 0x7f) << 28); if (b >= 0) break;
b = *p++; val |= uint64_t((b & 0x7f) << 35); if (b >= 0) break;
b = *p++; val |= uint64_t((b & 0x7f) << 42); if (b >= 0) break;
b = *p++; val |= uint64_t((b & 0x7f) << 49); if (b >= 0) break;
b = *p++; val |= uint64_t((b & 0x7f) << 56); if (b >= 0) break;
b = *p++; val |= uint64_t((b & 0x7f) << 63); if (b >= 0) break;
throw varint_too_long_exception();
int64_t b = *p++;
val = ((uint64_t(b) & 0x7fU) ); if (b >= 0) { break; }
b = *p++; val |= ((uint64_t(b) & 0x7fU) << 7U); if (b >= 0) { break; }
b = *p++; val |= ((uint64_t(b) & 0x7fU) << 14U); if (b >= 0) { break; }
b = *p++; val |= ((uint64_t(b) & 0x7fU) << 21U); if (b >= 0) { break; }
b = *p++; val |= ((uint64_t(b) & 0x7fU) << 28U); if (b >= 0) { break; }
b = *p++; val |= ((uint64_t(b) & 0x7fU) << 35U); if (b >= 0) { break; }
b = *p++; val |= ((uint64_t(b) & 0x7fU) << 42U); if (b >= 0) { break; }
b = *p++; val |= ((uint64_t(b) & 0x7fU) << 49U); if (b >= 0) { break; }
b = *p++; val |= ((uint64_t(b) & 0x7fU) << 56U); if (b >= 0) { break; }
b = *p++; val |= ((uint64_t(b) & 0x01U) << 63U); if (b >= 0) { break; }
throw varint_too_long_exception{};
} while (false);
} else {
int shift = 0;
unsigned int shift = 0;
while (p != iend && *p < 0) {
val |= uint64_t(*p++ & 0x7f) << shift;
val |= (uint64_t(*p++) & 0x7fU) << shift;
shift += 7;
}
if (p == iend) {
throw end_of_buffer_exception();
throw end_of_buffer_exception{};
}
val |= uint64_t(*p++) << shift;
}
@@ -88,8 +89,8 @@ namespace detail {
*/
inline uint64_t decode_varint(const char** data, const char* end) {
// If this is a one-byte varint, decode it here.
if (end != *data && ((**data & 0x80) == 0)) {
uint64_t val = uint64_t(**data);
if (end != *data && ((static_cast<uint64_t>(**data) & 0x80U) == 0)) {
const auto val = static_cast<uint64_t>(**data);
++(*data);
return val;
}
@@ -110,20 +111,20 @@ inline uint64_t decode_varint(const char** data, const char* end) {
* before the end of the varint.
*/
inline void skip_varint(const char** data, const char* end) {
const int8_t* begin = reinterpret_cast<const int8_t*>(*data);
const int8_t* iend = reinterpret_cast<const int8_t*>(end);
const auto* begin = reinterpret_cast<const int8_t*>(*data);
const auto* iend = reinterpret_cast<const int8_t*>(end);
const int8_t* p = begin;
while (p != iend && *p < 0) {
++p;
}
if (p >= begin + max_varint_length) {
throw varint_too_long_exception();
if (p - begin >= max_varint_length) {
throw varint_too_long_exception{};
}
if (p == iend) {
throw end_of_buffer_exception();
throw end_of_buffer_exception{};
}
++p;
@@ -138,18 +139,75 @@ inline void skip_varint(const char** data, const char* end) {
* @param data Output iterator the varint encoded value will be written to
* byte by byte.
* @param value The integer that will be encoded.
* @returns the number of bytes written
* @throws Any exception thrown by increment or dereference operator on data.
* @deprecated Use add_varint_to_buffer() instead.
*/
template <typename T>
inline int write_varint(T data, uint64_t value) {
int n = 1;
while (value >= 0x80) {
*data++ = char((value & 0x7f) | 0x80);
value >>= 7;
while (value >= 0x80U) {
*data++ = char((value & 0x7fU) | 0x80U);
value >>= 7U;
++n;
}
*data = char(value);
return n;
}
/**
* Varint encode a 64 bit integer.
*
* @tparam TBuffer A buffer type.
* @param buffer Output buffer the varint will be written to.
* @param value The integer that will be encoded.
* @returns the number of bytes written
* @throws Any exception thrown by calling the buffer_push_back() function.
*/
template <typename TBuffer>
inline void add_varint_to_buffer(TBuffer* buffer, uint64_t value) {
while (value >= 0x80U) {
buffer_customization<TBuffer>::push_back(buffer, char((value & 0x7fU) | 0x80U));
value >>= 7U;
}
buffer_customization<TBuffer>::push_back(buffer, char(value));
}
/**
* Varint encode a 64 bit integer.
*
* @param data Where to add the varint. There must be enough space available!
* @param value The integer that will be encoded.
* @returns the number of bytes written
*/
inline int add_varint_to_buffer(char* data, uint64_t value) noexcept {
int n = 1;
while (value >= 0x80U) {
*data++ = char((value & 0x7fU) | 0x80U);
value >>= 7U;
++n;
}
*data = char(value);
return n;
}
/**
* Get the length of the varint the specified value would produce.
*
* @param value The integer to be encoded.
* @returns the number of bytes the varint would have if we created it.
*/
inline int length_of_varint(uint64_t value) noexcept {
int n = 1;
while (value >= 0x80U) {
value >>= 7U;
++n;
}
*data++ = char(value);
return n;
}
@@ -158,28 +216,28 @@ inline int write_varint(T data, uint64_t value) {
* ZigZag encodes a 32 bit integer.
*/
inline constexpr uint32_t encode_zigzag32(int32_t value) noexcept {
return (static_cast<uint32_t>(value) << 1) ^ (static_cast<uint32_t>(value >> 31));
return (static_cast<uint32_t>(value) << 1U) ^ static_cast<uint32_t>(-static_cast<int32_t>(static_cast<uint32_t>(value) >> 31U));
}
/**
* ZigZag encodes a 64 bit integer.
*/
inline constexpr uint64_t encode_zigzag64(int64_t value) noexcept {
return (static_cast<uint64_t>(value) << 1) ^ (static_cast<uint64_t>(value >> 63));
return (static_cast<uint64_t>(value) << 1U) ^ static_cast<uint64_t>(-static_cast<int64_t>(static_cast<uint64_t>(value) >> 63U));
}
/**
* Decodes a 32 bit ZigZag-encoded integer.
*/
inline constexpr int32_t decode_zigzag32(uint32_t value) noexcept {
return static_cast<int32_t>(value >> 1) ^ -static_cast<int32_t>(value & 1);
return static_cast<int32_t>((value >> 1U) ^ static_cast<uint32_t>(-static_cast<int32_t>(value & 1U)));
}
/**
* Decodes a 64 bit ZigZag-encoded integer.
*/
inline constexpr int64_t decode_zigzag64(uint64_t value) noexcept {
return static_cast<int64_t>(value >> 1) ^ -static_cast<int64_t>(value & 1);
return static_cast<int64_t>((value >> 1U) ^ static_cast<uint64_t>(-static_cast<int64_t>(value & 1U)));
}
} // end namespace protozero
+3 -3
View File
@@ -20,15 +20,15 @@ documentation.
#define PROTOZERO_VERSION_MAJOR 1
/// The minor version number
#define PROTOZERO_VERSION_MINOR 5
#define PROTOZERO_VERSION_MINOR 7
/// The patch number
#define PROTOZERO_VERSION_PATCH 2
#define PROTOZERO_VERSION_PATCH 1
/// The complete version number
#define PROTOZERO_VERSION_CODE (PROTOZERO_VERSION_MAJOR * 10000 + PROTOZERO_VERSION_MINOR * 100 + PROTOZERO_VERSION_PATCH)
/// Version number as string
#define PROTOZERO_VERSION_STRING "1.5.2"
#define PROTOZERO_VERSION_STRING "1.7.1"
#endif // PROTOZERO_VERSION_HPP
+3 -2
View File
@@ -12,6 +12,7 @@
#include "text.hpp"
#include "mvt.hpp"
#include "milo/dtoa_milo.h"
#include "errors.hpp"
const char *geometry_names[GEOM_TYPES] = {
"Point",
@@ -95,7 +96,7 @@ void parse_geometry(int t, json_object *j, drawvec &out, int op, const char *fna
fprintf(stderr, "%s:%d: malformed point\n", fname, line);
json_context(j);
json_context(feature);
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
}
@@ -147,7 +148,7 @@ void stringify_value(json_object *value, int &type, std::string &stringified, co
if (err != "") {
fprintf(stderr, "%s:%d: %s\n", reading, line, err.c_str());
json_context(feature);
exit(EXIT_FAILURE);
exit(EXIT_UTF8);
}
} else if (vt == JSON_NUMBER) {
type = mvt_double;
+7 -6
View File
@@ -20,6 +20,7 @@
#include "projection.hpp"
#include "evaluator.hpp"
#include "milo/dtoa_milo.h"
#include "errors.hpp"
// Offset coordinates to keep them positive
#define COORD_OFFSET (4LL << 32)
@@ -30,7 +31,7 @@ size_t fwrite_check(const void *ptr, size_t size, size_t nitems, FILE *stream, c
size_t w = fwrite(ptr, size, nitems, stream);
if (w != nitems) {
fprintf(stderr, "%s: Write to temporary file failed: %s\n", fname, strerror(errno));
exit(EXIT_FAILURE);
exit(EXIT_WRITE);
}
return w;
}
@@ -52,14 +53,14 @@ void serialize_ulong_long(FILE *out, unsigned long long zigzag, std::atomic<long
b |= 0x80;
if (putc(b, out) == EOF) {
fprintf(stderr, "%s: Write to temporary file failed: %s\n", fname, strerror(errno));
exit(EXIT_FAILURE);
exit(EXIT_WRITE);
}
*fpos += 1;
zigzag >>= 7;
} else {
if (putc(b, out) == EOF) {
fprintf(stderr, "%s: Write to temporary file failed: %s\n", fname, strerror(errno));
exit(EXIT_FAILURE);
exit(EXIT_WRITE);
}
*fpos += 1;
break;
@@ -509,7 +510,7 @@ int serialize_feature(struct serialization_state *sst, serial_feature &sf) {
if (extent > 10000) {
fprintf(stderr, "Exiting because this can't be right.\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
}
}
@@ -613,7 +614,7 @@ int serialize_feature(struct serialization_state *sst, serial_feature &sf) {
}
} else {
fprintf(stderr, "Internal error: can't find layer name %s\n", sf.layername.c_str());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
for (ssize_t i = (ssize_t) sf.full_keys.size() - 1; i >= 0; i--) {
@@ -772,7 +773,7 @@ void coerce_value(std::string const &key, int &vt, std::string &val, std::map<st
}
} else {
fprintf(stderr, "Can't happen: attribute type %d\n", a->second);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
}
}
@@ -8,6 +8,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "tests/join-population/tabblock_06001420.mbtiles",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -8,6 +8,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "tests/join-population/tabblock_06001420.mbtiles",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -8,6 +8,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "tests/join-population/tabblock_06001420.mbtiles",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -8,6 +8,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "tests/join-population/tabblock_06001420.mbtiles",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -8,6 +8,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "tests/join-population/tabblock_06001420.mbtiles",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -8,6 +8,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "tests/join-population/tabblock_06001420.mbtiles",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -8,6 +8,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "tests/join-population/tabblock_06001420.mbtiles",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -9,6 +9,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "macarthur name",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -8,6 +8,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "tests/join-population/macarthur-folder + tests/join-population/macarthur2-folder + tests/join-population/tabblock_06001420-folder",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -8,6 +8,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "tests/join-population/macarthur.mbtiles + tests/join-population/macarthur2.mbtiles + tests/join-population/tabblock_06001420.mbtiles",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -8,6 +8,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "tests/join-population/macarthur.mbtiles + tests/join-population/macarthur2.mbtiles + tests/join-population/tabblock_06001420.mbtiles",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -8,6 +8,7 @@
"maxzoom": "12",
"minzoom": "0",
"name": "tests/join-population/macarthur.mbtiles + tests/join-population/macarthur2.mbtiles + tests/join-population/tabblock_06001420.mbtiles",
"strategies": "[ { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 260 }, { \"tiny_polygons\": 258 }, { \"tiny_polygons\": 255 }, { \"tiny_polygons\": 248 }, { \"tiny_polygons\": 152 }, { \"tiny_polygons\": 76 }, { \"tiny_polygons\": 46 } ]",
"type": "overlay",
"version": "2"
}, "features": [
@@ -0,0 +1,64 @@
{ "type": "FeatureCollection", "properties": {
"bounds": "-122.538670,37.705764,-12.240000,37.836443",
"center": "-122.431641,37.788049,11",
"description": "tests/muni/decode/multi.mbtiles",
"format": "pbf",
"generator_options": "./tippecanoe -q -z11 -Z11 -f -o tests/muni/decode/multi.mbtiles tests/muni/muni.json",
"json": "{\"vector_layers\": [ { \"id\": \"muni\", \"description\": \"\", \"minzoom\": 11, \"maxzoom\": 11, \"fields\": {\"name\": \"String\"} }, { \"id\": \"subway\", \"description\": \"\", \"minzoom\": 11, \"maxzoom\": 11, \"fields\": {\"name\": \"String\"} } ],\"tilestats\": {\"layerCount\": 2,\"layers\": [{\"layer\": \"muni\",\"count\": 4592,\"geometry\": \"Point\",\"attributeCount\": 1,\"attributes\": [{\"attribute\": \"name\",\"count\": 1000,\"type\": \"string\",\"values\": [\" 4th St & Brannan St\",\" Conzelman Rd & Mccullough Rd\",\"100 O'Shaughnessy Blvd\",\"101 Dakota St\",\"1095 CONNECTICUT ST\",\"10th Ave & Ortega St\",\"10th Ave & Pacheco St\",\"10th Ave & Quintara St\",\"1100 Lake Merced Blvd\",\"115 TELEGRAPH Hill Blvd\",\"117 Warren Dr\",\"11th St & Bryant St\",\"11th St & Folsom St\",\"11th St & Harrison St\",\"11th St & Howard St\",\"11th St & Market St\",\"11th St & Mission St\",\"11th St/btw Market & Mission\",\"120 Portola Dr\",\"126 Miraloma Dr\",\"13th St & Gateview Ave\",\"14 Dakota St\",\"14th Avenue & Geary Boulevard\",\"14th Ave & Quintara St\",\"14th Ave & Santiago St\",\"14th Ave & Taraval St\",\"14th Ave & Ulloa St\",\"14th St & Alpine Ter\",\"14th St & Castro St\",\"14th St & Church St\",\"14th St & Mission St\",\"14th St & Noe St\",\"14th St & SANCHEZ ST\",\"14th St & Sanchez St\",\"150 Otis St\",\"15th Ave & Noriega St\",\"15th Ave & Ortega St\",\"15th Ave & Pacheco St\",\"15th Ave & Quintara St\",\"15th Ave & Taraval St\",\"15th Ave & Ulloa St\",\"15th Ave & West Portal Ave\",\"15th St & Mission St\",\"16 th St & South Van Ness\",\"164 Addison St\",\"1650 Geneva Ave\",\"1697 7th Ave\",\"16th Ave & Lawton St\",\"16th Ave & Lomita Ave\",\"16th Ave & Moraga St\",\"16th Ave & Noriega St\",\"16th Ave & Ortega St\",\"16th Ave & Pacheco St\",\"16th Avenue at Lawton Street\",\"16th St & 4th St\",\"16th St & Bryant St\",\"16th St & Church St\",\"16th St & Dolores St\",\"16th St & Folsom St\",\"16th St & Guerrero St\",\"16th St & Harrison St\",\"16th St & Kansas St\",\"16th St & Mission St\",\"16th St & Missouri St\",\"16th St & Potrero Ave\",\"16th St & San Bruno Ave\",\"16th St & Shotwell St\",\"16th St & South Van Ness\",\"16th St & Valencia St\",\"16th St & Vermont St\",\"16th St & Wisconsin St\",\"16th St& Rhode Island St\",\"16th Street & 4th Street\",\"16th Street & Missouri St\",\"16th Street & Rhode Islandi St\",\"16th Street & Wisconsin St\",\"170 Buckingham Way\",\"1701 Geneva Ave\",\"1721 Geneva Ave\",\"1725 Sunnydale Ave\",\"1730 3rd St\",\"1731 3RD ST\",\"1750 Geneva Ave\",\"176 Rhode Island St\",\"1798 Laguna Honda Blvd\",\"17TH ST & KANSAS ST\",\"17th Ave & Quintara St\",\"17th Ave & Rivera St\",\"17th Ave & Santiago St\",\"17th St & Belvedere St\",\"17th St & Castro St\",\"17th St & Clayton St\",\"17th St & Cole St\",\"17th St & De Haro St\",\"17th St & Diamond St\",\"17th St & Kansas St\",\"17th St & Noe St\",\"17th St & Wisconsin St\",\"1800 Sunnydale Ave\",\"18th St & 3rd St\"]}]},{\"layer\": \"subway\",\"count\": 19,\"geometry\": \"Point\",\"attributeCount\": 1,\"attributes\": [{\"attribute\": \"name\",\"count\": 18,\"type\": \"string\",\"values\": [\"Metro Castro Station/Downtown\",\"Metro Castro Station/Outbound\",\"Metro Church Station/Downtown\",\"Metro Church Station/Outbound\",\"Metro Civic Center Station/Downtn\",\"Metro Civic Center Station/Downtown\",\"Metro Civic Center Station/Outbd\",\"Metro Embarcadero Station\",\"Metro Embarcadero Station/Downtown\",\"Metro Forest Hill Station/Downtown\",\"Metro Montgomery Station/Downtown\",\"Metro Montgomery Station/Outbound\",\"Metro Powell Station/Downtown\",\"Metro Powell Station/Outbound\",\"Metro Van Ness Station\",\"Metro Van Ness Station/Downtown\",\"Metro Van Ness Station/Outbound\",\"Van Ness Station Outbound\"]}]}]}}",
"maxzoom": "11",
"minzoom": "11",
"name": "tests/muni/decode/multi.mbtiles",
"type": "overlay",
"version": "2"
}, "features": [
{ "type": "FeatureCollection", "properties": { "zoom": 11, "x": 326, "y": 791 }, "features": [
] }
,
{ "type": "FeatureCollection", "properties": { "zoom": 11, "x": 327, "y": 792 }, "features": [
] }
,
{ "type": "FeatureCollection", "properties": { "zoom": 11, "x": 327, "y": 791 }, "features": [
{ "type": "FeatureCollection", "properties": { "layer": "subway", "version": 2, "extent": 4096 }, "features": [
{ "type": "Feature", "properties": { "name": "Metro Castro Station/Outbound" }, "geometry": { "type": "Point", "coordinates": [ 0.47900390625, 0.6826171875 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Castro Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 0.4794921875, 0.68310546875 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Forest Hill Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 0.346435546875, 0.785888671875 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Montgomery Station/Outbound" }, "geometry": { "type": "Point", "coordinates": [ 0.667724609375, 0.494873046875 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Montgomery Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 0.6689453125, 0.495361328125 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Embarcadero Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 0.699462890625, 0.46435546875 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Embarcadero Station" }, "geometry": { "type": "Point", "coordinates": [ 0.7001953125, 0.46337890625 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Embarcadero Station" }, "geometry": { "type": "Point", "coordinates": [ 0.700439453125, 0.46337890625 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Civic Center Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 0.608642578125, 0.5556640625 ] } }
,
{ "type": "Feature", "properties": { "name": "Van Ness Station Outbound" }, "geometry": { "type": "Point", "coordinates": [ 0.56982421875, 0.59228515625 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Van Ness Station/Outbound" }, "geometry": { "type": "Point", "coordinates": [ 0.5703125, 0.593017578125 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Van Ness Station" }, "geometry": { "type": "Point", "coordinates": [ 0.57080078125, 0.593505859375 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Van Ness Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 0.5703125, 0.59375 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Civic Center Station/Outbd" }, "geometry": { "type": "Point", "coordinates": [ 0.594482421875, 0.567626953125 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Civic Center Station/Downtn" }, "geometry": { "type": "Point", "coordinates": [ 0.595703125, 0.568603515625 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Church Station/Outbound" }, "geometry": { "type": "Point", "coordinates": [ 0.51318359375, 0.649169921875 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Church Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 0.513916015625, 0.650146484375 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Powell Station/Outbound" }, "geometry": { "type": "Point", "coordinates": [ 0.635498046875, 0.527099609375 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Powell Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 0.635986328125, 0.52783203125 ] } }
] }
] }
,
{ "type": "FeatureCollection", "properties": { "zoom": 11, "x": 954, "y": 791 }, "features": [
] }
] }
@@ -0,0 +1,64 @@
{ "type": "FeatureCollection", "properties": {
"bounds": "-122.538670,37.705764,-12.240000,37.836443",
"center": "-122.431641,37.788049,11",
"description": "tests/muni/decode/multi.mbtiles",
"format": "pbf",
"generator_options": "./tippecanoe -q -z11 -Z11 -f -o tests/muni/decode/multi.mbtiles tests/muni/muni.json",
"json": "{\"vector_layers\": [ { \"id\": \"muni\", \"description\": \"\", \"minzoom\": 11, \"maxzoom\": 11, \"fields\": {\"name\": \"String\"} }, { \"id\": \"subway\", \"description\": \"\", \"minzoom\": 11, \"maxzoom\": 11, \"fields\": {\"name\": \"String\"} } ],\"tilestats\": {\"layerCount\": 2,\"layers\": [{\"layer\": \"muni\",\"count\": 4592,\"geometry\": \"Point\",\"attributeCount\": 1,\"attributes\": [{\"attribute\": \"name\",\"count\": 1000,\"type\": \"string\",\"values\": [\" 4th St & Brannan St\",\" Conzelman Rd & Mccullough Rd\",\"100 O'Shaughnessy Blvd\",\"101 Dakota St\",\"1095 CONNECTICUT ST\",\"10th Ave & Ortega St\",\"10th Ave & Pacheco St\",\"10th Ave & Quintara St\",\"1100 Lake Merced Blvd\",\"115 TELEGRAPH Hill Blvd\",\"117 Warren Dr\",\"11th St & Bryant St\",\"11th St & Folsom St\",\"11th St & Harrison St\",\"11th St & Howard St\",\"11th St & Market St\",\"11th St & Mission St\",\"11th St/btw Market & Mission\",\"120 Portola Dr\",\"126 Miraloma Dr\",\"13th St & Gateview Ave\",\"14 Dakota St\",\"14th Avenue & Geary Boulevard\",\"14th Ave & Quintara St\",\"14th Ave & Santiago St\",\"14th Ave & Taraval St\",\"14th Ave & Ulloa St\",\"14th St & Alpine Ter\",\"14th St & Castro St\",\"14th St & Church St\",\"14th St & Mission St\",\"14th St & Noe St\",\"14th St & SANCHEZ ST\",\"14th St & Sanchez St\",\"150 Otis St\",\"15th Ave & Noriega St\",\"15th Ave & Ortega St\",\"15th Ave & Pacheco St\",\"15th Ave & Quintara St\",\"15th Ave & Taraval St\",\"15th Ave & Ulloa St\",\"15th Ave & West Portal Ave\",\"15th St & Mission St\",\"16 th St & South Van Ness\",\"164 Addison St\",\"1650 Geneva Ave\",\"1697 7th Ave\",\"16th Ave & Lawton St\",\"16th Ave & Lomita Ave\",\"16th Ave & Moraga St\",\"16th Ave & Noriega St\",\"16th Ave & Ortega St\",\"16th Ave & Pacheco St\",\"16th Avenue at Lawton Street\",\"16th St & 4th St\",\"16th St & Bryant St\",\"16th St & Church St\",\"16th St & Dolores St\",\"16th St & Folsom St\",\"16th St & Guerrero St\",\"16th St & Harrison St\",\"16th St & Kansas St\",\"16th St & Mission St\",\"16th St & Missouri St\",\"16th St & Potrero Ave\",\"16th St & San Bruno Ave\",\"16th St & Shotwell St\",\"16th St & South Van Ness\",\"16th St & Valencia St\",\"16th St & Vermont St\",\"16th St & Wisconsin St\",\"16th St& Rhode Island St\",\"16th Street & 4th Street\",\"16th Street & Missouri St\",\"16th Street & Rhode Islandi St\",\"16th Street & Wisconsin St\",\"170 Buckingham Way\",\"1701 Geneva Ave\",\"1721 Geneva Ave\",\"1725 Sunnydale Ave\",\"1730 3rd St\",\"1731 3RD ST\",\"1750 Geneva Ave\",\"176 Rhode Island St\",\"1798 Laguna Honda Blvd\",\"17TH ST & KANSAS ST\",\"17th Ave & Quintara St\",\"17th Ave & Rivera St\",\"17th Ave & Santiago St\",\"17th St & Belvedere St\",\"17th St & Castro St\",\"17th St & Clayton St\",\"17th St & Cole St\",\"17th St & De Haro St\",\"17th St & Diamond St\",\"17th St & Kansas St\",\"17th St & Noe St\",\"17th St & Wisconsin St\",\"1800 Sunnydale Ave\",\"18th St & 3rd St\"]}]},{\"layer\": \"subway\",\"count\": 19,\"geometry\": \"Point\",\"attributeCount\": 1,\"attributes\": [{\"attribute\": \"name\",\"count\": 18,\"type\": \"string\",\"values\": [\"Metro Castro Station/Downtown\",\"Metro Castro Station/Outbound\",\"Metro Church Station/Downtown\",\"Metro Church Station/Outbound\",\"Metro Civic Center Station/Downtn\",\"Metro Civic Center Station/Downtown\",\"Metro Civic Center Station/Outbd\",\"Metro Embarcadero Station\",\"Metro Embarcadero Station/Downtown\",\"Metro Forest Hill Station/Downtown\",\"Metro Montgomery Station/Downtown\",\"Metro Montgomery Station/Outbound\",\"Metro Powell Station/Downtown\",\"Metro Powell Station/Outbound\",\"Metro Van Ness Station\",\"Metro Van Ness Station/Downtown\",\"Metro Van Ness Station/Outbound\",\"Van Ness Station Outbound\"]}]}]}}",
"maxzoom": "11",
"minzoom": "11",
"name": "tests/muni/decode/multi.mbtiles",
"type": "overlay",
"version": "2"
}, "features": [
{ "type": "FeatureCollection", "properties": { "zoom": 11, "x": 326, "y": 791 }, "features": [
] }
,
{ "type": "FeatureCollection", "properties": { "zoom": 11, "x": 327, "y": 792 }, "features": [
] }
,
{ "type": "FeatureCollection", "properties": { "zoom": 11, "x": 327, "y": 791 }, "features": [
{ "type": "FeatureCollection", "properties": { "layer": "subway", "version": 2, "extent": 4096 }, "features": [
{ "type": "Feature", "properties": { "name": "Metro Castro Station/Outbound" }, "geometry": { "type": "Point", "coordinates": [ 1962, 2796 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Castro Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 1964, 2798 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Forest Hill Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 1419, 3219 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Montgomery Station/Outbound" }, "geometry": { "type": "Point", "coordinates": [ 2735, 2027 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Montgomery Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 2740, 2029 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Embarcadero Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 2865, 1902 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Embarcadero Station" }, "geometry": { "type": "Point", "coordinates": [ 2868, 1898 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Embarcadero Station" }, "geometry": { "type": "Point", "coordinates": [ 2869, 1898 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Civic Center Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 2493, 2276 ] } }
,
{ "type": "Feature", "properties": { "name": "Van Ness Station Outbound" }, "geometry": { "type": "Point", "coordinates": [ 2334, 2426 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Van Ness Station/Outbound" }, "geometry": { "type": "Point", "coordinates": [ 2336, 2429 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Van Ness Station" }, "geometry": { "type": "Point", "coordinates": [ 2338, 2431 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Van Ness Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 2336, 2432 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Civic Center Station/Outbd" }, "geometry": { "type": "Point", "coordinates": [ 2435, 2325 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Civic Center Station/Downtn" }, "geometry": { "type": "Point", "coordinates": [ 2440, 2329 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Church Station/Outbound" }, "geometry": { "type": "Point", "coordinates": [ 2102, 2659 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Church Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 2105, 2663 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Powell Station/Outbound" }, "geometry": { "type": "Point", "coordinates": [ 2603, 2159 ] } }
,
{ "type": "Feature", "properties": { "name": "Metro Powell Station/Downtown" }, "geometry": { "type": "Point", "coordinates": [ 2605, 2162 ] } }
] }
] }
,
{ "type": "FeatureCollection", "properties": { "zoom": 11, "x": 954, "y": 791 }, "features": [
] }
] }
+3 -2
View File
@@ -5,6 +5,7 @@
#include <string.h>
#include "milo/dtoa_milo.h"
#include "milo/milo.h"
#include "errors.hpp"
/**
* Returns an empty string if `s` is valid utf8;
@@ -132,7 +133,7 @@ int integer_zoom(std::string where, std::string text) {
double d = atof(text.c_str());
if (!isfinite(d) || d != floor(d) || d < 0 || d > 32) {
fprintf(stderr, "%s: Expected integer zoom level in \"tippecanoe\" GeoJSON extension, not %s\n", where.c_str(), text.c_str());
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
return d;
}
@@ -179,7 +180,7 @@ char *dtoa_milo(double val) {
char *dup = strdup(s.c_str());
if (dup == NULL) {
perror("strdup");
exit(EXIT_FAILURE);
exit(EXIT_MEMORY);
}
return dup;
}
+73 -17
View File
@@ -37,6 +37,7 @@
#include <functional>
#include "jsonpull/jsonpull.h"
#include "milo/dtoa_milo.h"
#include "errors.hpp"
int pk = false;
int pC = false;
@@ -54,6 +55,7 @@ struct stats {
int maxzoom;
double midlat, midlon;
double minlat, minlon, maxlat, maxlon;
std::vector<struct strategy> strategies;
};
void aprintf(std::string *buf, const char *format, ...) {
@@ -63,7 +65,7 @@ void aprintf(std::string *buf, const char *format, ...) {
va_start(ap, format);
if (vasprintf(&tmp, format, ap) < 0) {
fprintf(stderr, "memory allocation failure\n");
exit(EXIT_FAILURE);
exit(EXIT_MEMORY);
}
va_end(ap);
@@ -78,7 +80,7 @@ void handle(std::string message, int z, unsigned x, unsigned y, std::map<std::st
if (!tile.decode(message, was_compressed)) {
fprintf(stderr, "Couldn't decompress tile %d/%u/%u\n", z, x, y);
exit(EXIT_FAILURE);
exit(EXIT_MVT);
}
for (size_t l = 0; l < tile.layers.size(); l++) {
@@ -430,13 +432,13 @@ struct reader *begin_reading(char *fname) {
if (sqlite3_open(fname, &db) != SQLITE_OK) {
fprintf(stderr, "%s: %s\n", fname, sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
char *err = NULL;
if (sqlite3_exec(db, "PRAGMA integrity_check;", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "%s: integrity_check: %s\n", fname, err);
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
const char *sql = "SELECT zoom_level, tile_column, tile_row, tile_data from tiles order by zoom_level, tile_column, tile_row;";
@@ -444,7 +446,7 @@ struct reader *begin_reading(char *fname) {
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_SQLITE);
}
r->db = db;
@@ -561,7 +563,7 @@ void handle_tasks(std::map<zxy, std::vector<std::string>> &tasks, std::vector<st
for (size_t i = 0; i < CPUS; i++) {
if (pthread_create(&pthreads[i], NULL, join_worker, &args[i]) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
}
@@ -582,6 +584,54 @@ void handle_tasks(std::map<zxy, std::vector<std::string>> &tasks, std::vector<st
}
}
void handle_strategies(const unsigned char *s, std::vector<strategy> *st) {
json_pull *jp = json_begin_string((const char *) s);
json_object *o = json_read_tree(jp);
if (o != NULL && o->type == JSON_ARRAY) {
for (size_t i = 0; i < o->value.array.length; i++) {
json_object *h = o->value.array.array[i];
if (h->type == JSON_HASH) {
for (size_t j = 0; j < h->value.object.length; j++) {
json_object *k = h->value.object.keys[j];
json_object *v = h->value.object.values[j];
if (k->type != JSON_STRING) {
fprintf(stderr, "Key %zu of %zu is not a string: %s\n", j, i, s);
} else if (v->type != JSON_NUMBER) {
fprintf(stderr, "Value %zu of %zu is not a number: %s\n", j, i, s);
} else {
if (i <= st->size()) {
st->resize(i + 1);
}
if (strcmp(k->value.string.string, "dropped_by_rate") == 0) {
(*st)[i].dropped_by_rate += v->value.number.number;
} else if (strcmp(k->value.string.string, "dropped_by_gamma") == 0) {
(*st)[i].dropped_by_gamma += v->value.number.number;
} else if (strcmp(k->value.string.string, "dropped_as_needed") == 0) {
(*st)[i].dropped_as_needed += v->value.number.number;
} else if (strcmp(k->value.string.string, "coalesced_as_needed") == 0) {
(*st)[i].coalesced_as_needed += v->value.number.number;
} else if (strcmp(k->value.string.string, "detail_reduced") == 0) {
(*st)[i].detail_reduced += v->value.number.number;
} else if (strcmp(k->value.string.string, "tiny_polygons") == 0) {
(*st)[i].tiny_polygons += v->value.number.number;
} else if (strcmp(k->value.string.string, "tile_size_desired") == 0) {
(*st)[i].tile_size += v->value.number.number;
}
}
}
} else {
fprintf(stderr, "Element %zu is not a hash: %s\n", i, s);
}
}
json_free(o);
}
json_end(jp);
}
void handle_vector_layers(json_object *vector_layers, std::map<std::string, layermap_entry> &layermap, std::map<std::string, std::string> &attribute_descriptions) {
if (vector_layers != NULL && vector_layers->type == JSON_ARRAY) {
for (size_t i = 0; i < vector_layers->value.array.length; i++) {
@@ -621,7 +671,7 @@ void handle_vector_layers(json_object *vector_layers, std::map<std::string, laye
}
}
void decode(struct reader *readers, std::map<std::string, layermap_entry> &layermap, sqlite3 *outdb, const char *outdir, struct stats *st, std::vector<std::string> &header, std::map<std::string, std::vector<std::string>> &mapping, std::set<std::string> &exclude, int ifmatched, std::string &attribution, std::string &description, std::set<std::string> &keep_layers, std::set<std::string> &remove_layers, std::string &name, json_object *filter, std::map<std::string, std::string> &attribute_descriptions, std::string &generator_options) {
void decode(struct reader *readers, std::map<std::string, layermap_entry> &layermap, sqlite3 *outdb, const char *outdir, struct stats *st, std::vector<std::string> &header, std::map<std::string, std::vector<std::string>> &mapping, std::set<std::string> &exclude, int ifmatched, std::string &attribution, std::string &description, std::set<std::string> &keep_layers, std::set<std::string> &remove_layers, std::string &name, json_object *filter, std::map<std::string, std::string> &attribute_descriptions, std::string &generator_options, std::vector<strategy> *strategies) {
std::vector<std::map<std::string, layermap_entry>> layermaps;
for (size_t i = 0; i < CPUS; i++) {
layermaps.push_back(std::map<std::string, layermap_entry>());
@@ -840,11 +890,18 @@ void decode(struct reader *readers, std::map<std::string, layermap_entry> &layer
}
sqlite3_finalize(r->stmt);
}
if (sqlite3_prepare_v2(db, "SELECT value from metadata where name = 'strategies'", -1, &r->stmt, NULL) == SQLITE_OK) {
if (sqlite3_step(r->stmt) == SQLITE_ROW) {
const unsigned char *s = sqlite3_column_text(r->stmt, 0);
handle_strategies(s, strategies);
}
sqlite3_finalize(r->stmt);
}
// Closes either real db or temp mirror of metadata.json
if (sqlite3_close(db) != SQLITE_OK) {
fprintf(stderr, "Could not close database: %s\n", sqlite3_errmsg(db));
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
delete r;
@@ -853,7 +910,7 @@ void decode(struct reader *readers, std::map<std::string, layermap_entry> &layer
void usage(char **argv) {
fprintf(stderr, "Usage: %s [-f] [-i] [-pk] [-pC] [-c joins.csv] [-X] [-x exclude ...] -o new.mbtiles source.mbtiles ...\n", argv[0]);
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
int main(int argc, char **argv) {
@@ -994,14 +1051,14 @@ int main(int argc, char **argv) {
pe = true;
} else {
fprintf(stderr, "%s: Unknown option for -p%s\n", argv[0], optarg);
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
break;
case 'c':
if (csv != NULL) {
fprintf(stderr, "Only one -c for now\n");
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
csv = optarg;
@@ -1028,7 +1085,7 @@ int main(int argc, char **argv) {
char *cp = strchr(optarg, ':');
if (cp == NULL || cp == optarg) {
fprintf(stderr, "%s: -R requires old:new\n", argv[0]);
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
std::string before = std::string(optarg).substr(0, cp - optarg);
std::string after = std::string(cp + 1);
@@ -1050,7 +1107,7 @@ int main(int argc, char **argv) {
max_tilestats_values = atoi(optarg);
} else {
fprintf(stderr, "%s: Unrecognized option --%s\n", argv[0], opt);
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
break;
}
@@ -1076,7 +1133,7 @@ int main(int argc, char **argv) {
if (minzoom > maxzoom) {
fprintf(stderr, "%s: Minimum zoom -Z%d cannot be greater than maxzoom -z%d\n", argv[0], minzoom, maxzoom);
exit(EXIT_FAILURE);
exit(EXIT_ARGS);
}
if (out_mbtiles != NULL) {
@@ -1117,8 +1174,9 @@ int main(int argc, char **argv) {
std::map<std::string, std::string> attribute_descriptions;
std::string generator_options;
std::vector<strategy> strategies;
decode(readers, layermap, outdb, out_dir, &st, header, mapping, exclude, ifmatched, attribution, description, keep_layers, remove_layers, name, filter, attribute_descriptions, generator_options);
decode(readers, layermap, outdb, out_dir, &st, header, mapping, exclude, ifmatched, attribution, description, keep_layers, remove_layers, name, filter, attribute_descriptions, generator_options, &strategies);
if (set_attribution.size() != 0) {
attribution = set_attribution;
@@ -1144,8 +1202,6 @@ int main(int argc, char **argv) {
}
}
std::vector<strategy> strategies;
mbtiles_write_metadata(outdb, out_dir, name.c_str(), st.minzoom, st.maxzoom, st.minlat, st.minlon, st.maxlat, st.maxlon, st.midlat, st.midlon, 0, attribution.size() != 0 ? attribution.c_str() : NULL, layermap, true, description.c_str(), !pg, attribute_descriptions, "tile-join", generator_options, strategies);
if (outdb != NULL) {
+97 -76
View File
@@ -39,6 +39,7 @@
#include "write_json.hpp"
#include "milo/dtoa_milo.h"
#include "evaluator.hpp"
#include "errors.hpp"
extern "C" {
#include "jsonpull/jsonpull.h"
@@ -819,7 +820,7 @@ bool find_common_edges(std::vector<partial> &partials, int z, int line_detail, d
if (e1.first == e1.second || e2.first == e2.second) {
fprintf(stderr, "Internal error: polygon edge lookup failed for %lld,%lld to %lld,%lld or %lld,%lld to %lld,%lld\n", left[0].x, left[0].y, left[1].x, left[1].y, right[0].x, right[0].y, right[1].x, right[1].y);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
if (!edges_same(e1, e2)) {
@@ -896,7 +897,7 @@ bool find_common_edges(std::vector<partial> &partials, int z, int line_detail, d
if (tmp.size() != l - k) {
fprintf(stderr, "internal error shifting ring\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
for (size_t m = 0; m < tmp.size(); m++) {
@@ -916,7 +917,7 @@ bool find_common_edges(std::vector<partial> &partials, int z, int line_detail, d
for (size_t m = k; m < l; m++) {
if (!g[m].necessary) {
fprintf(stderr, "internal error in arc building\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
drawvec arc;
@@ -1596,7 +1597,7 @@ void *run_prefilter(void *v) {
decode_meta(sf.keys, sf.values, rpa->stringpool + rpa->pool_off[sf.segment], tmp_layer, tmp_feature);
tmp_layer.features.push_back(tmp_feature);
layer_to_geojson(tmp_layer, 0, 0, 0, false, true, false, true, sf.index, sf.seq, sf.extent, true, state);
layer_to_geojson(tmp_layer, 0, 0, 0, false, true, false, true, sf.index, sf.seq, sf.extent, true, state, 0);
}
if (fclose(rpa->prefilter_fp) != 0) {
@@ -1608,7 +1609,7 @@ void *run_prefilter(void *v) {
}
} else {
perror("fclose output to prefilter");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
return NULL;
@@ -1632,7 +1633,7 @@ void add_tilestats(std::string const &layername, int z, std::vector<std::map<std
auto fk = layermap.find(layername);
if (fk == layermap.end()) {
fprintf(stderr, "Internal error: layer %s not found\n", layername.c_str());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
type_and_string attrib;
@@ -1803,11 +1804,11 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
int max_zoom_increment = std::log(child_shards) / std::log(4);
if (child_shards < 4 || max_zoom_increment < 1) {
fprintf(stderr, "Internal error: %d shards, max zoom increment %d\n", child_shards, max_zoom_increment);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
if ((((child_shards - 1) << 1) & child_shards) != child_shards) {
fprintf(stderr, "Internal error: %d shards not a power of 2\n", child_shards);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
int nextzoom = z + 1;
@@ -1848,6 +1849,8 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
drawvec shared_nodes;
int tile_detail = line_detail;
size_t skipped = 0;
size_t kept = 0;
int within[child_shards];
std::atomic<long long> geompos[child_shards];
@@ -1859,7 +1862,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
if (*geompos_in != og) {
if (fseek(geoms, og, SEEK_SET) != 0) {
perror("fseek geom");
exit(EXIT_FAILURE);
exit(EXIT_SEEK);
}
*geompos_in = og;
}
@@ -1882,7 +1885,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
prefilter_fp = fdopen(prefilter_write, "w");
if (prefilter_fp == NULL) {
perror("freopen prefilter");
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
rpa.geoms = geoms;
@@ -1921,13 +1924,13 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
if (pthread_create(&prefilter_writer, NULL, run_prefilter, &rpa) != 0) {
perror("pthread_create (prefilter writer)");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
prefilter_read_fp = fdopen(prefilter_read, "r");
if (prefilter_read_fp == NULL) {
perror("fdopen prefilter output");
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
prefilter_jp = json_begin_file(prefilter_read_fp);
}
@@ -2074,47 +2077,55 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
}
if (sf.geometry.size() > 0) {
if (prevent[P_SIMPLIFY_SHARED_NODES]) {
for (auto &g : sf.geometry) {
shared_nodes.push_back(g);
if (partials.size() > max_tile_size) {
// Even being maximally conservative, each feature is still going to be
// at least one byte in the output tile, so this can't possibly work.
skipped++;
} else {
kept++;
if (prevent[P_SIMPLIFY_SHARED_NODES]) {
for (auto &g : sf.geometry) {
shared_nodes.push_back(g);
}
}
}
partial p;
p.geoms.push_back(sf.geometry);
p.layer = sf.layer;
p.t = sf.t;
p.segment = sf.segment;
p.original_seq = sf.seq;
p.reduced = reduced;
p.z = z;
p.line_detail = line_detail;
p.extra_detail = line_detail;
p.maxzoom = maxzoom;
p.keys = sf.keys;
p.values = sf.values;
p.full_keys = sf.full_keys;
p.full_values = sf.full_values;
p.spacing = spacing;
p.simplification = simplification;
p.id = sf.id;
p.has_id = sf.has_id;
p.index = sf.index;
p.renamed = -1;
p.extent = sf.extent;
p.clustered = 0;
partial p;
p.geoms.push_back(sf.geometry);
p.layer = sf.layer;
p.t = sf.t;
p.segment = sf.segment;
p.original_seq = sf.seq;
p.reduced = reduced;
p.z = z;
p.line_detail = line_detail;
p.extra_detail = line_detail;
p.maxzoom = maxzoom;
p.keys = sf.keys;
p.values = sf.values;
p.full_keys = sf.full_keys;
p.full_values = sf.full_values;
p.spacing = spacing;
p.simplification = simplification;
p.id = sf.id;
p.has_id = sf.has_id;
p.index = sf.index;
p.renamed = -1;
p.extent = sf.extent;
p.clustered = 0;
if (line_detail == detail && extra_detail >= 0 && z == maxzoom) {
p.extra_detail = extra_detail;
// maximum allowed coordinate delta in geometries is 2^31 - 1
// so we need to stay under that, including the buffer
if (p.extra_detail >= 30 - z) {
p.extra_detail = 30 - z;
if (line_detail == detail && extra_detail >= 0 && z == maxzoom) {
p.extra_detail = extra_detail;
// maximum allowed coordinate delta in geometries is 2^31 - 1
// so we need to stay under that, including the buffer
if (p.extra_detail >= 30 - z) {
p.extra_detail = 30 - z;
}
tile_detail = p.extra_detail;
}
tile_detail = p.extra_detail;
}
partials.push_back(p);
partials.push_back(p);
}
}
merge_previndex = sf.index;
@@ -2184,13 +2195,13 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
json_end(prefilter_jp);
if (fclose(prefilter_read_fp) != 0) {
perror("close output from prefilter");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
while (1) {
int stat_loc;
if (waitpid(prefilter_pid, &stat_loc, 0) < 0) {
perror("waitpid for prefilter\n");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
if (WIFEXITED(stat_loc) || WIFSIGNALED(stat_loc)) {
break;
@@ -2199,7 +2210,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
void *ret;
if (pthread_join(prefilter_writer, &ret) != 0) {
perror("pthread_join prefilter writer");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
}
@@ -2227,7 +2238,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
if (tasks > 1) {
if (pthread_create(&pthreads[i], NULL, partial_feature_worker, &args[i]) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
} else {
partial_feature_worker(&args[i]);
@@ -2282,7 +2293,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
fprintf(stderr, "Internal error: couldn't find layer %s\n", layername.c_str());
fprintf(stderr, "segment %d\n", partials[i].segment);
fprintf(stderr, "layer %lld\n", partials[i].layer);
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
l->second.push_back(c);
}
@@ -2504,7 +2515,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
line_detail++;
continue;
} else if (additional[A_DROP_SMALLEST_AS_NEEDED] || additional[A_COALESCE_SMALLEST_AS_NEEDED]) {
minextent_fraction = minextent_fraction * max_tile_features / totalsize * 0.90;
minextent_fraction = minextent_fraction * max_tile_features / totalsize * 0.75;
long long m = choose_minextent(extents, minextent_fraction);
if (m != minextent) {
minextent = m;
@@ -2550,16 +2561,26 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
}
if (compressed.size() > max_tile_size && !prevent[P_KILOBYTE_LIMIT]) {
// Estimate how big it really should have been compressed
// from how many features were kept vs skipped for already being
// over the threshold
double kept_adjust = (skipped + kept) / (double) kept;
if (compressed.size() > arg->tile_size_out) {
arg->tile_size_out = compressed.size();
arg->tile_size_out = compressed.size() * kept_adjust;
}
if (!quiet) {
fprintf(stderr, "tile %d/%u/%u size is %lld with detail %d, >%zu \n", z, tx, ty, (long long) compressed.size(), line_detail, max_tile_size);
if (skipped > 0) {
fprintf(stderr, "tile %d/%u/%u size is %lld (probably really %lld) with detail %d, >%zu \n", z, tx, ty, (long long) compressed.size(), (long long) (compressed.size() * kept_adjust), line_detail, max_tile_size);
} else {
fprintf(stderr, "tile %d/%u/%u size is %lld with detail %d, >%zu \n", z, tx, ty, (long long) compressed.size(), line_detail, max_tile_size);
}
}
if (has_polygons && additional[A_MERGE_POLYGONS_AS_NEEDED] && merge_fraction > .05 && merge_successful) {
merge_fraction = merge_fraction * max_tile_size / compressed.size() * 0.95;
merge_fraction = merge_fraction * max_tile_size / (kept_adjust * compressed.size()) * 0.95;
if (!quiet) {
fprintf(stderr, "Going to try merging %0.2f%% of the polygons to make it fit\n", 100 - merge_fraction * 100);
}
@@ -2581,7 +2602,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
}
line_detail++; // to keep it the same when the loop decrements it
} else if (mingap < ULONG_MAX && (additional[A_DROP_DENSEST_AS_NEEDED] || additional[A_COALESCE_DENSEST_AS_NEEDED] || additional[A_CLUSTER_DENSEST_AS_NEEDED])) {
mingap_fraction = mingap_fraction * max_tile_size / compressed.size() * 0.90;
mingap_fraction = mingap_fraction * max_tile_size / (kept_adjust * compressed.size()) * 0.90;
unsigned long long mg = choose_mingap(indices, mingap_fraction);
if (mg <= mingap) {
double nmg = (mingap + 1) * 1.5;
@@ -2606,7 +2627,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
}
line_detail++;
} else if (additional[A_DROP_SMALLEST_AS_NEEDED] || additional[A_COALESCE_SMALLEST_AS_NEEDED]) {
minextent_fraction = minextent_fraction * max_tile_size / compressed.size() * 0.90;
minextent_fraction = minextent_fraction * max_tile_size / (kept_adjust * compressed.size()) * 0.75;
long long m = choose_minextent(extents, minextent_fraction);
if (m != minextent) {
minextent = m;
@@ -2624,7 +2645,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
// The 95% is a guess to avoid too many retries
// and probably actually varies based on how much duplicated metadata there is
fraction = fraction * max_tile_size / compressed.size() * 0.95;
fraction = fraction * max_tile_size / (kept_adjust * compressed.size()) * 0.95;
if (!quiet) {
fprintf(stderr, "Going to try keeping %0.2f%% of the features to make it fit\n", fraction * 100);
}
@@ -2642,7 +2663,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
if (pass == 1) {
if (pthread_mutex_lock(&db_lock) != 0) {
perror("pthread_mutex_lock");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
if (outdb != NULL) {
@@ -2653,7 +2674,7 @@ long long write_tile(FILE *geoms, std::atomic<long long> *geompos_in, char *meta
if (pthread_mutex_unlock(&db_lock) != 0) {
perror("pthread_mutex_unlock");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
}
@@ -2692,8 +2713,8 @@ void *run_thread(void *vargs) {
FILE *geom = fdopen(arg->geomfd[j], "rb");
if (geom == NULL) {
perror("mmap geom");
exit(EXIT_FAILURE);
perror("open geom");
exit(EXIT_OPEN);
}
std::atomic<long long> geompos(0);
@@ -2723,7 +2744,7 @@ void *run_thread(void *vargs) {
if (pthread_mutex_lock(&var_lock) != 0) {
perror("pthread_mutex_lock");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
if (z == arg->maxzoom) {
@@ -2748,7 +2769,7 @@ void *run_thread(void *vargs) {
if (pthread_mutex_unlock(&var_lock) != 0) {
perror("pthread_mutex_unlock");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
}
@@ -2759,18 +2780,18 @@ void *run_thread(void *vargs) {
int newfd = dup(arg->geomfd[j]);
if (newfd < 0) {
perror("dup geometry");
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
if (lseek(newfd, 0, SEEK_SET) < 0) {
perror("lseek geometry");
exit(EXIT_FAILURE);
exit(EXIT_SEEK);
}
arg->geomfd[j] = newfd;
}
if (fclose(geom) != 0) {
perror("close geom");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
@@ -2815,12 +2836,12 @@ int traverse_zooms(int *geomfd, off_t *geom_size, char *metabase, char *stringpo
// printf("%s\n", geomname);
if (subfd[j] < 0) {
perror(geomname);
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
sub[j] = fopen_oflag(geomname, "wb", O_WRONLY | O_CLOEXEC);
if (sub[j] == NULL) {
perror(geomname);
exit(EXIT_FAILURE);
exit(EXIT_OPEN);
}
unlink(geomname);
}
@@ -2982,7 +3003,7 @@ int traverse_zooms(int *geomfd, off_t *geom_size, char *metabase, char *stringpo
if (pthread_create(&pthreads[thread], NULL, run_thread, &args[thread]) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
exit(EXIT_PTHREAD);
}
}
@@ -3035,18 +3056,18 @@ int traverse_zooms(int *geomfd, off_t *geom_size, char *metabase, char *stringpo
if (geomfd[j] >= 0) {
if (close(geomfd[j]) != 0) {
perror("close geom");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
if (fclose(sub[j]) != 0) {
perror("close subfile");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
struct stat geomst;
if (fstat(subfd[j], &geomst) != 0) {
perror("stat geom\n");
exit(EXIT_FAILURE);
exit(EXIT_STAT);
}
geomfd[j] = subfd[j];
@@ -3063,7 +3084,7 @@ int traverse_zooms(int *geomfd, off_t *geom_size, char *metabase, char *stringpo
if (geomfd[j] >= 0) {
if (close(geomfd[j]) != 0) {
perror("close geom");
exit(EXIT_FAILURE);
exit(EXIT_CLOSE);
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
#ifndef VERSION_HPP
#define VERSION_HPP
#define VERSION "v2.6.0"
#define VERSION "v2.6.2"
#endif
+34 -31
View File
@@ -14,6 +14,7 @@
#include "mvt.hpp"
#include "write_json.hpp"
#include "milo/dtoa_milo.h"
#include "errors.hpp"
void json_writer::json_adjust() {
if (state.size() == 0) {
@@ -62,7 +63,7 @@ void json_writer::json_adjust() {
state[state.size() - 1] = JSON_WRITE_ARRAY_ELEMENT;
} else {
fprintf(stderr, "Impossible JSON state\n");
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
}
@@ -76,7 +77,7 @@ void json_writer::json_write_array() {
void json_writer::json_end_array() {
if (state.size() == 0) {
fprintf(stderr, "End JSON array at top level\n");
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_write_tok tok = state[state.size() - 1];
@@ -90,7 +91,7 @@ void json_writer::json_end_array() {
addc(']');
} else {
fprintf(stderr, "End JSON array with unexpected state\n");
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
}
@@ -104,7 +105,7 @@ void json_writer::json_write_hash() {
void json_writer::json_end_hash() {
if (state.size() == 0) {
fprintf(stderr, "End JSON hash at top level\n");
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
json_write_tok tok = state[state.size() - 1];
@@ -124,7 +125,7 @@ void json_writer::json_end_hash() {
addc('}');
} else {
fprintf(stderr, "End JSON hash with unexpected state\n");
exit(EXIT_FAILURE);
exit(EXIT_JSON);
}
}
@@ -207,7 +208,7 @@ void json_writer::aprintf(const char *format, ...) {
va_start(ap, format);
if (vasprintf(&tmp, format, ap) < 0) {
fprintf(stderr, "memory allocation failure\n");
exit(EXIT_FAILURE);
exit(EXIT_MEMORY);
}
va_end(ap);
@@ -247,7 +248,17 @@ struct lonlat {
}
};
void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y, bool comma, bool name, bool zoom, bool dropped, unsigned long long index, long long sequence, long long extent, bool complain, json_writer &state) {
void write_coords(json_writer &state, lonlat const &ll, double scale) {
if (scale == 0) {
state.json_write_float(ll.lon);
state.json_write_float(ll.lat);
} else {
state.json_write_number(ll.x / scale);
state.json_write_number(ll.y / scale);
}
}
void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y, bool comma, bool name, bool zoom, bool dropped, unsigned long long index, long long sequence, long long extent, bool complain, json_writer &state, double scale) {
for (size_t f = 0; f < layer.features.size(); f++) {
mvt_feature const &feat = layer.features[f];
@@ -306,11 +317,11 @@ void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y
for (size_t t = 0; t + 1 < feat.tags.size(); t += 2) {
if (feat.tags[t] >= layer.keys.size()) {
fprintf(stderr, "Error: out of bounds feature key (%u in %zu)\n", feat.tags[t], layer.keys.size());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
if (feat.tags[t + 1] >= layer.values.size()) {
fprintf(stderr, "Error: out of bounds feature value (%u in %zu)\n", feat.tags[t + 1], layer.values.size());
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
const char *key = layer.keys[feat.tags[t]].c_str();
@@ -342,7 +353,7 @@ void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y
state.json_write_null();
} else {
fprintf(stderr, "Internal error: property with unknown type\n");
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
}
@@ -359,9 +370,9 @@ void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y
long long py = feat.geometry[g].y;
if (op == VT_MOVETO || op == VT_LINETO) {
long long scale = 1LL << (32 - z);
long long wx = scale * x + (scale / layer.extent) * px;
long long wy = scale * y + (scale / layer.extent) * py;
long long wscale = 1LL << (32 - z);
long long wx = wscale * x + (wscale / layer.extent) * px;
long long wy = wscale * y + (wscale / layer.extent) * py;
double lat, lon;
projection->unproject(wx, wy, 32, &lon, &lat);
@@ -380,8 +391,7 @@ void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y
state.json_write_string("coordinates");
state.json_write_array();
state.json_write_float(ops[0].lon);
state.json_write_float(ops[0].lat);
write_coords(state, ops[0], scale);
state.json_end_array();
} else {
state.json_write_string("type");
@@ -392,8 +402,7 @@ void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y
for (size_t i = 0; i < ops.size(); i++) {
state.json_write_array();
state.json_write_float(ops[i].lon);
state.json_write_float(ops[i].lat);
write_coords(state, ops[i], scale);
state.json_end_array();
}
@@ -416,8 +425,7 @@ void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y
for (size_t i = 0; i < ops.size(); i++) {
state.json_write_array();
state.json_write_float(ops[i].lon);
state.json_write_float(ops[i].lat);
write_coords(state, ops[i], scale);
state.json_end_array();
}
@@ -435,8 +443,7 @@ void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y
if (ops[i].op == VT_MOVETO) {
if (sstate == 0) {
state.json_write_array();
state.json_write_float(ops[i].lon);
state.json_write_float(ops[i].lat);
write_coords(state, ops[i], scale);
state.json_end_array();
sstate = 1;
@@ -445,16 +452,14 @@ void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y
state.json_write_array();
state.json_write_array();
state.json_write_float(ops[i].lon);
state.json_write_float(ops[i].lat);
write_coords(state, ops[i], scale);
state.json_end_array();
sstate = 1;
}
} else {
state.json_write_array();
state.json_write_float(ops[i].lon);
state.json_write_float(ops[i].lat);
write_coords(state, ops[i], scale);
state.json_end_array();
}
}
@@ -488,7 +493,7 @@ void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y
if (!warned) {
fprintf(stderr, "Ring does not end with closepath (ends with %d)\n", ops[i].op);
if (complain) {
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
warned = true;
@@ -542,7 +547,7 @@ void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y
if (!warned) {
fprintf(stderr, "Polygon begins with an inner ring\n");
if (complain) {
exit(EXIT_FAILURE);
exit(EXIT_IMPOSSIBLE);
}
warned = true;
@@ -570,13 +575,11 @@ void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y
for (size_t j = 0; j < rings[i].size(); j++) {
if (rings[i][j].op != VT_CLOSEPATH) {
state.json_write_array();
state.json_write_float(rings[i][j].lon);
state.json_write_float(rings[i][j].lat);
write_coords(state, rings[i][j], scale);
state.json_end_array();
} else {
state.json_write_array();
state.json_write_float(rings[i][0].lon);
state.json_write_float(rings[i][0].lat);
write_coords(state, rings[i][j], scale);
state.json_end_array();
}
}
+1 -1
View File
@@ -60,7 +60,7 @@ struct json_writer {
void adds(std::string const &s);
};
void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y, bool comma, bool name, bool zoom, bool dropped, unsigned long long index, long long sequence, long long extent, bool complain, json_writer &state);
void layer_to_geojson(mvt_layer const &layer, unsigned z, unsigned x, unsigned y, bool comma, bool name, bool zoom, bool dropped, unsigned long long index, long long sequence, long long extent, bool complain, json_writer &state, double scale);
void fprintq(FILE *f, const char *s);
#endif