Skip to content

Commit fd1201a

Browse files
committed
Refactor mapbox::feature::value
- add converting constructors - add `bool` operator - add uint tests
1 parent e6870e7 commit fd1201a

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed

include/mapbox/feature.hpp

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,37 @@ using value_base = mapbox::util::variant<null_value_t, bool, uint64_t, int64_t,
3333
mapbox::util::recursive_wrapper<std::vector<value>>,
3434
mapbox::util::recursive_wrapper<std::unordered_map<std::string, value>>>;
3535

36-
struct value : value_base
36+
struct value : public value_base
3737
{
38-
using value_base::value_base;
38+
using array_type = std::vector<value>;
39+
using object_type = std::unordered_map<std::string, value>;
40+
41+
value() : value_base(null_value) {}
42+
value(null_value_t) : value_base(null_value) {}
43+
value(bool v) : value_base(v) {}
44+
value(const char* c) : value_base(std::string(c)) {}
45+
value(std::string str) : value_base(std::move(str)) {}
46+
47+
template <typename T, typename std::enable_if_t<std::is_integral<T>::value, int> = 0,
48+
typename std::enable_if_t<std::is_signed<T>::value, int> = 0>
49+
value(T t) : value_base(int64_t(t))
50+
{
51+
}
52+
53+
template <typename T, typename std::enable_if_t<std::is_integral<T>::value, int> = 0,
54+
typename std::enable_if_t<!std::is_signed<T>::value, int> = 0>
55+
value(T t) : value_base(uint64_t(t))
56+
{
57+
}
58+
59+
template <typename T, typename std::enable_if_t<std::is_floating_point<T>::value, int> = 0>
60+
value(T t) : value_base(double(t))
61+
{
62+
}
63+
value(array_type array) : value_base(std::move(array)) {}
64+
value(object_type object) : value_base(std::move(object)) {}
65+
66+
explicit operator bool() const { return !is<null_value_t>(); }
3967
};
4068

4169
using property_map = std::unordered_map<std::string, value>;

test/feature.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,36 @@ using mapbox::feature::feature;
77
using mapbox::feature::feature_collection;
88
using mapbox::feature::null_value;
99
using mapbox::feature::null_value_t;
10+
using mapbox::feature::value;
11+
12+
namespace {
13+
14+
template <typename T, typename U>
15+
void checkType(U&& arg) try
16+
{
17+
value v{std::forward<U>(arg)};
18+
CHECK(v);
19+
CHECK(v.template is<T>());
20+
CHECK(v.template get<T>() == arg);
21+
}
22+
catch (...)
23+
{
24+
FAIL();
25+
}
26+
27+
} // namespace
28+
29+
TEST_CASE("test value")
30+
{
31+
CHECK(!value());
32+
checkType<int64_t>(32);
33+
checkType<uint64_t>(32u);
34+
checkType<bool>(false);
35+
checkType<std::string>("hello");
36+
37+
value intV{32};
38+
CHECK_THROWS(intV.get<uint64_t>());
39+
}
1040

1141
TEST_CASE("test feature")
1242
{

0 commit comments

Comments
 (0)