Merge branch 'value-at'

This commit is contained in:
ToruNiina
2019-09-28 19:40:51 +09:00
3 changed files with 67 additions and 0 deletions

View File

@@ -454,6 +454,22 @@ class value {
} // toml
```
### `at()`
You can access to the element of a table and an array by `toml::basic_value::at`.
```cpp
const toml::value v{1,2,3,4,5};
std::cout << v.at(2).as_integer() << std::endl; // 3
const toml::value v{{"foo", 42}, {"bar", 3.14}};
std::cout << v.at("foo").as_integer() << std::endl; // 42
```
If an invalid key (integer for a table, string for an array), it throws
`toml::type_error` for the conversion. If the provided key is out-of-range,
it throws `std::out_of_range`.
## Checking value type
You can check the type of a value by `is_xxx` function.

View File

@@ -905,3 +905,32 @@ BOOST_AUTO_TEST_CASE(test_value_empty)
BOOST_CHECK_THROW(v1.as_array(), toml::type_error);
BOOST_CHECK_THROW(v1.as_table(), toml::type_error);
}
BOOST_AUTO_TEST_CASE(test_value_at)
{
{
toml::value v1{{"foo", 42}, {"bar", 3.14}, {"baz", "qux"}};
BOOST_TEST(v1.at("foo").as_integer() == 42);
BOOST_TEST(v1.at("bar").as_floating() == 3.14);
BOOST_TEST(v1.at("baz").as_string() == "qux");
BOOST_CHECK_THROW(v1.at(0), toml::type_error);
BOOST_CHECK_THROW(v1.at("quux"), std::out_of_range);
}
{
toml::value v1{1,2,3,4,5};
BOOST_TEST(v1.at(0).as_integer() == 1);
BOOST_TEST(v1.at(1).as_integer() == 2);
BOOST_TEST(v1.at(2).as_integer() == 3);
BOOST_TEST(v1.at(3).as_integer() == 4);
BOOST_TEST(v1.at(4).as_integer() == 5);
BOOST_CHECK_THROW(v1.at("foo"), toml::type_error);
BOOST_CHECK_THROW(v1.at(5), std::out_of_range);
}
}

View File

@@ -1567,6 +1567,28 @@ class basic_value
return std::move(this->table_.value());
}
// accessors =============================================================
//
// may throw type_error or out_of_range
//
value_type& at(const key& k)
{
return this->as_table().at(k);
}
value_type const& at(const key& k) const
{
return this->as_table().at(k);
}
value_type& at(const std::size_t idx)
{
return this->as_array().at(idx);
}
value_type const& at(const std::size_t idx) const
{
return this->as_array().at(idx);
}
source_location location() const
{
return source_location(this->region_info_.get());