From 2c4e7ae70f68eecf56707f0ebd9810340f41e6a3 Mon Sep 17 00:00:00 2001 From: Ivo van Dongen Date: Mon, 28 Nov 2016 17:35:10 +0200 Subject: [PATCH] =?UTF-8?q?[core]=20guard=20against=20duplicate=20source?= =?UTF-8?q?=20id=E2=80=99s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/mbgl/style/style.cpp | 10 ++++++++++ test/style/style.test.cpp | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/mbgl/style/style.cpp b/src/mbgl/style/style.cpp index d57f5cf98..e55119f9f 100644 --- a/src/mbgl/style/style.cpp +++ b/src/mbgl/style/style.cpp @@ -136,6 +136,16 @@ void Style::setJSON(const std::string& json) { } void Style::addSource(std::unique_ptr source) { + //Guard against duplicate source ids + auto it = std::find_if(sources.begin(), sources.end(), [&](const auto& existing) { + return existing->getID() == source->getID(); + }); + + if (it != sources.end()) { + std::string msg = "Source " + source->getID() + " already exists"; + throw std::runtime_error(msg.c_str()); + } + source->baseImpl->setObserver(this); sources.emplace_back(std::move(source)); } diff --git a/test/style/style.test.cpp b/test/style/style.test.cpp index 41f12f6ff..89c5c4ce6 100644 --- a/test/style/style.test.cpp +++ b/test/style/style.test.cpp @@ -3,10 +3,13 @@ #include #include +#include #include #include #include +#include + using namespace mbgl; using namespace mbgl::style; @@ -113,3 +116,21 @@ TEST(Style, Properties) { ASSERT_EQ(0, style.getDefaultZoom()); ASSERT_EQ(0, style.getDefaultPitch()); } + +TEST(Style, DuplicateSource) { + util::RunLoop loop; + + StubFileSource fileSource; + Style style { fileSource, 1.0 }; + + style.setJSON(util::read_file("test/fixtures/resources/style-unused-sources.json")); + + style.addSource(std::make_unique("sourceId", "mapbox://mapbox.mapbox-terrain-v2")); + + try { + style.addSource(std::make_unique("sourceId", "mapbox://mapbox.mapbox-terrain-v2")); + FAIL() << "Should not have been allowed to add a duplicate source id"; + } catch (std::runtime_error) { + //Expected + } +}