Compare commits

..

863 Commits

Author SHA1 Message Date
ToruNiina
a344668fa2 doc: update version to 3.5.0 2020-07-19 19:12:18 +09:00
ToruNiina
25aa97a435 doc: add actions status badge to README 2020-07-19 19:09:47 +09:00
ToruNiina
af70d3dfed ci [skip ci]: add github actions workflow file 2020-07-19 17:13:39 +09:00
ToruNiina
8b5cfb4105 test: add missing binary flag to ifstream 2020-07-19 16:57:20 +09:00
ToruNiina
4e0624aa60 feat: make sure the last null is removed 2020-07-19 16:56:31 +09:00
ToruNiina
3ac2c065eb Merge branch 'reorder-headers' to master 2020-07-17 15:17:40 +09:00
ToruNiina
470f81dc94 fix: #123 merge branch 'windows-nominmax' 2020-07-10 20:55:53 +09:00
ToruNiina
93a9f2711c test: add windows.h test 2020-07-10 18:32:59 +09:00
ToruNiina
761e576991 fix: workaround for windows.h that defines min/max
related to #123
2020-07-10 15:07:13 +09:00
ToruNiina
e6e84714c5 Merge branch 'master' into reorder-headers 2020-07-10 00:06:22 +09:00
Toru Niina
1efc99e11c Merge pull request #121 from SeverinLeonhardt/fix_msvc_c4866
Fix MSVC warning C4866
2020-07-03 21:37:22 +09:00
Marius Maaß
92aa42a58e Fix MSVC warning C4866
This fixes the warning "compiler may not enforce left-to-right
evaluation order for call to" that is caused by Visual Studio if this is
compiled with a target of C++17.
2020-07-03 08:00:47 +02:00
ToruNiina
b1c9df8998 feat: reorder headers following google c++ style
related to: #115
2020-06-28 00:58:20 +09:00
ToruNiina
9633e5fe5a doc: add iteration examples into as_xxx section
related to #120
2020-06-21 14:11:26 +09:00
ToruNiina
2164fd39f7 doc: explain about the type of the top-level value
fix #120.
2020-06-21 14:04:20 +09:00
ToruNiina
c22a3fd227 feat: support parse(std::filesystem::path) #113 2020-06-07 15:11:48 +09:00
ToruNiina
57c6652360 Merge branch 'master' into std-filesystem 2020-06-06 17:25:26 +09:00
ToruNiina
defde33544 fix: avoid ambiguity in overload resolution
Since both `std::string` and `std::filesystem::path` can be convertible
from `const char &[N]` (like, `parse("file.toml")`), after adding
`parse(std::filesystem::path)`, the overload resolution of
`parse("file.toml")` becomes ambiguous. By adding `parse(...)` that
exactly matches to `parse("file.toml")`, we can remove this ambiguity.
2020-06-06 17:18:02 +09:00
ToruNiina
46ed051740 fix: pass path.string as a filename 2020-06-05 23:15:19 +09:00
ToruNiina
2963d9a25b feat: add std::filesystem::path support 2020-06-05 19:43:23 +09:00
Toru Niina
531f335417 Merge pull request #119 from halfelf/fix/readme_finding_value_in_table
fix: "Finding a value in an array" example in README
2020-05-20 00:27:33 +09:00
Shu Wang
f29f42277e fix: "Finding a value in an array" example in README 2020-05-18 13:53:48 +08:00
Toru Niina
b03cde566a Merge pull request #117 from usefulcat/master
when parsing a local_time, parse up to 9 digits worth (nanoseconds) o…
2020-05-11 13:36:23 +09:00
Scott McCaskill
57d4e196a3 when parsing a local_time, parse up to 9 digits worth (nanoseconds) of fractional seconds 2020-05-10 16:06:52 -05:00
ToruNiina
deb3ab6617 ci: add DISALLOW_HETEROGENEOUS_ARRAYS 2020-04-03 23:57:52 +09:00
ToruNiina
bf992e8f94 doc: update README for v1-rc1 2020-04-03 23:45:45 +09:00
ToruNiina
7c07f4382c ci: add DISALLOW_HETEROGENEOUS_ARRAYS to toml-test 2020-04-03 23:43:59 +09:00
ToruNiina
125f608fa5 feat: remove TOML11_UNRELEASED_FEATURES.
v1.0.0-rc.1 has been released
2020-04-03 23:42:58 +09:00
ToruNiina
4d0ed847f9 test: remove default ctor from test code 2020-03-30 15:04:51 +09:00
ToruNiina
79594709fe fix: don't use default ctor when converting to map 2020-03-30 15:02:26 +09:00
ToruNiina
55a738c11f Merge branch 'do-not-require-default-ctor-108'
fix #108.
2020-03-28 23:19:52 +09:00
ToruNiina
eebe1f87e6 fix: update cmake version 3.4.0 2020-03-28 17:59:10 +09:00
ToruNiina
95c3b5f538 feat: use push_back instead of resize 2020-03-27 18:06:26 +09:00
ToruNiina
e2790c9e7b test: remove test_resize and add test_try_reserve 2020-03-27 18:06:02 +09:00
ToruNiina
9b52dc0131 feat: remove resize and add try_reserve 2020-03-27 18:05:31 +09:00
ToruNiina
5212992f05 feat: add is_std_forward_list
std::forward_list does not have push_back, insert, or emplace but
push_front, insert_after, and emplace_after. We need to distinguish it
from other continers.
2020-03-27 18:02:37 +09:00
ToruNiina
fcd6e47500 feat: add meta funcs, has_reserve/push_back_method 2020-03-27 18:01:47 +09:00
ToruNiina
31826b55ce feat: avoid double checking in helper methods 2020-03-25 22:49:19 +09:00
ToruNiina
e3fc354e8d Merge branch 'shorten-switch-cast' 2020-03-24 22:43:09 +09:00
ToruNiina
ea87f92358 doc: update exception section in README (fix #107) 2020-03-23 20:57:36 +09:00
ToruNiina
c259456282 ci: fix Travis.CI OS X build 2020-03-22 20:40:02 +09:00
ToruNiina
d7662347f2 refactor: shorten switch_cast definition by macro 2020-03-21 17:44:23 +09:00
ToruNiina
5f5539d402 feat: throw informative error from value.at(...) 2020-03-21 17:09:04 +09:00
ToruNiina
c2151cab0b refactor: show func name in bad_cast from helpers 2020-03-21 17:06:34 +09:00
ToruNiina
653c87592c feat: enable to show function name in bad_cast 2020-03-21 17:04:05 +09:00
ToruNiina
bdf4e75122 refactor: move helper function from get to value 2020-03-21 16:57:12 +09:00
ToruNiina
60d23116ba Merge branch 'master' of github.com:ToruNiina/toml11 2020-03-13 14:38:33 +09:00
ToruNiina
af8cf9ddc5 refactor: remove redundant functions in serializer 2020-03-13 13:55:14 +09:00
ToruNiina
f125cca010 refactor: simplify serializer's template argument 2020-03-12 13:46:17 +09:00
ToruNiina
a20a2c0b80 doc: update README 2020-03-01 00:35:27 +09:00
ToruNiina
9694afbe32 Merge branch 'improve-error-message' 2020-02-29 23:43:23 +09:00
ToruNiina
d11e42ca7e fix: explicitly say the table is top-level
The top-level table has its region at the first character of the file.
That means that, in the case when a key is not found in the top-level
table, the error message points to the first character. If the file has
its first table at the first line, the error message would be like this.
```console
[error] key "a" not found
 --> example.toml
   |
 1 | [table]
   | ^------ in this table
```
It actually points to the top-level table at the first character,
not `[table]`. But it is too confusing. To avoid the confusion, the
error message should explicitly say "key not found in the top-level
table".
2020-02-29 22:56:29 +09:00
ToruNiina
128b66bda9 refactor: add missing whitespace 2020-02-29 22:54:50 +09:00
ToruNiina
d1af42f151 refactor: add throw_key_not_found_error
and replace related throw statements with it
2020-02-29 22:23:15 +09:00
ToruNiina
8acf105b56 doc: update contributor list and test commands 2020-02-27 19:30:34 +09:00
Toru Niina
b86b5364ba Merge pull request #103 from jwillikers/fix_tests
Use FetchContent to retrieve TOML test data
2020-02-27 19:13:02 +09:00
Jordan Williams
bfe57340f4 no longer explicitly clone the TOML repository in CI builds 2020-02-24 08:03:29 -06:00
Jordan Williams
02a6f029ad use ExternalProject to download the toml tests
In order to evaluate the relative paths correctly, add_test should use the current binary directory as the working directory.
2020-02-24 07:59:59 -06:00
Jordan Williams
9017900ff3 set version directly from CMake project command
This silences the warning for CMake policy CMP0048: https://cmake.org/cmake/help/v3.0/policy/CMP0048.html
2020-02-24 07:35:59 -06:00
Jordan Williams
3c5ebd73d7 require CMake version 3.1 2020-02-24 07:31:48 -06:00
Jordan Williams
2223eb4f62 Revert "no longer explicitly clone the TOML repository in CI builds"
This reverts commit fe644ea4b7.
2020-02-24 07:31:15 -06:00
Jordan Williams
a655a71cef Revert "use FetchContent to retrieve TOML test data"
This reverts commit 4c34986db0.
2020-02-24 07:31:06 -06:00
ToruNiina
c34001725c Merge branch 'workaround-gcc-48x' 2020-02-20 11:59:49 +09:00
ToruNiina
5e3ffb70dd fix: check clang macro when checking gcc is used 2020-02-19 17:00:22 +09:00
ToruNiina
2265ca41c6 ci: test with gcc 4.8 and 4.9 on CI 2020-02-19 15:47:34 +09:00
ToruNiina
82fec38e37 refactor: simplify internally-used function 2020-02-19 15:46:25 +09:00
ToruNiina
189b910384 fix: solve #97 in the naivest way, macros 2020-02-19 15:44:38 +09:00
Jordan Williams
fe644ea4b7 no longer explicitly clone the TOML repository in CI builds 2020-02-18 20:21:02 -06:00
Jordan Williams
4c34986db0 use FetchContent to retrieve TOML test data 2020-02-18 19:37:28 -06:00
ToruNiina
ac1130f9f4 tag: update patch version v3.3.1 2020-02-16 22:02:40 +09:00
ToruNiina
d290c3b7e5 doc: add contributor to README 2020-02-14 19:25:41 +09:00
Toru Niina
e4140ac1fd Merge pull request #102 from jwillikers/cmake_cache_variables
Set CMake Standard Cache Variables. Fixes #101
2020-02-13 13:22:25 +09:00
Jordan Williams
ef33c10ba8 use cache variables for the CMake standard and extensions settings 2020-02-12 07:44:47 -06:00
Toru Niina
ced710bb4c Merge pull request #100 from jwillikers/clang_warnings
Silence Clang Warnings. Fixes #98 & #99
2020-02-12 13:37:58 +09:00
Jordan Williams
6b5944e839 fix -Wundef warnings 2020-02-11 06:30:18 -06:00
Jordan Williams
76cae8c057 enable -Wundef flag for tests 2020-02-11 06:25:10 -06:00
Jordan Williams
3930a44ccd enable range-loop-analysis flag for tests 2020-02-11 06:17:54 -06:00
Jordan Williams
3b6417de00 fix clang range-loop-analysis warnings 2020-02-11 06:13:55 -06:00
ToruNiina
573a6f1d81 test: use JSON format_key to format a key in JSON
The rule to format a basic string and a key is different. `"""` cannot
be used with JSON keys. Also, toml key is basically not wrapped by `"`.
So we need a function to format a key in JSON.
2020-02-06 01:28:37 +09:00
ToruNiina
f6a41d986c feat: handle quotes in strings in the better way
- if a basic string contains any double quote, make it multiline.
  - because 1 or 2 consecutive "s do not require escape sequence in it.
- if a basic string will be sufficiently long, make it multiline.
- if 3 consecutive "s appeared, insert backslash to break it down.
2020-02-05 22:42:10 +09:00
ToruNiina
16fc172b21 feat: check string length before adding newline
In literal strings, only the first newline will be trimmed.
```toml
str = '''
The first newline will be trimmed.'''
```
The previous code always adds this first-newline, but after this commit
it checks the length of the string and adds newline if the string is
sufficiently long.
2020-02-05 22:39:08 +09:00
ToruNiina
7d03eb489a test: add test cases with quotes in ml-string
some of these example strings are copied from toml-lang/toml:README.md
and some are modified.
2020-02-04 22:37:11 +09:00
ToruNiina
0582e1535b fix: handle edge-cases with quotes in ml-string
See comments in the code for detail.
2020-02-04 22:36:39 +09:00
ToruNiina
d495df93a6 refactor: remove trailing whitespaces 2020-02-04 22:21:37 +09:00
ToruNiina
5ca3a3c262 refactor: change ifdef UNRELEASED_FEATURE region
to eliminate dead code after returning from a function
2020-02-04 21:05:03 +09:00
ToruNiina
aa8d574dfe chore: update minor version 2020-01-24 22:08:12 +09:00
ToruNiina
49fdb61731 refactor: add explicit to ctors of internal types 2020-01-24 15:58:24 +09:00
ToruNiina
b2bb21a473 doc: update year of copyright notice 2020-01-23 22:18:04 +09:00
ToruNiina
0c58549fc6 Merge branch 'master' of github.com:ToruNiina/toml11 2020-01-22 12:20:34 +09:00
ToruNiina
b7b5e847d3 ci: test with C++14, not only 11/17 2020-01-22 12:19:53 +09:00
ToruNiina
22d630fec1 feat: replace detail::stuff by std if possible 2020-01-20 12:18:05 +09:00
ToruNiina
f7bf341452 fix: add missing noexcept specifier 2020-01-19 21:06:10 +09:00
ToruNiina
0934d90f90 refactor: move ctors that are only used internally 2020-01-19 18:30:27 +09:00
ToruNiina
f2c8d0e279 refactor: add missing explicit to toml::exception 2020-01-19 17:51:24 +09:00
ToruNiina
8c7d83d985 Merge branch 'add-value-member-methods' 2020-01-17 20:30:26 +09:00
ToruNiina
5ce44adbdc doc: add description about toml::value memfuns 2020-01-17 20:26:36 +09:00
ToruNiina
5c5b1320d0 test: add test for map/vector methods 2020-01-16 20:58:36 +09:00
ToruNiina
8b737dc21f feat: add member methods to toml::value 2020-01-16 20:58:10 +09:00
ToruNiina
ee654b6c3f chore: add -Werror when building test codes 2020-01-13 11:31:03 +09:00
ToruNiina
c59782d180 fix: remove useless conversions in the test codes 2020-01-13 11:29:17 +09:00
ToruNiina
9bef715ccd fix: use u32 as a result of binary operation 2020-01-13 11:26:53 +09:00
ToruNiina
d2b1cf5123 refactor: just use a constructor
to remove conversions
2020-01-13 11:26:29 +09:00
ToruNiina
9f92916d1d fix: suppress -Wuseless-conversion
`{integer} + 1` will automatically be an int, so static_cast<int>(a+1)
will be useless conversion.
2020-01-13 11:24:48 +09:00
ToruNiina
666e4cf9dc fix: suppress sign-conversion warnings 2020-01-13 00:46:21 +09:00
ToruNiina
cafee29c64 test: add some combinations of types in toml::find 2020-01-13 00:27:39 +09:00
ToruNiina
a7a2272b29 chore: turn more diagnostic flags on 2020-01-13 00:16:33 +09:00
ToruNiina
dc0bca2bb6 fix: update patch version ... 2020-01-12 23:18:03 +09:00
ToruNiina
490abe04fd refactor: remove redundant template argument 2020-01-12 23:07:17 +09:00
ToruNiina
81ed4c0e9d Merge branch 'master' of github.com:ToruNiina/toml11 2020-01-10 21:17:17 +09:00
ToruNiina
1b07baf184 doc: add toml::get specialization using ctor 2020-01-10 20:46:54 +09:00
ToruNiina
9073d52159 test: check get<foo> works with constructor 2020-01-10 20:39:56 +09:00
ToruNiina
55260654bf feat: get user-defined value by constructor
If a user-defined constructor has constructor(const toml::value&),
then it should be convertible in `toml::get` and `toml::find`.
2020-01-10 20:38:52 +09:00
ToruNiina
aa6271af75 doc: update README 2020-01-09 01:40:05 +09:00
ToruNiina
c54a03f189 Merge branch 'master' into find-idx 2020-01-09 00:27:51 +09:00
ToruNiina
c153c0e8c3 ci: test with sanitizers 2020-01-08 23:28:17 +09:00
ToruNiina
1f90af8e67 ci: refactor list of env vars 2020-01-08 23:17:38 +09:00
ToruNiina
a0c5192b74 chore: add option to use sanitizers 2020-01-08 23:07:05 +09:00
ToruNiina
7f020f3f44 refactor: remove error prefix
that will automatically be added in format_underline
2020-01-07 22:27:13 +09:00
ToruNiina
827b433389 Merge branch 'master' into find-idx 2020-01-07 22:13:15 +09:00
ToruNiina
b1827e6fca test: check immutability of inline tables 2019-12-20 19:46:54 +09:00
ToruNiina
18f84088b4 perf: avoid tmp str construction while checking 2019-12-19 22:13:47 +09:00
ToruNiina
c199bd8b49 feat: enable to access the 1st char of region 2019-12-19 22:13:33 +09:00
ToruNiina
5b35c1a74e fix: prohibit modification on inline table
According to toml-lang/toml:36d3091b3 "Clarify that inline tables are
immutable", check if it adds key-value pair to an inline table.
  This is one of the unreleased (after-0.5.0) toml feature. But this is
marked as "Clarify", so TOML-lang intended that inline tables are
immutable in all version.
2019-12-19 22:02:17 +09:00
ToruNiina
d3513c0f84 fix: fmt line num in err msg correctly 2019-12-17 19:35:26 +09:00
ToruNiina
8567f09cbf chore: update version info in CMake 2019-12-13 20:25:52 +09:00
ToruNiina
a6d24b02d5 Merge branch 'colorize-err-msg' 2019-12-13 20:23:27 +09:00
ToruNiina
08bf5ffbdf doc: put screenshot to colorize-error-message 2019-12-13 17:28:43 +09:00
ToruNiina
a945bd6eac ci: pass TOML11_COLORIZE_ERROR_MESSAGE on CircleCI 2019-12-13 16:47:33 +09:00
ToruNiina
f4ac286b0f doc: add description about format_error 2019-12-12 21:31:21 +09:00
ToruNiina
f31dc6ba37 doc: add example of hints in an error message 2019-12-12 18:09:13 +09:00
ToruNiina
fecd50dfeb doc: add contributors 2019-12-12 18:02:16 +09:00
ToruNiina
d48d454a61 doc: modify README a bit 2019-12-12 17:55:20 +09:00
ToruNiina
4688c235f5 refactor: rename internal macro value 2019-12-12 17:38:29 +09:00
ToruNiina
5c146857a3 Merge branch 'master' into colorize-err-msg 2019-12-11 22:49:38 +09:00
ToruNiina
bc51699415 Merge branch 'bracket-operator' 2019-12-11 19:36:21 +09:00
Toru Niina
8b923d56e9 Merge pull request #96 from kenichiice/icpc_warning2
Suppress warning on Intel C++ Compiler
2019-12-11 18:30:44 +09:00
OGAWA KenIchi
3190c1da9f fix: suppress warning on Intel C++ Compiler 2019-12-11 17:47:16 +09:00
ToruNiina
a41dc08025 doc: add document of operator[] 2019-12-10 20:06:01 +09:00
ToruNiina
0c084b3a5c test: add test: accessing via bracket operator 2019-12-10 00:08:40 +09:00
ToruNiina
8fbeaabfd9 feat: add operator[] to access table/array 2019-12-10 00:00:05 +09:00
ToruNiina
331de4ea5d fix: use datetime info while getting time offset
to convert offset_datetime to system_clock::time_point.
2019-12-08 22:44:12 +11:00
ToruNiina
b246f5ac5c fix: combine date and time to convert loc datetime
Normally DST begins at A.M. 3 or 4. If we re-use conversion operator
of local_date and local_time independently, the conversion fails if
it is the day when DST begins or ends. Since local_date considers the
time is 00:00 A.M. and local_time does not consider DST because it
does not have any date information. We need to consider both date and
time information at the same time to convert it correctly.
2019-12-08 22:38:49 +11:00
ToruNiina
89714fb24b doc: note about local timezone and datetime 2019-12-06 21:15:31 +09:00
ToruNiina
62c01f9826 fix: consider timezone correctly
explicitly set tm.tm_isdst = 0 and use UTC offset
2019-12-06 20:57:51 +09:00
ToruNiina
5a8d368927 feat: add thread-safe detail::gmtime_s 2019-12-06 20:33:15 +09:00
ToruNiina
28519f5712 doc: add colorize section to README 2019-12-02 17:08:00 +09:00
Toru Niina
63fdbd25cf Merge pull request #95 from blockparty-sh/unused-variable-warning
Suppress unused variable warning
2019-11-23 12:59:21 +09:00
blockparty
6d41a1adb9 Suppress unused variable warning 2019-11-22 05:59:55 -06:00
Toru Niina
26a09b2f65 Merge pull request #93 from blockparty-sh/fix_compile_error
Check if features are defined
2019-11-21 21:57:26 +09:00
blockparty
7e62dad6dc Check if features are defined 2019-11-21 05:51:31 -06:00
ToruNiina
2fd466a3c3 fix: skip only the prefix, keep spaces 2019-11-14 15:32:17 +09:00
ToruNiina
6f7539dc6a fix: deduplicate [error] prefix in the messages 2019-11-14 15:31:27 +09:00
ToruNiina
f290390c63 fix: consider the no-space cases like [error]: 2019-11-13 18:14:42 +09:00
ToruNiina
571baa2c26 refactor: remove nocolor:: operations
since color can be on-off at runtime
2019-11-13 18:08:31 +09:00
ToruNiina
bbe33e87d9 feat: detect [error] prefix duplication 2019-11-13 18:05:37 +09:00
ToruNiina
4c5076f263 feat: add runtime colorize flag 2019-11-13 18:01:47 +09:00
ToruNiina
d47174954f feat: colorize user-defined msg by format_error 2019-11-13 18:00:55 +09:00
ToruNiina
821eb9632b feat: add a macro-dependent constant 2019-11-13 17:59:47 +09:00
ToruNiina
af116991b6 fix: remove overlapping [error] sign 2019-11-13 17:35:23 +09:00
ToruNiina
87bebbc37d feat: put color to the internal error messages 2019-11-13 17:35:05 +09:00
ToruNiina
c2d0351e69 feat: add (ANSI) terminal colorize operators 2019-11-13 17:24:51 +09:00
ToruNiina
1526b9feee Merge branch 'heterogeneous-array' 2019-11-09 11:03:18 +09:00
ToruNiina
281206dcc6 doc: add heterogeneous array to README 2019-11-08 19:03:16 +09:00
ToruNiina
adf8fa9234 fix: fix typos in an error message in toml::get
when converting toml::value to std::tuple
2019-11-08 16:12:18 +09:00
ToruNiina
0a66be3257 test: add test for parsing heterogeneous array
this test case is activated only if TOML11_USE_UNRELEASED_TOML_FEATURES
is defined.
2019-11-08 15:52:31 +09:00
ToruNiina
160537360c test: deactivate error check for hetero array
if TOML11_USE_UNRELEASED_TOML_FEATURES is activated.
2019-11-08 15:39:14 +09:00
ToruNiina
9af2d65417 feat: allow heterogenous array
if TOML11_USE_UNRELEASED_TOML_FEATURES is activated.
In TOML v0.5.0, heterogenous arrays are not allowed. But after some
discussions in toml-lang/toml, it is decided to allow it in the next
release (toml-lang/toml/pull/676).
To support it, disable type check in parse_array function.
2019-11-08 15:36:58 +09:00
ToruNiina
429763377f Merge branch 'add-src-loc-to-exception' #87 2019-11-02 13:42:14 +09:00
ToruNiina
c774beb79a doc: write about source_location in exceptions 2019-11-02 13:03:50 +09:00
ToruNiina
8240fffeca Merge branch 'master' into add-src-loc-to-exception 2019-11-02 12:53:16 +09:00
ToruNiina
047611764c fix: silly typo 2019-11-01 21:15:20 +09:00
ToruNiina
bc3eb9d967 feat: add src_loc to all the exceptions
including internal_error.
2019-11-01 21:14:33 +09:00
ToruNiina
6862264bde feat: use the first char as the top-level region
A bit related to #89
2019-11-01 20:47:25 +09:00
ToruNiina
2ee69fc420 fix: improve error messages about strings a bit 2019-11-01 13:34:15 +09:00
ToruNiina
6a15e8360f refactor: remove redundant namespace specifier 2019-10-31 23:13:49 +09:00
ToruNiina
b4c6d26842 Merge origin/add-src-loc-to-exception #87 2019-10-31 23:11:53 +09:00
ToruNiina
41eb1d6887 feat: pass source_location to exception 2019-10-31 22:23:31 +09:00
ToruNiina
3ca712a8da feat: check line_num before converting it to int 2019-10-31 22:21:24 +09:00
ToruNiina
8e589ff4d7 feat: add source_location to (syntax_|type_)error 2019-10-31 22:04:16 +09:00
ToruNiina
56812114c3 refactor: simplify inclusion dependencies 2019-10-31 21:58:28 +09:00
ToruNiina
f98615d0df fix: check file content is empty or not 2019-10-30 16:49:49 +09:00
ToruNiina
37769e28f0 fix #88: check if input is null-terminated or not 2019-10-30 16:33:22 +09:00
ToruNiina
2acdec00aa Merge branch 'refactor-ci' 2019-10-15 23:13:44 +09:00
ToruNiina
354cfc979a ci: cache brew directory 2019-10-15 23:13:11 +09:00
ToruNiina
3dc3b001ff ci: update clang 3.x from 3.7 to 3.9 2019-10-15 23:13:06 +09:00
ToruNiina
ea24a91f4c ci: use sourceline 2019-10-15 20:32:09 +09:00
ToruNiina
5bba73a8ca ci: use addons in OS X on Travis.CI 2019-10-15 20:27:27 +09:00
ToruNiina
54eced6c82 test: add test for toml::string::operator+= 2019-10-09 21:51:33 +09:00
ToruNiina
258e62f8f3 feat: add operator+= to toml::string 2019-10-09 21:51:14 +09:00
ToruNiina
06086a9ff7 doc: add note about value::at 2019-10-09 21:09:38 +09:00
ToruNiina
b4b35ea33e feat: allow 0-prefix exponent if the flag is on
If unreleased feature is activated, zero-prefixes in an exponent part of
a floating point is allowed. If the flag TOML11_UNRELEASED_TOML_FEATURES
is turned on, we don't need to check whether there is a zero prefix in
the exponent part that is formatted by a standard library.
2019-10-08 23:23:53 +09:00
ToruNiina
d7b4d104d3 refactor: reduce checking; just check once 2019-10-08 23:15:03 +09:00
ToruNiina
1148d01c70 Merge branch 'master' into find-idx 2019-10-07 11:11:08 +09:00
ToruNiina
e12fd4d944 doc: add contributors 2019-10-04 14:28:43 +09:00
ToruNiina
36af02cb3a test: add test cases for one-way conversion 2019-10-04 13:01:15 +09:00
ToruNiina
488015df49 fix: toml -> T is required; related to #83 2019-10-04 13:00:34 +09:00
Toru Niina
1f951e49b1 Merge pull request #84 from jcmoyer/master
Update documentation for toml::from and toml::into
2019-10-04 12:58:13 +09:00
J.C. Moyer
6a7dbb7875 Update documentation for toml::from and toml::into 2019-10-03 21:28:06 -04:00
ToruNiina
17d78553ff test: add test cases for find(v, idx)
- check whether find(v, idx) throws
- check find(v, ks...) works with both indices and strings
2019-10-03 15:48:04 +09:00
ToruNiina
4c12dad51f feat: add find<T>(value, idx) for arrays (#79) 2019-10-03 15:27:25 +09:00
ToruNiina
ad7eb56634 fix: avoid potential memory bugs related to move 2019-10-03 14:42:52 +09:00
ToruNiina
b01c5534ed test: add test cases for const-ref version 2019-10-03 13:52:12 +09:00
ToruNiina
22dac3c9f2 Merge branch 'value-at' 2019-09-28 19:40:51 +09:00
ToruNiina
d5adfe8c7d refactor: use as_xxx instead of cast<enum>
because cast<enum>() requires `template` specifier inside a template
function. it makes code long.
2019-09-28 17:01:45 +09:00
ToruNiina
4bb8045c84 doc: add basic_value::at. 2019-09-28 16:31:45 +09:00
ToruNiina
babb6ab3fe test: add test case for basic_value::at 2019-09-28 16:22:01 +09:00
ToruNiina
d73bc6076c feat: add basic_value::at(key) and at(idx) 2019-09-28 16:21:51 +09:00
ToruNiina
8d1da6e8b5 test: add test cases for find_or(&&) + conversion 2019-09-28 14:01:33 +09:00
ToruNiina
8276e12f06 test: add test cases for toml::find_or(value&&) 2019-09-28 13:38:59 +09:00
ToruNiina
f3d3f63ff9 fix: return values from find_or(value&&) 2019-09-28 13:38:26 +09:00
ToruNiina
d9689c878d test: add test cases for toml::find(value&&, key) 2019-09-28 13:05:13 +09:00
ToruNiina
df097cb09a test: add test cases of get_or(value&&, U) 2019-09-28 12:13:59 +09:00
ToruNiina
a425e3b7c6 test: add test cases of toml::get_or(value&&, T&&) 2019-09-28 12:08:14 +09:00
ToruNiina
e4b4503b81 style: add comment to test::operator<< 2019-09-28 12:07:53 +09:00
ToruNiina
b44fbad925 fix: remove needless ::type 2019-09-28 11:14:14 +09:00
ToruNiina
826c9444ac refactor: use remove_cvref 2019-09-28 11:03:46 +09:00
ToruNiina
a1095f3e4c refactor: use std::map::at instead of [] 2019-09-28 11:03:14 +09:00
ToruNiina
483a39beb4 refactor: remove unsupported overload
expect<T>(table, ...)
2019-09-28 11:00:35 +09:00
ToruNiina
1409114c96 refactor: add utility meta-func for internal use 2019-09-28 10:58:02 +09:00
ToruNiina
ecfc9d0c5a fix: make return type rvalue when rvalue is passed 2019-09-28 10:31:10 +09:00
ToruNiina
94f76137a3 doc: add description of unreleased toml features 2019-09-05 14:31:05 +09:00
ToruNiina
c2e1aa9a3c Merge branch 'master' into fp-exp-leading-zeroes 2019-09-05 13:50:58 +09:00
ToruNiina
5b5ece6c32 fix: add "unreleased" flag to raw-tab-in-string 2019-09-04 18:10:15 +09:00
ToruNiina
b696e327d7 ci: add options to test toml-head features 2019-09-04 13:37:08 +09:00
ToruNiina
757e5d60be test: add flag for toml-head features to tests 2019-09-04 13:36:42 +09:00
ToruNiina
c02093de7f chore: add an option to tests
that enable/disable to use unreleased toml features
2019-09-04 13:34:28 +09:00
ToruNiina
4f8b62a7e9 feat: add TOML11_USE_UNRELEASED_TOML_FEATURES flag
to choose to use unreleased toml feature
2019-09-04 13:32:05 +09:00
ToruNiina
d9b8582c47 test: add test for toml::get<T>(std::move(v)) 2019-09-01 19:39:37 +09:00
ToruNiina
c9543d8d9e test: add test of find_or with conversion 2019-08-31 13:05:05 +09:00
ToruNiina
15b68a89c6 fix: suppress warnings by forwarding argument 2019-08-31 13:04:25 +09:00
ToruNiina
64e7bdb835 test: add test for leading zeroes in fp exp 2019-08-28 17:49:12 +09:00
ToruNiina
1acf87679e feat: permit leading 0s in exp parts of floats
This is an unreleased feature of toml language, but is merged into
toml-lang/toml:master.
2019-08-28 16:02:10 +09:00
ToruNiina
7a1b5bd64e fix: skip whitespaces without newline 2019-08-26 18:16:09 +09:00
ToruNiina
e332e018db feat: allow raw tab characters in basic strings
This feature is planned to be incorporated in toml v1.0.0 but not
released yet.
2019-08-21 11:19:47 +09:00
ToruNiina
b1ec6d87bd chore: update patch version 2019-08-07 15:58:28 +09:00
ToruNiina
8dded288b4 Merge branch 'master' into find-or-value 2019-08-07 14:58:56 +09:00
ToruNiina
0f491c7f3a fix: add overload for find_or with toml::value 2019-08-07 14:55:30 +09:00
ToruNiina
5edf43a1d2 test: add missing include file to test code 2019-07-23 22:32:32 +09:00
ToruNiina
cffc605505 fix: stop including iostream 2019-07-23 22:27:20 +09:00
ToruNiina
fb91936a1d fix #76: correct version description in CMakeLists 2019-07-21 13:16:48 +09:00
ToruNiina
8833292858 doc: rearrange toml::find section in README 2019-07-19 20:42:47 +09:00
ToruNiina
3fe04aff77 doc: fix sample script in README 2019-07-19 20:13:12 +09:00
ToruNiina
138f030b5d doc: fix sample codes in README 2019-07-18 17:39:24 +09:00
ToruNiina
2eb2e0a753 doc: update README 2019-07-13 15:11:01 +09:00
ToruNiina
87e0ba201e feat: enable to swap comment and strings 2019-07-13 14:33:14 +09:00
ToruNiina
24a05c7c93 doc: update serialization section #73 2019-07-10 09:12:38 +09:00
ToruNiina
c3653b85f1 doc: fix include directory #72 2019-07-10 08:45:09 +09:00
ToruNiina
00b05c63b9 doc: add explanation about os << toml::string 2019-07-07 21:24:33 +09:00
ToruNiina
35b7c79ebd doc: update README 2019-07-03 17:33:24 +09:00
ToruNiina
9ef146d022 🔀 Merge branch 'v3' 2019-07-03 17:31:45 +09:00
ToruNiina
2c192af35d test: add test for toml::string format 2019-06-29 20:20:31 +09:00
ToruNiina
c2435b0d56 feat:boom:: format toml::string as TOML format 2019-06-29 20:19:47 +09:00
ToruNiina
9b12b17d5e ci: fix ci job script 2019-06-29 17:36:16 +09:00
ToruNiina
e61b38fac2 ci: add test_serialization to the jobs 2019-06-29 16:45:59 +09:00
ToruNiina
716f7bacba ci: run serialization test to circleci 2019-06-29 16:43:11 +09:00
ToruNiina
299d1098e4 test: add serialization test for arbitrary file 2019-06-29 16:40:42 +09:00
ToruNiina
c272188060 fix: check inline table does not include LF 2019-06-29 16:39:54 +09:00
ToruNiina
0fc0967f6f fix: remove CR before comparing to the reference 2019-06-29 15:38:28 +09:00
ToruNiina
df0d870c97 test: add test for serialization with nocomment 2019-06-29 15:00:00 +09:00
ToruNiina
d5299fef04 feat: add no_comment option to serializer 2019-06-29 14:59:18 +09:00
ToruNiina
937a3b4a2e test: add test for nocomment/showcomment 2019-06-28 19:09:05 +09:00
ToruNiina
0502924d25 feat: add nocomment and showcomment 2019-06-28 19:08:48 +09:00
ToruNiina
6182f3ee9d test: add test for operator<<(os, non-table-value) 2019-06-28 17:56:41 +09:00
ToruNiina
3624e4b690 fix: put comment just after non-table values
When non-table value is passed to the `operator<<`, it assumes that the
original C++ code looks like the following.

```cpp
std::cout << "key = " << v << std::endl;
```

In this case, the comment associated to `v` should be put just after
`v`, not before.
```toml
key = # comment <= bad
"value"

key = "value" # comment <= good
```

So, if `v` is not a table it would put comments just after the value.
2019-06-28 17:53:19 +09:00
ToruNiina
37e96ed8dc test: add test for format_key() 2019-06-28 17:47:42 +09:00
ToruNiina
79e7511871 feat: add format_key to help serialization 2019-06-28 17:47:19 +09:00
ToruNiina
284f122433 refactor: replace for-loop by comment output 2019-06-28 14:58:47 +09:00
ToruNiina
134475e292 test: check ostream op for comment containers 2019-06-28 14:58:16 +09:00
ToruNiina
28b3f7d6fb feat: add ostream operator to comment containers 2019-06-28 14:57:45 +09:00
ToruNiina
6b5fd349aa fix: initialize source_location correctly 2019-06-26 21:35:01 +09:00
ToruNiina
76e44a0c48 refactor: remove needless inline specifier 2019-06-26 21:34:36 +09:00
ToruNiina
b4bbd0a005 chore: update version string in CMakeLists 2019-06-26 21:31:35 +09:00
ToruNiina
f9ee645dc2 doc: add link to v3 branch 2019-06-23 21:00:59 +09:00
ToruNiina
6a251f582e refactor: remove needless code snippet 2019-06-22 17:52:01 +09:00
ToruNiina
74ef494797 feat: remove unused trait types 2019-06-22 17:35:40 +09:00
ToruNiina
3a5f8a4b88 test: rename test source file 2019-06-22 17:23:51 +09:00
ToruNiina
4d2b24b647 test: add test_find_or 2019-06-22 16:58:45 +09:00
ToruNiina
3fcb6bb20d test: fix test module name 2019-06-22 16:58:21 +09:00
ToruNiina
1e8af710a0 test: add test for get_or 2019-06-22 16:39:01 +09:00
ToruNiina
0ca8eeeb09 test: add missing include files 2019-06-21 17:11:21 +09:00
ToruNiina
a343ffd2a1 doc: update README 2019-06-21 17:02:30 +09:00
ToruNiina
b79797d2c7 refactor: replace BOOST_CHECK_EQUAL by BOOST_TEST 2019-06-21 16:01:14 +09:00
ToruNiina
90918b6d76 test: add basic_value type to serialization tests 2019-06-21 16:01:08 +09:00
ToruNiina
dd9b04ae3b fix: fix test case name 2019-06-21 16:01:04 +09:00
ToruNiina
4032b438c0 fix: time offset may change while conversion 2019-06-21 16:00:48 +09:00
ToruNiina
7b37d876ae refactor: update Boost.Test v2 to v3 2019-06-21 14:50:17 +09:00
ToruNiina
713b42e589 refactor: use CHECK_THROW macro to check it throws 2019-06-21 14:47:27 +09:00
ToruNiina
1694f74510 chore: update boost test library usage (v2->v3) 2019-06-21 14:43:13 +09:00
ToruNiina
9f69ffa993 fix: add unsigned symbol to integer literals 2019-06-21 14:42:44 +09:00
ToruNiina
0cee58b0b1 Merge branch 'v3' of github.com:ToruNiina/toml11 into v3 2019-06-21 14:31:52 +09:00
ToruNiina
ab1ef63da6 doc: add value ctor with comments to README 2019-06-21 14:31:28 +09:00
ToruNiina
e8d535e485 test: add tests for constructors with comments 2019-06-21 14:26:49 +09:00
ToruNiina
d4afed5bbb feat: construct value with a list of comments 2019-06-21 14:26:05 +09:00
ToruNiina
3ef8bddb6d doc: update README 2019-06-21 13:23:15 +09:00
ToruNiina
a68543a895 fix: detect comment in stricter way 2019-06-21 13:10:02 +09:00
ToruNiina
ec839bbd75 chore: add -Wextra when compiling tests 2019-06-21 00:29:45 +09:00
ToruNiina
ecf55f86d6 refactor: add explicit type conversion 2019-06-21 00:25:57 +09:00
ToruNiina
3b71f80652 refactor: streamsize is a signed integer 2019-06-21 00:00:37 +09:00
ToruNiina
be2d2aec52 refactor: explicitly convert difference_t to size_t 2019-06-20 23:59:16 +09:00
ToruNiina
be04bf1302 refactor: convert file size to size_t 2019-06-20 23:58:35 +09:00
ToruNiina
427706d671 fix: explicitly add float conversion 2019-06-20 23:58:15 +09:00
ToruNiina
71ff54e76c fix: rearrange internal int types in datetimes 2019-06-20 23:58:08 +09:00
ToruNiina
8208bbf236 fix: check and convert value manually
I totally have no idea when std::count returns a negative value, but the
result type of `std::count` is a differnce_type. So when it is added
with size_t value, implicit sign conversion happens. This changes check
this kind of (almost trivial but required) checking.
2019-06-20 22:27:16 +09:00
ToruNiina
f689d26294 refactor: add conversion function to utf8 encoder 2019-06-20 22:25:40 +09:00
ToruNiina
9e6d8e76d0 fix: replace null deref by terminate for safety
Since empty_iterator never points anything, so it always points null
(it returns nullptr by operator->). but dereferencing null causes UB.
Just calling std::terminate is of course better.
2019-06-20 20:56:49 +09:00
ToruNiina
0e2e4a26be ci: Revert "ci: use libstdc++ when compiling"
Ok, it already worked without this.
This reverts commit 092db50700.
2019-06-20 20:48:17 +09:00
ToruNiina
092db50700 ci: use libstdc++ when compiling
because some of the earlier versions of libc++ does not conform c++11
2019-06-20 20:43:57 +09:00
ToruNiina
295e9bb795 ci: try to update system library 2019-06-20 20:24:12 +09:00
ToruNiina
dd2238e1ad ci: change apt source on travis
clang 3.7 trusty version seems to be restricted. I don't know why, but
precise version seems to be working.
2019-06-20 20:21:06 +09:00
ToruNiina
5dfa88a1b3 ci: rename package to be installed 2019-06-20 20:13:16 +09:00
ToruNiina
37b4442d7f ci: upgrade boost on Travis Linux 2019-06-20 20:00:56 +09:00
ToruNiina
48aa0a4c67 ci: update boost version on appveyor 2019-06-20 19:53:27 +09:00
ToruNiina
86a1f7ad75 fix: add missing include files 2019-06-20 16:23:51 +09:00
ToruNiina
99c10dd6bc fix: enable to deduce what basic_value to be used 2019-06-20 16:21:01 +09:00
ToruNiina
7d087ef2a8 doc: update README 2019-06-20 15:22:20 +09:00
ToruNiina
a0d74a5542 doc: add info about breaking changes to README 2019-06-20 14:58:18 +09:00
ToruNiina
c3922c0d51 test: move some test_cases across test files 2019-06-20 14:43:31 +09:00
ToruNiina
5e5a757208 fix: conversion between different basic_value s 2019-06-20 14:35:38 +09:00
ToruNiina
f178379c07 test: add test_find 2019-06-20 14:34:42 +09:00
ToruNiina
321db42b1c Merge branch 'master' into v3 2019-06-19 23:44:09 +09:00
ToruNiina
1bf9e42835 chore: update version 2019-06-19 21:12:05 +09:00
ToruNiina
3379ed82ec refactor: remove meaningless meta conditions 2019-06-19 20:06:06 +09:00
ToruNiina
9663a6bbdb Merge branch 'master' into v3 2019-06-19 19:53:08 +09:00
ToruNiina
4a2c823d56 fix: comparison between values that has a table 2019-06-19 19:32:25 +09:00
ToruNiina
9a47c2a15a Merge branch 'v3' of gitlab.com:ToruNiina/toml11 into v3 2019-06-19 19:03:47 +09:00
ToruNiina
3311d00845 Merge branch 'v3' of gitlab.com:ToruNiina/toml11 into v3 2019-06-19 19:05:22 +09:00
ToruNiina
24c28c7f4f fix: correct some SFINAE expressions 2019-06-19 18:59:12 +09:00
ToruNiina
cab3144507 style: format CMakelists.txt 2019-06-19 16:53:45 +09:00
ToruNiina
7e5859ba73 Merge branch 'master' into v3 2019-06-19 15:36:27 +09:00
ToruNiina
dee32e7d5e style: make hint messages clearer 2019-06-19 12:58:34 +09:00
ToruNiina
53a185e7a9 fix: revert misjudgement as a bug
Probably I'm too tired.

This reverts commit adcd75e017.
2019-06-18 21:41:30 +09:00
ToruNiina
fd980a8c5d 🔀 Merge branch 'guess-type-error' 2019-06-18 21:29:45 +09:00
ToruNiina
73ac43d70c doc: add contributor 2019-06-18 21:28:50 +09:00
ToruNiina
adcd75e017 fix: correctly initialize offset 2019-06-18 21:27:16 +09:00
ToruNiina
3613580bb3 doc: update README 2019-06-18 21:26:17 +09:00
ToruNiina
d9f9df61a2 fix: fix links in README 2019-06-18 01:39:36 +09:00
ToruNiina
32d5c9e924 fix: serialize array correctly 2019-06-18 01:27:52 +09:00
ToruNiina
262f9c5fcc fix: avoid duplicating comment: array/table elems 2019-06-18 01:26:40 +09:00
ToruNiina
86e55c3bf7 test: check serialization keeps comments 2019-06-18 01:26:16 +09:00
ToruNiina
159283fdad test: check preserve_comment keep it read 2019-06-18 01:25:43 +09:00
ToruNiina
fb5834caab refactor: exchange order of test section 2019-06-18 00:45:30 +09:00
ToruNiina
ca084abe90 feat: consider the first comments as a file comment 2019-06-18 00:44:49 +09:00
ToruNiina
7b1a788e2d feat: enable to convert vector<string> to comments 2019-06-18 00:43:25 +09:00
ToruNiina
228487eafd test: fix typos in tests 2019-06-17 23:46:42 +09:00
ToruNiina
f744a792e2 fix: constructor with array-like types 2019-06-17 23:45:43 +09:00
ToruNiina
bf2dc76d5e test: add test for templatized conversions 2019-06-17 23:21:18 +09:00
ToruNiina
4d267cadf4 doc: add templatized conversion to README 2019-06-17 23:12:46 +09:00
ToruNiina
bc68a9d9ee refactor: remove needless include file 2019-06-17 23:07:14 +09:00
ToruNiina
4008c24e84 test: add test for init-list-map to value conversion 2019-06-17 22:50:38 +09:00
ToruNiina
c2b0de623f feat: enable to convert map-like to toml::value 2019-06-17 22:50:14 +09:00
ToruNiina
af11d56e79 fix: correctly move value from find_or to get_or 2019-06-17 22:40:52 +09:00
ToruNiina
5cb7c961aa fix: update README 2019-06-17 22:26:41 +09:00
ToruNiina
bf4eae0b76 test: drop test for find_or(table) 2019-06-17 22:14:26 +09:00
ToruNiina
6399d44e3b fix: consider comments while serialization 2019-06-17 22:13:58 +09:00
ToruNiina
d10c0725fd fix: consider closing bracket when collect comments
table = {key = "value"} # comment.
a value named "table" ({key = "value"}) has the above comment.
but a value named "key" ("value") does not have any comment.
2019-06-17 22:12:20 +09:00
ToruNiina
7eac3a3028 feat: support serialization of basic_value 2019-06-17 20:34:42 +09:00
ToruNiina
57b5545ba2 fix: add _type suffix to value::xxx_type 2019-06-17 20:34:13 +09:00
ToruNiina
f36b39c04f fix: consider comments while comparing values 2019-06-17 20:33:57 +09:00
Toru Niina
569341a514 Merge pull request #69 from KerstinKeller/cmake_install
Allow to install toml11 library with CMake.
2019-06-17 18:03:00 +09:00
KerstinKeller
0357d8fb57 Add newline to end of CMake files. 2019-06-17 10:04:39 +02:00
ToruNiina
00d40140ac doc: add an example of error message to README 2019-06-17 12:59:29 +09:00
ToruNiina
1bfe8f1f54 Merge branch 'master' into guess-type-error 2019-06-17 12:48:36 +09:00
ToruNiina
b3300fad2a fix: move element of map in toml::find(val&&) 2019-06-17 12:13:59 +09:00
ToruNiina
94bcf0aae9 Merge branch remote into v3 2019-06-17 12:10:45 +09:00
ToruNiina
bc143263cd Merge branch 'revert-recursive-find' 2019-06-17 11:54:52 +09:00
ToruNiina
0ef232a1e0 feat: 💥 remove toml::find_or for toml::table 2019-06-17 01:26:05 +09:00
ToruNiina
0604cf813a feat: 💥 remove toml::find for tables 2019-06-17 01:24:32 +09:00
ToruNiina
10f410a02c doc: add some notes and comments to README 2019-06-17 00:48:06 +09:00
ToruNiina
12ef0f6287 doc: add containers and comments to README 2019-06-17 00:29:43 +09:00
ToruNiina
d9ad0e4b92 doc: add source_location to README 2019-06-16 23:44:54 +09:00
ToruNiina
1b19d5f1eb doc: update README 2019-06-16 21:44:59 +09:00
ToruNiina
fd7da05798 doc: update README 2019-06-16 20:31:08 +09:00
ToruNiina
cbaaaaca7c revert recursive find function
I found that in a user-code (I'm also one of the users of this library),
this new feature sometimes causes an error. Some of my code won't
compile because of this change. Since toml::table is convertible to
toml::value *implicitly*, if toml::find(table, key, tablename) was
called, the overload resolution becomes ambiguous with toml::find(
value, key1, key2). But dropping support for toml::find(toml::table,
key, tablename) is a breaking change. So I concluded that now is not
the right time yet.
2019-06-16 19:55:40 +09:00
ToruNiina
cf1c9371b6 fix: correct example and positions in err msgs 2019-06-16 17:52:42 +09:00
ToruNiina
62e8d58d8d feat: guess possible format errors 2019-06-16 17:32:29 +09:00
ToruNiina
fec4e1db9a doc(WIP): add source_location to README 2019-06-15 20:34:20 +09:00
ToruNiina
8665272bab test: add test for custom basic_value type 2019-06-15 20:25:19 +09:00
ToruNiina
cc4a9c8d5d fix: consider identity conversion in SFINAE 2019-06-15 20:20:14 +09:00
ToruNiina
af19dfe032 fix: conversion between different basic_values 2019-06-15 20:19:51 +09:00
ToruNiina
64dc086878 doc(WIP): re-write README 2019-06-15 19:50:31 +09:00
ToruNiina
9acc55a7ac test: add test for discard_comment 2019-06-15 17:18:25 +09:00
ToruNiina
177022b2cb test: update tests for comment 2019-06-15 17:13:25 +09:00
ToruNiina
5726d10339 feat: save comment information in value 2019-06-15 17:13:02 +09:00
ToruNiina
a6706f7879 fix: templatize internal function for value 2019-06-15 17:12:30 +09:00
ToruNiina
558349170d fix: correct the order and remove last CR 2019-06-15 17:11:49 +09:00
ToruNiina
eb4eca86db feat: 💥 change comment interface in region 2019-06-15 16:11:05 +09:00
ToruNiina
d8a9ee4f72 🔀 Merge branch 'master' into v3 2019-06-15 15:17:08 +09:00
KerstinKeller
acbc2a73cb Allow to install tom11 library with CMake.
Add option to build tests.
2019-06-14 17:24:21 +02:00
ToruNiina
b2daf916b3 doc: add contributor to README 2019-06-11 22:45:46 +09:00
Toru Niina
e66bb3d359 Merge pull request #67 from ToruNiina/hotfix
suppress warnings on clang v7+
2019-06-10 10:54:54 +09:00
Toru Niina
cfaa94f072 Merge pull request #68 from khoitd1997/master
fix sign-compare warning
2019-06-10 10:49:49 +09:00
khoitd1997
2f4f3efbf0 fix sign-compare warning 2019-06-09 12:00:28 -07:00
ToruNiina
06ae67502a fix: move argument correctly 2019-06-09 21:05:46 +09:00
ToruNiina
6345910c3e 🔀 Merge branch 'master' into v3 2019-06-08 20:05:05 +09:00
ToruNiina
9948549b62 fix: add missing template parameters 2019-06-08 19:53:50 +09:00
ToruNiina
54d46f08c3 🔀 Merge branch 'master' into v3 2019-06-08 19:40:11 +09:00
ToruNiina
57cb806e14 Merge branch 'master' into throw-from-as-something 2019-06-08 19:23:32 +09:00
ToruNiina
d6f3654185 refactor: reduce test code by using CHECK_THROW 2019-06-08 19:23:12 +09:00
ToruNiina
8befe3f1ad test: add test for throw/nothrow versions of as_* 2019-06-08 19:20:09 +09:00
ToruNiina
2d43119ac7 doc: change README a bit 2019-06-07 21:05:33 +09:00
ToruNiina
436af12815 doc: update README 2019-06-07 19:43:01 +09:00
ToruNiina
4f4d4380f2 feat: throw from as_* if type differs 2019-06-07 19:34:04 +09:00
ToruNiina
31debcb8aa 🔀 Merge branch 'master' into recursive-find 2019-06-07 19:02:20 +09:00
ToruNiina
2afa0ff0c3 doc: add find(value, key1, key2, ...) to README 2019-06-07 19:01:46 +09:00
ToruNiina
46047c48bf doc: add note about is|as_float to README 2019-06-07 13:40:21 +09:00
ToruNiina
897aecf5d4 test: avoid deprecated functions in the test codes 2019-06-07 13:32:02 +09:00
ToruNiina
7db8388d17 fix: avoid deprecated stuff in the internal code 2019-06-07 13:27:10 +09:00
ToruNiina
62c993e096 feat: add as|is_floating and deprecate as|is_float
to make the function names consistent with snake_case_typenames
2019-06-07 00:10:12 +09:00
ToruNiina
014d882f8f feat: enable to find value by recursive search 2019-06-07 00:06:14 +09:00
ToruNiina
e781545c53 feat(WIP): diable test for comments once
because the interfaces would be changed a lot.
2019-06-06 22:34:08 +09:00
ToruNiina
a8b5fef827 feat(WIP): add workaround to make literal compiles 2019-06-06 22:32:51 +09:00
ToruNiina
7258c52334 feat: enable to edit comments through memfun 2019-06-03 22:17:10 +09:00
ToruNiina
407d9223f6 feat: 💥 is_float -> is_floating 2019-06-03 22:01:47 +09:00
ToruNiina
53efaed179 test: update interfaces of parse_* and value 2019-06-03 22:01:16 +09:00
ToruNiina
d7c5606dcf fix: update as_float -> floating 2019-06-03 21:46:48 +09:00
ToruNiina
761718b3b9 test: update retval of parse and related get/find 2019-06-03 21:44:47 +09:00
ToruNiina
ae2bafa907 fix: correct SFINAE conditions and types 2019-06-03 21:44:11 +09:00
ToruNiina
f19b3822bb feat: 💥 change as_float -> as_floating 2019-06-03 21:43:35 +09:00
ToruNiina
2cbb93d86e fix: #65 Merge branch 'hotfix' 2019-06-03 21:27:25 +09:00
ToruNiina
a19b94511b fix: add space between operator"" and _toml
In C++11, it is required.
2019-06-03 20:58:35 +09:00
ToruNiina
cf1114b47b test: update typenames from Camel to snake 2019-06-02 22:13:36 +09:00
ToruNiina
ad3c1950f2 test: use find instead of get<T>(v.at("")) 2019-06-02 22:12:52 +09:00
ToruNiina
296ba060ef test: update typename from CamelCase to snake_case 2019-06-02 22:11:37 +09:00
ToruNiina
fe8a909213 fix: correctly put references 2019-06-02 22:09:26 +09:00
ToruNiina
c313e1382c test: update test for multiple translation units 2019-06-02 22:00:56 +09:00
ToruNiina
5fe166e375 fix: update value_t::* names in serializer
Although currently serializer does not support basic_value, it compiles.
2019-06-02 21:51:37 +09:00
ToruNiina
319365f86b feat: update types in format_error 2019-06-02 21:50:27 +09:00
ToruNiina
89f0ace6ee fix: initialize comment container correctly 2019-06-02 21:50:01 +09:00
ToruNiina
2e34035e7a feat: 💥 update types and retval of parser
- change return value from toml::table to toml::value
- enable to change container types and comment policy by template
2019-06-02 21:47:57 +09:00
ToruNiina
7d34436535 test: update value_t::* names in the test code 2019-06-02 21:36:09 +09:00
ToruNiina
8456186eac fix: remove inclusion of removed file 2019-06-02 21:34:57 +09:00
ToruNiina
e094d6e85a refactor: move type alias from get to trait 2019-06-02 20:43:08 +09:00
ToruNiina
4664f91517 feat: remove unused meta-function alias 2019-06-02 20:40:44 +09:00
ToruNiina
c0b6ca762a feat: 💥 drop from_toml support 2019-06-02 19:27:03 +09:00
ToruNiina
5ef9890d0c feat: update find_or for basic_value 2019-06-02 19:22:17 +09:00
ToruNiina
bda337b51f feat: support conversion between basic_values 2019-06-02 19:09:56 +09:00
ToruNiina
6569c26e1b feat: make SFINAE condition strict 2019-06-02 19:04:32 +09:00
ToruNiina
6d17d5f60f feat: update expect for basic_value 2019-06-02 19:02:25 +09:00
ToruNiina
c00eeb18ef feat: add meta function that detects toml::basic_value 2019-06-02 19:02:01 +09:00
ToruNiina
3ce1aa31f3 feat: update get_or for basic_value 2019-06-02 18:55:02 +09:00
ToruNiina
cf28c3fb95 feat: update toml::find for basic_value 2019-06-02 18:36:49 +09:00
ToruNiina
6de494598a fix: remove unused argument to suppress warnings 2019-06-02 18:32:47 +09:00
ToruNiina
b06ae03deb feat: update toml::get<T> for basic_value 2019-06-02 17:53:08 +09:00
ToruNiina
725d915ba9 feat(WIP): update toml::get 2019-06-02 17:31:49 +09:00
ToruNiina
e1556183d1 refactor: remove unused include files 2019-06-02 17:12:01 +09:00
ToruNiina
9676499ab5 refactor: move file inclusion to correct position 2019-06-02 15:29:34 +09:00
ToruNiina
5792411d5e feat: add default template argument to basic_value 2019-06-02 15:15:43 +09:00
ToruNiina
44184026f9 feat: enable to convert different basic_values 2019-06-02 00:13:12 +09:00
ToruNiina
898423166f feat: enable to convert preserve/discard comments 2019-06-02 00:02:31 +09:00
ToruNiina
f9b5166c09 refactor: move default value types to value.hpp 2019-06-01 23:58:17 +09:00
ToruNiina
5c5d8b686a feat: introduce basic_value
it is capable to change comment policy, backend container of an array
and a table.
2019-06-01 20:18:57 +09:00
ToruNiina
5c3c1bd0e7 feat: add missing default array/table type 2019-06-01 20:18:15 +09:00
ToruNiina
696e5bb66f feat: extend has_from_toml_method to be generic 2019-06-01 20:16:59 +09:00
ToruNiina
65540fbb5c fix: typos 2019-06-01 19:47:10 +09:00
ToruNiina
351320491d fix: fix has_from_toml using basic_value 2019-06-01 19:46:20 +09:00
ToruNiina
d30700517d fix: add missing include file 2019-06-01 19:43:35 +09:00
ToruNiina
14ad8d0556 fix: fix typos and invalid names 2019-06-01 19:43:15 +09:00
ToruNiina
f04c97b587 refactor: simplify format_underline a bit 2019-06-01 19:06:08 +09:00
ToruNiina
b8d3038d38 feat: add meta function to detect conversions 2019-06-01 16:03:26 +09:00
ToruNiina
eaa3604dce refactor: introduce value_t_constant
as an alias for integral_constant
2019-06-01 16:01:48 +09:00
ToruNiina
8acc348106 feat: 💥 change interface around types
- change value_t::typename from CamelCase to snake_case.
- drop CamelCase typename supports.
The changes are introduced to make the interfaces uniform. For some
(historical) reasons, toml11 has both CamelCase names and snake_case
names for types. Additionally, since `float` is a keyword, snake_case
names uses `floating` to avoid collision and CamelCase name uses `Float`
because toml official calls it `Float`. This is too confusing.
Since it is a major upgrade, I think it is a big chance to make them
uniform.
2019-06-01 13:33:57 +09:00
ToruNiina
2567f2a787 feat: add source_location for error message generation. 2019-06-01 13:25:02 +09:00
ToruNiina
84b5749c6b feat: implement comment containers 2019-06-01 13:24:54 +09:00
ToruNiina
70d0049511 refactor: move some meta-funcs to traits.hpp 2019-06-01 12:35:40 +09:00
ToruNiina
717f5929c2 feat: use detail::none_t instead of char
Although the error value from combinators currently does not have any
information, it can have an information because it is a char value. It
is better to use no-information-type explicitly to make it clear that
it does not have any information. So I added none_t in toml::detai and
use it in combinators and parsers as an error value from combinators.
2019-05-31 17:07:52 +09:00
ToruNiina
81abb6c9d7 perf: remove err-msg from combinator
Generate error message in `parse_something()`, not in `lex_something`.
Since the error message generated by `lex_something` is too difficult to
read for humans, I've disabled the error message generation for the sake
of efficiency (it takes time to generate error message that will never
be read). I think now the error message generation itself safely can be
removed from combinators. At this stage, `lex_something` does not need
to return `result<T, E>` because all the error type would be discarded.
Now it is turned out that returing `optional<T>` from lex_* is enough.
Maybe later I would change the return type itself, but currently I
changed the error type from std::string to char because implementing
optional takes time and effort. It makes the parsing process a bit
faster.
2019-05-30 20:08:37 +09:00
ToruNiina
8bba3c8a14 refactor: use literal instead of empty string
so far, the error value of the lexer is just ignored because they are
not readable (results from all the nested combinator are concatenated,
so they are too redundant). those ones are replaced by a simple literal.
2019-05-30 19:33:25 +09:00
ToruNiina
b13e727b90 refactor: remove unused func, combinator::pattern
because it is not human-readable (too long and redundant)
2019-05-30 18:05:47 +09:00
ToruNiina
d352c9e66f perf: suppress unused error message generation 2019-05-30 17:47:06 +09:00
ToruNiina
c0aaba06d0 Merge branch 'refactoring' 2019-05-30 16:25:10 +09:00
ToruNiina
1633268d57 refactor: use snake_case typename only 2019-05-30 14:39:15 +09:00
ToruNiina
3bf1c2b820 Merge branch 'refactoring' to master 2019-05-30 00:18:07 +09:00
ToruNiina
4dbd2cb9fe refactor: use as_* to avoid needless checking 2019-05-29 21:22:32 +09:00
ToruNiina
65124a8d2e refactor: use is_something instead of is(...)
to reduce the code size a bit
2019-05-29 21:20:22 +09:00
ToruNiina
1b78f161f5 refactor: use is_something/as_something in parser
this reduces the size of the code. And also it skips needless
double-checking, so we can expect it makes parsing a bit faster.
2019-05-29 21:18:17 +09:00
ToruNiina
0ce259ada0 refactor: split throw_bad_cast from value::cast 2019-05-29 21:06:25 +09:00
ToruNiina
74da49f87f refactor: move switch_cast from inside of value
use as_something() instead of it. To realize this, the implementation of
as_something() is also changed. Now as_something does not depends on
`cast`. This reduces complexity around casting toml::value to other types.
2019-05-29 20:18:15 +09:00
ToruNiina
d5d697639c docs: add contributor to README 2019-05-10 23:02:23 +09:00
Toru Niina
0b365ca7d3 Merge pull request #63 from chronoxor/master
Fix Visual Studio 2019 warnings in pedantic compilation mode (/W4 /WX)
2019-05-10 22:58:17 +09:00
Ivan Shynkarenka
db6f3d5d11 Fix Visual Studio 2019 warnings in pedantic compilation mode (/W4 /WX) 2019-05-10 14:58:22 +03:00
ToruNiina
87be890e07 feat: remove deprecated functions 2019-04-28 15:59:09 +09:00
Toru Niina
d72dc706d0 Merge pull request #61 from ToruNiina/as-something
feat: add as_something functions for convenience
2019-04-28 15:02:19 +09:00
ToruNiina
4cbbcd8f62 Merge branch 'master' into as-something 2019-04-27 19:04:44 +09:00
Toru Niina
a2631ecacb Merge pull request #60 from ToruNiina/string-view
support std::string_view
2019-04-27 18:33:59 +09:00
ToruNiina
4bcc5e8375 Merge branch 'master' into as-something 2019-04-27 17:42:12 +09:00
Toru Niina
90f84000ba Merge pull request #59 from ToruNiina/preserve-comments
Preserve comments; related to #48
2019-04-27 17:40:26 +09:00
ToruNiina
20a13754a7 chore: update README for as_* functions 2019-04-27 16:50:44 +09:00
ToruNiina
aa7b9a3965 refactor: rename as_floating -> as_float
Actually, since `floating` is used for toml::types, `as_floating`
seems to be clearer. But currently `is_*` functions uses `float`,
not `floating`, so `as_float` is chosen for the consistency.
In a future release, possibly v3, those names may need to be
re-considered for clarity.
2019-04-27 16:45:25 +09:00
ToruNiina
84ac1d10f3 test: add test for toml::value::as_something 2019-04-27 16:22:50 +09:00
ToruNiina
0d623856a7 feat: add value::as_something() for convenience 2019-04-27 16:22:23 +09:00
ToruNiina
ec0d4e4e8c chore: update README for comments 2019-04-27 15:50:54 +09:00
ToruNiina
80ea736b3f ci: try to update standard library on travis 2019-04-27 14:46:40 +09:00
ToruNiina
ebaa5dfb51 chore: fix build settings for OS X on Travis 2019-04-26 21:10:29 +09:00
ToruNiina
f3bdf083fe fix: fix typo in test code for string_view 2019-04-26 16:51:23 +09:00
ToruNiina
1ce54a9cf9 chore: add auto test with c++17 + latest compilers 2019-04-26 16:35:03 +09:00
ToruNiina
6383a93ce7 chore: check CXX_STANDARD exists or not 2019-04-26 16:33:48 +09:00
ToruNiina
01aa2ef5b2 feat: add ctor to value to init with string_view 2019-04-26 16:33:09 +09:00
ToruNiina
819351f5a4 test: add test for init toml::value by string_view 2019-04-26 16:32:23 +09:00
ToruNiina
2967cebfb3 test: add test to get a toml::value as string_view 2019-04-26 16:31:59 +09:00
ToruNiina
32e9a2c1c7 test: add test for comments in an array 2019-04-26 15:35:41 +09:00
ToruNiina
8e0a40a1aa test: add test for getting comments 2019-04-25 22:34:12 +09:00
ToruNiina
e460826084 feat: enable to get a comment related to a value
- comment_before(): get comments just before a value.
- comment_inline(): get a comment in the same line as a value.
- comment(): get comment_before() + comment_inline().
2019-04-25 22:32:39 +09:00
ToruNiina
aa3445f38c feat: add functions to get comments around region 2019-04-25 22:32:18 +09:00
ToruNiina
408b7bf35e Merge branch 'master' into string-view 2019-04-23 23:32:08 +09:00
ToruNiina
6185dfee14 chore: fix typo in README 2019-04-23 23:31:37 +09:00
ToruNiina
37aa2739a5 chore: add description about string_view to README 2019-04-23 23:27:53 +09:00
ToruNiina
d061c33a16 feat: enable toml::get with std::string_view 2019-04-23 23:24:23 +09:00
ToruNiina
0c7d2d07d4 feat: do not consider string_view as a container
it is a kind of string.
2019-04-23 23:23:57 +09:00
ToruNiina
62cf4373bd feat: conversion toml::string <-> string_view 2019-04-22 23:18:05 +09:00
Toru Niina
a74ad23514 Merge pull request #58 from ToruNiina/improve-err-msg-literal
Improve error message from toml literal
2019-04-22 20:50:11 +09:00
ToruNiina
2d9b4992ec fix: restrict length of underline by size of line
in some cases, `region` contains several lines and `region::size`
returns the whole size that is a sum of lengthes of all the lines.
To avoid too long underlines, restrict the length of underline by
the length of the line that is shown in the message.
2019-04-21 16:38:08 +09:00
ToruNiina
82e8c1e68b fix: skip first ws/newlines in toml literal
when ""_toml literal is used with C++11 raw-string literal,
it normally starts with newline like the following.
```cpp
const auto v = u8R"(
    [table]
    key = "value"
    )"_toml;
```
With this, the error message shows the first empty line that starts just
after `u8R"(` and thus the error message shows nothing. To avoid this,
skip the first empty lines and whitespaces in literal.
2019-04-21 16:31:24 +09:00
ToruNiina
46be054ce9 fix: improve err msg for multiline inline table
show "missing curly brace" instead of "missing table key-value separator"
2019-04-19 13:22:13 +09:00
ToruNiina
789d784769 chore: update README; about literals 2019-04-19 13:18:35 +09:00
ToruNiina
81deb8efde chore: update README 2019-04-19 12:41:24 +09:00
Toru Niina
072dccd05d Merge pull request #56 from ToruNiina/optimization
Optimization
2019-04-19 01:30:29 +09:00
ToruNiina
637c99d637 refactor: generate error message in parser 2019-04-18 15:09:58 +09:00
ToruNiina
0f48852730 perf: check value type before parsing
to avoid needless error message generation
2019-04-18 14:26:27 +09:00
ToruNiina
0499b2907d Merge branch 'master' into optimization 2019-04-18 14:10:08 +09:00
ToruNiina
61e69c9251 fix: count line number from 1, not 0 2019-04-18 13:56:19 +09:00
ToruNiina
4a560ea1e5 fix: show correct error message 2019-04-18 00:04:33 +09:00
ToruNiina
c5b6ee6f81 feat: add yet another constructor to value
to make implementation of parse_value easier
2019-04-17 23:43:42 +09:00
ToruNiina
1a7bf63622 Merge branch 'master' into optimization 2019-04-17 14:58:28 +09:00
Toru Niina
8847cdc0a9 Merge pull request #55 from wbenny/master
fix /W4 warnings on MSVC
2019-04-17 13:16:19 +09:00
ToruNiina
c82e76a111 perf: check string type before parsing it
to avoid unncessary error message generation, check the first some
characters before parsing it. It makes parsing process faster and
is also helpful to generate more accurate error messages.
2019-04-16 21:47:24 +09:00
ToruNiina
4db486d76d perf: check integer prefix before trying to parse
all the parsers generate error messages and error message generation is
not a lightweight task. It concatenates a lot of strings, it formats
many values, etc. To avoid useless error-message generation, first check
which prefix is used and then parse special integers. Additionally, by
checking that, the quality of the error message can be improved (later).
2019-04-16 21:37:12 +09:00
ToruNiina
91966a6917 perf: do not use concat_string if it is not needed
At the earlier stage of the development, I thought that it is useful if
lexer-combinators generate error messages, because by doing this,
parser would not need to generate an error message. But now it turned
out that to show an appropriate error message, parser need to generate
according to the context. And almost all the messages from lexer are
discarded. So I added another parameter to lexer-combinator to suppress
error message generation. In the future, we may want to remove messages
completely from lexers, but currently I will keep it. Removing those
unused message generation makes the parsing process faster.
2019-04-16 21:09:59 +09:00
ToruNiina
b3917aaadf refactor: use snprintf to show char in hex
instead of std::ostringstream.
2019-04-16 20:54:29 +09:00
Petr Benes
ba307003c4 fix /W4 warnings on MSVC 2019-04-16 13:25:45 +02:00
Toru Niina
21fd1271d9 Merge pull request #54 from ToruNiina/hotfix
fix: resolve ambiguity in the `""_toml` literal
2019-04-15 13:34:35 +09:00
ToruNiina
f9ab7d6f56 chore: add note about literals to README.md 2019-04-14 20:08:23 +09:00
ToruNiina
0a3a41a708 test: add test for literals for difficult case 2019-04-14 20:06:11 +09:00
ToruNiina
6c2a536fa5 fix: check literal has a table or an array first
The literal like this `"[[table]]"_toml` caused a syntax error. It is
because the literal parser first check that it might be a bare value
without a key, and parse_array directory throws syntax_error. This
change makes the parser first check a literal is a name of table, and
then parse the content.
2019-04-14 19:48:43 +09:00
Toru Niina
26eced3640 Merge pull request #52 from ToruNiina/speedup-for-large-files
Speedup parsing large files
2019-04-13 16:11:21 +09:00
ToruNiina
6f950c9ec8 perf: cache current line number in location
`location::line_num()` function used to be implemented by using
`std::count`, so each time the parser encounters a type mismatch,
`std::count` was called with almost whole file. It decelerates the
parsing process too much, so I decided to add `line_number_` member
variable to `location` and add `advance/retrace/reset` to `location`
in order to modify the position that is pointed.
2019-04-12 18:32:46 +09:00
ToruNiina
ea13e40889 feat: add static_assert for location/range
to check the container is randomly-accessible
2019-04-12 18:00:53 +09:00
ToruNiina
595fb1aef3 refactor: remove unused function parameter names 2019-04-06 19:39:13 +09:00
ToruNiina
18986978fb chore: add short example code to README 2019-03-24 21:30:27 +09:00
ToruNiina
c3cb22a789 chore: fix example of err msg by re-running sample 2019-03-21 18:12:35 +09:00
ToruNiina
5aebd6b562 fix: restore the back compat of format_error
the following code was okay in the last release
```
toml::format_error("[test]", v, "test", {"hint1", "hint2"})
```
but was not okay in the current master. This commit fixes this.

cons: By this, the number of values to show is limited upto 3.
2019-03-20 20:46:22 +09:00
ToruNiina
4c13085b35 fix: add stream operator for toml::table 2019-03-20 19:30:08 +09:00
ToruNiina
8709e8a14e chore: fix incorrect syntax highlight in README 2019-03-20 19:29:03 +09:00
ToruNiina
9eea46ec01 chore: fix typoes and broken links in README 2019-03-20 12:06:55 +09:00
ToruNiina
2e9f937c43 chore: update README 2019-03-20 11:53:03 +09:00
Toru Niina
65b10b6537 Merge pull request #46 from ToruNiina/toml-literal
feat: add ""_toml literal
2019-03-20 10:12:56 +09:00
ToruNiina
b51a8d5966 fix: add missing include file in test code 2019-03-20 00:58:58 +09:00
Toru Niina
55e3d70869 Merge pull request #47 from ToruNiina/format-table
`toml::format` and top-level table
2019-03-20 00:49:59 +09:00
ToruNiina
20ba57e389 fix: add missing const specifier to some of get()s 2019-03-20 00:37:13 +09:00
ToruNiina
39bc3c64fe test: add test for ""_toml literals 2019-03-20 00:36:46 +09:00
ToruNiina
40ccf1d912 feat: add argument to control top-level inlinization 2019-03-19 23:25:26 +09:00
ToruNiina
982ae36428 feat: add ""_toml literal 2019-03-19 21:34:57 +09:00
ToruNiina
d6714ec450 feat: detect value type and format as a file
in toml::format
2019-03-19 21:24:51 +09:00
ToruNiina
773c3816be ci: remove needless confirmation on CI 2019-03-19 19:39:45 +09:00
Toru Niina
1b417ddc7a Merge pull request #45 from ToruNiina/get_or
fix `get_or` and add `find_or`
2019-03-19 01:41:21 +09:00
ToruNiina
7a0ecf977d feat: add find_or(table, key, fallback)
get_or(value, fallback) is still ok, but get_or(table, key, fallback)
is now deprecated.
2019-03-18 17:44:03 +09:00
ToruNiina
aade704411 refactor: remove needless overload of get_or 2019-03-18 17:10:18 +09:00
ToruNiina
ca3f6102ef fix: correctly resolve overloads of get_or 2019-03-18 16:44:36 +09:00
ToruNiina
4a58b629ce feat: add a way to check arg is "string literal" 2019-03-18 16:31:12 +09:00
ToruNiina
3adba237b8 feat: enable to show message for deprecated() 2019-03-18 16:28:27 +09:00
Toru Niina
ccf03d9291 Merge pull request #44 from ToruNiina/test-link
test: add test for multiple translation unit
2019-03-18 15:20:04 +09:00
Toru Niina
30ae90ebd5 Merge pull request #43 from ToruNiina/hotfix
fix: incorrect move in constructor and return type deducing in toml::visit
2019-03-18 14:08:23 +09:00
ToruNiina
d5369c3429 test: add test for multiple translation unit 2019-03-18 12:39:58 +09:00
Toru Niina
48f2f0555d Merge pull request #42 from ToruNiina/test-suite
run toml-test suite
2019-03-18 12:33:48 +09:00
ToruNiina
f40fd12e25 refactor: add and rewrite comments 2019-03-18 11:09:12 +09:00
ToruNiina
65c2c3c238 fix: correctly deduce return value of visitor 2019-03-18 10:53:04 +09:00
ToruNiina
891a61a5e3 fix: do not move array element without checking 2019-03-18 02:05:55 +09:00
ToruNiina
1e6f30f6fa chore: update README.md 2019-03-18 01:50:23 +09:00
ToruNiina
02346a3126 Merge branch 'master' into test-suite 2019-03-18 01:40:17 +09:00
Toru Niina
1908f18e95 Merge pull request #41 from ToruNiina/hotfix
fix: simplify and correct the format of timezone
2019-03-18 01:39:11 +09:00
ToruNiina
3bfa7f09ba test: use the test suite in the effective way
add tests/check_toml_test.cpp to compare json object
2019-03-18 01:36:43 +09:00
ToruNiina
243f43fafd Merge branch 'master' into hotfix 2019-03-17 21:16:37 +09:00
ToruNiina
66e27a94b6 fix: simplify and correct the format of timezone 2019-03-17 21:14:17 +09:00
ToruNiina
227688ec63 ci: make result clearer a bit 2019-03-17 19:36:23 +09:00
ToruNiina
e761a503c0 ci: fix silly mistake in circleci script 2019-03-17 19:27:58 +09:00
ToruNiina
209ad79a8f ci: fix config file of circleci 2019-03-17 19:26:22 +09:00
ToruNiina
cdf209d7f6 ci: show the status on CI 2019-03-17 19:23:52 +09:00
ToruNiina
77ab391885 ci: fix name of directory and add test script 2019-03-17 19:20:24 +09:00
ToruNiina
6628fe5ace test: add language agnostic toml-test 2019-03-17 19:12:13 +09:00
Toru Niina
f3e3000d45 Merge pull request #40 from ToruNiina/remove-to-toml
refactor: remove to_toml and related tests
2019-03-17 13:12:30 +09:00
Toru Niina
f7380c6e32 Merge pull request #39 from ToruNiina/throw-incorrect-unicode
Throw syntax_error when parser encounter an incorrect utf-8 codepoint
2019-03-17 13:12:16 +09:00
Toru Niina
d86870e038 Merge pull request #38 from ToruNiina/get-any-type
extended conversions
2019-03-17 13:11:59 +09:00
Toru Niina
0908806915 Merge pull request #33 from ToruNiina/is-something
add `is_boolean` and other stuffs like that
2019-03-16 23:55:01 +09:00
ToruNiina
d17c192681 refactor: remove to_toml and related tests 2019-03-16 17:05:58 +09:00
ToruNiina
cad8f51256 doc: add explanation of conversions to README 2019-03-16 16:56:37 +09:00
ToruNiina
43014c6619 fix: remove redefined default template argument 2019-03-16 16:24:10 +09:00
ToruNiina
30a41aa710 fix: use older style in BOOST_TEST 2019-03-16 16:15:01 +09:00
ToruNiina
04bfeba3f2 merge branch master into get-any-type 2019-03-16 15:58:18 +09:00
ToruNiina
190636b791 fix: support getting a container of external types 2019-03-16 15:52:22 +09:00
ToruNiina
31e450f9af test: add test for from/into based conversions 2019-03-16 15:46:21 +09:00
ToruNiina
b1b72a94a8 feat: support conversion with external types 2019-03-16 14:44:04 +09:00
ToruNiina
6929bcdf78 feat: add from<T> and into<T> 2019-03-16 14:27:05 +09:00
ToruNiina
fd063af7ce refactor: make include guard style uniform 2019-03-16 14:19:47 +09:00
ToruNiina
df6dcbc4ed feat: check a class has from/into_toml member fn
to support better serialization
2019-03-16 14:16:31 +09:00
ToruNiina
9b8db6a225 fix: remove extraneous null character after float
the bug was introduced by snprintf
2019-03-15 19:30:36 +09:00
ToruNiina
76863cb27f refactor: simplify branches about utf8 codepoint 2019-03-15 17:48:47 +09:00
ToruNiina
514df99e40 feat: consider invalid UTF-8 as syntax_error
the following codepoints are considered to be a syntax_error
- [0xD800, 0xDFFF]
- larger than 0x10FFFF
2019-03-15 17:39:31 +09:00
ToruNiina
055353a460 chore: merge branch 'master' into is-something 2019-03-15 17:25:17 +09:00
Toru Niina
9eb4008d6d Merge pull request #37 from ToruNiina/to-toml-deprecated
feat: mark to_toml as deprecated
2019-03-15 17:12:45 +09:00
ToruNiina
a04544637b feat: mark to_toml as deprecated
because the constructor of `toml::value()` supports all the stuff that
are supported by `to_toml`.
2019-03-15 14:29:32 +09:00
Toru Niina
4c7dc17b78 Merge pull request #36 from ToruNiina/refactor-format-underline
refactor: remove redundant function overload
2019-03-15 13:41:16 +09:00
ToruNiina
59aaaab436 test: add test to check format_error compiles 2019-03-15 12:40:01 +09:00
ToruNiina
61dfa4a2dc feat: format any number of values into an err msg
```cpp
toml::format_error("[error] message", v1, "v1", v2, "v2", ...);
```
2019-03-15 12:38:37 +09:00
ToruNiina
ca337a1110 chore: merge branch 'master' into travis-ci 2019-03-14 23:02:04 +09:00
ToruNiina
510e10de95 ci: test numerous compilers on CI 2019-03-14 22:58:44 +09:00
ToruNiina
0babe8d589 fix: use format_underline for N regions everywhere 2019-03-14 00:59:10 +09:00
ToruNiina
5b2ce26721 refactor: remove redundant function
since N region format_underline() has been implemented, overloads for 1
and 2 region(s) are not needed.
2019-03-14 00:56:35 +09:00
Toru Niina
db4d99cd4f Merge pull request #35 from ToruNiina/suppress-warning
fix: suppress warning about sign-unsign comparison
2019-03-13 15:01:51 +09:00
ToruNiina
74ceceef73 fix: suppress warning about sign-unsign comparison
The solution is not ideal, but it's okay at the line
2019-03-13 14:03:04 +09:00
Toru Niina
360e890cc0 Merge pull request #34 from ToruNiina/consider-locale
fix: use snprintf instead of stringstream
2019-03-13 09:56:32 +09:00
ToruNiina
46b35870c5 style: remove needless type casting 2019-03-13 01:17:27 +09:00
ToruNiina
dddcecb034 fix: use snprintf instead of stringstream
to avoid the effect of locale
2019-03-12 23:37:46 +09:00
ToruNiina
c4c416e8b2 doc: add is_* function to README 2019-03-12 22:18:25 +09:00
ToruNiina
6693ec78f4 test: add test for toml::value::is_something() 2019-03-12 20:44:27 +09:00
ToruNiina
dc112bd6c1 feat: add is_[boolean|integer|...]() member func
it is an alias to is<toml::value_t::[Boolean|Integer|...]>
2019-03-12 20:43:07 +09:00
ToruNiina
084e82a8a9 chore: update README 2019-03-07 14:09:02 +09:00
Toru Niina
f5079a7892 Merge pull request #32 from ToruNiina/allow-deeper-table-before
Allow deeper table before
2019-03-06 12:03:14 +09:00
ToruNiina
d90ffb63c6 Merge branch 'master' into allow-deeper-table-before 2019-03-05 23:27:11 +09:00
ToruNiina
b0ed122214 fix: allow deeper table appeared before
allow the following toml file.
```toml
[a.b.c]
d = 10
[a]
e = 2.718
```
2019-03-05 23:25:25 +09:00
ToruNiina
d88521d63c feat: enable to change region of value
To allow the following toml file, we need to replace the region after
the more precise region is found.
```toml
[a.b.c]
d = 42
[a]
e = 2.71
```
If the precise region (here, [a]) is found, the region of `a` should be
`[a]`, not `[a.b.c]`. After `[a]` is defined, toml does not allow to
write `[a]` twice. To check it, we need to replace the region of values
to the precise one.
2019-03-04 15:01:28 +09:00
ToruNiina
2accc9d22c fix: diagnose, but not throw for unicode error
in 2.0.x and 2.1.0, README says "it shows warning" for invalid unicode
codepoints. So far, this library just show an error message in stderr
for this case. It is not good to change the behavior fatal in the next
minor release, 2.1.1, that includes patches and improved error msgs.
I will make it throw syntax_error after 2.2.0 for invalid unicode
codepoints. For now, I will keep it to be "warning".
2019-03-03 18:56:45 +09:00
Toru Niina
363927f489 Merge pull request #31 from ToruNiina/err-msg-inhomogenous-array
improve error messages for invalid arrays
2019-03-02 23:07:29 +09:00
ToruNiina
ae793fb631 feat: improve error message for invalid array 2019-03-02 17:56:16 +09:00
ToruNiina
944b83642a feat: make location to inherit region_base
To generate error message, it is better to have the same interface.
Also, location can be considered as a region having only one character.
2019-03-02 17:52:00 +09:00
Toru Niina
5a8e5dee73 Merge pull request #30 from ToruNiina/hotfix
small patches for parser
2019-03-02 16:11:31 +09:00
ToruNiina
7f870d5861 fix: diagnose invalid UTF-8 codepoints 2019-03-02 01:57:05 +09:00
ToruNiina
536b23dc84 fix: allow empty table in the middle of a file 2019-03-01 22:53:16 +09:00
ToruNiina
0c9806e99f fix: diagnose key after [table.key] pattern
the following is not a valid toml format.
```
[table] key = "value"
```
this commit enables to diagnose that pattern.
2019-03-01 22:37:52 +09:00
ToruNiina
5a92932019 fix: disallow invalid escape sequence 2019-03-01 22:13:32 +09:00
ToruNiina
e929d2f00f fix: allow empty input file (to be an empty table) 2019-02-27 12:30:57 +09:00
Toru Niina
1e1e4c06e8 Merge pull request #29 from ToruNiina/err-msg-dotted-key
Error message for getting values corresponds to dotted keys
2019-02-27 12:21:03 +09:00
ToruNiina
d0726db473 chore: merge branch master into err-msg-dotted-key 2019-02-27 01:26:36 +09:00
Toru Niina
4cdc15a824 Merge pull request #28 from xaxousis/master
Add location to error string in parse_* functions
2019-02-27 01:25:52 +09:00
ToruNiina
b36fdf2f54 refactor: remove internal fn not needed any more
The function was needed to copy region information from value to value,
for a useful error message. Because of the last few commits, the region
information about keys are passed to insert_nested_keys that requires
the function which is removed. And it turned out that the function is no
longer required. It is originally a workaround, so I removed it.
2019-02-27 01:07:00 +09:00
ToruNiina
73ba6b385f feat: use key-region to represent table
use x.y.z = 42
    ~~~ here as the region of the table `x.y`
2019-02-27 01:02:39 +09:00
ToruNiina
30d1639aa4 refactor: return region info from parse_kvpair 2019-02-27 00:21:05 +09:00
Quentin Khan
d82814fc86 Add location to error string in parse_* functions 2019-02-26 14:56:58 +01:00
ToruNiina
2220efd682 chore: show appvayor status of master branch
other branches might be unstable, so they might fail. It is good to show
the status of the stable branch, rather than the experimental branches.
2019-02-26 00:26:04 +09:00
ToruNiina
679b365cf7 feat: get region info when parsing keys
Error messages related to dotted keys looks weird. like:
 1 | a.b.c = 42
   |         ~~ in this table
The underlined token is not a table. This should be like the following.
 1 | a.b.c = 42
   | ~~~ in this table
To implement this, the region information is needed when the keys are
read. This commit add this functionality, though currently the region
information is not used yet.
2019-02-26 00:17:28 +09:00
ToruNiina
83bf83b6dd style: add braces to if and remove additional else 2019-02-19 02:56:15 +09:00
ToruNiina
321364c7c2 fix: format char in an error message correctly 2019-02-19 02:46:48 +09:00
ToruNiina
d8707d5867 chore: fix README 2019-02-17 00:22:19 +09:00
ToruNiina
2dd0a78c52 fix: reset stream width before printing
without this, the first line of the serialized result becomes too wide
2019-02-16 23:55:19 +09:00
Toru Niina
d7b8c3c78f Merge pull request #18 from ToruNiina/threadsafe-localtime
add threadsafe localtime_(s|r)
2019-02-16 23:28:48 +09:00
Toru Niina
2f0148a2df Merge pull request #26 from ToruNiina/serialize
add serializer
2019-02-16 23:27:05 +09:00
ToruNiina
4accc29984 chore: update README 2019-02-14 16:47:15 +09:00
ToruNiina
19b9af2494 Merge branch 'master' into serialize 2019-02-14 16:34:45 +09:00
ToruNiina
0aa50e9439 style: just add newlines to README 2019-02-14 16:26:48 +09:00
ToruNiina
a00a906482 fix: add comma at correct position 2019-02-14 16:17:32 +09:00
ToruNiina
19ad7d7c96 fix: remove needless empty line from serialization 2019-02-14 16:17:04 +09:00
ToruNiina
251e55da42 fix: don't ignore std::setw(0) 2019-02-14 15:49:27 +09:00
ToruNiina
32f1b2060a fix: avoid width overflow 2019-02-14 15:49:13 +09:00
ToruNiina
b1c54532df feat: improve array serialization
- make multiline array more clean
- short-circuit for empty array
2019-02-14 15:48:05 +09:00
ToruNiina
38c67f16e8 fix: initialize float precition correctly 2019-02-14 15:47:00 +09:00
ToruNiina
24aefc52a1 test: set width in test_serialize 2019-02-14 15:46:12 +09:00
ToruNiina
ba8c205253 fix: change CRLF into LF before comparison 2019-02-13 23:48:53 +09:00
ToruNiina
31193d99ba Merge branch 'master' into serialize 2019-02-13 23:16:39 +09:00
ToruNiina
c4aecc8e4b chore: update README badges 2019-02-13 22:36:29 +09:00
Toru Niina
60c81d06a0 Merge pull request #25 from ToruNiina/hotfix
fix: open file as binary-mode #16
2019-02-13 21:14:15 +09:00
ToruNiina
46569da231 fix: avoid auto-conversion while making test case 2019-02-13 19:51:54 +09:00
ToruNiina
5e20a8ff16 fix: add scope to the test case to flush 2019-02-13 19:26:52 +09:00
ToruNiina
dd9319245e fix: open file as binary-mode #16
to avoid inconsistency between file size (obtained by tellg) and the
size of the actual contents that would be read later
2019-02-13 19:18:09 +09:00
ToruNiina
4bbe42d105 test: add test_serialize_file 2019-02-13 13:51:36 +09:00
ToruNiina
5bdc022627 fix: correctly serialize quoted keys 2019-02-13 13:51:08 +09:00
ToruNiina
41e354f1ee supress warnings while skipping switch-cases 2019-02-13 13:50:33 +09:00
ToruNiina
d1c76709b0 add serializer #23 2019-02-13 13:37:58 +09:00
ToruNiina
64774a8db0 add toml::visit to use it in serializer 2019-02-13 13:36:55 +09:00
ToruNiina
53f6b8268b fix: compare offset_datetime correctly 2019-02-13 13:34:26 +09:00
ToruNiina
32dcc35918 move return_type_of_t from result to traits 2019-02-13 13:34:03 +09:00
ToruNiina
8c3854b28b update README 2019-01-31 15:37:25 +09:00
Toru Niina
75af9c79df Merge pull request #22 from xaxousis/master
Fix multiple definition error
2019-01-31 01:34:33 +09:00
Quentin Khan
1dfe32acd8 Fix multiple definition error 2019-01-30 17:06:23 +01:00
Toru Niina
5dfdbe4bff Merge pull request #20 from ToruNiina/format-error
add an extra parameter `hints` to format_error
2018-12-27 20:34:53 +09:00
Toru Niina
4584eeb57a Merge pull request #19 from ToruNiina/find-default-type
add default template arg to toml::find
2018-12-27 20:34:36 +09:00
ToruNiina
aa67069387 move hints to the internal function 2018-12-27 16:32:20 +09:00
ToruNiina
ee3424ad51 add an extra parameter hints to format_error 2018-12-27 16:26:23 +09:00
ToruNiina
17def14ab6 add default template arg to toml::find
in most of the use cases, toml::value is used (to show error message).
2018-12-27 15:58:50 +09:00
ToruNiina
51dd3abcae remove one branch by preprocessor
since localtime in windows is already thread-safe, there are no need to
change the function.
2018-12-26 13:38:01 +09:00
ToruNiina
825b2c30a1 add threadsafe localtime_(s|r) 2018-12-25 22:40:52 +09:00
Toru Niina
b5b8830c29 Merge pull request #17 from ToruNiina/hotfix
fix the error with BOM and end of file w/o newline
2018-12-24 16:37:10 +09:00
ToruNiina
87a5c844c2 add test cases for the end-of-file problems 2018-12-24 16:02:32 +09:00
ToruNiina
11c7ee4501 fix the case of file w/o newline at the end
toml::parse failed with the file that contains whitespace or comment at
the end of file without newline. this commit fixes the error.
2018-12-24 16:00:33 +09:00
ToruNiina
d24a188d4c fix the error while reading BOM.
remove possible UB because of the use-after-move.
2018-12-24 15:06:26 +09:00
Toru Niina
29876221f8 Merge pull request #15 from ToruNiina/performance
speedup by removing needless format_underline
2018-12-23 18:30:19 +09:00
ToruNiina
7c03c446fe speedup by removing needless format_underline
drastical speedup for long toml files
2018-12-23 15:22:12 +09:00
Toru Niina
cfdd4d4a90 Merge pull request #14 from ToruNiina/error-message
improve error message quality
2018-12-22 18:46:00 +09:00
ToruNiina
5546b3389d Merge branch 'master' into error-message 2018-12-22 17:55:59 +09:00
ToruNiina
9c95992dad fix error message for empty value 2018-12-22 17:44:09 +09:00
ToruNiina
edb48b2872 add test_error_detection to check it detects error 2018-12-22 17:43:42 +09:00
ToruNiina
c63ac7e435 detect syntax_error; appending array-of-tables
toml file like the following is explicitly prohibited.
a = [{b = 1}]
[[a]]
b = 2
this commit detects this kind of syntax-error while parsing toml file
2018-12-22 17:07:06 +09:00
ToruNiina
fec49aaaa3 fix error message: add missing spaces 2018-12-22 17:06:36 +09:00
ToruNiina
617187969c fix result::unwrap_or with rvalue ref; merge branch 'hotfix' 2018-12-17 23:54:17 +09:00
ToruNiina
e3217cd572 quit returning rvalue ref from unwrap_or 2018-12-17 23:17:45 +09:00
ToruNiina
4d02f399a2 add temporary to receive rvalue 2018-12-17 23:03:53 +09:00
ToruNiina
24723226f1 remove template argument from result::unwrap_or 2018-12-17 19:18:16 +09:00
ToruNiina
7b3684b54e add and_other and or_other to toml::result
effectively same as Rust's std::Result::and and or.
2018-12-17 18:24:41 +09:00
ToruNiina
13c1f9c259 output filename of the second value2 if different
in format_error.
2018-12-17 18:07:57 +09:00
ToruNiina
6df75ad28e fix README 2018-12-17 16:56:09 +09:00
ToruNiina
74fc70cfee return copied object from except
having reference makes some technical difficulties.
2018-12-17 10:57:40 +09:00
Toru Niina
91ac2debce Merge pull request #12 from ToruNiina/hotfix
enable to get toml::value as toml::value
2018-12-17 10:50:05 +09:00
Toru Niina
0de89a9f19 Merge pull request #13 from ToruNiina/error-format
enable to show user-defined error message with (a) toml::value(s)
2018-12-17 10:49:47 +09:00
ToruNiina
130609bf5f update README 2018-12-16 23:51:38 +09:00
ToruNiina
ab41e7acb9 enable to pass 2 value and change interface for clarity 2018-12-16 21:50:18 +09:00
ToruNiina
c15bc8df4a add format_error(toml::value, msg, comment) 2018-12-16 21:46:32 +09:00
ToruNiina
19524dbc4b fix silly typo 2018-12-16 21:13:21 +09:00
ToruNiina
c2e733a65d enable to get toml::value as toml::value 2018-12-16 20:50:40 +09:00
ToruNiina
0c08b9e940 fix typo 2018-12-15 22:02:46 +09:00
ToruNiina
06197605ba add link to toml-v0.5.0 official 2018-12-13 23:58:37 +09:00
ToruNiina
5c24cfd325 add example of multi-line error message 2018-12-13 23:47:32 +09:00
Toru Niina
abb6ae517d Merge pull request #11 from ToruNiina/toml-v050
WIP: major update: support TOML v0.5.0
2018-12-13 21:38:03 +09:00
ToruNiina
fd21d5dd95 add simplest copyright notice 2018-12-13 20:44:10 +09:00
ToruNiina
57de57a1de improve error message for empty value 2018-12-13 20:37:40 +09:00
ToruNiina
e86777d19c improve error message for conflicting tables 2018-12-13 20:17:57 +09:00
ToruNiina
e79069cc47 enable to show err msg for invalid insertion
like, with the following (invalid) toml file

> a.b = "value"
> a.b.c = 42

The error message becomes

> terminate called after throwing an instance of 'toml::syntax_error'
>   what():  [error] toml::insert_value: target (a.b) is neither table nor
> an array of tables
>  --> example.toml
>  1 | a.b = "value"
>    |       ~~~~~~~ actual type is string
>  ...
>  2 | a.b.c = 42
>    |         ~~ inserting this
2018-12-13 17:09:38 +09:00
ToruNiina
f60e93c36f enable to assign value keeping region info 2018-12-13 17:07:26 +09:00
ToruNiina
e5c29c2870 enable to show err msg for 2 different location 2018-12-13 17:07:03 +09:00
ToruNiina
acc7b7870f remove format_error_for_value and add get_region instead
it is convenient to have get_region function that can access region_info
in toml::value. get_region is placed in toml::detail and made friend of
toml::value because I don't want to make toml::value::region_info public
and keep it internal use only.
2018-12-13 16:13:05 +09:00
ToruNiina
06f04af375 fix typoes in README 2018-12-13 14:58:42 +09:00
ToruNiina
5125287ac7 fix datetime conversion
use internal duration type in std::chrono::system_clock::time_point
2018-12-13 14:57:42 +09:00
ToruNiina
56287803e7 update README a bit 2018-12-13 13:21:26 +09:00
ToruNiina
95d73a290f add test case for reading dotted-keys 2018-12-13 13:07:48 +09:00
ToruNiina
26e0d87d3b enable nanoseconds in datetimes 2018-12-13 12:49:53 +09:00
ToruNiina
fb6d51954a turn test_parse_unicode on; no change required 2018-12-13 02:28:52 +09:00
ToruNiina
4d7cfc9d1d turn test_parse_file on
the required change is;
- change Datetime -> offset_datetime and construct correctly.
2018-12-13 02:26:55 +09:00
ToruNiina
514f3c773f set test_from_toml 2018-12-13 02:24:03 +09:00
ToruNiina
77b237c53a update README 2018-12-13 02:00:42 +09:00
ToruNiina
27a80b1214 rename get(table, key) to find() 2018-12-13 02:00:13 +09:00
ToruNiina
f62bcb3077 update cmakelists 2018-12-13 01:30:25 +09:00
ToruNiina
be1a310ae5 move test for find to get_related 2018-12-13 01:30:06 +09:00
ToruNiina
affa159c82 add get_or(value, key, opt) 2018-12-13 01:29:23 +09:00
ToruNiina
901c299c40 add unwrap_or to result 2018-12-13 01:28:55 +09:00
ToruNiina
2080b30110 add test cases for test_to_toml 2018-12-13 00:38:36 +09:00
ToruNiina
c15cb15c4c simplify to_toml implementation 2018-12-13 00:38:04 +09:00
ToruNiina
d370ae7d0d set tm_isdst as negative value 2018-12-13 00:35:43 +09:00
ToruNiina
83b588a8c8 rename test code 2018-12-13 00:35:05 +09:00
ToruNiina
5bfbbe35a6 update README 2018-12-12 23:23:59 +09:00
ToruNiina
c69969733f use carriage return depending on env 2018-12-12 23:22:31 +09:00
ToruNiina
47cd6f5a41 remove redundant error message 2018-12-12 23:17:28 +09:00
ToruNiina
a19c9b4a39 add test case for find & get 2018-12-12 21:55:11 +09:00
ToruNiina
f64430af92 remove old test; individual test cases are added
test_parse_* is now available, old test_parser is not needed now
2018-12-12 20:55:58 +09:00
ToruNiina
8e154cdd74 add test case for parsing datetime 2018-12-12 20:55:30 +09:00
ToruNiina
65cfa9d06b remove unused file because its not stable
since toml::format is not stable now, remove once for the next release.
2018-12-12 20:35:21 +09:00
ToruNiina
cfd82c95f0 add test case for getting converted map 2018-12-12 20:32:26 +09:00
ToruNiina
18a22eb3c4 add test cases for datetime variants 2018-12-12 20:28:31 +09:00
ToruNiina
03be08a2e6 fix conversion from offset_datetime to system_clock::time_point 2018-12-12 20:28:11 +09:00
ToruNiina
27ad4e2d8f cleanup headers 2018-12-12 19:39:04 +09:00
ToruNiina
0924164f51 add a note about the error message 2018-12-12 19:36:57 +09:00
ToruNiina
d4a4865217 fix some errors in README 2018-12-12 19:35:33 +09:00
ToruNiina
1bc66f6c28 Merge branch 'toml-v050' of github.com:ToruNiina/toml11 into toml-v050 2018-12-12 19:33:13 +09:00
ToruNiina
b015e1ac5b update README for the next version 2018-12-12 19:33:01 +09:00
ToruNiina
5aae0b17c8 change error message; require unicode codepoint
before this, it recommends the range that can be represented by utf-8
but the range of valid unicode codepoint is narrower than that. for
error message, it is good to recommend valid unicode codepoint.
2018-12-12 19:14:27 +09:00
ToruNiina
0f83ee6039 change temporaly loc from token to copy of loc
location constructed from token string does not has correct line number
information. to show an informative error message about UTF-8 and escape
sequences, parse_(ml_)basic_string requires those information that can
only be given from root location<Container>.
2018-12-12 19:12:23 +09:00
ToruNiina
879b7d3bff improve format of error message for utf-8 2018-12-12 19:01:22 +09:00
ToruNiina
c33ad31981 split lexer for escape sequence for unicode 2018-12-12 18:59:20 +09:00
ToruNiina
5d29509d98 remove duplicated default argument for SFINAE 2018-12-12 18:58:54 +09:00
ToruNiina
717e03cd4a add find-get overload functions 2018-12-12 17:55:34 +09:00
ToruNiina
5a20d55dd0 add test for toml::get 2018-12-12 17:23:06 +09:00
ToruNiina
dc060ba840 add explicit std::move to toml::get(&&) 2018-12-12 17:22:41 +09:00
ToruNiina
fcbfbd3a26 supress warning about comparison between signed and unsigned 2018-12-12 16:12:10 +09:00
ToruNiina
0c9b785969 add missing include file 2018-12-12 16:11:37 +09:00
ToruNiina
bcaf5baf88 fix parse_array_of_table_key
allow whitespace before and after [[ and ]] (like, [[ a.b ]])
2018-12-12 12:14:11 +09:00
ToruNiina
5dea88001e add test case for array-of-tables 2018-12-12 12:13:49 +09:00
ToruNiina
b63dc1f370 remove extra comma 2018-12-12 01:36:20 +09:00
ToruNiina
d3e88b3082 add test case for table key 2018-12-12 01:31:36 +09:00
ToruNiina
a1a81089c5 skip whitespace before/inside/after dotted-keys 2018-12-12 01:30:47 +09:00
ToruNiina
765ab97d8b add whitespace between [] and key
[ a.b.c ] is allowed. also, [[ a . b ]] is allowed.
dotted key matches `a.b.c` only, so the explicit whitespace is needed.
2018-12-12 01:27:10 +09:00
ToruNiina
9f8e86524a add a lot of dotted keys to test_lex 2018-12-12 01:26:56 +09:00
ToruNiina
4d64c0d8af add tests for inline table 2018-12-11 23:38:57 +09:00
ToruNiina
e810c3d35e add tests for equivalent operator 2018-12-11 23:33:32 +09:00
ToruNiina
fc3471434f add test for array 2018-12-11 23:31:24 +09:00
ToruNiina
be8600abfa add test for key and string 2018-12-11 23:25:44 +09:00
ToruNiina
e79e6150f2 update testing macro 2018-12-11 23:25:23 +09:00
ToruNiina
fc6a15440d enable format_underline to print hint with region 2018-12-11 22:22:07 +09:00
ToruNiina
d7bba10fa3 improve error message in parse_key_value_pair 2018-12-11 22:21:22 +09:00
ToruNiina
247bcb0714 show error message for inhomogenous array 2018-12-11 22:17:28 +09:00
ToruNiina
3055645323 remove old tests 2018-12-11 21:52:53 +09:00
ToruNiina
0253f49101 add a test for parser (WIP) 2018-12-11 21:51:39 +09:00
ToruNiina
27b9334f10 skip BOM if exists 2018-12-11 21:40:48 +09:00
ToruNiina
38135940e9 add expect<T>(toml::value) 2018-12-11 11:36:40 +09:00
ToruNiina
d75a977066 improve error message for bad unwrap a bit 2018-12-11 11:35:07 +09:00
ToruNiina
75c136924b add datetimes to chrono 2018-12-10 22:06:06 +09:00
ToruNiina
0759e757ae move is_chrono_duration from types to traits 2018-12-10 22:05:42 +09:00
ToruNiina
4e57c5f5df improve error message for invalid line
like a = 12 = true, newline is expected after 12
2018-12-10 21:43:02 +09:00
ToruNiina
ff83a6a477 remove redundant part of error messages 2018-12-10 21:42:56 +09:00
ToruNiina
3f991c4759 improve power of get 2018-12-10 15:58:20 +09:00
ToruNiina
bf2158ae98 add map from exact toml type -> toml::value_t 2018-12-10 15:57:44 +09:00
ToruNiina
ff19c9f492 add corresponding region to each value 2018-12-10 15:57:17 +09:00
ToruNiina
28ba2713ee fix initialization of region in value 2018-12-10 15:25:27 +09:00
ToruNiina
129ea81f66 remove redundant words in error message 2018-12-10 15:23:46 +09:00
ToruNiina
8dfe187d59 add a function to show a better error message 2018-12-10 15:06:28 +09:00
ToruNiina
8078c719fe remove old code 2018-12-10 00:15:41 +09:00
ToruNiina
8e18aa9b16 add toml::parse 2018-12-10 00:14:46 +09:00
ToruNiina
ed155a5040 remove help msgs in parse_value
because the error message becomes too long
2018-12-09 21:54:47 +09:00
ToruNiina
cf03a08632 re-write parser using result and new value
wip.
2018-12-09 19:32:30 +09:00
ToruNiina
34c3d33936 use vector instead of initializer_list 2018-12-09 19:30:46 +09:00
ToruNiina
c04b75b2e3 consider LF in the range when writing error msg 2018-12-09 18:08:04 +09:00
ToruNiina
e24039f4ef update toml::value and improve test_value
- enable to store new types
- store source string if possible
- refactoring
2018-12-09 18:03:20 +09:00
ToruNiina
dc8ccdc458 construct much more tmp variables
std::chrono::seconds -= std::chrono::milliseconds cannot be done bc
it represents the duration as integer value and milliseconds are less
than seconds. it causes compilation error when we pass a duration to
toml::local_time. to avoid this, we need to type-cast the values to
smaller duration, like sec -> msec
2018-12-09 18:00:46 +09:00
ToruNiina
2696e4e6ba split storage from value
also, quit inheritance in storage class
2018-12-09 16:41:45 +09:00
ToruNiina
d1d5ca6bf8 add toml::string to have basic/literal flag 2018-12-09 16:40:57 +09:00
ToruNiina
80eafd1424 add datetime variants and rearrange type-related functions 2018-12-09 16:34:47 +09:00
ToruNiina
9fadf71a10 add constructor from duration to local_time 2018-12-09 16:27:47 +09:00
ToruNiina
ac3025d92f change default return value of region_base 2018-12-09 13:39:13 +09:00
ToruNiina
b0e7efa1e0 make some constructors explicit 2018-12-09 13:38:57 +09:00
ToruNiina
84676eab0b improve quality of error message 2018-12-09 13:05:09 +09:00
ToruNiina
2b3a4d49a5 add region_base to contain it in toml::value
to make toml::get and toml::value::cast return better error messages
2018-12-09 12:41:38 +09:00
ToruNiina
f834e0d142 cosmetic: sort value_t in types.h 2018-12-09 11:06:19 +09:00
ToruNiina
a1aa780a60 Merge branch 'toml-v050' of github.com 2018-12-09 11:05:26 +09:00
ToruNiina
48f3b73b91 add ctor(local_datetime, time_offset) to offset_datetime 2018-12-09 00:11:07 +09:00
ToruNiina
04854f9d21 stop having begin/end iterator in region/location 2018-12-09 00:00:15 +09:00
ToruNiina
8388664fc6 add map_err_or_else to result 2018-12-08 22:44:15 +09:00
ToruNiina
bb215836dc add missing header files 2018-12-08 20:39:37 +09:00
ToruNiina
2b2a05148e add from_string to utility 2018-12-08 20:21:15 +09:00
ToruNiina
66807d19d1 add specializations 2018-12-08 19:40:58 +09:00
ToruNiina
861444a02b disable some of the tests once 2018-12-08 19:23:53 +09:00
ToruNiina
25789d1450 set Datetime as offset_datetime
prepare for TOML v0.5.0
2018-12-08 19:23:09 +09:00
ToruNiina
1e28cb2d13 add test for concat_string 2018-12-08 19:22:41 +09:00
ToruNiina
ae564bd814 change include file of test_traits 2018-12-08 19:22:31 +09:00
ToruNiina
366f72bbdd Merge branch 'datetime' into combinator 2018-12-08 19:06:19 +09:00
ToruNiina
3ef33c1637 change almost everything about datetime 2018-12-08 19:04:41 +09:00
ToruNiina
e05d0bdb84 stop using distance(next(iter), last)
under some condition, it causes serious error.
2018-12-06 20:13:06 +09:00
ToruNiina
5dbbc1fb1a add escaped newline to lexer for multiline string
to use it in parse_ml_basic_string
2018-12-06 19:53:49 +09:00
ToruNiina
b3b5682cc0 add message to bad_unwrap 2018-12-06 17:15:19 +09:00
ToruNiina
df314da751 change error message considering context
combinators are used with other parser-combinators. in such cases, empty
input means `not enough character`.
2018-12-06 17:03:57 +09:00
ToruNiina
3d1783e12a Merge 'types' into combinator 2018-12-06 16:06:25 +09:00
ToruNiina
f8aa604959 Merge branch 'result' into combinator
- fix some of the constructors of result
- add some utility member functions to boost
2018-12-06 12:57:58 +09:00
ToruNiina
e3f6805629 add conversion members to result 2018-12-06 12:47:14 +09:00
ToruNiina
1dddc6e26c add missing std::move for ctors 2018-12-06 12:46:32 +09:00
ToruNiina
5e052237ba add alias for snake_case types 2018-12-06 01:20:11 +09:00
ToruNiina
a995bd515b Merge branch 'master' into combinator
split typedefs from value.hpp
2018-12-05 21:42:14 +09:00
ToruNiina
00619c1c85 Merge branch 'types'; split typedefs from value 2018-12-05 21:41:22 +09:00
ToruNiina
532457345c split type definitions from value.hpp 2018-12-05 20:55:25 +09:00
ToruNiina
f9a018b5ea add source_name to test_lex_aux macros 2018-12-05 17:19:37 +09:00
ToruNiina
aa05858de3 add source_name to location/region to show filename
now error message prints the filename
2018-12-05 16:55:31 +09:00
ToruNiina
2b3c8887d6 add comment to confusing implementation 2018-12-04 22:17:20 +09:00
ToruNiina
932a0646ce force clamping character code in [0,256) 2018-12-04 21:58:47 +09:00
ToruNiina
c3a2cd8c1e use hexcode instead of u8 string on windows 2018-12-04 21:43:43 +09:00
ToruNiina
c0ce5a2d7d remove debug message from test code 2018-12-04 21:00:34 +09:00
ToruNiina
c3e1f68ef6 add u8 to the front of UTF-8 string literal
explicitly set the character encoding for them, for compatibility
2018-12-04 20:59:44 +09:00
ToruNiina
1a2fa6d53a add test for lexers 2018-12-04 20:30:21 +09:00
ToruNiina
17f3d96766 add lexers 2018-12-04 20:29:59 +09:00
ToruNiina
1f564ec047 add combinators to scan content 2018-12-04 20:29:39 +09:00
ToruNiina
679e282e23 make variables in region/location read-only
to avoid modifying mistakenly
2018-12-03 00:10:26 +09:00
ToruNiina
59588e3a10 add static_assert and useful member funcs 2018-12-02 23:22:27 +09:00
ToruNiina
f83a8b450e add concat_to_string to utility for error messges 2018-12-02 23:05:15 +09:00
ToruNiina
8bf97d8a00 add constructors that receive range to region 2018-12-02 23:04:49 +09:00
ToruNiina
2ee8ffab21 add begin/end to region 2018-12-02 21:54:39 +09:00
ToruNiina
9c1bfbd5eb make region::source immutable 2018-12-02 21:03:08 +09:00
ToruNiina
c38b9b7dc7 add region and location to represent tokens
location is almost same as an Iterator, but having shared_ptr that points
the content. region is almost same as a range. by adding pointer to the
content source, utility function to show the error message can be
implemented easier. it is expected that this also makes easy to show
error messages after parse (e.g., in the case of bad_get)
2018-12-02 20:52:04 +09:00
ToruNiina
4791088106 Merge branch 'result' into combinator 2018-12-02 18:30:39 +09:00
ToruNiina
b53d11ce79 ci: downgrade test modules, use BOOST_CHECK
Because travis.CI installs old, out-of-date version of Boost,
BOOST_TEST is not supported. we need to use BOOST_CHECK to link
with it.
2018-12-02 18:25:09 +09:00
ToruNiina
00c3c2f773 Merge branch 'result' into combinator 2018-12-02 18:15:58 +09:00
ToruNiina
6c0a12148b add result<T, E> struct to handle errors
aiming later updates and refactoring of parsers
2018-12-02 18:01:37 +09:00
ToruNiina
a32ccd82f3 fix UB in test_value (use after move) 2018-10-22 19:00:16 +09:00
ToruNiina
f326334147 add definition of constexpr static value to avoid linker error 2018-07-08 18:58:38 +09:00
ToruNiina
b1a55b1331 simplify SFINAE in to_toml 2018-05-05 13:09:40 +09:00
ToruNiina
170b0d6b3f use constexpr value instead of call constexpr func directory 2018-05-05 12:06:06 +09:00
ToruNiina
433636a06f simplify the implementation of from_toml 2018-05-05 11:59:34 +09:00
ToruNiina
9555817901 add get<pair>, get<tuple> 2018-05-05 11:46:09 +09:00
ToruNiina
e54deacf1a simplify SFINAE expressions in toml::get 2018-05-05 11:42:11 +09:00
ToruNiina
b6f53cae7a update test_traits
now is_container returns false when map-like class is passed
2018-05-05 11:40:13 +09:00
ToruNiina
f953a9cf23 add conjunction, disjunction, negation, index_seq 2018-05-05 11:37:18 +09:00
ToruNiina
117549bf70 change is_(map|container) and remove needless trait 2018-05-05 11:36:47 +09:00
ToruNiina
4287160254 add a badge 2018-03-28 19:21:17 +09:00
83 changed files with 20778 additions and 6053 deletions

83
.circleci/config.yml Normal file
View File

@@ -0,0 +1,83 @@
version: 2.1
jobs:
test_suite:
environment:
- GOPATH: /home/circleci/go
docker:
- image: circleci/golang:1.9
steps:
- checkout
- run:
command: |
g++ --version
cd tests/
g++ -std=c++11 -O2 -Wall -Wextra -Werror -DTOML11_DISALLOW_HETEROGENEOUS_ARRAYS -I../ check_toml_test.cpp -o check_toml_test
go get github.com/BurntSushi/toml-test
$GOPATH/bin/toml-test ./check_toml_test
test_serialization:
docker:
- image: circleci/buildpack-deps:bionic
steps:
- checkout
- run:
command: |
g++ --version
cd tests/
g++ -std=c++11 -O2 -Wall -Wextra -Wpedantic -Werror -DTOML11_DISALLOW_HETEROGENEOUS_ARRAYS -I../ check_serialization.cpp -o check_serialization
git clone https://github.com/BurntSushi/toml-test.git
cp check_serialization toml-test/tests/valid
cd toml-test/tests/valid
for f in $(ls ./*.toml);
do echo "==> ${f}";
cat ${f};
echo "---------------------------------------";
./check_serialization ${f};
if [ $? -ne 0 ] ; then
exit 1
fi
echo "=======================================";
done
output_result:
docker:
- image: circleci/buildpack-deps:bionic
steps:
- checkout
- run:
command: |
g++ --version
cd tests/
g++ -std=c++11 -O2 -Wall -Wextra -Wpedantic -Werror -DTOML11_DISALLOW_HETEROGENEOUS_ARRAYS -I../ check.cpp -o check
git clone https://github.com/BurntSushi/toml-test.git
cp check toml-test/tests/invalid
cp check toml-test/tests/valid
cd toml-test/tests/invalid
for f in $(ls ./*.toml);
do echo "==> ${f}";
cat ${f};
echo "---------------------------------------";
./check ${f} invalid;
if [ $? -ne 0 ] ; then
exit 1
fi
echo "=======================================";
done
cd ../valid
for f in $(ls ./*.toml);
do echo "==> ${f}";
cat ${f};
echo "---------------------------------------";
./check ${f} valid;
if [ $? -ne 0 ] ; then
exit 1
fi
echo "=======================================";
done
workflows:
version: 2.1
test:
jobs:
- test_suite
- test_serialization
- output_result

105
.github/workflows/main.yml vendored Normal file
View File

@@ -0,0 +1,105 @@
name: build
on: [push, pull_request]
jobs:
build-linux-gcc:
runs-on: Ubuntu-18.04
strategy:
matrix:
# g++-4.8 and 4.9 are tested on Travis.CI.
compiler: ['g++-9', 'g++-8', 'g++-7', 'g++-6', 'g++-5']
standard: ['11', '14', '17']
exclude:
- {compiler: 'g++-5', standard: '17'}
- {compiler: 'g++-6', standard: '17'}
steps:
- name: Checkout
uses: actions/checkout@v2
with:
submodules: true
- name: Install
run: |
sudo apt-add-repository ppa:mhier/libboost-latest
sudo apt-get update
sudo apt-get install boost1.70
if [[ "${{ matrix.compiler }}" == "g++-6" || "${{ matrix.compiler }}" == "g++-5" ]] ; then
sudo apt-add-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install ${{ matrix.compiler }}
fi
- name: Configure
run: |
mkdir build && cd build
cmake .. -DCMAKE_CXX_COMPILER=${{ matrix.compiler }} -DCMAKE_CXX_STANDARD=${{ matrix.standard }}
- name: Build
run: |
cd build && cmake --build .
- name: Test
run: |
cd build && ctest --output-on-failure
build-linux-clang:
runs-on: Ubuntu-18.04
strategy:
matrix:
compiler: ['10', '9', '8', '7', '6.0', '5.0', '4.0', '3.9']
standard: ['11', '14', '17']
exclude:
- {compiler: '3.9', standard: '17'}
- {compiler: '4.0', standard: '17'}
- {compiler: '5.0', standard: '17'}
steps:
- name: Checkout
uses: actions/checkout@v2
with:
submodules: true
- name: Install
run: |
sudo apt-add-repository ppa:mhier/libboost-latest
sudo apt-get update
sudo apt-get install boost1.70
if [[ "${{ matrix.compiler }}" != "6" && "${{ matrix.compiler }}" != "8" && "${{ matrix.compiler }}" != "9" ]] ; then
sudo apt-add-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install clang-${{ matrix.compiler }}
fi
- name: Configure
run: |
mkdir build && cd build
cmake .. -DCMAKE_CXX_COMPILER=clang++-${{ matrix.compiler }} -DCMAKE_CXX_STANDARD=${{ matrix.standard }}
- name: Build
run: |
cd build && cmake --build .
- name: Test
run: |
cd build && ctest --output-on-failure
build-windows-msvc:
runs-on: windows-2019
strategy:
matrix:
standard: ['11', '14', '17']
config: ['Release', 'Debug']
steps:
- name: Checkout
uses: actions/checkout@v2
with:
submodules: true
- uses: ilammy/msvc-dev-cmd@v1
- name: Configure
shell: cmd
run: |
mkdir build
cd build
cmake ../ -G "NMake Makefiles" -DCMAKE_CXX_STANDARD=${{ matrix.standard }} -DBoost_ADDITIONAL_VERSIONS=1.72.0 -DBoost_USE_MULTITHREADED=ON -DBoost_ARCHITECTURE=-x64 -DBoost_NO_BOOST_CMAKE=ON -DBOOST_ROOT=%BOOST_ROOT_1_72_0%
- name: Build
working-directory: ./build
run: |
cmake --build . --config "${{ matrix.config }}"
- name: Test
working-directory: ./build
run: |
file --mime-encoding tests/toml/tests/example.toml
file --mime-encoding tests/toml/tests/fruit.toml
file --mime-encoding tests/toml/tests/hard_example.toml
file --mime-encoding tests/toml/tests/hard_example_unicode.toml
ctest --build-config "${{ matrix.config }}" --output-on-failure

View File

@@ -5,38 +5,327 @@ matrix:
- os: linux
language: cpp
compiler: gcc
env: COMPILER="g++-5"
env: COMPILER="g++-4.8" CXX_STANDARD=11
addons:
apt:
sources:
- ubuntu-toolchain-r-test
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
packages:
- g++-4.8
- boost1.70
- os: linux
language: cpp
compiler: gcc
env: COMPILER="g++-4.9" CXX_STANDARD=11
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
packages:
- g++-4.9
- boost1.70
- os: linux
language: cpp
compiler: gcc
env: COMPILER="g++-5" CXX_STANDARD=11
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
packages:
- g++-5
- build-essential
- cmake
- libboost-all-dev
- boost1.70
- os: linux
language: cpp
compiler: gcc
env: COMPILER="g++-6" CXX_STANDARD=11
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
packages:
- g++-6
- boost1.70
- os: linux
language: cpp
compiler: gcc
env: COMPILER="g++-7" CXX_STANDARD=11
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
packages:
- g++-7
- boost1.70
- os: linux
language: cpp
compiler: gcc
env: COMPILER="g++-8" CXX_STANDARD=11
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
packages:
- g++-8
- boost1.70
- os: linux
language: cpp
compiler: gcc
env: COMPILER="g++-8" CXX_STANDARD=11 TOML_HEAD=ON
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
packages:
- g++-8
- boost1.70
- os: linux
language: cpp
compiler: gcc
env: COMPILER="g++-8" CXX_STANDARD=14
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
packages:
- g++-8
- boost1.70
- os: linux
language: cpp
compiler: gcc
env: COMPILER="g++-8" CXX_STANDARD=17
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
packages:
- g++-8
- boost1.70
- os: linux
language: cpp
compiler: gcc
env: COMPILER="g++-8" CXX_STANDARD=17 TOML_HEAD=ON
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
packages:
- g++-8
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-3.7"
env: COMPILER="clang++-3.9" CXX_STANDARD=11
addons:
apt:
sources:
- ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.7
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-3.9
packages:
- clang-3.7
- build-essential
- cmake
- libboost-all-dev
- g++-8
- clang-3.9
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-4.0" CXX_STANDARD=11
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-4.0
packages:
- g++-8
- clang-4.0
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-5.0" CXX_STANDARD=11
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-5.0
packages:
- g++-8
- clang-5.0
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-6.0" CXX_STANDARD=11
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-6.0
packages:
- g++-8
- clang-6.0
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-7" CXX_STANDARD=11
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-7
packages:
- g++-8
- clang-7
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-8" CXX_STANDARD=11
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-8
packages:
- g++-8
- clang-8
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-8" CXX_STANDARD=11 TOML_HEAD=ON
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-8
packages:
- g++-8
- clang-8
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-8" CXX_STANDARD=14
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-8
packages:
- clang-8
- g++-8
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-8" CXX_STANDARD=17
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-8
packages:
- clang-8
- g++-8
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-8" CXX_STANDARD=17 TOML_HEAD=ON
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-8
packages:
- clang-8
- g++-8
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-8" CXX_STANDARD=11 WITH_ASAN=ON
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-8
packages:
- clang-8
- g++-8
- boost1.70
- os: linux
language: cpp
compiler: clang
env: COMPILER="clang++-8" CXX_STANDARD=11 WITH_UBSAN=ON
addons:
apt:
sources:
- sourceline: 'ppa:ubuntu-toolchain-r/test'
- sourceline: 'ppa:mhier/libboost-latest'
- llvm-toolchain-trusty-8
packages:
- clang-8
- g++-8
- boost1.70
- os: osx
language: cpp
compiler: clang
script:
- |
if [[ "${TRAVIS_OS_NAME}" == "linux" ]]; then
mkdir -p cmake
travis_retry wget "https://github.com/Kitware/CMake/releases/download/v3.14.5/cmake-3.14.5-Linux-x86_64.tar.gz"
tar xf cmake-3.14.5-Linux-x86_64.tar.gz -C cmake --strip-components=1
export PATH=${TRAVIS_BUILD_DIR}/cmake/bin:${PATH}
fi
- |
if [[ "${CXX_STANDARD}" == "" ]]; then
export CXX_STANDARD="11"
fi
- |
if [[ "${TOML_HEAD}" != "ON" ]]; then
export TOML_HEAD="OFF"
fi
- echo "TOML_HEAD = ${TOML_HEAD}"
- |
if [[ "${WITH_ASAN}" != "ON" ]]; then
export WITH_ASAN="OFF"
fi
- echo "WITH_ASAN = ${WITH_ASAN}"
- |
if [[ "${WITH_UBSAN}" != "ON" ]]; then
export WITH_UBSAN="OFF"
fi
- echo "WITH_UBSAN = ${WITH_UBSAN}"
- cmake --version
- mkdir build
- cd build
- git clone https://github.com/toml-lang/toml.git
- cmake -DCMAKE_CXX_COMPILER=$COMPILER ..
- echo "COMPILER = ${COMPILER}"
- echo "CXX_STANDARD = ${CXX_STANDARD}"
- cmake -DCMAKE_CXX_COMPILER=$COMPILER -DCMAKE_CXX_STANDARD=$CXX_STANDARD -DTOML11_USE_UNRELEASED_TOML_FEATURES=${TOML_HEAD} -Dtoml11_TEST_WITH_ASAN=${WITH_ASAN} -Dtoml11_TEST_WITH_UBSAN=${WITH_UBSAN} ..
- make
- ctest --output-on-failure

View File

@@ -1,11 +1,17 @@
cmake_minimum_required(VERSION 2.8)
cmake_minimum_required(VERSION 3.1)
enable_testing()
project(toml11)
project(toml11 VERSION 3.5.0)
option(toml11_BUILD_TEST "Build toml tests" ON)
option(toml11_TEST_WITH_ASAN "use LLVM address sanitizer" OFF)
option(toml11_TEST_WITH_UBSAN "use LLVM undefined behavior sanitizer" OFF)
include(CheckCXXCompilerFlag)
if("${CMAKE_VERSION}" VERSION_GREATER 3.1)
set(CMAKE_CXX_STANDARD 11)
set(CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 11 CACHE STRING "The C++ standard whose features are requested to build all targets.")
set(CMAKE_CXX_STANDARD_REQUIRED ON CACHE BOOL "Boolean describing whether the value of CXX_STANDARD is a requirement.")
set(CMAKE_CXX_EXTENSIONS OFF CACHE BOOL "Boolean specifying whether compiler specific extensions are requested.")
else()
# Manually check for C++11 compiler flag.
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
@@ -31,5 +37,62 @@ else()
endif()
endif()
include_directories(${PROJECT_SOURCE_DIR})
add_subdirectory(tests)
# Set some common directories
include(GNUInstallDirs)
set(toml11_install_cmake_dir ${CMAKE_INSTALL_LIBDIR}/cmake/toml11)
set(toml11_install_include_dir ${CMAKE_INSTALL_INCLUDEDIR})
set(toml11_config_dir ${CMAKE_CURRENT_BINARY_DIR}/cmake/)
set(toml11_config ${toml11_config_dir}/toml11Config.cmake)
set(toml11_config_version ${toml11_config_dir}/toml11ConfigVersion.cmake)
add_library(toml11 INTERFACE)
target_include_directories(toml11 INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
$<INSTALL_INTERFACE:${toml11_install_include_dir}>
)
add_library(toml11::toml11 ALIAS toml11)
# Write config and version config files
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
${toml11_config_version}
VERSION ${toml11_VERSION}
COMPATIBILITY SameMajorVersion
)
configure_package_config_file(
cmake/toml11Config.cmake.in
${toml11_config}
INSTALL_DESTINATION ${toml11_install_cmake_dir}
PATH_VARS toml11_install_cmake_dir
)
# Install config files
install(FILES ${toml11_config} ${toml11_config_version}
DESTINATION ${toml11_install_cmake_dir}
)
# Install header files
install(
FILES toml.hpp
DESTINATION "${toml11_install_include_dir}"
)
install(
DIRECTORY "toml"
DESTINATION "${toml11_install_include_dir}"
FILES_MATCHING PATTERN "*.hpp"
)
# Export targets and install them
install(TARGETS toml11
EXPORT toml11Targets
)
install(EXPORT toml11Targets
FILE toml11Targets.cmake
DESTINATION ${toml11_install_cmake_dir}
NAMESPACE toml11::
)
if (toml11_BUILD_TEST)
add_subdirectory(tests)
endif ()

View File

@@ -1,59 +0,0 @@
### encoding user's data
You can encode your data to toml format.
```cpp
const toml::value integer(1);
const toml::value array{3.1, 3.14, 3.141, 3.1415};
const toml::value table{{"answer", 42}, {"pi", 3.14}, {"string", "foobar"}};
std::cout << toml::format("integer", integer) << std::endl;
std::cout << toml::format("array", array) << std::endl;
std::cout << toml::format("table", table) << std::endl;
```
this program will output as below.
```toml
integer = 1
array = [3.1, 3.14, 3.141, 3.1415]
[table]
answer = 42
pi = 3.14
string = "foobar"
```
Without key name, you can make string formatted as toml.
```cpp
const std::string integer_ = toml::format(integer); // "1"
const std::string array_ = toml::format(array); // "[3.1, 3.14, 3.141, 3.1415]"
const std::string table_ = toml::format(table); // "answer = 42\npi=3.14\nstring=foobar"
```
### inlinize
You can make `toml::Table` inline.
```cpp
const toml::value table{{"answer", 42}, {"pi", 3.14}, {"string", "foobar"}};
// if the inline-table format length is less than 80, the table will be inlined
std::cout << toml::format("table", table, toml::make_inline(80)) << std::endl;
// In any case, the table will be inlined.
std::cout << toml::format("table", table, toml::forceinline) << std::endl;
```
```toml
table = {answer = 42, pi = 3.14, string = "foobar"}
```
And there are some stream manipulators for toml format.
```cpp
const toml::value table{{"answer", 42}, {"pi", 3.14}, {"string", "foobar"}};
// if the inline-table format length is less than 80, the table will be inlined
std::cout << toml::make_inline(80) << table << std::endl;
// In any case, the table will be inlined.
std::cout << toml::forceinline << table << std::endl;
```

1920
README.md

File diff suppressed because it is too large Load Diff

View File

@@ -17,10 +17,9 @@ build_script:
- cd C:\toml11
- mkdir build
- cd build
- git clone https://github.com/toml-lang/toml.git
- file --mime-encoding toml/tests/hard_example_unicode.toml
- cmake -G"%generator%" -DBOOST_ROOT=C:/Libraries/boost_1_63_0 ..
- cmake -G"%generator%" -DBOOST_ROOT=C:/Libraries/boost_1_69_0 ..
- cmake --build . --config "%configuration%"
- file --mime-encoding tests/toml/tests/hard_example_unicode.toml
test_script:
- ctest --build-config "%configuration%" --timeout 300 --output-on-failure

View File

@@ -0,0 +1,2 @@
@PACKAGE_INIT@
include("@PACKAGE_toml11_install_cmake_dir@/toml11Targets.cmake")

View File

@@ -1,29 +1,112 @@
include(ExternalProject)
ExternalProject_Add(toml
SOURCE_DIR ${CMAKE_CURRENT_BINARY_DIR}/toml
GIT_REPOSITORY https://github.com/toml-lang/toml
GIT_TAG v0.5.0
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND "")
set(TEST_NAMES
test_traits
test_datetime
test_string
test_utility
test_result
test_traits
test_value
test_to_toml
test_from_toml
test_lex_boolean
test_lex_integer
test_lex_floating
test_lex_datetime
test_lex_string
test_lex_key_comment
test_parse_boolean
test_parse_integer
test_parse_floating
test_parse_string
test_parse_datetime
test_parse_array
test_parse_table
test_parse_inline_table
test_parse_key
test_parse_table_key
test_literals
test_comments
test_get
test_get_or
test_value_operator
test_datetime
test_acceptor
test_parser
test_find
test_find_or
test_expect
test_parse_file
test_serialize_file
test_parse_unicode
)
test_error_detection
test_format_error
test_extended_conversions
)
CHECK_CXX_COMPILER_FLAG("-Wall" COMPILER_SUPPORTS_WALL)
CHECK_CXX_COMPILER_FLAG("-Wall" COMPILER_SUPPORTS_WALL)
CHECK_CXX_COMPILER_FLAG("-Wextra" COMPILER_SUPPORTS_WEXTRA)
CHECK_CXX_COMPILER_FLAG("-Wpedantic" COMPILER_SUPPORTS_WPEDANTIC)
CHECK_CXX_COMPILER_FLAG("-Werror" COMPILER_SUPPORTS_WERROR)
CHECK_CXX_COMPILER_FLAG("-Wsign-conversion" COMPILER_SUPPORTS_WSIGN_CONVERSION)
CHECK_CXX_COMPILER_FLAG("-Wconversion" COMPILER_SUPPORTS_WCONVERSION)
CHECK_CXX_COMPILER_FLAG("-Wduplicated-cond" COMPILER_SUPPORTS_WDUPLICATED_COND)
CHECK_CXX_COMPILER_FLAG("-Wduplicated-branches" COMPILER_SUPPORTS_WDUPLICATED_BRANCHES)
CHECK_CXX_COMPILER_FLAG("-Wlogical-op" COMPILER_SUPPORTS_WLOGICAL_OP)
CHECK_CXX_COMPILER_FLAG("-Wuseless-cast" COMPILER_SUPPORTS_WUSELESS_CAST)
CHECK_CXX_COMPILER_FLAG("-Wdouble-promotion" COMPILER_SUPPORTS_WDOUBLE_PROMOTION)
CHECK_CXX_COMPILER_FLAG("-Wrange-loop-analysis" COMPILER_SUPPORTS_WRANGE_LOOP_ANALYSIS)
CHECK_CXX_COMPILER_FLAG("-Wundef" COMPILER_SUPPORTS_WUNDEF)
if(COMPILER_SUPPORTS_WALL)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
endif()
if(COMPILER_SUPPORTS_WEXTRA)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wextra")
endif()
if(COMPILER_SUPPORTS_WPEDANTIC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wpedantic")
endif()
if(COMPILER_SUPPORTS_WERROR)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror")
endif()
if(COMPILER_SUPPORTS_WSIGN_CONVERSION)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wsign-conversion")
endif()
if(COMPILER_SUPPORTS_WCONVERSION)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wconversion")
endif()
if(COMPILER_SUPPORTS_WDUPLICATED_COND)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wduplicated-cond")
endif()
if(COMPILER_SUPPORTS_WDUPLICATED_BRANCHES)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wduplicated-branches")
endif()
if(COMPILER_SUPPORTS_WLOGICAL_OP)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wlogical-op")
endif()
if(COMPILER_SUPPORTS_WUSELESS_CAST)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wuseless-cast")
endif()
if(COMPILER_SUPPORTS_WDOUBLE_PROMOTION)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wdouble-promotion")
endif()
if(COMPILER_SUPPORTS_WRANGE_LOOP_ANALYSIS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wrange-loop-analysis")
endif()
if(COMPILER_SUPPORTS_WUNDEF)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wundef")
endif()
option(TOML11_USE_UNRELEASED_TOML_FEATURES
"use features in toml-lang/toml master while testing" OFF)
if(TOML11_USE_UNRELEASED_TOML_FEATURES)
message(STATUS "adding TOML11_USE_UNRELEASED_TOML_FEATURES flag")
add_definitions("-DTOML11_USE_UNRELEASED_TOML_FEATURES")
endif()
# Disable some MSVC warnings
if(MSVC)
@@ -69,9 +152,22 @@ add_definitions(-DUNITTEST_FRAMEWORK_LIBRARY_EXIST)
foreach(TEST_NAME ${TEST_NAMES})
add_executable(${TEST_NAME} ${TEST_NAME}.cpp)
target_link_libraries(${TEST_NAME} ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY})
target_link_libraries(${TEST_NAME} ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY} toml11::toml11)
target_include_directories(${TEST_NAME} PRIVATE ${Boost_INCLUDE_DIRS})
add_test(NAME ${TEST_NAME} COMMAND ${TEST_NAME} WORKING_DIRECTORY ${PROJECT_BINARY_DIR})
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
if(toml11_TEST_WITH_ASAN)
set_target_properties(${TEST_NAME} PROPERTIES
COMPILE_FLAGS "-fsanitize=address -fno-omit-frame-pointer"
LINK_FLAGS "-fsanitize=address -fno-omit-frame-pointer")
elseif(toml11_TEST_WITH_UBSAN)
set_target_properties(${TEST_NAME} PROPERTIES
COMPILE_FLAGS "-fsanitize=undefined"
LINK_FLAGS "-fsanitize=undefined")
endif()
endif()
add_test(NAME ${TEST_NAME} COMMAND ${TEST_NAME} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
# Set the PATH to be able to find Boost DLL
if(WIN32)
@@ -81,3 +177,15 @@ foreach(TEST_NAME ${TEST_NAMES})
)
endif()
endforeach(TEST_NAME)
# this test is to check it compiles. it will not run
add_executable(test_multiple_translation_unit
test_multiple_translation_unit_1.cpp
test_multiple_translation_unit_2.cpp)
target_link_libraries(test_multiple_translation_unit toml11::toml11)
if(WIN32)
add_executable(test_windows test_windows.cpp)
target_link_libraries(test_windows toml11::toml11)
endif()

41
tests/check.cpp Normal file
View File

@@ -0,0 +1,41 @@
#include "toml.hpp"
#include <iostream>
#include <iomanip>
int main(int argc, char **argv)
{
if(argc != 3)
{
std::cerr << "usage: ./check [filename] [valid|invalid]" << std::endl;
return 1;
}
const std::string file_kind(argv[2]);
try
{
const auto data = toml::parse(argv[1]);
std::cout << std::setprecision(16) << std::setw(80) << data;
if(file_kind == "valid")
{
return 0;
}
else
{
return 1;
}
}
catch(const toml::syntax_error& err)
{
std::cout << "what(): " << err.what() << std::endl;
if(file_kind == "invalid")
{
return 0;
}
else
{
return 1;
}
}
return 127;
}

View File

@@ -0,0 +1,57 @@
#include "toml.hpp"
#include <iostream>
#include <iomanip>
int main(int argc, char **argv)
{
if(argc != 2)
{
std::cerr << "usage: ./check [filename]" << std::endl;
return 1;
}
const std::string filename(argv[1]);
{
const auto data = toml::parse(filename);
{
std::ofstream ofs("tmp.toml");
ofs << std::setprecision(16) << std::setw(80) << data;
}
const auto serialized = toml::parse("tmp.toml");
if(data != serialized)
{
std::cerr << "============================================================\n";
std::cerr << "result (w/o comment) different: " << filename << std::endl;
std::cerr << "------------------------------------------------------------\n";
std::cerr << "# serialized\n";
std::cerr << serialized;
std::cerr << "------------------------------------------------------------\n";
std::cerr << "# data\n";
std::cerr << data;
return 1;
}
}
{
const auto data = toml::parse<toml::preserve_comments>(filename);
{
std::ofstream ofs("tmp.toml");
ofs << std::setprecision(16) << std::setw(80) << data;
}
const auto serialized = toml::parse<toml::preserve_comments>("tmp.toml");
if(data != serialized)
{
std::cerr << "============================================================\n";
std::cerr << "result (w/ comment) different: " << filename << std::endl;
std::cerr << "------------------------------------------------------------\n";
std::cerr << "# serialized\n";
std::cerr << serialized;
std::cerr << "------------------------------------------------------------\n";
std::cerr << "# data\n";
std::cerr << data;
return 1;
}
}
return 0;
}

146
tests/check_toml_test.cpp Normal file
View File

@@ -0,0 +1,146 @@
#include "toml.hpp"
#include <iostream>
#include <iomanip>
struct json_serializer
{
void operator()(toml::boolean v)
{
std::cout << "{\"type\":\"bool\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(toml::integer v)
{
std::cout << "{\"type\":\"integer\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(toml::floating v)
{
std::cout << "{\"type\":\"float\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::string& v)
{
// since toml11 automatically convert string to multiline string that is
// valid only in TOML, we need to format the string to make it valid in
// JSON.
std::cout << "{\"type\":\"string\",\"value\":\""
<< this->escape_string(v.str) << "\"}";
return ;
}
void operator()(const toml::local_time& v)
{
std::cout << "{\"type\":\"local_time\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::local_date& v)
{
std::cout << "{\"type\":\"local_date\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::local_datetime& v)
{
std::cout << "{\"type\":\"local_datetime\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::offset_datetime& v)
{
std::cout << "{\"type\":\"datetime\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::array& v)
{
if(!v.empty() && v.front().is_table())
{
std::cout << '[';
bool is_first = true;
for(const auto& elem : v)
{
if(!is_first) {std::cout << ", ";}
is_first = false;
toml::visit(*this, elem);
}
std::cout << ']';
}
else
{
std::cout << "{\"type\":\"array\",\"value\":[";
bool is_first = true;
for(const auto& elem : v)
{
if(!is_first) {std::cout << ", ";}
is_first = false;
toml::visit(*this, elem);
}
std::cout << "]}";
}
return ;
}
void operator()(const toml::table& v)
{
std::cout << '{';
bool is_first = true;
for(const auto& elem : v)
{
if(!is_first) {std::cout << ", ";}
is_first = false;
std::cout << this->format_key(elem.first) << ':';
toml::visit(*this, elem.second);
}
std::cout << '}';
return ;
}
std::string escape_string(const std::string& s) const
{
std::string retval;
for(const char c : s)
{
switch(c)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\\n"; break;}
case '\r': {retval += "\\r"; break;}
default : {retval += c; break;}
}
}
return retval;
}
std::string format_key(const std::string& s) const
{
const auto quote("\"");
return quote + escape_string(s) + quote;
}
};
int main()
{
try
{
std::vector<char> buf;
std::cin.peek();
while(!std::cin.eof())
{
buf.push_back(std::cin.get());
std::cin.peek();
}
std::string bufstr(buf.begin(), buf.end());
std::istringstream ss(bufstr);
const auto data = toml::parse(ss);
std::cout << std::setprecision(std::numeric_limits<double>::max_digits10);
toml::visit(json_serializer(), data);
return 0;
}
catch(const toml::syntax_error& err)
{
std::cout << "what(): " << err.what() << std::endl;
return 1;
}
}

View File

@@ -1,592 +0,0 @@
#define BOOST_TEST_MODULE "test_acceptor"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/acceptor.hpp>
#include <locale>
#include <iostream>
BOOST_AUTO_TEST_CASE(test_conditions)
{
{
const std::string tmp(" ");
const std::string dummy("dummy");
BOOST_CHECK(toml::is_space<char>::invoke(tmp.begin(), tmp.end()) == tmp.end());
BOOST_CHECK(toml::is_space<char>::invoke(dummy.begin(), dummy.end()) == dummy.begin());
}
{
const std::string tmp("\t");
const std::string dummy("dummy");
BOOST_CHECK(toml::is_tab<char>::invoke(tmp.begin(), tmp.end()) == tmp.end());
BOOST_CHECK(toml::is_tab<char>::invoke(dummy.begin(), dummy.end()) == dummy.begin());
}
{
for(int i=0; i<10; ++i)
{
const std::string tmp = std::to_string(i);
const std::string dummy("dummy");
BOOST_CHECK(toml::is_number<char>::invoke(tmp.begin(), tmp.end()) == tmp.end());
BOOST_CHECK(toml::is_number<char>::invoke(dummy.begin(), dummy.end()) == dummy.begin());
}
}
{
for(char c='a'; c <= 'z'; ++c)
{
const std::string tmp(1, c);
const std::string dummy(1, std::toupper(c));
BOOST_CHECK(toml::is_lowercase<char>::invoke(tmp.begin(), tmp.end()) == tmp.end());
BOOST_CHECK(toml::is_lowercase<char>::invoke(dummy.begin(), dummy.end()) == dummy.begin());
}
}
{
for(char c='A'; c <= 'Z'; ++c)
{
const std::string tmp(1, c);
const std::string dummy(1, std::tolower(c));
BOOST_CHECK(toml::is_uppercase<char>::invoke(tmp.begin(), tmp.end()) == tmp.end());
BOOST_CHECK(toml::is_uppercase<char>::invoke(dummy.begin(), dummy.end()) == dummy.begin());
}
}
{
const std::string tmp(" ");
const std::string dummy("a");
BOOST_CHECK(toml::is_whitespace<char>::invoke(tmp.begin(), tmp.end()) == tmp.end());
BOOST_CHECK(toml::is_whitespace<char>::invoke(dummy.begin(), dummy.end()) == dummy.begin());
}
{
const std::string tmp("\t");
const std::string dummy("a");
BOOST_CHECK(toml::is_whitespace<char>::invoke(tmp.begin(), tmp.end()) == tmp.end());
BOOST_CHECK(toml::is_whitespace<char>::invoke(dummy.begin(), dummy.end()) == dummy.begin());
}
{
const std::string tmp("hoge1-piyo2_fuga3");
const std::string dummy(" \t");
BOOST_CHECK(toml::is_barekey<char>::invoke(tmp.begin(), tmp.end()) != tmp.begin());
BOOST_CHECK(toml::is_barekey<char>::invoke(dummy.begin(), dummy.end()) == dummy.begin());
}
}
BOOST_AUTO_TEST_CASE(test_basic_inline_string)
{
using is_valid = toml::is_basic_inline_string<char>;
{
const std::string simple("\"hoge1-piyo2_fuga3\"");
BOOST_CHECK(is_valid::invoke(simple.cbegin(), simple.cend()) == simple.cend());
}
{
const std::string quote("\"hoge1-\\\"piyo2\\\"_fuga3\"");
BOOST_CHECK(is_valid::invoke(quote.cbegin(), quote.cend()) == quote.cend());
}
{
const std::string escape("\"I'm a string. \\\"You can quote me\\\". Name\\tJos\\u00E9\\nLocation\\tSF.\"");
BOOST_CHECK(is_valid::invoke(escape.cbegin(), escape.cend()) == escape.cend());
}
{
const std::string empty("\"\"");
BOOST_CHECK(is_valid::invoke(empty.cbegin(), empty.cend()) == empty.cend());
}
{
const std::string newline("\"newline\r\nhoge\"");
BOOST_CHECK(is_valid::invoke(newline.cbegin(), newline.cend()) == newline.cbegin());
}
{
const std::string invalid_escape("\"foo\\abar\"");
BOOST_CHECK(is_valid::invoke(invalid_escape.cbegin(), invalid_escape.cend()) == invalid_escape.cbegin());
}
{
const std::string invalid_character("\"foo\10bar\"");
BOOST_CHECK(is_valid::invoke(invalid_character.cbegin(), invalid_character.cend()) == invalid_character.cbegin());
}
{
const std::string multi("\"\"\"multiline\"\"\"");
BOOST_CHECK(is_valid::invoke(multi.cbegin(), multi.cend()) == multi.cbegin());
}
}
BOOST_AUTO_TEST_CASE(test_basic_multiline_string)
{
using is_valid = toml::is_basic_multiline_string<char>;
{
const std::string simple("\"\"\"foobar\"\"\"");
BOOST_CHECK(is_valid::invoke(simple.cbegin(), simple.cend()) == simple.cend());
}
{
const std::string quote("\"\"\"hoge1-\"piyo2\"_fuga3\"\"\"");
BOOST_CHECK(is_valid::invoke(quote.cbegin(), quote.cend()) == quote.cend());
}
{
const std::string newline("\"\"\"hoge1-\npiyo2_\r\nfuga3\"\"\"");
BOOST_CHECK(is_valid::invoke(newline.cbegin(), newline.cend()) == newline.cend());
}
{
const std::string escape("\"\"\"I'm a string. \"You can quote me\". Name\\tJos\\u00E9\\nLocation\\tSF.\"\"\"");
BOOST_CHECK(is_valid::invoke(escape.cbegin(), escape.cend()) == escape.cend());
}
{
const std::string empty("\"\"\"\"\"\"");
BOOST_CHECK(is_valid::invoke(empty.cbegin(), empty.cend()) == empty.cend());
}
{
const std::string ending_backslash("\"\"\"hoge\\\n piyo\\\n\"\"\"");
BOOST_CHECK(is_valid::invoke(ending_backslash.cbegin(), ending_backslash.cend()) == ending_backslash.cend());
}
{
const std::string invalid_escape("\"\"\"foo\\abar\"\"\"");
BOOST_CHECK(is_valid::invoke(invalid_escape.cbegin(), invalid_escape.cend()) == invalid_escape.cbegin());
}
{
const std::string invalid_character("\"\"\"foo\10bar\"\"\"");
BOOST_CHECK(is_valid::invoke(invalid_character.cbegin(), invalid_character.cend()) == invalid_character.cbegin());
}
{
const std::string single("\"singleline\"");
BOOST_CHECK(is_valid::invoke(single.cbegin(), single.cend()) == single.cbegin());
}
}
BOOST_AUTO_TEST_CASE(test_literal_inline_string)
{
using is_valid = toml::is_literal_inline_string<char>;
{
const std::string simple("'foobar'");
BOOST_CHECK(is_valid::invoke(simple.cbegin(), simple.cend()) == simple.cend());
}
{
const std::string nonescape("'C:\\Users\\nodejs\\templates'");
BOOST_CHECK(is_valid::invoke(nonescape.cbegin(), nonescape.cend()) == nonescape.cend());
}
{
const std::string empty("''");
BOOST_CHECK(is_valid::invoke(empty.cbegin(), empty.cend()) == empty.cend());
}
{
const std::string quote("'hoge1-'piyo2'_fuga3'");
BOOST_CHECK(is_valid::invoke(quote.cbegin(), quote.cend()) == quote.cbegin() + 8);
}
{
const std::string newline("'hoge1-\npiyo2_\r\nfuga3'");
BOOST_CHECK(is_valid::invoke(newline.cbegin(), newline.cend()) == newline.cbegin());
}
{
const std::string invalid_character("'foo\10bar'");
BOOST_CHECK(is_valid::invoke(invalid_character.cbegin(), invalid_character.cend()) == invalid_character.cbegin());
}
{
const std::string multi("'''multiline'''");
BOOST_CHECK(is_valid::invoke(multi.cbegin(), multi.cend()) == multi.cbegin());
}
}
BOOST_AUTO_TEST_CASE(test_literal_multiline_string)
{
using is_valid = toml::is_literal_multiline_string<char>;
{
const std::string simple("'''foobar'''");
BOOST_CHECK(is_valid::invoke(simple.cbegin(), simple.cend()) == simple.cend());
}
{
const std::string quote("'''hoge1-'piyo2'_fuga3'''");
BOOST_CHECK(is_valid::invoke(quote.cbegin(), quote.cend()) == quote.cend());
}
{
const std::string nonescape("'''C:\\Users\\nodejs\\templates'''");
BOOST_CHECK(is_valid::invoke(nonescape.cbegin(), nonescape.cend()) == nonescape.cend());
}
{
const std::string newline("'''hoge1-\npiyo2_\r\nfuga3'''");
BOOST_CHECK(is_valid::invoke(newline.cbegin(), newline.cend()) == newline.cend());
}
{
const std::string empty("''''''");
BOOST_CHECK(is_valid::invoke(empty.cbegin(), empty.cend()) == empty.cend());
}
{
const std::string invalid_character("'''foo\10bar'''");
BOOST_CHECK(is_valid::invoke(invalid_character.cbegin(), invalid_character.cend()) == invalid_character.cbegin());
}
{
const std::string single("'singleline'");
BOOST_CHECK(is_valid::invoke(single.cbegin(), single.cend()) == single.cbegin());
}
}
BOOST_AUTO_TEST_CASE(test_integer)
{
using is_valid = toml::is_integer<char>;
{
const std::string simple("1");
BOOST_CHECK(is_valid::invoke(simple.cbegin(), simple.cend()) == simple.cend());
}
{
const std::string psign("+1234");
BOOST_CHECK(is_valid::invoke(psign.cbegin(), psign.cend()) == psign.cend());
const std::string nsign("-1234");
BOOST_CHECK(is_valid::invoke(nsign.cbegin(), nsign.cend()) == nsign.cend());
}
{
const std::string zero("0");
BOOST_CHECK(is_valid::invoke(zero.cbegin(), zero.cend()) == zero.cend());
}
{
const std::string us("1_2_3_4_5");
BOOST_CHECK(is_valid::invoke(us.cbegin(), us.cend()) == us.cend());
}
{
const std::string f("12.34");
BOOST_CHECK(is_valid::invoke(f.cbegin(), f.cend()) == f.cbegin()+2);
}
{
const std::string f("12e34");
BOOST_CHECK(is_valid::invoke(f.cbegin(), f.cend()) == f.cbegin()+2);
}
{
const std::string ascii("1234a");
BOOST_CHECK(is_valid::invoke(ascii.cbegin(), ascii.cend()) == ascii.cbegin()+4);
}
}
BOOST_AUTO_TEST_CASE(test_float)
{
using is_valid = toml::is_float<char>;
{
const std::string simplef("1.0");
BOOST_CHECK(is_valid::invoke(simplef.cbegin(), simplef.cend()) == simplef.cend());
const std::string simplee("1e0");
BOOST_CHECK(is_valid::invoke(simplee.cbegin(), simplee.cend()) == simplee.cend());
const std::string both("6.626e-34");
BOOST_CHECK(is_valid::invoke(both.cbegin(), both.cend()) == both.cend());
}
{
const std::string psign("+1.0");
BOOST_CHECK(is_valid::invoke(psign.cbegin(), psign.cend()) == psign.cend());
const std::string nsign("-1.0");
BOOST_CHECK(is_valid::invoke(nsign.cbegin(), nsign.cend()) == nsign.cend());
}
{
const std::string psmall("+0.001");
BOOST_CHECK(is_valid::invoke(psmall.cbegin(), psmall.cend()) == psmall.cend());
const std::string nsmall("-0.001");
BOOST_CHECK(is_valid::invoke(nsmall.cbegin(), nsmall.cend()) == nsmall.cend());
}
{
const std::string zero("0.0");
BOOST_CHECK(is_valid::invoke(zero.cbegin(), zero.cend()) == zero.cend());
}
{
const std::string us("9_224_617.445_991_228_313");
BOOST_CHECK(is_valid::invoke(us.cbegin(), us.cend()) == us.cend());
}
}
BOOST_AUTO_TEST_CASE(test_boolean)
{
using is_valid = toml::is_boolean<char>;
{
const std::string t("true");
BOOST_CHECK(is_valid::invoke(t.cbegin(), t.cend()) == t.cend());
const std::string f("false");
BOOST_CHECK(is_valid::invoke(f.cbegin(), f.cend()) == f.cend());
}
{
const std::string t("True");
BOOST_CHECK(is_valid::invoke(t.cbegin(), t.cend()) == t.cbegin());
const std::string f("False");
BOOST_CHECK(is_valid::invoke(f.cbegin(), f.cend()) == f.cbegin());
}
}
BOOST_AUTO_TEST_CASE(test_localtime)
{
using is_valid = toml::is_local_time<char>;
{
const std::string t("07:32:00");
BOOST_CHECK(is_valid::invoke(t.cbegin(), t.cend()) == t.cend());
const std::string tf("07:32:00.0000");
BOOST_CHECK(is_valid::invoke(tf.cbegin(), tf.cend()) == tf.cend());
}
{
const std::string d("1907-32-00");
BOOST_CHECK(is_valid::invoke(d.cbegin(), d.cend()) == d.cbegin());
const std::string f("1907:32:00");
BOOST_CHECK(is_valid::invoke(f.cbegin(), f.cend()) == f.cbegin());
}
}
BOOST_AUTO_TEST_CASE(test_localdate)
{
using is_valid = toml::is_local_date<char>;
{
const std::string d("1907-32-00");
BOOST_CHECK(is_valid::invoke(d.cbegin(), d.cend()) == d.cend());
}
{
const std::string t("07:32:00");
BOOST_CHECK(is_valid::invoke(t.cbegin(), t.cend()) == t.cbegin());
const std::string f("1907:32:00");
BOOST_CHECK(is_valid::invoke(f.cbegin(),f.cend()) == f.cbegin());
}
}
BOOST_AUTO_TEST_CASE(test_localdatetime)
{
using is_valid = toml::is_local_date_time<char>;
{
const std::string dt("1907-32-00T07:32:00");
BOOST_CHECK(is_valid::invoke(dt.cbegin(), dt.cend()) == dt.cend());
const std::string dtf("1907-32-00T07:32:00.0000");
BOOST_CHECK(is_valid::invoke(dtf.cbegin(), dtf.cend()) == dtf.cend());
}
{
const std::string d("1907-32-00");
BOOST_CHECK(is_valid::invoke(d.cbegin(), d.cend()) == d.cbegin());
const std::string t("07:32:00");
BOOST_CHECK(is_valid::invoke(t.cbegin(), t.cend()) == t.cbegin());
const std::string f("1907-32-00 07:32:00");
BOOST_CHECK(is_valid::invoke(f.cbegin(), f.cend()) == f.cbegin());
}
}
BOOST_AUTO_TEST_CASE(test_offsetdatetime)
{
using is_valid = toml::is_offset_date_time<char>;
{
const std::string dtZ("1907-32-00T07:32:00Z");
BOOST_CHECK(is_valid::invoke(dtZ.cbegin(), dtZ.cend()) == dtZ.cend());
const std::string dtfZ("1907-32-00T07:32:00.0000Z");
BOOST_CHECK(is_valid::invoke(dtfZ.cbegin(), dtfZ.cend()) == dtfZ.cend());
const std::string dtp("1907-32-00T07:32:00+12:34");
BOOST_CHECK(is_valid::invoke(dtp.cbegin(), dtp.cend()) == dtp.cend());
const std::string dtfp("1907-32-00T07:32:00.0000+12:34");
BOOST_CHECK(is_valid::invoke(dtfp.cbegin(), dtfp.cend()) == dtfp.cend());
const std::string dtn("1907-32-00T07:32:00-12:34");
BOOST_CHECK(is_valid::invoke(dtn.cbegin(), dtn.cend()) == dtn.cend());
const std::string dtfn("1907-32-00T07:32:00.0000-12:34");
BOOST_CHECK(is_valid::invoke(dtfn.cbegin(), dtfn.cend()) == dtfn.cend());
}
{
const std::string d("1907-32-00");
BOOST_CHECK(is_valid::invoke(d.cbegin(), d.cend()) == d.cbegin());
const std::string t("07:32:00");
BOOST_CHECK(is_valid::invoke(t.cbegin(), t.cend()) == t.cbegin());
const std::string l("1907-32-00T07:32:00");
BOOST_CHECK(is_valid::invoke(l.cbegin(), l.cend()) == l.cbegin());
}
}
BOOST_AUTO_TEST_CASE(test_array)
{
using is_valid = toml::is_array<char>;
{
const std::string arr0("[]");
BOOST_CHECK(is_valid::invoke(arr0.cbegin(), arr0.cend()) == arr0.cend());
const std::string arr1("[1,2,3]");
BOOST_CHECK(is_valid::invoke(arr1.cbegin(), arr1.cend()) == arr1.cend());
const std::string arr2("[ 1,2,3 ]");
BOOST_CHECK(is_valid::invoke(arr2.cbegin(), arr2.cend()) == arr2.cend());
const std::string arr3("[ 1, 2, 3 ]");
BOOST_CHECK(is_valid::invoke(arr3.cbegin(), arr3.cend()) == arr3.cend());
const std::string arr4("[ 1, 2, 3, ]");
BOOST_CHECK(is_valid::invoke(arr4.cbegin(), arr4.cend()) == arr4.cend());
const std::string arr5("[ 1, 2, 3,]");
BOOST_CHECK(is_valid::invoke(arr5.cbegin(), arr5.cend()) == arr5.cend());
const std::string arr6("[ 1 , 2 , 3 ,]");
BOOST_CHECK(is_valid::invoke(arr6.cbegin(), arr6.cend()) == arr6.cend());
}
{
const std::string arr1("[\"red\", \"yellow\", \"green\"]");
BOOST_CHECK(is_valid::invoke(arr1.cbegin(), arr1.cend()) == arr1.cend());
const std::string arr2("[\"]\", \"#\", \" \"]");
BOOST_CHECK(is_valid::invoke(arr2.cbegin(), arr2.cend()) == arr2.cend());
const std::string arr3("[[1, 2, 3], ['a', 'b', 'c']]");
BOOST_CHECK(is_valid::invoke(arr3.cbegin(), arr3.cend()) == arr3.cend());
const std::string arr4("[{hoge = 1}, {piyo = 'a'}, {fuga = [1,2,3]}]");
BOOST_CHECK(is_valid::invoke(arr4.cbegin(), arr4.cend()) == arr4.cend());
}
{
const std::string arr1("[1,\n2,#comment\n3]");
BOOST_CHECK(is_valid::invoke(arr1.cbegin(), arr1.cend()) == arr1.cend());
const std::string arr2("[#c\n1,\n2,#comment\r\n3]");
BOOST_CHECK(is_valid::invoke(arr2.cbegin(), arr2.cend()) == arr2.cend());
}
{
const std::string invalid("[1, 3.14, 'string']");
BOOST_CHECK(is_valid::invoke(invalid.cbegin(), invalid.cend()) == invalid.cbegin());
const std::string valid("[[1,2,3], [3.14, 2.71, 1.414], ['foo', 'bar']]");
BOOST_CHECK(is_valid::invoke(valid.cbegin(), valid.cend()) == valid.cend());
}
}
BOOST_AUTO_TEST_CASE(test_inline_table)
{
using is_valid = toml::is_inline_table<char>;
{
const std::string tab0("{}");
BOOST_CHECK(is_valid::invoke(tab0.cbegin(), tab0.cend()) == tab0.cend());
const std::string tab1("{hoge=1,piyo=2,fuga=3}");
BOOST_CHECK(is_valid::invoke(tab1.cbegin(), tab1.cend()) == tab1.cend());
const std::string tab2("{hoge=1, piyo=2, fuga=3}");
BOOST_CHECK(is_valid::invoke(tab2.cbegin(), tab2.cend()) == tab2.cend());
const std::string tab3("{ hoge=1, piyo=2, fuga=3 }");
BOOST_CHECK(is_valid::invoke(tab3.cbegin(), tab3.cend()) == tab3.cend());
const std::string tab4("{ hoge = 1, piyo = 2, fuga = 3 }");
BOOST_CHECK(is_valid::invoke(tab4.cbegin(), tab4.cend()) == tab4.cend());
const std::string tab5("{hoge = 1, piyo = 2, fuga = 3}");
BOOST_CHECK(is_valid::invoke(tab5.cbegin(), tab5.cend()) == tab5.cend());
const std::string tab6("{hoge = 1, piyo = 2, fuga = 3,}");
BOOST_CHECK(is_valid::invoke(tab6.cbegin(), tab6.cend()) == tab6.cend());
const std::string tab7("{hoge = 1, piyo = 2, fuga = 3, }");
BOOST_CHECK(is_valid::invoke(tab7.cbegin(), tab7.cend()) == tab7.cend());
}
{
const std::string tab0("{hoge = 1, piyo = 2.0}");
BOOST_CHECK(is_valid::invoke(tab0.cbegin(), tab0.cend()) == tab0.cend());
const std::string tab1("{hoge = [1,2,3], piyo = {fuga = {}}}");
BOOST_CHECK(is_valid::invoke(tab1.cbegin(), tab1.cend()) == tab1.cend());
const std::string tab2("{hoge = \"}\", piyo = \"#\"}");
BOOST_CHECK(is_valid::invoke(tab2.cbegin(), tab2.cend()) == tab2.cend());
const std::string tab3("{b=true, i=1, f=2.0, d=1907-03-02T07:32:00, s='str', a=[1,2,3], t={foo=1}}");
BOOST_CHECK(is_valid::invoke(tab3.cbegin(), tab3.cend()) == tab3.cend());
}
{
const std::string tab0("{hoge = \"}\",\n piyo = \"#\"}");
BOOST_CHECK(is_valid::invoke(tab0.cbegin(), tab0.cend()) == tab0.cbegin());
}
}
BOOST_AUTO_TEST_CASE(test_table_definition)
{
using is_valid = toml::is_table_definition<char>;
{
const std::string simple("[hoge]");
BOOST_CHECK(is_valid::invoke(simple.cbegin(), simple.cend()) == simple.cend());
const std::string dotted("[hoge.piyo.fuga]");
BOOST_CHECK(is_valid::invoke(dotted.cbegin(), dotted.cend()) == dotted.cend());
const std::string spaced_dotted("[hoge . piyo .fuga. foo]");
BOOST_CHECK(is_valid::invoke(spaced_dotted.cbegin(), spaced_dotted.cend()) == spaced_dotted.cend());
const std::string quoted("[\"hoge\"]");
BOOST_CHECK(is_valid::invoke(quoted.cbegin(), quoted.cend()) == quoted.cend());
const std::string quoted_dot("[\"hoge\".'piyo'.fuga]");
BOOST_CHECK(is_valid::invoke(quoted_dot.cbegin(), quoted_dot.cend()) == quoted_dot.cend());
}
}
BOOST_AUTO_TEST_CASE(test_array_of_table_definition)
{
using is_valid = toml::is_array_of_table_definition<char>;
{
const std::string simple("[[hoge]]");
BOOST_CHECK(is_valid::invoke(simple.cbegin(), simple.cend()) == simple.cend());
const std::string dotted("[[hoge.piyo.fuga]]");
BOOST_CHECK(is_valid::invoke(dotted.cbegin(), dotted.cend()) == dotted.cend());
const std::string spaced_dotted("[[hoge . piyo .fuga. foo]]");
BOOST_CHECK(is_valid::invoke(spaced_dotted.cbegin(), spaced_dotted.cend()) == spaced_dotted.cend());
const std::string quoted("[[\"hoge\"]]");
BOOST_CHECK(is_valid::invoke(quoted.cbegin(), quoted.cend()) == quoted.cend());
const std::string quoted_dot("[[\"hoge\".'piyo'.fuga]]");
BOOST_CHECK(is_valid::invoke(quoted_dot.cbegin(), quoted_dot.cend()) == quoted_dot.cend());
}
}
BOOST_AUTO_TEST_CASE(test_key)
{
using is_valid = toml::is_key<char>;
{
const std::string simple("foobar");
BOOST_CHECK(is_valid::invoke(simple.cbegin(), simple.cend()) == simple.cend());
const std::string quoted("\"foo#bar.baz\\n\"");
BOOST_CHECK(is_valid::invoke(quoted.cbegin(), quoted.cend()) == quoted.cend());
}
}
BOOST_AUTO_TEST_CASE(test_value)
{
using is_valid = toml::is_value<char>;
{
const std::string boolean("true");
BOOST_CHECK(is_valid::invoke(boolean.cbegin(), boolean.cend()) == boolean.cend());
const std::string integer("-42");
BOOST_CHECK(is_valid::invoke(integer.cbegin(), integer.cend()) == integer.cend());
const std::string floating("-42e0");
BOOST_CHECK(is_valid::invoke(floating.cbegin(), floating.cend()) == floating.cend());
const std::string string("\"string\"");
BOOST_CHECK(is_valid::invoke(string.cbegin(), string.cend()) == string.cend());
const std::string datetime("1901-01-01T00:00:00");
BOOST_CHECK(is_valid::invoke(datetime.cbegin(), datetime.cend()) == datetime.cend());
const std::string array("[1,2,3]");
BOOST_CHECK(is_valid::invoke(array.cbegin(), array.cend()) == array.cend());
const std::string table("{foo=1,bar=2.0,baz='3'}");
BOOST_CHECK(is_valid::invoke(table.cbegin(), table.cend()) == table.cend());
}
}
BOOST_AUTO_TEST_CASE(test_key_value_pair)
{
using is_valid = toml::is_key_value_pair<char>;
{
const std::string kv("key=1");
BOOST_CHECK(is_valid::invoke(kv.cbegin(), kv.cend()) == kv.cend());
}
{
const std::string kv("key = 1");
BOOST_CHECK(is_valid::invoke(kv.cbegin(), kv.cend()) == kv.cend());
}
{
const std::string kv(" key = 1");
BOOST_CHECK(is_valid::invoke(kv.cbegin(), kv.cend()) == kv.cend());
}
{
const std::string kv(" key = 1 ");
BOOST_CHECK(is_valid::invoke(kv.cbegin(), kv.cend()) == kv.cend());
}
{
const std::string boolean("key = true");
BOOST_CHECK(is_valid::invoke(boolean.cbegin(), boolean.cend()) == boolean.cend());
const std::string integer("key = -42");
BOOST_CHECK(is_valid::invoke(integer.cbegin(), integer.cend()) == integer.cend());
const std::string floating("key = -42.0");
BOOST_CHECK(is_valid::invoke(floating.cbegin(), floating.cend()) == floating.cend());
const std::string string("key = \"string\"");
BOOST_CHECK(is_valid::invoke(string.cbegin(), string.cend()) == string.cend());
const std::string datetime("key = 1901-01-01T00:00:00");
BOOST_CHECK(is_valid::invoke(datetime.cbegin(), datetime.cend()) == datetime.cend());
const std::string array("key = [1,2,3]");
BOOST_CHECK(is_valid::invoke(array.cbegin(), array.cend()) == array.cend());
const std::string table("key = {foo=1,bar=2.0,baz='3'}");
BOOST_CHECK(is_valid::invoke(table.cbegin(), table.cend()) == table.cend());
}
}
BOOST_AUTO_TEST_CASE(test_empty_line)
{
using is_valid = toml::is_empty_line<char>;
{
const std::string empty("\n");
BOOST_CHECK(is_valid::invoke(empty.cbegin(), empty.cend()) == empty.cend());
}
{
const std::string empty(" \n");
BOOST_CHECK(is_valid::invoke(empty.cbegin(), empty.cend()) == empty.cend());
}
{
const std::string empty("#comment\n");
BOOST_CHECK(is_valid::invoke(empty.cbegin(), empty.cend()) == empty.cend());
}
{
const std::string empty(" #comment\n");
BOOST_CHECK(is_valid::invoke(empty.cbegin(), empty.cend()) == empty.cend());
}
}

514
tests/test_comments.cpp Normal file
View File

@@ -0,0 +1,514 @@
#define BOOST_TEST_MODULE "test_comments"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
BOOST_AUTO_TEST_CASE(test_comment_before)
{
{
const std::string file = u8R"(
# comment for a.
a = 42
# comment for b.
b = "baz"
)";
std::istringstream iss(file);
const auto v = toml::parse<toml::preserve_comments>(iss);
const auto& a = toml::find(v, "a");
const auto& b = toml::find(v, "b");
BOOST_TEST(a.comments().size() == 1u);
BOOST_TEST(a.comments().front() == u8" comment for a.");
BOOST_TEST(b.comments().size() == 1u);
BOOST_TEST(b.comments().front() == u8" comment for b.");
}
{
const std::string file = u8R"(
# comment for a.
# another comment for a.
a = 42
# comment for b.
# also comment for b.
b = "baz"
)";
std::istringstream iss(file);
const auto v = toml::parse<toml::preserve_comments>(iss);
const auto& a = toml::find(v, "a");
const auto& b = toml::find(v, "b");
BOOST_TEST(a.comments().size() == 2u);
BOOST_TEST(a.comments().front() == u8" comment for a.");
BOOST_TEST(a.comments().back() == u8" another comment for a.");
BOOST_TEST(b.comments().size() == 2u);
BOOST_TEST(b.comments().front() == u8" comment for b.");
BOOST_TEST(b.comments().back() == u8" also comment for b.");
}
}
BOOST_AUTO_TEST_CASE(test_comment_inline)
{
{
const std::string file = u8R"(
a = 42 # comment for a.
b = "baz" # comment for b.
)";
std::istringstream iss(file);
const auto v = toml::parse<toml::preserve_comments>(iss);
const auto& a = toml::find(v, "a");
const auto& b = toml::find(v, "b");
BOOST_TEST(a.comments().size() == 1u);
BOOST_TEST(a.comments().front() == u8" comment for a.");
BOOST_TEST(b.comments().size() == 1u);
BOOST_TEST(b.comments().front() == u8" comment for b.");
}
{
const std::string file = u8R"(
a = [
42,
] # comment for a.
b = [
"bar", # this is not a comment for b, but "bar"
] # this is a comment for b.
)";
std::istringstream iss(file);
const auto v = toml::parse<toml::preserve_comments>(iss);
const auto& a = toml::find(v, "a");
const auto& b = toml::find(v, "b");
const auto& b0 = b.as_array().at(0);
BOOST_TEST(a.comments().size() == 1u);
BOOST_TEST(a.comments().front() == u8" comment for a.");
BOOST_TEST(b.comments().size() == 1u);
BOOST_TEST(b.comments().front() == u8" this is a comment for b.");
BOOST_TEST(b0.comments().size() == 1u);
BOOST_TEST(b0.comments().front() == u8" this is not a comment for b, but \"bar\"");
}
}
BOOST_AUTO_TEST_CASE(test_comment_both)
{
{
const std::string file = u8R"(
# comment for a.
a = 42 # inline comment for a.
# comment for b.
b = "baz" # inline comment for b.
# comment for c.
c = [ # this comment will be ignored
# comment for the first element.
10 # this also.
] # another comment for c.
)";
std::istringstream iss(file);
const auto v = toml::parse<toml::preserve_comments>(iss);
const auto& a = toml::find(v, "a");
const auto& b = toml::find(v, "b");
const auto& c = toml::find(v, "c");
const auto& c0 = c.as_array().at(0);
BOOST_TEST(a.comments().size() == 2u);
BOOST_TEST(a.comments().front() == u8" comment for a.");
BOOST_TEST(a.comments().back() == u8" inline comment for a.");
BOOST_TEST(b.comments().size() == 2u);
BOOST_TEST(b.comments().front() == u8" comment for b.");
BOOST_TEST(b.comments().back() == u8" inline comment for b.");
BOOST_TEST(c.comments().size() == 2u);
BOOST_TEST(c.comments().front() == u8" comment for c.");
BOOST_TEST(c.comments().back() == u8" another comment for c.");
BOOST_TEST(c0.comments().size() == 2u);
BOOST_TEST(c0.comments().front() == u8" comment for the first element.");
BOOST_TEST(c0.comments().back() == u8" this also.");
}
}
BOOST_AUTO_TEST_CASE(test_discard_comment)
{
const std::string file = u8R"(
# comment for a.
a = 42 # inline comment for a.
# comment for b.
b = "baz" # inline comment for b.
# comment for c.
c = [ # this comment will be ignored
# comment for the first element.
10 # this also.
] # another comment for c.
)";
std::istringstream iss(file);
const auto v = toml::parse(iss);
const auto& a = toml::find(v, "a");
const auto& b = toml::find(v, "b");
const auto& c = toml::find(v, "c");
const auto& c0 = c.as_array().at(0);
BOOST_TEST(a.comments().empty());
BOOST_TEST(b.comments().empty());
BOOST_TEST(c.comments().empty());
BOOST_TEST(c0.comments().empty());
}
BOOST_AUTO_TEST_CASE(test_construct_value_with_comments)
{
using value_type = toml::basic_value<toml::preserve_comments>;
{
const value_type v(true, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_boolean());
BOOST_TEST(v.as_boolean() == true);
}
{
const value_type v(42, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_integer());
BOOST_TEST(v.as_integer() == 42);
}
{
const value_type v(3.14, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_floating());
BOOST_TEST(v.as_floating() == 3.14);
}
{
const value_type v(toml::string("str"), {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_string());
BOOST_TEST(v.as_string() == "str");
}
{
const value_type v(std::string("str"), {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_string());
BOOST_TEST(v.as_string() == "str");
}
{
const value_type v(std::string("str"), toml::string_t::literal,
{"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_string());
BOOST_TEST(v.as_string() == "str");
}
{
const value_type v("str", {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_string());
BOOST_TEST(v.as_string() == "str");
}
{
const value_type v("str", toml::string_t::literal,
{"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_string());
BOOST_TEST(v.as_string() == "str");
}
#if __cplusplus >= 201703L
{
using namespace std::literals::string_view_literals;
const value_type v("str"sv, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_string());
BOOST_TEST(v.as_string() == "str");
}
{
using namespace std::literals::string_view_literals;
const value_type v("str"sv, toml::string_t::literal,
{"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_string());
BOOST_TEST(v.as_string() == "str");
}
#endif
const toml::local_date ld{2019, toml::month_t::Apr, 1};
const toml::local_time lt{12, 30, 45};
const toml::local_datetime ldt{ld, lt};
const toml::offset_datetime odt{ld, lt, toml::time_offset{9, 0}};
{
const value_type v(ld, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_local_date());
BOOST_TEST(v.as_local_date() == ld);
}
{
const value_type v(lt, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_local_time());
BOOST_TEST(v.as_local_time() == lt);
}
{
const toml::local_time three_hours{3,0,0};
const value_type v(std::chrono::hours(3), {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_local_time());
BOOST_TEST(v.as_local_time() == three_hours);
}
{
const value_type v(ldt, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_local_datetime());
BOOST_TEST(v.as_local_datetime() == ldt);
}
{
const value_type v(odt, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_offset_datetime());
BOOST_TEST(v.as_offset_datetime() == odt);
}
{
const auto systp = static_cast<std::chrono::system_clock::time_point>(odt);
const value_type v(systp, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_offset_datetime());
// While the conversion, the information about time offset may change.
const auto systp2 = static_cast<std::chrono::system_clock::time_point>(
v.as_offset_datetime());
const bool result = systp == systp2; // because there is no operator<<
BOOST_TEST(result);
}
{
const typename value_type::array_type a{1,2,3,4,5};
const value_type v(a, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_array());
BOOST_TEST(v.as_array().at(0).is_integer());
BOOST_TEST(v.as_array().at(1).is_integer());
BOOST_TEST(v.as_array().at(2).is_integer());
BOOST_TEST(v.as_array().at(3).is_integer());
BOOST_TEST(v.as_array().at(4).is_integer());
BOOST_TEST(v.as_array().at(0).as_integer() == 1);
BOOST_TEST(v.as_array().at(1).as_integer() == 2);
BOOST_TEST(v.as_array().at(2).as_integer() == 3);
BOOST_TEST(v.as_array().at(3).as_integer() == 4);
BOOST_TEST(v.as_array().at(4).as_integer() == 5);
}
{
const std::initializer_list<int> a = {1,2,3,4,5};
const value_type v(a, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_array());
BOOST_TEST(v.as_array().at(0).is_integer());
BOOST_TEST(v.as_array().at(1).is_integer());
BOOST_TEST(v.as_array().at(2).is_integer());
BOOST_TEST(v.as_array().at(3).is_integer());
BOOST_TEST(v.as_array().at(4).is_integer());
BOOST_TEST(v.as_array().at(0).as_integer() == 1);
BOOST_TEST(v.as_array().at(1).as_integer() == 2);
BOOST_TEST(v.as_array().at(2).as_integer() == 3);
BOOST_TEST(v.as_array().at(3).as_integer() == 4);
BOOST_TEST(v.as_array().at(4).as_integer() == 5);
}
{
const std::vector<int> a = {1,2,3,4,5};
const value_type v(a, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_array());
BOOST_TEST(v.as_array().at(0).is_integer());
BOOST_TEST(v.as_array().at(1).is_integer());
BOOST_TEST(v.as_array().at(2).is_integer());
BOOST_TEST(v.as_array().at(3).is_integer());
BOOST_TEST(v.as_array().at(4).is_integer());
BOOST_TEST(v.as_array().at(0).as_integer() == 1);
BOOST_TEST(v.as_array().at(1).as_integer() == 2);
BOOST_TEST(v.as_array().at(2).as_integer() == 3);
BOOST_TEST(v.as_array().at(3).as_integer() == 4);
BOOST_TEST(v.as_array().at(4).as_integer() == 5);
}
{
const typename value_type::table_type t{
{"key1", 42}, {"key2", "foobar"}
};
const value_type v(t, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_table());
BOOST_TEST(v.as_table().at("key1").is_integer());
BOOST_TEST(v.as_table().at("key1").as_integer() == 42);
BOOST_TEST(v.as_table().at("key2").is_string());
BOOST_TEST(v.as_table().at("key2").as_string() == "foobar");
}
{
const std::initializer_list<std::pair<std::string, value_type>> t{
{"key1", 42}, {"key2", "foobar"}
};
const value_type v(t, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_table());
BOOST_TEST(v.as_table().at("key1").is_integer());
BOOST_TEST(v.as_table().at("key1").as_integer() == 42);
BOOST_TEST(v.as_table().at("key2").is_string());
BOOST_TEST(v.as_table().at("key2").as_string() == "foobar");
}
{
const std::map<std::string, value_type> t{
{"key1", 42}, {"key2", "foobar"}
};
const value_type v(t, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_table());
BOOST_TEST(v.as_table().at("key1").is_integer());
BOOST_TEST(v.as_table().at("key1").as_integer() == 42);
BOOST_TEST(v.as_table().at("key2").is_string());
BOOST_TEST(v.as_table().at("key2").as_string() == "foobar");
}
}
BOOST_AUTO_TEST_CASE(test_overwrite_comments)
{
using value_type = toml::basic_value<toml::preserve_comments>;
{
const value_type v(42, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_integer());
BOOST_TEST(v.as_integer() == 42);
const value_type u(v, {"comment3", "comment4"});
BOOST_TEST(u.comments().size() == 2u);
BOOST_TEST(u.comments().at(0) == "comment3");
BOOST_TEST(u.comments().at(1) == "comment4");
BOOST_TEST(u.is_integer());
BOOST_TEST(u.as_integer() == 42);
}
{
const value_type v(42, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_integer());
BOOST_TEST(v.as_integer() == 42);
const value_type u(v);
BOOST_TEST(u.comments().size() == 2u);
BOOST_TEST(u.comments().at(0) == "comment1");
BOOST_TEST(u.comments().at(1) == "comment2");
BOOST_TEST(u.is_integer());
BOOST_TEST(u.as_integer() == 42);
}
{
const value_type v(42, {"comment1", "comment2"});
BOOST_TEST(v.comments().size() == 2u);
BOOST_TEST(v.comments().at(0) == "comment1");
BOOST_TEST(v.comments().at(1) == "comment2");
BOOST_TEST(v.is_integer());
BOOST_TEST(v.as_integer() == 42);
const value_type u(v, {});
BOOST_TEST(u.comments().size() == 0u);
BOOST_TEST(u.is_integer());
BOOST_TEST(u.as_integer() == 42);
}
}
BOOST_AUTO_TEST_CASE(test_output_comments)
{
using value_type = toml::basic_value<toml::preserve_comments>;
{
const value_type v(42, {"comment1", "comment2"});
std::ostringstream oss;
oss << v.comments();
std::ostringstream ref;
ref << "#comment1\n";
ref << "#comment2\n";
BOOST_TEST(oss.str() == ref.str());
}
{
const value_type v(42, {"comment1", "comment2"});
std::ostringstream oss;
// If v is not a table, toml11 assumes that user is writing something
// like the following.
oss << "answer = " << v;
BOOST_TEST(oss.str() == "answer = 42 #comment1comment2");
}
{
const value_type v(42, {"comment1", "comment2"});
std::ostringstream oss;
// If v is not a table, toml11 assumes that user is writing something
// like the following.
oss << toml::nocomment << "answer = " << v;
BOOST_TEST(oss.str() == "answer = 42");
}
{
const value_type v(42, {"comment1", "comment2"});
std::ostringstream oss;
// If v is not a table, toml11 assumes that user is writing something
// like the following.
oss << toml::nocomment << toml::showcomment << "answer = " << v;
BOOST_TEST(oss.str() == "answer = 42 #comment1comment2");
}
}

View File

@@ -5,26 +5,118 @@
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <thread>
#include <toml/datetime.hpp>
BOOST_AUTO_TEST_CASE(test_datetime_convertible)
BOOST_AUTO_TEST_CASE(test_local_date)
{
const auto now = std::chrono::system_clock::now();
toml::Datetime d1(now);
const std::chrono::system_clock::time_point cvt(d1);
toml::Datetime d2(cvt);
const toml::local_date date(2018, toml::month_t::Jan, 1);
const toml::local_date date1(date);
BOOST_TEST(date == date1);
BOOST_CHECK_EQUAL(d1, d2);
const std::chrono::system_clock::time_point tp(date);
const toml::local_date date2(tp);
BOOST_TEST(date == date2);
const auto time = std::chrono::system_clock::to_time_t(now);
toml::Datetime d3(time);
toml::Datetime d4(std::chrono::system_clock::from_time_t(time));
const toml::local_date date3(2017, toml::month_t::Dec, 31);
BOOST_TEST(date > date3);
BOOST_CHECK_EQUAL(d3, d4);
std::this_thread::sleep_for(std::chrono::seconds(1));
const auto later = std::chrono::system_clock::now();
toml::Datetime d5(later);
BOOST_CHECK(d1 < d5);
std::ostringstream oss;
oss << date;
BOOST_TEST(oss.str() == std::string("2018-01-01"));
}
BOOST_AUTO_TEST_CASE(test_local_time)
{
const toml::local_time time(12, 30, 45);
const toml::local_time time1(time);
BOOST_TEST(time == time1);
const std::chrono::nanoseconds dur(time);
std::chrono::nanoseconds ns(0);
ns += std::chrono::hours (12);
ns += std::chrono::minutes(30);
ns += std::chrono::seconds(45);
BOOST_TEST(dur.count() == ns.count());
const toml::local_time time3(12, 15, 45);
BOOST_TEST(time > time3);
{
std::ostringstream oss;
oss << time;
BOOST_TEST(oss.str() == std::string("12:30:45"));
}
{
const toml::local_time time4(12, 30, 45, 123, 456);
std::ostringstream oss;
oss << time4;
BOOST_TEST(oss.str() == std::string("12:30:45.123456"));
}
}
BOOST_AUTO_TEST_CASE(test_time_offset)
{
const toml::time_offset time(9, 30);
const toml::time_offset time1(time);
BOOST_TEST(time == time1);
const std::chrono::minutes dur(time);
std::chrono::minutes m(0);
m += std::chrono::hours (9);
m += std::chrono::minutes(30);
BOOST_TEST(dur.count() == m.count());
const toml::time_offset time2(9, 0);
BOOST_TEST(time2 < time);
std::ostringstream oss;
oss << time;
BOOST_TEST(oss.str() == std::string("+09:30"));
}
BOOST_AUTO_TEST_CASE(test_local_datetime)
{
const toml::local_datetime dt(toml::local_date(2018, toml::month_t::Jan, 1),
toml::local_time(12, 30, 45));
const toml::local_datetime dt1(dt);
BOOST_TEST(dt == dt1);
const std::chrono::system_clock::time_point tp(dt);
const toml::local_datetime dt2(tp);
BOOST_TEST(dt == dt2);
std::ostringstream oss;
oss << dt;
BOOST_TEST(oss.str() == std::string("2018-01-01T12:30:45"));
}
BOOST_AUTO_TEST_CASE(test_offset_datetime)
{
const toml::offset_datetime dt(toml::local_date(2018, toml::month_t::Jan, 1),
toml::local_time(12, 30, 45),
toml::time_offset(9, 30));
const toml::offset_datetime dt1(dt);
BOOST_TEST(dt == dt1);
const std::chrono::system_clock::time_point tp1(dt);
const toml::offset_datetime dt2(tp1);
const std::chrono::system_clock::time_point tp2(dt2);
const bool tp_same = (tp1 == tp2);
BOOST_TEST(tp_same);
{
std::ostringstream oss;
oss << dt;
BOOST_TEST(oss.str() == std::string("2018-01-01T12:30:45+09:30"));
}
{
const toml::offset_datetime dt3(
toml::local_date(2018, toml::month_t::Jan, 1),
toml::local_time(12, 30, 45),
toml::time_offset(0, 0));
std::ostringstream oss;
oss << dt3;
BOOST_TEST(oss.str() == std::string("2018-01-01T12:30:45Z"));
}
}

View File

@@ -0,0 +1,101 @@
#define BOOST_TEST_MODULE "test_error_detection"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <iostream>
#include <fstream>
BOOST_AUTO_TEST_CASE(test_detect_empty_key)
{
std::istringstream stream(std::string("= \"value\""));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
}
BOOST_AUTO_TEST_CASE(test_detect_missing_value)
{
std::istringstream stream(std::string("a ="));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
}
BOOST_AUTO_TEST_CASE(test_detect_too_many_value)
{
std::istringstream stream(std::string("a = 1 = \"value\""));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
}
BOOST_AUTO_TEST_CASE(test_detect_duplicate_table)
{
std::istringstream stream(std::string(
"[table]\n"
"a = 42\n"
"[table]\n"
"b = 42\n"
));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
}
BOOST_AUTO_TEST_CASE(test_detect_conflict_array_table)
{
std::istringstream stream(std::string(
"[[table]]\n"
"a = 42\n"
"[table]\n"
"b = 42\n"
));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
}
BOOST_AUTO_TEST_CASE(test_detect_conflict_table_array)
{
std::istringstream stream(std::string(
"[table]\n"
"a = 42\n"
"[[table]]\n"
"b = 42\n"
));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
}
BOOST_AUTO_TEST_CASE(test_detect_duplicate_value)
{
std::istringstream stream(std::string(
"a = 1\n"
"a = 2\n"
));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
}
BOOST_AUTO_TEST_CASE(test_detect_conflicting_value)
{
std::istringstream stream(std::string(
"a.b = 1\n"
"a.b.c = 2\n"
));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
}
BOOST_AUTO_TEST_CASE(test_detect_inhomogeneous_array)
{
#ifdef TOML11_DISALLOW_HETEROGENEOUS_ARRAYS
std::istringstream stream(std::string(
"a = [1, 1.0]\n"
));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
#else
BOOST_TEST_MESSAGE("After v1.0.0-rc.1, heterogeneous arrays are allowed");
#endif
}
BOOST_AUTO_TEST_CASE(test_detect_appending_array_of_table)
{
std::istringstream stream(std::string(
"a = [{b = 1}]\n"
"[[a]]\n"
"b = 2\n"
));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
}

30
tests/test_expect.cpp Normal file
View File

@@ -0,0 +1,30 @@
#define BOOST_TEST_MODULE "test_expect"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <map>
#include <unordered_map>
#include <list>
#include <deque>
#include <array>
BOOST_AUTO_TEST_CASE(test_expect)
{
{
toml::value v1(42);
toml::value v2(3.14);
const auto v1_or_0 = toml::expect<int>(v1).unwrap_or(0);
const auto v2_or_0 = toml::expect<int>(v2).unwrap_or(0);
BOOST_TEST(42 == v1_or_0);
BOOST_TEST( 0 == v2_or_0);
const auto v1_or_none = toml::expect<int>(v1).map([](int i){return std::to_string(i);}).unwrap_or(std::string("none"));
const auto v2_or_none = toml::expect<int>(v2).map([](int i){return std::to_string(i);}).unwrap_or(std::string("none"));
BOOST_TEST("42" == v1_or_none);
BOOST_TEST("none" == v2_or_none);
}
}

View File

@@ -0,0 +1,547 @@
#define BOOST_TEST_MODULE "test_extended_conversions"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <deque>
#include <map>
namespace extlib
{
struct foo
{
int a;
std::string b;
};
struct bar
{
int a;
std::string b;
void from_toml(const toml::value& v)
{
this->a = toml::find<int>(v, "a");
this->b = toml::find<std::string>(v, "b");
return ;
}
toml::table into_toml() const
{
return toml::table{{"a", this->a}, {"b", this->b}};
}
};
struct baz
{
int a;
std::string b;
};
struct qux
{
int a;
std::string b;
};
struct foobar
{
// via constructor
explicit foobar(const toml::value& v)
: a(toml::find<int>(v, "a")), b(toml::find<std::string>(v, "b"))
{}
int a;
std::string b;
};
} // extlib
namespace toml
{
template<>
struct from<extlib::foo>
{
static extlib::foo from_toml(const toml::value& v)
{
return extlib::foo{toml::find<int>(v, "a"), toml::find<std::string>(v, "b")};
}
};
template<>
struct into<extlib::foo>
{
static toml::table into_toml(const extlib::foo& f)
{
return toml::table{{"a", f.a}, {"b", f.b}};
}
};
template<>
struct from<extlib::baz>
{
static extlib::baz from_toml(const toml::value& v)
{
return extlib::baz{toml::find<int>(v, "a"), toml::find<std::string>(v, "b")};
}
};
template<>
struct into<extlib::qux>
{
static toml::table into_toml(const extlib::qux& f)
{
return toml::table{{"a", f.a}, {"b", f.b}};
}
};
} // toml
// ---------------------------------------------------------------------------
namespace extlib2
{
struct foo
{
int a;
std::string b;
};
struct bar
{
int a;
std::string b;
template<typename C, template<typename ...> class M, template<typename ...> class A>
void from_toml(const toml::basic_value<C, M, A>& v)
{
this->a = toml::find<int>(v, "a");
this->b = toml::find<std::string>(v, "b");
return ;
}
toml::table into_toml() const
{
return toml::table{{"a", this->a}, {"b", this->b}};
}
};
struct baz
{
int a;
std::string b;
};
struct qux
{
int a;
std::string b;
};
struct foobar
{
template<typename C, template<typename ...> class M, template<typename ...> class A>
explicit foobar(const toml::basic_value<C, M, A>& v)
: a(toml::find<int>(v, "a")), b(toml::find<std::string>(v, "b"))
{}
int a;
std::string b;
};
} // extlib2
namespace toml
{
template<>
struct from<extlib2::foo>
{
template<typename C, template<typename ...> class M, template<typename ...> class A>
static extlib2::foo from_toml(const toml::basic_value<C, M, A>& v)
{
return extlib2::foo{toml::find<int>(v, "a"), toml::find<std::string>(v, "b")};
}
};
template<>
struct into<extlib2::foo>
{
static toml::table into_toml(const extlib2::foo& f)
{
return toml::table{{"a", f.a}, {"b", f.b}};
}
};
template<>
struct from<extlib2::baz>
{
template<typename C, template<typename ...> class M, template<typename ...> class A>
static extlib2::baz from_toml(const toml::basic_value<C, M, A>& v)
{
return extlib2::baz{toml::find<int>(v, "a"), toml::find<std::string>(v, "b")};
}
};
template<>
struct into<extlib2::qux>
{
static toml::basic_value<toml::preserve_comments, std::map>
into_toml(const extlib2::qux& f)
{
return toml::basic_value<toml::preserve_comments, std::map>{
{"a", f.a}, {"b", f.b}
};
}
};
} // toml
// ---------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(test_conversion_by_member_methods)
{
{
const toml::value v{{"a", 42}, {"b", "baz"}};
const auto foo = toml::get<extlib::foo>(v);
BOOST_TEST(foo.a == 42);
BOOST_TEST(foo.b == "baz");
const toml::value v2(foo);
BOOST_TEST(v == v2);
}
{
const toml::value v{{"a", 42}, {"b", "baz"}};
const auto foo = toml::get<extlib2::foo>(v);
BOOST_TEST(foo.a == 42);
BOOST_TEST(foo.b == "baz");
const toml::value v2(foo);
BOOST_TEST(v == v2);
}
{
const toml::basic_value<toml::discard_comments, std::map, std::deque>
v{{"a", 42}, {"b", "baz"}};
const auto foo = toml::get<extlib2::foo>(v);
BOOST_TEST(foo.a == 42);
BOOST_TEST(foo.b == "baz");
const toml::basic_value<toml::discard_comments, std::map, std::deque>
v2(foo);
BOOST_TEST(v == v2);
}
}
BOOST_AUTO_TEST_CASE(test_conversion_by_specialization)
{
{
const toml::value v{{"a", 42}, {"b", "baz"}};
const auto bar = toml::get<extlib::bar>(v);
BOOST_TEST(bar.a == 42);
BOOST_TEST(bar.b == "baz");
const toml::value v2(bar);
BOOST_TEST(v == v2);
}
{
const toml::value v{{"a", 42}, {"b", "baz"}};
const auto bar = toml::get<extlib2::bar>(v);
BOOST_TEST(bar.a == 42);
BOOST_TEST(bar.b == "baz");
const toml::value v2(bar);
BOOST_TEST(v == v2);
}
{
const toml::basic_value<toml::discard_comments, std::map, std::deque>
v{{"a", 42}, {"b", "baz"}};
const auto bar = toml::get<extlib2::bar>(v);
BOOST_TEST(bar.a == 42);
BOOST_TEST(bar.b == "baz");
const toml::basic_value<toml::discard_comments, std::map, std::deque>
v2(bar);
BOOST_TEST(v == v2);
}
}
BOOST_AUTO_TEST_CASE(test_conversion_one_way)
{
{
const toml::value v{{"a", 42}, {"b", "baz"}};
const auto baz = toml::get<extlib::baz>(v);
BOOST_TEST(baz.a == 42);
BOOST_TEST(baz.b == "baz");
}
{
const extlib::qux q{42, "qux"};
const toml::value v(q);
BOOST_TEST(toml::find<int>(v, "a") == 42);
BOOST_TEST(toml::find<std::string>(v, "b") == "qux");
}
{
const toml::basic_value<toml::discard_comments, std::map> v{
{"a", 42}, {"b", "baz"}
};
const auto baz = toml::get<extlib2::baz>(v);
BOOST_TEST(baz.a == 42);
BOOST_TEST(baz.b == "baz");
}
{
const extlib::qux q{42, "qux"};
const toml::basic_value<toml::preserve_comments, std::map> v(q);
BOOST_TEST(toml::find<int>(v, "a") == 42);
BOOST_TEST(toml::find<std::string>(v, "b") == "qux");
}
}
BOOST_AUTO_TEST_CASE(test_conversion_via_constructor)
{
{
const toml::value v{{"a", 42}, {"b", "foobar"}};
const auto foobar = toml::get<extlib::foobar>(v);
BOOST_TEST(foobar.a == 42);
BOOST_TEST(foobar.b == "foobar");
}
{
const toml::basic_value<toml::discard_comments, std::map> v{
{"a", 42}, {"b", "foobar"}
};
const auto foobar = toml::get<extlib2::foobar>(v);
BOOST_TEST(foobar.a == 42);
BOOST_TEST(foobar.b == "foobar");
}
}
BOOST_AUTO_TEST_CASE(test_recursive_conversion)
{
{
const toml::value v{
toml::table{{"a", 42}, {"b", "baz"}},
toml::table{{"a", 43}, {"b", "qux"}},
toml::table{{"a", 44}, {"b", "quux"}},
toml::table{{"a", 45}, {"b", "foobar"}},
};
const auto foos = toml::get<std::vector<extlib::foo>>(v);
BOOST_TEST(foos.size() == 4ul);
BOOST_TEST(foos.at(0).a == 42);
BOOST_TEST(foos.at(1).a == 43);
BOOST_TEST(foos.at(2).a == 44);
BOOST_TEST(foos.at(3).a == 45);
BOOST_TEST(foos.at(0).b == "baz");
BOOST_TEST(foos.at(1).b == "qux");
BOOST_TEST(foos.at(2).b == "quux");
BOOST_TEST(foos.at(3).b == "foobar");
const auto bars = toml::get<std::vector<extlib::bar>>(v);
BOOST_TEST(bars.size() == 4ul);
BOOST_TEST(bars.at(0).a == 42);
BOOST_TEST(bars.at(1).a == 43);
BOOST_TEST(bars.at(2).a == 44);
BOOST_TEST(bars.at(3).a == 45);
BOOST_TEST(bars.at(0).b == "baz");
BOOST_TEST(bars.at(1).b == "qux");
BOOST_TEST(bars.at(2).b == "quux");
BOOST_TEST(bars.at(3).b == "foobar");
}
{
const toml::value v{
toml::table{{"a", 42}, {"b", "baz"}},
toml::table{{"a", 43}, {"b", "qux"}},
toml::table{{"a", 44}, {"b", "quux"}},
toml::table{{"a", 45}, {"b", "foobar"}},
};
const auto foos = toml::get<std::vector<extlib2::foo>>(v);
BOOST_TEST(foos.size() == 4ul);
BOOST_TEST(foos.at(0).a == 42);
BOOST_TEST(foos.at(1).a == 43);
BOOST_TEST(foos.at(2).a == 44);
BOOST_TEST(foos.at(3).a == 45);
BOOST_TEST(foos.at(0).b == "baz");
BOOST_TEST(foos.at(1).b == "qux");
BOOST_TEST(foos.at(2).b == "quux");
BOOST_TEST(foos.at(3).b == "foobar");
const auto bars = toml::get<std::vector<extlib2::bar>>(v);
BOOST_TEST(bars.size() == 4ul);
BOOST_TEST(bars.at(0).a == 42);
BOOST_TEST(bars.at(1).a == 43);
BOOST_TEST(bars.at(2).a == 44);
BOOST_TEST(bars.at(3).a == 45);
BOOST_TEST(bars.at(0).b == "baz");
BOOST_TEST(bars.at(1).b == "qux");
BOOST_TEST(bars.at(2).b == "quux");
BOOST_TEST(bars.at(3).b == "foobar");
}
{
const toml::basic_value<toml::discard_comments, std::map, std::deque>
v{
toml::table{{"a", 42}, {"b", "baz"}},
toml::table{{"a", 43}, {"b", "qux"}},
toml::table{{"a", 44}, {"b", "quux"}},
toml::table{{"a", 45}, {"b", "foobar"}}
};
const auto foos = toml::get<std::vector<extlib2::foo>>(v);
BOOST_TEST(foos.size() == 4ul);
BOOST_TEST(foos.at(0).a == 42);
BOOST_TEST(foos.at(1).a == 43);
BOOST_TEST(foos.at(2).a == 44);
BOOST_TEST(foos.at(3).a == 45);
BOOST_TEST(foos.at(0).b == "baz");
BOOST_TEST(foos.at(1).b == "qux");
BOOST_TEST(foos.at(2).b == "quux");
BOOST_TEST(foos.at(3).b == "foobar");
const auto bars = toml::get<std::vector<extlib2::bar>>(v);
BOOST_TEST(bars.size() == 4ul);
BOOST_TEST(bars.at(0).a == 42);
BOOST_TEST(bars.at(1).a == 43);
BOOST_TEST(bars.at(2).a == 44);
BOOST_TEST(bars.at(3).a == 45);
BOOST_TEST(bars.at(0).b == "baz");
BOOST_TEST(bars.at(1).b == "qux");
BOOST_TEST(bars.at(2).b == "quux");
BOOST_TEST(bars.at(3).b == "foobar");
}
// via constructor
{
const toml::value v{
toml::table{{"a", 42}, {"b", "baz"}},
toml::table{{"a", 43}, {"b", "qux"}},
toml::table{{"a", 44}, {"b", "quux"}},
toml::table{{"a", 45}, {"b", "foobar"}}
};
{
const auto foobars = toml::get<std::vector<extlib::foobar>>(v);
BOOST_TEST(foobars.size() == 4ul);
BOOST_TEST(foobars.at(0).a == 42);
BOOST_TEST(foobars.at(1).a == 43);
BOOST_TEST(foobars.at(2).a == 44);
BOOST_TEST(foobars.at(3).a == 45);
BOOST_TEST(foobars.at(0).b == "baz");
BOOST_TEST(foobars.at(1).b == "qux");
BOOST_TEST(foobars.at(2).b == "quux");
BOOST_TEST(foobars.at(3).b == "foobar");
}
{
const auto foobars = toml::get<std::vector<extlib2::foobar>>(v);
BOOST_TEST(foobars.size() == 4ul);
BOOST_TEST(foobars.at(0).a == 42);
BOOST_TEST(foobars.at(1).a == 43);
BOOST_TEST(foobars.at(2).a == 44);
BOOST_TEST(foobars.at(3).a == 45);
BOOST_TEST(foobars.at(0).b == "baz");
BOOST_TEST(foobars.at(1).b == "qux");
BOOST_TEST(foobars.at(2).b == "quux");
BOOST_TEST(foobars.at(3).b == "foobar");
}
}
{
const toml::basic_value<toml::discard_comments, std::map, std::deque>
v{
toml::table{{"a", 42}, {"b", "baz"}},
toml::table{{"a", 43}, {"b", "qux"}},
toml::table{{"a", 44}, {"b", "quux"}},
toml::table{{"a", 45}, {"b", "foobar"}}
};
const auto foobars = toml::get<std::vector<extlib2::foobar>>(v);
BOOST_TEST(foobars.size() == 4ul);
BOOST_TEST(foobars.at(0).a == 42);
BOOST_TEST(foobars.at(1).a == 43);
BOOST_TEST(foobars.at(2).a == 44);
BOOST_TEST(foobars.at(3).a == 45);
BOOST_TEST(foobars.at(0).b == "baz");
BOOST_TEST(foobars.at(1).b == "qux");
BOOST_TEST(foobars.at(2).b == "quux");
BOOST_TEST(foobars.at(3).b == "foobar");
}
// via constructor
{
const toml::value v{
{"0", toml::table{{"a", 42}, {"b", "baz"}}},
{"1", toml::table{{"a", 43}, {"b", "qux"}}},
{"2", toml::table{{"a", 44}, {"b", "quux"}}},
{"3", toml::table{{"a", 45}, {"b", "foobar"}}}
};
{
const auto foobars = toml::get<std::map<std::string, extlib::foobar>>(v);
BOOST_TEST(foobars.size() == 4ul);
BOOST_TEST(foobars.at("0").a == 42);
BOOST_TEST(foobars.at("1").a == 43);
BOOST_TEST(foobars.at("2").a == 44);
BOOST_TEST(foobars.at("3").a == 45);
BOOST_TEST(foobars.at("0").b == "baz");
BOOST_TEST(foobars.at("1").b == "qux");
BOOST_TEST(foobars.at("2").b == "quux");
BOOST_TEST(foobars.at("3").b == "foobar");
}
{
const auto foobars = toml::get<std::map<std::string, extlib2::foobar>>(v);
BOOST_TEST(foobars.size() == 4ul);
BOOST_TEST(foobars.at("0").a == 42);
BOOST_TEST(foobars.at("1").a == 43);
BOOST_TEST(foobars.at("2").a == 44);
BOOST_TEST(foobars.at("3").a == 45);
BOOST_TEST(foobars.at("0").b == "baz");
BOOST_TEST(foobars.at("1").b == "qux");
BOOST_TEST(foobars.at("2").b == "quux");
BOOST_TEST(foobars.at("3").b == "foobar");
}
}
{
const toml::basic_value<toml::discard_comments, std::map, std::deque>
v{
{"0", toml::table{{"a", 42}, {"b", "baz"}}},
{"1", toml::table{{"a", 43}, {"b", "qux"}}},
{"2", toml::table{{"a", 44}, {"b", "quux"}}},
{"3", toml::table{{"a", 45}, {"b", "foobar"}}}
};
const auto foobars = toml::get<std::map<std::string, extlib::foobar>>(v);
BOOST_TEST(foobars.size() == 4ul);
BOOST_TEST(foobars.at("0").a == 42);
BOOST_TEST(foobars.at("1").a == 43);
BOOST_TEST(foobars.at("2").a == 44);
BOOST_TEST(foobars.at("3").a == 45);
BOOST_TEST(foobars.at("0").b == "baz");
BOOST_TEST(foobars.at("1").b == "qux");
BOOST_TEST(foobars.at("2").b == "quux");
BOOST_TEST(foobars.at("3").b == "foobar");
}
}

833
tests/test_find.cpp Normal file
View File

@@ -0,0 +1,833 @@
#define BOOST_TEST_MODULE "test_find"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <map>
#include <unordered_map>
#include <list>
#include <deque>
#include <array>
#if __cplusplus >= 201703L
#include <string_view>
#endif
#include <tuple>
using test_value_types = std::tuple<
toml::value,
toml::basic_value<toml::preserve_comments>,
toml::basic_value<toml::discard_comments, std::map, std::deque>,
toml::basic_value<toml::preserve_comments, std::map, std::deque>
>;
BOOST_AUTO_TEST_CASE(test_find_throws)
{
// -----------------------------------------------------------------------
// const-reference version
{
// value is not a table
const toml::value v(true);
BOOST_CHECK_THROW(toml::find<toml::boolean>(v, "key"), toml::type_error);
}
{
// the value corresponding to the key is not the expected type
const toml::value v{{"key", 42}};
BOOST_CHECK_THROW(toml::find<toml::boolean>(v, "key"), toml::type_error);
}
{
// the value corresponding to the key is not found
const toml::value v{{"key", 42}};
BOOST_CHECK_THROW(toml::find<toml::integer>(v, "different_key"),
std::out_of_range);
}
{
// the positive control.
const toml::value v{{"key", 42}};
BOOST_TEST(42 == toml::find<int>(v, "key"));
}
// -----------------------------------------------------------------------
// reference version
{
// value is not a table
toml::value v(true);
BOOST_CHECK_THROW(toml::find<toml::boolean>(v, "key"), toml::type_error);
}
{
// the value corresponding to the key is not the expected type
toml::value v{{"key", 42}};
BOOST_CHECK_THROW(toml::find<toml::boolean>(v, "key"), toml::type_error);
}
{
// the value corresponding to the key is not found
toml::value v{{"key", 42}};
BOOST_CHECK_THROW(toml::find<toml::integer>(v, "different_key"),
std::out_of_range);
}
{
// the positive control.
toml::value v{{"key", 42}};
BOOST_TEST(42 == toml::find<int>(v, "key"));
}
// -----------------------------------------------------------------------
// move version
{
// value is not a table
toml::value v(true);
BOOST_CHECK_THROW(toml::find<toml::boolean>(std::move(v), "key"), toml::type_error);
}
{
// the value corresponding to the key is not the expected type
toml::value v{{"key", 42}};
BOOST_CHECK_THROW(toml::find<toml::boolean>(std::move(v), "key"), toml::type_error);
}
{
// the value corresponding to the key is not found
toml::value v{{"key", 42}};
BOOST_CHECK_THROW(toml::find<toml::integer>(std::move(v), "different_key"),
std::out_of_range);
}
{
// the positive control.
toml::value v{{"key", 42}};
BOOST_TEST(42 == toml::find<int>(std::move(v), "key"));
}
}
BOOST_AUTO_TEST_CASE(test_find_array_throws)
{
// -----------------------------------------------------------------------
// const-reference version
{
// value is not an array
const toml::value v(true);
BOOST_CHECK_THROW(toml::find<toml::boolean>(v, 0), toml::type_error);
}
{
// the value corresponding to the key is not the expected type
const toml::value v{1, 2, 3, 4, 5};
BOOST_CHECK_THROW(toml::find<toml::boolean>(v, 0), toml::type_error);
}
{
// the value corresponding to the key is not found
const toml::value v{1, 2, 3, 4, 5};
BOOST_CHECK_THROW(toml::find<toml::integer>(v, 6), std::out_of_range);
}
{
// the positive control.
const toml::value v{1, 2, 3, 4, 5};
BOOST_TEST(3 == toml::find<int>(v, 2));
}
// -----------------------------------------------------------------------
// non-const reference version
{
// value is not an array
toml::value v(true);
BOOST_CHECK_THROW(toml::find<toml::boolean>(v, 0), toml::type_error);
}
{
// the value corresponding to the key is not the expected type
toml::value v{1, 2, 3, 4, 5};
BOOST_CHECK_THROW(toml::find<toml::boolean>(v, 0), toml::type_error);
}
{
// the value corresponding to the key is not found
toml::value v{1, 2, 3, 4, 5};
BOOST_CHECK_THROW(toml::find<toml::integer>(v, 6), std::out_of_range);
}
{
// the positive control.
toml::value v{1, 2, 3, 4, 5};
BOOST_TEST(3 == toml::find<int>(v, 2));
}
// -----------------------------------------------------------------------
// move version
{
// value is not an array
toml::value v(true);
BOOST_CHECK_THROW(toml::find<toml::boolean>(std::move(v), 0), toml::type_error);
}
{
// the value corresponding to the key is not the expected type
toml::value v{1, 2, 3, 4, 5};
BOOST_CHECK_THROW(toml::find<toml::boolean>(std::move(v), 0), toml::type_error);
}
{
// the value corresponding to the key is not found
toml::value v{1, 2, 3, 4, 5};
BOOST_CHECK_THROW(toml::find<toml::integer>(std::move(v), 6), std::out_of_range);
}
{
// the positive control.
toml::value v{1, 2, 3, 4, 5};
BOOST_TEST(3 == toml::find<int>(std::move(v), 2));
}
}
BOOST_AUTO_TEST_CASE(test_find_recursive)
{
// recursively search tables
{
toml::value v{
{"a", {
{"b", {
{"c", {
{"d", 42}
}}
}}
}}
};
BOOST_TEST(42 == toml::find<int>(v, "a", "b", "c", "d"));
// reference that can be used to modify the content
auto& num = toml::find<toml::integer>(v, "a", "b", "c", "d");
num = 54;
BOOST_TEST(54 == toml::find<int>(v, "a", "b", "c", "d"));
const std::string a("a"), b("b"), c("c"), d("d");
auto& num2 = toml::find<toml::integer>(v, a, b, c, d);
num2 = 42;
BOOST_TEST(42 == toml::find<int>(v, a, b, c, d));
auto num3 = toml::find<toml::integer>(v, a, "b", c, "d");
BOOST_TEST(42 == num3);
auto num4 = toml::find<toml::integer>(std::move(v), a, b, c, d);
BOOST_TEST(42 == num4);
}
// recursively search arrays
{
toml::value v{
toml::array{"array", "of", "string"},
toml::array{toml::array{1, 2, 3}, toml::array{3.14, 2.71}}
};
BOOST_TEST("array" == toml::find<std::string>(v, 0, 0));
BOOST_TEST("of" == toml::find<std::string>(v, 0, 1));
BOOST_TEST("string" == toml::find<std::string>(v, 0, 2));
BOOST_TEST(1 == toml::find<int>(v, 1, 0, 0));
BOOST_TEST(2 == toml::find<int>(v, 1, 0, 1));
BOOST_TEST(3 == toml::find<int>(v, 1, 0, 2));
BOOST_TEST(3.14 == toml::find<double>(v, 1, 1, 0));
BOOST_TEST(2.71 == toml::find<double>(v, 1, 1, 1));
// reference that can be used to modify the content
auto& num = toml::find<toml::integer>(v, 1, 0, 2);
num = 42;
BOOST_TEST( 1 == toml::find<int>(v, 1, 0, 0));
BOOST_TEST( 2 == toml::find<int>(v, 1, 0, 1));
BOOST_TEST(42 == toml::find<int>(v, 1, 0, 2));
// move value
auto num2 = toml::find<toml::integer>(std::move(v), 1, 0, 2);
BOOST_TEST(42 == num2);
}
// recursively search mixtures
{
toml::value v = toml::table{{"array", toml::array{
toml::array{1, 2, 3},
toml::array{
toml::table{{"foo", "bar"}, {"baz", "qux"}},
toml::table{{"pi", 3.14}, {"e", 2.71}}
}}
}};
BOOST_TEST(1 == toml::find<int>(v, "array", 0, 0));
BOOST_TEST(2 == toml::find<int>(v, "array", 0, 1));
BOOST_TEST(3 == toml::find<int>(v, "array", 0, 2));
BOOST_TEST("bar" == toml::find<std::string>(v, "array", 1, 0, "foo"));
BOOST_TEST("qux" == toml::find<std::string>(v, "array", 1, 0, "baz"));
BOOST_TEST(3.14 == toml::find<double>(v, "array", 1, 1, "pi"));
BOOST_TEST(2.71 == toml::find<double>(v, "array", 1, 1, "e"));
const std::string ar("array");
const auto ar_c = "array";
const std::string pi("pi");
const auto pi_c = "pi";
BOOST_TEST(3.14 == toml::find<double>(v, ar, 1, 1, "pi"));
BOOST_TEST(3.14 == toml::find<double>(v, ar, 1, 1, pi));
BOOST_TEST(3.14 == toml::find<double>(v, ar, 1, 1, pi_c));
BOOST_TEST(3.14 == toml::find<double>(v, ar_c, 1, 1, "pi"));
BOOST_TEST(3.14 == toml::find<double>(v, ar_c, 1, 1, pi));
BOOST_TEST(3.14 == toml::find<double>(v, ar_c, 1, 1, pi_c));
BOOST_TEST(3.14 == toml::find<double>(v, "array", 1, 1, pi));
BOOST_TEST(3.14 == toml::find<double>(v, "array", 1, 1, pi_c));
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_exact, value_type, test_value_types)
{
{
value_type v{{"key", true}};
BOOST_TEST(true == toml::find<toml::boolean>(v, "key"));
toml::find<toml::boolean>(v, "key") = false;
BOOST_TEST(false == toml::find<toml::boolean>(v, "key"));
const auto moved = toml::find<toml::boolean>(std::move(v), "key");
BOOST_TEST(false == moved);
}
{
value_type v{{"key", 42}};
BOOST_TEST(toml::integer(42) == toml::find<toml::integer>(v, "key"));
toml::find<toml::integer>(v, "key") = 54;
BOOST_TEST(toml::integer(54) == toml::find<toml::integer>(v, "key"));
const auto moved = toml::find<toml::integer>(std::move(v), "key");
BOOST_TEST(toml::integer(54) == moved);
}
{
value_type v{{"key", 3.14}};
BOOST_TEST(toml::floating(3.14) == toml::find<toml::floating>(v, "key"));
toml::find<toml::floating>(v, "key") = 2.71;
BOOST_TEST(toml::floating(2.71) == toml::find<toml::floating>(v, "key"));
const auto moved = toml::find<toml::floating>(std::move(v), "key");
BOOST_TEST(toml::floating(2.71) == moved);
}
{
value_type v{{"key", "foo"}};
BOOST_TEST(toml::string("foo", toml::string_t::basic) ==
toml::find<toml::string>(v, "key"));
toml::find<toml::string>(v, "key").str += "bar";
BOOST_TEST(toml::string("foobar", toml::string_t::basic) ==
toml::find<toml::string>(v, "key"));
const auto moved = toml::find<toml::string>(std::move(v), "key");
BOOST_TEST(toml::string("foobar", toml::string_t::basic) == moved);
}
{
value_type v{{"key", value_type("foo", toml::string_t::literal)}};
BOOST_TEST(toml::string("foo", toml::string_t::literal) ==
toml::find<toml::string>(v, "key"));
toml::find<toml::string>(v, "key").str += "bar";
BOOST_TEST(toml::string("foobar", toml::string_t::literal) ==
toml::find<toml::string>(v, "key"));
const auto moved = toml::find<toml::string>(std::move(v), "key");
BOOST_TEST(toml::string("foobar", toml::string_t::literal) == moved);
}
{
toml::local_date d(2018, toml::month_t::Apr, 22);
value_type v{{"key", d}};
BOOST_CHECK(d == toml::find<toml::local_date>(v, "key"));
toml::find<toml::local_date>(v, "key").year = 2017;
d.year = 2017;
BOOST_CHECK(d == toml::find<toml::local_date>(v, "key"));
const auto moved = toml::find<toml::local_date>(std::move(v), "key");
BOOST_CHECK(d == moved);
}
{
toml::local_time t(12, 30, 45);
value_type v{{"key", t}};
BOOST_CHECK(t == toml::find<toml::local_time>(v, "key"));
toml::find<toml::local_time>(v, "key").hour = 9;
t.hour = 9;
BOOST_CHECK(t == toml::find<toml::local_time>(v, "key"));
const auto moved = toml::find<toml::local_time>(std::move(v), "key");
BOOST_CHECK(t == moved);
}
{
toml::local_datetime dt(toml::local_date(2018, toml::month_t::Apr, 22),
toml::local_time(12, 30, 45));
value_type v{{"key", dt}};
BOOST_CHECK(dt == toml::find<toml::local_datetime>(v, "key"));
toml::find<toml::local_datetime>(v, "key").date.year = 2017;
dt.date.year = 2017;
BOOST_CHECK(dt == toml::find<toml::local_datetime>(v, "key"));
const auto moved = toml::find<toml::local_datetime>(std::move(v), "key");
BOOST_CHECK(dt == moved);
}
{
toml::offset_datetime dt(toml::local_datetime(
toml::local_date(2018, toml::month_t::Apr, 22),
toml::local_time(12, 30, 45)), toml::time_offset(9, 0));
value_type v{{"key", dt}};
BOOST_CHECK(dt == toml::find<toml::offset_datetime>(v, "key"));
toml::find<toml::offset_datetime>(v, "key").date.year = 2017;
dt.date.year = 2017;
BOOST_CHECK(dt == toml::find<toml::offset_datetime>(v, "key"));
const auto moved = toml::find<toml::offset_datetime>(std::move(v), "key");
BOOST_CHECK(dt == moved);
}
{
typename value_type::array_type vec;
vec.push_back(value_type(42));
vec.push_back(value_type(54));
value_type v{{"key", vec}};
const bool result1 = (vec == toml::find<typename value_type::array_type>(v, "key"));
BOOST_CHECK(result1);
toml::find<typename value_type::array_type>(v, "key").push_back(value_type(123));
vec.push_back(value_type(123));
const bool result2 = (vec == toml::find<typename value_type::array_type>(v, "key"));
BOOST_CHECK(result2);
const auto moved = toml::find<typename value_type::array_type>(std::move(v), "key");
const bool result3 = (vec == moved);
BOOST_CHECK(result3);
}
{
typename value_type::table_type tab;
tab["key1"] = value_type(42);
tab["key2"] = value_type(3.14);
value_type v{{"key", tab}};
const bool result1 = (tab == toml::find<typename value_type::table_type>(v, "key"));
BOOST_CHECK(result1);
toml::find<typename value_type::table_type>(v, "key")["key3"] = value_type(123);
tab["key3"] = value_type(123);
const bool result2 = (tab == toml::find<typename value_type::table_type>(v, "key"));
BOOST_CHECK(result2);
const auto moved = toml::find<typename value_type::table_type>(std::move(v), "key");
const bool result3 = (tab == moved);
BOOST_CHECK(result3);
}
{
value_type v1(42);
value_type v{{"key", v1}};
BOOST_CHECK(v1 == toml::find(v, "key"));
value_type v2(54);
toml::find(v, "key") = v2;
BOOST_CHECK(v2 == toml::find(v, "key"));
const auto moved = toml::find(std::move(v), "key");
BOOST_CHECK(v2 == moved);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_integer_type, value_type, test_value_types)
{
{
value_type v{{"key", 42}};
BOOST_TEST(int(42) == toml::find<int >(v, "key"));
BOOST_TEST(short(42) == toml::find<short >(v, "key"));
BOOST_TEST(char(42) == toml::find<char >(v, "key"));
BOOST_TEST(unsigned(42) == toml::find<unsigned >(v, "key"));
BOOST_TEST(long(42) == toml::find<long >(v, "key"));
BOOST_TEST(std::int64_t(42) == toml::find<std::int64_t >(v, "key"));
BOOST_TEST(std::uint64_t(42) == toml::find<std::uint64_t>(v, "key"));
BOOST_TEST(std::int16_t(42) == toml::find<std::int16_t >(v, "key"));
BOOST_TEST(std::uint16_t(42) == toml::find<std::uint16_t>(v, "key"));
BOOST_TEST(std::uint16_t(42) == toml::find<std::uint16_t>(std::move(v), "key"));
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_floating_type, value_type, test_value_types)
{
{
value_type v{{"key", 3.14}};
const double ref(3.14);
BOOST_TEST(static_cast<float >(ref) == toml::find<float >(v, "key"));
BOOST_TEST( ref == toml::find<double >(v, "key"));
BOOST_TEST(static_cast<long double>(ref) == toml::find<long double>(v, "key"));
BOOST_TEST(static_cast<float >(ref) == toml::find<float >(std::move(v), "key"));
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_string_type, value_type, test_value_types)
{
{
value_type v{{"key", toml::string("foo", toml::string_t::basic)}};
BOOST_TEST("foo" == toml::find<std::string>(v, "key"));
toml::find<std::string>(v, "key") += "bar";
BOOST_TEST("foobar" == toml::find<std::string>(v, "key"));
}
{
value_type v{{"key", toml::string("foo", toml::string_t::literal)}};
BOOST_TEST("foo" == toml::find<std::string>(v, "key"));
toml::find<std::string>(v, "key") += "bar";
BOOST_TEST("foobar" == toml::find<std::string>(v, "key"));
}
{
value_type v{{"key", toml::string("foo", toml::string_t::literal)}};
const auto moved = toml::find<std::string>(std::move(v), "key");
BOOST_TEST("foo" == moved);
}
#if __cplusplus >= 201703L
{
value_type v{{"key", toml::string("foo", toml::string_t::basic)}};
BOOST_TEST("foo" == toml::find<std::string_view>(v, "key"));
}
{
value_type v{{"key", toml::string("foo", toml::string_t::literal)}};
BOOST_TEST("foo" == toml::find<std::string_view>(v, "key"));
}
#endif
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_toml_array, value_type, test_value_types)
{
value_type v{{"key", {42, 54, 69, 72}}};
const std::vector<int> vec = toml::find<std::vector<int>>(v, "key");
const std::list<short> lst = toml::find<std::list<short>>(v, "key");
const std::deque<std::int64_t> deq = toml::find<std::deque<std::int64_t>>(v, "key");
BOOST_TEST(42 == vec.at(0));
BOOST_TEST(54 == vec.at(1));
BOOST_TEST(69 == vec.at(2));
BOOST_TEST(72 == vec.at(3));
std::list<short>::const_iterator iter = lst.begin();
BOOST_TEST(static_cast<short>(42) == *(iter++));
BOOST_TEST(static_cast<short>(54) == *(iter++));
BOOST_TEST(static_cast<short>(69) == *(iter++));
BOOST_TEST(static_cast<short>(72) == *(iter++));
BOOST_TEST(static_cast<std::int64_t>(42) == deq.at(0));
BOOST_TEST(static_cast<std::int64_t>(54) == deq.at(1));
BOOST_TEST(static_cast<std::int64_t>(69) == deq.at(2));
BOOST_TEST(static_cast<std::int64_t>(72) == deq.at(3));
std::array<int, 4> ary = toml::find<std::array<int, 4>>(v, "key");
BOOST_TEST(42 == ary.at(0));
BOOST_TEST(54 == ary.at(1));
BOOST_TEST(69 == ary.at(2));
BOOST_TEST(72 == ary.at(3));
std::tuple<int, short, unsigned, long> tpl =
toml::find<std::tuple<int, short, unsigned, long>>(v, "key");
BOOST_TEST( 42 == std::get<0>(tpl));
BOOST_TEST(static_cast<short >(54) == std::get<1>(tpl));
BOOST_TEST(static_cast<unsigned>(69) == std::get<2>(tpl));
BOOST_TEST(static_cast<long >(72) == std::get<3>(tpl));
value_type p{{"key", {3.14, 2.71}}};
std::pair<double, double> pr = toml::find<std::pair<double, double> >(p, "key");
BOOST_TEST(3.14 == pr.first);
BOOST_TEST(2.71 == pr.second);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_move_toml_array, value_type, test_value_types)
{
value_type v1{{"key", {42, 54, 69, 72}}};
value_type v2{{"key", {42, 54, 69, 72}}};
value_type v3{{"key", {42, 54, 69, 72}}};
value_type v4{{"key", {42, 54, 69, 72}}};
value_type v5{{"key", {42, 54, 69, 72}}};
const std::vector<int> vec = toml::find<std::vector<int>>(std::move(v1), "key");
const std::list<short> lst = toml::find<std::list<short>>(std::move(v2), "key");
const std::deque<std::int64_t> deq = toml::find<std::deque<std::int64_t>>(std::move(v3), "key");
BOOST_TEST(42 == vec.at(0));
BOOST_TEST(54 == vec.at(1));
BOOST_TEST(69 == vec.at(2));
BOOST_TEST(72 == vec.at(3));
std::list<short>::const_iterator iter = lst.begin();
BOOST_TEST(static_cast<short>(42) == *(iter++));
BOOST_TEST(static_cast<short>(54) == *(iter++));
BOOST_TEST(static_cast<short>(69) == *(iter++));
BOOST_TEST(static_cast<short>(72) == *(iter++));
BOOST_TEST(static_cast<std::int64_t>(42) == deq.at(0));
BOOST_TEST(static_cast<std::int64_t>(54) == deq.at(1));
BOOST_TEST(static_cast<std::int64_t>(69) == deq.at(2));
BOOST_TEST(static_cast<std::int64_t>(72) == deq.at(3));
std::array<int, 4> ary = toml::find<std::array<int, 4>>(std::move(v4), "key");
BOOST_TEST(42 == ary.at(0));
BOOST_TEST(54 == ary.at(1));
BOOST_TEST(69 == ary.at(2));
BOOST_TEST(72 == ary.at(3));
std::tuple<int, short, unsigned, long> tpl =
toml::find<std::tuple<int, short, unsigned, long>>(std::move(v5), "key");
BOOST_TEST( 42 == std::get<0>(tpl));
BOOST_TEST(static_cast<short >(54) == std::get<1>(tpl));
BOOST_TEST(static_cast<unsigned>(69) == std::get<2>(tpl));
BOOST_TEST(static_cast<long >(72) == std::get<3>(tpl));
value_type p{{"key", {3.14, 2.71}}};
std::pair<double, double> pr = toml::find<std::pair<double, double> >(std::move(p), "key");
BOOST_TEST(3.14 == pr.first);
BOOST_TEST(2.71 == pr.second);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_toml_array_of_array, value_type, test_value_types)
{
value_type v1{42, 54, 69, 72};
value_type v2{"foo", "bar", "baz"};
value_type v{{"key", {v1, v2}}};
std::pair<std::vector<int>, std::vector<std::string>> p =
toml::find<std::pair<std::vector<int>, std::vector<std::string>>>(v, "key");
BOOST_TEST(p.first.at(0) == 42);
BOOST_TEST(p.first.at(1) == 54);
BOOST_TEST(p.first.at(2) == 69);
BOOST_TEST(p.first.at(3) == 72);
BOOST_TEST(p.second.at(0) == "foo");
BOOST_TEST(p.second.at(1) == "bar");
BOOST_TEST(p.second.at(2) == "baz");
std::tuple<std::vector<int>, std::vector<std::string>> t =
toml::find<std::tuple<std::vector<int>, std::vector<std::string>>>(v, "key");
BOOST_TEST(std::get<0>(t).at(0) == 42);
BOOST_TEST(std::get<0>(t).at(1) == 54);
BOOST_TEST(std::get<0>(t).at(2) == 69);
BOOST_TEST(std::get<0>(t).at(3) == 72);
BOOST_TEST(std::get<1>(t).at(0) == "foo");
BOOST_TEST(std::get<1>(t).at(1) == "bar");
BOOST_TEST(std::get<1>(t).at(2) == "baz");
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_move_toml_array_of_array, value_type, test_value_types)
{
value_type a1{42, 54, 69, 72};
value_type a2{"foo", "bar", "baz"};
value_type v1{{"key", {a1, a2}}};
value_type v2{{"key", {a1, a2}}};
std::pair<std::vector<int>, std::vector<std::string>> p =
toml::find<std::pair<std::vector<int>, std::vector<std::string>>>(std::move(v1), "key");
BOOST_TEST(p.first.at(0) == 42);
BOOST_TEST(p.first.at(1) == 54);
BOOST_TEST(p.first.at(2) == 69);
BOOST_TEST(p.first.at(3) == 72);
BOOST_TEST(p.second.at(0) == "foo");
BOOST_TEST(p.second.at(1) == "bar");
BOOST_TEST(p.second.at(2) == "baz");
std::tuple<std::vector<int>, std::vector<std::string>> t =
toml::find<std::tuple<std::vector<int>, std::vector<std::string>>>(std::move(v2), "key");
BOOST_TEST(std::get<0>(t).at(0) == 42);
BOOST_TEST(std::get<0>(t).at(1) == 54);
BOOST_TEST(std::get<0>(t).at(2) == 69);
BOOST_TEST(std::get<0>(t).at(3) == 72);
BOOST_TEST(std::get<1>(t).at(0) == "foo");
BOOST_TEST(std::get<1>(t).at(1) == "bar");
BOOST_TEST(std::get<1>(t).at(2) == "baz");
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_toml_table, value_type, test_value_types)
{
{
value_type v1{{"key", {
{"key1", 1}, {"key2", 2}, {"key3", 3}, {"key4", 4}
}}};
const auto v = toml::find<std::map<std::string, int>>(v1, "key");
BOOST_TEST(v.at("key1") == 1);
BOOST_TEST(v.at("key2") == 2);
BOOST_TEST(v.at("key3") == 3);
BOOST_TEST(v.at("key4") == 4);
}
{
value_type v1{{"key", {
{"key1", 1}, {"key2", 2}, {"key3", 3}, {"key4", 4}
}}};
const auto v = toml::find<std::map<std::string, int>>(std::move(v1), "key");
BOOST_TEST(v.at("key1") == 1);
BOOST_TEST(v.at("key2") == 2);
BOOST_TEST(v.at("key3") == 3);
BOOST_TEST(v.at("key4") == 4);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_toml_local_date, value_type, test_value_types)
{
{
value_type v1{{"key", toml::local_date{2018, toml::month_t::Apr, 1}}};
const auto date = std::chrono::system_clock::to_time_t(
toml::find<std::chrono::system_clock::time_point>(v1, "key"));
std::tm t;
t.tm_year = 2018 - 1900;
t.tm_mon = 4 - 1;
t.tm_mday = 1;
t.tm_hour = 0;
t.tm_min = 0;
t.tm_sec = 0;
t.tm_isdst = -1;
const auto c = std::mktime(&t);
BOOST_TEST(c == date);
}
{
value_type v1{{"key", toml::local_date{2018, toml::month_t::Apr, 1}}};
const auto date = std::chrono::system_clock::to_time_t(
toml::find<std::chrono::system_clock::time_point>(std::move(v1), "key"));
std::tm t;
t.tm_year = 2018 - 1900;
t.tm_mon = 4 - 1;
t.tm_mday = 1;
t.tm_hour = 0;
t.tm_min = 0;
t.tm_sec = 0;
t.tm_isdst = -1;
const auto c = std::mktime(&t);
BOOST_TEST(c == date);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_toml_local_time, value_type, test_value_types)
{
{
value_type v1{{"key", toml::local_time{12, 30, 45}}};
const auto time = toml::find<std::chrono::seconds>(v1, "key");
BOOST_CHECK(time == std::chrono::hours(12) +
std::chrono::minutes(30) + std::chrono::seconds(45));
}
{
value_type v1{{"key", toml::local_time{12, 30, 45}}};
const auto time = toml::find<std::chrono::seconds>(std::move(v1), "key");
BOOST_CHECK(time == std::chrono::hours(12) +
std::chrono::minutes(30) + std::chrono::seconds(45));
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_toml_local_datetime, value_type, test_value_types)
{
{
value_type v1{{"key", toml::local_datetime(
toml::local_date{2018, toml::month_t::Apr, 1},
toml::local_time{12, 30, 45})}};
const auto date = std::chrono::system_clock::to_time_t(
toml::find<std::chrono::system_clock::time_point>(v1, "key"));
std::tm t;
t.tm_year = 2018 - 1900;
t.tm_mon = 4 - 1;
t.tm_mday = 1;
t.tm_hour = 12;
t.tm_min = 30;
t.tm_sec = 45;
t.tm_isdst = -1;
const auto c = std::mktime(&t);
BOOST_TEST(c == date);
}
{
value_type v1{{"key", toml::local_datetime(
toml::local_date{2018, toml::month_t::Apr, 1},
toml::local_time{12, 30, 45})}};
const auto date = std::chrono::system_clock::to_time_t(
toml::find<std::chrono::system_clock::time_point>(std::move(v1), "key"));
std::tm t;
t.tm_year = 2018 - 1900;
t.tm_mon = 4 - 1;
t.tm_mday = 1;
t.tm_hour = 12;
t.tm_min = 30;
t.tm_sec = 45;
t.tm_isdst = -1;
const auto c = std::mktime(&t);
BOOST_TEST(c == date);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_toml_offset_datetime, value_type, test_value_types)
{
{
value_type v1{{"key", toml::offset_datetime(
toml::local_date{2018, toml::month_t::Apr, 1},
toml::local_time{12, 30, 0},
toml::time_offset{9, 0})}};
// 2018-04-01T12:30:00+09:00
// == 2018-04-01T03:30:00Z
const auto date = toml::find<std::chrono::system_clock::time_point>(v1, "key");
const auto timet = std::chrono::system_clock::to_time_t(date);
// get time_t as gmtime (2018-04-01T03:30:00Z)
const auto tmp = std::gmtime(std::addressof(timet)); // XXX not threadsafe!
BOOST_CHECK(tmp);
const auto tm = *tmp;
BOOST_TEST(tm.tm_year + 1900 == 2018);
BOOST_TEST(tm.tm_mon + 1 == 4);
BOOST_TEST(tm.tm_mday == 1);
BOOST_TEST(tm.tm_hour == 3);
BOOST_TEST(tm.tm_min == 30);
BOOST_TEST(tm.tm_sec == 0);
}
{
value_type v1{{"key", toml::offset_datetime(
toml::local_date{2018, toml::month_t::Apr, 1},
toml::local_time{12, 30, 0},
toml::time_offset{-8, 0})}};
// 2018-04-01T12:30:00-08:00
// == 2018-04-01T20:30:00Z
const auto date = toml::find<std::chrono::system_clock::time_point>(v1, "key");
const auto timet = std::chrono::system_clock::to_time_t(date);
// get time_t as gmtime (2018-04-01T03:30:00Z)
const auto tmp = std::gmtime(std::addressof(timet)); // XXX not threadsafe!
BOOST_CHECK(tmp);
const auto tm = *tmp;
BOOST_TEST(tm.tm_year + 1900 == 2018);
BOOST_TEST(tm.tm_mon + 1 == 4);
BOOST_TEST(tm.tm_mday == 1);
BOOST_TEST(tm.tm_hour == 20);
BOOST_TEST(tm.tm_min == 30);
BOOST_TEST(tm.tm_sec == 0);
}
{
value_type v1{{"key", toml::offset_datetime(
toml::local_date{2018, toml::month_t::Apr, 1},
toml::local_time{12, 30, 0},
toml::time_offset{-8, 0})}};
// 2018-04-01T12:30:00-08:00
// == 2018-04-01T20:30:00Z
const auto date = toml::find<std::chrono::system_clock::time_point>(std::move(v1), "key");
const auto timet = std::chrono::system_clock::to_time_t(date);
// get time_t as gmtime (2018-04-01T03:30:00Z)
const auto tmp = std::gmtime(std::addressof(timet)); // XXX not threadsafe!
BOOST_CHECK(tmp);
const auto tm = *tmp;
BOOST_TEST(tm.tm_year + 1900 == 2018);
BOOST_TEST(tm.tm_mon + 1 == 4);
BOOST_TEST(tm.tm_mday == 1);
BOOST_TEST(tm.tm_hour == 20);
BOOST_TEST(tm.tm_min == 30);
BOOST_TEST(tm.tm_sec == 0);
}
}

541
tests/test_find_or.cpp Normal file
View File

@@ -0,0 +1,541 @@
#define BOOST_TEST_MODULE "test_find_or"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <map>
#include <unordered_map>
#include <list>
#include <deque>
#include <array>
#include <tuple>
#if __cplusplus >= 201703L
#include <string_view>
#endif
using test_value_types = std::tuple<
toml::value,
toml::basic_value<toml::preserve_comments>,
toml::basic_value<toml::discard_comments, std::map, std::deque>,
toml::basic_value<toml::preserve_comments, std::map, std::deque>
>;
namespace test
{
template<typename charT, typename traits, typename T, typename Alloc>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const std::vector<T, Alloc>& v)
{
os << "[ ";
for(const auto& i : v) {os << i << ' ';}
os << ']';
return os;
}
template<typename charT, typename traits, typename T, typename Alloc>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const std::deque<T, Alloc>& v)
{
os << "[ ";
for(const auto& i : v) {os << i << ' ';}
os << ']';
return os;
}
template<typename charT, typename traits, typename T, typename Alloc>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const std::list<T, Alloc>& v)
{
os << "[ ";
for(const auto& i : v) {os << i << ' ';}
os << ']';
return os;
}
template<typename charT, typename traits,
typename Key, typename Value, typename Comp, typename Alloc>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os,
const std::map<Key, Value, Comp, Alloc>& v)
{
os << "[ ";
for(const auto& i : v) {os << '{' << i.first << ", " << i.second << "} ";}
os << ']';
return os;
}
template<typename charT, typename traits,
typename Key, typename Value, typename Hash, typename Eq, typename Alloc>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os,
const std::unordered_map<Key, Value, Hash, Eq, Alloc>& v)
{
os << "[ ";
for(const auto& i : v) {os << '{' << i.first << ", " << i.second << "} ";}
os << ']';
return os;
}
} // test
#define TOML11_TEST_FIND_OR_EXACT(toml_type, init_expr, opt_expr)\
{ \
using namespace test; \
const toml::toml_type init init_expr ; \
const toml::toml_type opt opt_expr ; \
const value_type v{{"key", init}}; \
BOOST_TEST(init != opt); \
BOOST_TEST(init == toml::find_or(v, "key", opt)); \
} \
/**/
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_or_exact, value_type, test_value_types)
{
TOML11_TEST_FIND_OR_EXACT(boolean, ( true), (false))
TOML11_TEST_FIND_OR_EXACT(integer, ( 42), ( 54))
TOML11_TEST_FIND_OR_EXACT(floating, ( 3.14), ( 2.71))
TOML11_TEST_FIND_OR_EXACT(string, ("foo"), ("bar"))
TOML11_TEST_FIND_OR_EXACT(local_time, (12, 30, 45), (6, 0, 30))
TOML11_TEST_FIND_OR_EXACT(local_date, (2019, toml::month_t::Apr, 1),
(1999, toml::month_t::Jan, 2))
TOML11_TEST_FIND_OR_EXACT(local_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30))
)
TOML11_TEST_FIND_OR_EXACT(offset_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45), toml::time_offset( 9, 0)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30), toml::time_offset(-3, 0))
)
{
const typename value_type::array_type init{1,2,3,4,5};
const typename value_type::array_type opt {6,7,8,9,10};
const value_type v{{"key", init}};
BOOST_TEST(init != opt);
BOOST_TEST(init == toml::find_or(v, "key", opt));
}
{
const typename value_type::table_type init{{"key1", 42}, {"key2", "foo"}};
const typename value_type::table_type opt {{"key1", 54}, {"key2", "bar"}};
const value_type v{{"key", init}};
BOOST_TEST(init != opt);
BOOST_TEST(init == toml::find_or(v, "key", opt));
}
}
#undef TOML11_TEST_FIND_OR_EXACT
#define TOML11_TEST_FIND_OR_MOVE(toml_type, init_expr, opt_expr) \
{ \
using namespace test; \
const toml::toml_type init init_expr ; \
toml::toml_type opt opt_expr ; \
value_type v{{"key", init}}; \
BOOST_TEST(init != opt); \
const auto moved = toml::find_or(std::move(v), "key", std::move(opt));\
BOOST_TEST(init == moved); \
} \
/**/
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_or_move, value_type, test_value_types)
{
TOML11_TEST_FIND_OR_MOVE(boolean, ( true), (false))
TOML11_TEST_FIND_OR_MOVE(integer, ( 42), ( 54))
TOML11_TEST_FIND_OR_MOVE(floating, ( 3.14), ( 2.71))
TOML11_TEST_FIND_OR_MOVE(string, ("foo"), ("bar"))
TOML11_TEST_FIND_OR_MOVE(local_time, (12, 30, 45), (6, 0, 30))
TOML11_TEST_FIND_OR_MOVE(local_date, (2019, toml::month_t::Apr, 1),
(1999, toml::month_t::Jan, 2))
TOML11_TEST_FIND_OR_MOVE(local_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30))
)
TOML11_TEST_FIND_OR_MOVE(offset_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45), toml::time_offset( 9, 0)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30), toml::time_offset(-3, 0))
)
{
typename value_type::array_type init{1,2,3,4,5};
typename value_type::array_type opt {6,7,8,9,10};
value_type v{{"key", init}};
BOOST_TEST(init != opt);
const auto moved = toml::find_or(std::move(v), "key", std::move(opt));
BOOST_TEST(init == moved);
}
{
typename value_type::table_type init{{"key1", 42}, {"key2", "foo"}};
typename value_type::table_type opt {{"key1", 54}, {"key2", "bar"}};
value_type v{{"key", init}};
BOOST_TEST(init != opt);
const auto moved = toml::find_or(std::move(v), "key", std::move(opt));
BOOST_TEST(init == moved);
}
}
#undef TOML11_TEST_FIND_OR_MOVE
#define TOML11_TEST_FIND_OR_MODIFY(toml_type, init_expr, opt_expr)\
{ \
using namespace test; \
const toml::toml_type init init_expr ; \
toml::toml_type opt1 opt_expr ; \
toml::toml_type opt2 opt_expr ; \
value_type v{{"key", init}}; \
BOOST_TEST(init != opt1); \
toml::find_or(v, "key", opt2) = opt1; \
BOOST_TEST(opt1 == toml::find<toml::toml_type>(v, "key"));\
} \
/**/
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_or_modify, value_type, test_value_types)
{
TOML11_TEST_FIND_OR_MODIFY(boolean, ( true), (false))
TOML11_TEST_FIND_OR_MODIFY(integer, ( 42), ( 54))
TOML11_TEST_FIND_OR_MODIFY(floating, ( 3.14), ( 2.71))
TOML11_TEST_FIND_OR_MODIFY(string, ("foo"), ("bar"))
TOML11_TEST_FIND_OR_MODIFY(local_time, (12, 30, 45), (6, 0, 30))
TOML11_TEST_FIND_OR_MODIFY(local_date, (2019, toml::month_t::Apr, 1),
(1999, toml::month_t::Jan, 2))
TOML11_TEST_FIND_OR_MODIFY(local_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30))
)
TOML11_TEST_FIND_OR_MODIFY(offset_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45), toml::time_offset( 9, 0)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30), toml::time_offset(-3, 0))
)
{
typename value_type::array_type init{1,2,3,4,5};
typename value_type::array_type opt1{6,7,8,9,10};
typename value_type::array_type opt2{6,7,8,9,10};
BOOST_TEST(init != opt1);
value_type v{{"key", init}};
toml::find_or(v, "key", opt2) = opt1;
BOOST_TEST(opt1 == toml::find<typename value_type::array_type>(v, "key"));
}
{
typename value_type::table_type init{{"key1", 42}, {"key2", "foo"}};
typename value_type::table_type opt1{{"key1", 54}, {"key2", "bar"}};
typename value_type::table_type opt2{{"key1", 54}, {"key2", "bar"}};
value_type v{{"key", init}};
BOOST_TEST(init != opt1);
toml::find_or(v, "key", opt2) = opt1;
BOOST_TEST(opt1 == toml::find<typename value_type::table_type>(v, "key"));
}
}
#undef TOML11_TEST_FIND_OR_MODIFY
#define TOML11_TEST_FIND_OR_FALLBACK(init_type, opt_type) \
{ \
using namespace test; \
value_type v(init_type); \
BOOST_TEST(opt_type == toml::find_or(v, "key", opt_type));\
} \
/**/
BOOST_AUTO_TEST_CASE_TEMPLATE(test_find_or_fallback, value_type, test_value_types)
{
const toml::boolean boolean (true);
const toml::integer integer (42);
const toml::floating floating (3.14);
const toml::string string ("foo");
const toml::local_time local_time (12, 30, 45);
const toml::local_date local_date (2019, toml::month_t::Apr, 1);
const toml::local_datetime local_datetime (
toml::local_date(2019, toml::month_t::Apr, 1),
toml::local_time(12, 30, 45));
const toml::offset_datetime offset_datetime(
toml::local_date(2019, toml::month_t::Apr, 1),
toml::local_time(12, 30, 45), toml::time_offset( 9, 0));
using array_type = typename value_type::array_type;
using table_type = typename value_type::table_type;
const array_type array{1, 2, 3, 4, 5};
const table_type table{{"key1", 42}, {"key2", "foo"}};
TOML11_TEST_FIND_OR_FALLBACK(boolean, integer );
TOML11_TEST_FIND_OR_FALLBACK(boolean, floating );
TOML11_TEST_FIND_OR_FALLBACK(boolean, string );
TOML11_TEST_FIND_OR_FALLBACK(boolean, local_time );
TOML11_TEST_FIND_OR_FALLBACK(boolean, local_date );
TOML11_TEST_FIND_OR_FALLBACK(boolean, local_datetime );
TOML11_TEST_FIND_OR_FALLBACK(boolean, offset_datetime);
TOML11_TEST_FIND_OR_FALLBACK(boolean, array );
TOML11_TEST_FIND_OR_FALLBACK(boolean, table );
TOML11_TEST_FIND_OR_FALLBACK(integer, boolean );
TOML11_TEST_FIND_OR_FALLBACK(integer, floating );
TOML11_TEST_FIND_OR_FALLBACK(integer, string );
TOML11_TEST_FIND_OR_FALLBACK(integer, local_time );
TOML11_TEST_FIND_OR_FALLBACK(integer, local_date );
TOML11_TEST_FIND_OR_FALLBACK(integer, local_datetime );
TOML11_TEST_FIND_OR_FALLBACK(integer, offset_datetime);
TOML11_TEST_FIND_OR_FALLBACK(integer, array );
TOML11_TEST_FIND_OR_FALLBACK(integer, table );
TOML11_TEST_FIND_OR_FALLBACK(floating, boolean );
TOML11_TEST_FIND_OR_FALLBACK(floating, integer );
TOML11_TEST_FIND_OR_FALLBACK(floating, string );
TOML11_TEST_FIND_OR_FALLBACK(floating, local_time );
TOML11_TEST_FIND_OR_FALLBACK(floating, local_date );
TOML11_TEST_FIND_OR_FALLBACK(floating, local_datetime );
TOML11_TEST_FIND_OR_FALLBACK(floating, offset_datetime);
TOML11_TEST_FIND_OR_FALLBACK(floating, array );
TOML11_TEST_FIND_OR_FALLBACK(floating, table );
TOML11_TEST_FIND_OR_FALLBACK(string, boolean );
TOML11_TEST_FIND_OR_FALLBACK(string, integer );
TOML11_TEST_FIND_OR_FALLBACK(string, floating );
TOML11_TEST_FIND_OR_FALLBACK(string, local_time );
TOML11_TEST_FIND_OR_FALLBACK(string, local_date );
TOML11_TEST_FIND_OR_FALLBACK(string, local_datetime );
TOML11_TEST_FIND_OR_FALLBACK(string, offset_datetime);
TOML11_TEST_FIND_OR_FALLBACK(string, array );
TOML11_TEST_FIND_OR_FALLBACK(string, table );
TOML11_TEST_FIND_OR_FALLBACK(local_time, boolean );
TOML11_TEST_FIND_OR_FALLBACK(local_time, integer );
TOML11_TEST_FIND_OR_FALLBACK(local_time, floating );
TOML11_TEST_FIND_OR_FALLBACK(local_time, string );
TOML11_TEST_FIND_OR_FALLBACK(local_time, local_date );
TOML11_TEST_FIND_OR_FALLBACK(local_time, local_datetime );
TOML11_TEST_FIND_OR_FALLBACK(local_time, offset_datetime);
TOML11_TEST_FIND_OR_FALLBACK(local_time, array );
TOML11_TEST_FIND_OR_FALLBACK(local_time, table );
TOML11_TEST_FIND_OR_FALLBACK(local_date, boolean );
TOML11_TEST_FIND_OR_FALLBACK(local_date, integer );
TOML11_TEST_FIND_OR_FALLBACK(local_date, floating );
TOML11_TEST_FIND_OR_FALLBACK(local_date, string );
TOML11_TEST_FIND_OR_FALLBACK(local_date, local_time );
TOML11_TEST_FIND_OR_FALLBACK(local_date, local_datetime );
TOML11_TEST_FIND_OR_FALLBACK(local_date, offset_datetime);
TOML11_TEST_FIND_OR_FALLBACK(local_date, array );
TOML11_TEST_FIND_OR_FALLBACK(local_date, table );
TOML11_TEST_FIND_OR_FALLBACK(local_datetime, boolean );
TOML11_TEST_FIND_OR_FALLBACK(local_datetime, integer );
TOML11_TEST_FIND_OR_FALLBACK(local_datetime, floating );
TOML11_TEST_FIND_OR_FALLBACK(local_datetime, string );
TOML11_TEST_FIND_OR_FALLBACK(local_datetime, local_time );
TOML11_TEST_FIND_OR_FALLBACK(local_datetime, local_date );
TOML11_TEST_FIND_OR_FALLBACK(local_datetime, offset_datetime);
TOML11_TEST_FIND_OR_FALLBACK(local_datetime, array );
TOML11_TEST_FIND_OR_FALLBACK(local_datetime, table );
TOML11_TEST_FIND_OR_FALLBACK(offset_datetime, boolean );
TOML11_TEST_FIND_OR_FALLBACK(offset_datetime, integer );
TOML11_TEST_FIND_OR_FALLBACK(offset_datetime, floating );
TOML11_TEST_FIND_OR_FALLBACK(offset_datetime, string );
TOML11_TEST_FIND_OR_FALLBACK(offset_datetime, local_time );
TOML11_TEST_FIND_OR_FALLBACK(offset_datetime, local_date );
TOML11_TEST_FIND_OR_FALLBACK(offset_datetime, local_datetime );
TOML11_TEST_FIND_OR_FALLBACK(offset_datetime, array );
TOML11_TEST_FIND_OR_FALLBACK(offset_datetime, table );
TOML11_TEST_FIND_OR_FALLBACK(array, boolean );
TOML11_TEST_FIND_OR_FALLBACK(array, integer );
TOML11_TEST_FIND_OR_FALLBACK(array, floating );
TOML11_TEST_FIND_OR_FALLBACK(array, string );
TOML11_TEST_FIND_OR_FALLBACK(array, local_time );
TOML11_TEST_FIND_OR_FALLBACK(array, local_date );
TOML11_TEST_FIND_OR_FALLBACK(array, local_datetime );
TOML11_TEST_FIND_OR_FALLBACK(array, offset_datetime);
TOML11_TEST_FIND_OR_FALLBACK(array, table );
TOML11_TEST_FIND_OR_FALLBACK(table, boolean );
TOML11_TEST_FIND_OR_FALLBACK(table, integer );
TOML11_TEST_FIND_OR_FALLBACK(table, floating );
TOML11_TEST_FIND_OR_FALLBACK(table, string );
TOML11_TEST_FIND_OR_FALLBACK(table, local_time );
TOML11_TEST_FIND_OR_FALLBACK(table, local_date );
TOML11_TEST_FIND_OR_FALLBACK(table, local_datetime );
TOML11_TEST_FIND_OR_FALLBACK(table, offset_datetime);
TOML11_TEST_FIND_OR_FALLBACK(table, array );
}
#undef TOML11_TEST_FIND_OR_FALLBACK
BOOST_AUTO_TEST_CASE(test_find_or_integer)
{
{
toml::value v{{"num", 42}};
BOOST_TEST(42u == toml::find_or(v, "num", 0u));
BOOST_TEST(0u == toml::find_or(v, "foo", 0u));
}
{
toml::value v{{"num", 42}};
const auto moved = toml::find_or(std::move(v), "num", 0u);
BOOST_TEST(42u == moved);
}
{
toml::value v{{"num", 42}};
const auto moved = toml::find_or(std::move(v), "foo", 0u);
BOOST_TEST(0u == moved);
}
}
BOOST_AUTO_TEST_CASE(test_find_or_floating)
{
{
toml::value v1{{"key", 42}};
toml::value v2{{"key", 3.14}};
BOOST_TEST(2.71f == toml::find_or(v1, "key", 2.71f));
const double ref(3.14);
BOOST_TEST(static_cast<float>(ref) == toml::find_or(v2, "key", 2.71f));
}
{
toml::value v1{{"key", 42}};
toml::value v2{{"key", 3.14}};
const auto moved1 = toml::find_or(std::move(v1), "key", 2.71f);
const auto moved2 = toml::find_or(std::move(v2), "key", 2.71f);
BOOST_TEST(2.71f == moved1);
const double ref(3.14);
BOOST_TEST(static_cast<float>(ref) == moved2);
}
}
BOOST_AUTO_TEST_CASE(test_find_or_string)
{
{
toml::value v1 = toml::table{{"key", "foobar"}};
toml::value v2 = toml::table{{"key", 42}};
std::string s1("bazqux");
const std::string s2("bazqux");
BOOST_TEST("foobar" == toml::find_or(v1, "key", s1));
BOOST_TEST("bazqux" == toml::find_or(v2, "key", s1));
std::string& v1r = toml::find_or(v1, "key", s1);
std::string& s1r = toml::find_or(v2, "key", s1);
BOOST_TEST("foobar" == v1r);
BOOST_TEST("bazqux" == s1r);
BOOST_TEST("foobar" == toml::find_or(v1, "key", s2));
BOOST_TEST("bazqux" == toml::find_or(v2, "key", s2));
BOOST_TEST("foobar" == toml::find_or(std::move(v1), "key", std::move(s1)));
s1 = "bazqux"; // restoring moved value
BOOST_TEST("bazqux" == toml::find_or(std::move(v2), "key", std::move(s1)));
}
{
toml::value v1 = toml::table{{"key", "foobar"}};
toml::value v2 = toml::table{{"key", 42}};
std::string s1("bazqux");
const auto moved1 = toml::find_or(std::move(v1), "key", s1);
const auto moved2 = toml::find_or(std::move(v2), "key", s1);
BOOST_TEST("foobar" == moved1);
BOOST_TEST("bazqux" == moved2);
}
{
toml::value v1 = toml::table{{"key", "foobar"}};
toml::value v2 = toml::table{{"key", 42}};
std::string s1("bazqux");
std::string s2("bazqux");
const auto moved1 = toml::find_or(std::move(v1), "key", std::move(s1));
const auto moved2 = toml::find_or(std::move(v2), "key", std::move(s2));
BOOST_TEST("foobar" == moved1);
BOOST_TEST("bazqux" == moved2);
}
// string literal
{
toml::value v1 = toml::table{{"key", "foobar"}};
toml::value v2 = toml::table{{"key",42}};
BOOST_TEST("foobar" == toml::find_or(v1, "key", "bazqux"));
BOOST_TEST("bazqux" == toml::find_or(v2, "key", "bazqux"));
const char* lit = "bazqux";
BOOST_TEST("foobar" == toml::find_or(v1, "key", lit));
BOOST_TEST("bazqux" == toml::find_or(v2, "key", lit));
}
{
toml::value v1 = toml::table{{"key", "foobar"}};
toml::value v2 = toml::table{{"key",42}};
const auto moved1 = toml::find_or(std::move(v1), "key", "bazqux");
const auto moved2 = toml::find_or(std::move(v2), "key", "bazqux");
BOOST_TEST("foobar" == moved1);
BOOST_TEST("bazqux" == moved2);
}
{
toml::value v1 = toml::table{{"key", "foobar"}};
toml::value v2 = toml::table{{"key",42}};
const char* lit = "bazqux";
const auto moved1 = toml::find_or(std::move(v1), "key", lit);
const auto moved2 = toml::find_or(std::move(v2), "key", lit);
BOOST_TEST("foobar" == moved1);
BOOST_TEST("bazqux" == moved2);
}
}
BOOST_AUTO_TEST_CASE(test_find_or_map)
{
using map_type = std::map<std::string, std::string>;
{
const toml::value v1{
{"key", {{"key", "value"}}}
};
const auto key = toml::find_or(v1, "key", map_type{});
const auto key2 = toml::find_or(v1, "key2", map_type{});
BOOST_TEST(!key.empty());
BOOST_TEST(key2.empty());
BOOST_TEST(key.size() == 1u);
BOOST_TEST(key.at("key") == "value");
}
{
toml::value v1{
{"key", {{"key", "value"}}}
};
const auto key = toml::find_or<map_type>(v1, "key", map_type{});
const auto key2 = toml::find_or<map_type>(v1, "key2", map_type{});
BOOST_TEST(!key.empty());
BOOST_TEST(key2.empty());
BOOST_TEST(key.size() == 1u);
BOOST_TEST(key.at("key") == "value");
}
{
toml::value v1{
{"key", {{"key", "value"}}}
};
toml::value v2(v1);
const auto key = toml::find_or(std::move(v1), "key", map_type{});
const auto key2 = toml::find_or(std::move(v2), "key2", map_type{});
BOOST_TEST(!key.empty());
BOOST_TEST(key2.empty());
BOOST_TEST(key.size() == 1u);
BOOST_TEST(key.at("key") == "value");
}
{
toml::value v1{
{"key", {{"key", "value"}}}
};
toml::value v2(v1);
const auto key = toml::find_or<map_type>(std::move(v1), "key", map_type{});
const auto key2 = toml::find_or<map_type>(std::move(v2), "key2", map_type{});
BOOST_TEST(!key.empty());
BOOST_TEST(key2.empty());
BOOST_TEST(key.size() == 1u);
BOOST_TEST(key.at("key") == "value");
}
}

View File

@@ -0,0 +1,76 @@
#define BOOST_TEST_MODULE "test_format_error"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <iostream>
// to check it successfully compiles. it does not check the formatted string.
BOOST_AUTO_TEST_CASE(test_1_value)
{
toml::value val(42);
{
const std::string pretty_error =
toml::format_error("[error] test error", val, "this is a value");
std::cout << pretty_error << std::endl;
}
{
const std::string pretty_error =
toml::format_error("[error] test error", val, "this is a value",
{"this is a hint"});
std::cout << pretty_error << std::endl;
}
}
BOOST_AUTO_TEST_CASE(test_2_values)
{
toml::value v1(42);
toml::value v2(3.14);
{
const std::string pretty_error =
toml::format_error("[error] test error with two values",
v1, "this is the answer",
v2, "this is the pi");
std::cout << pretty_error << std::endl;
}
{
const std::string pretty_error =
toml::format_error("[error] test error with two values",
v1, "this is the answer",
v2, "this is the pi",
{"hint"});
std::cout << pretty_error << std::endl;
}
}
BOOST_AUTO_TEST_CASE(test_3_values)
{
toml::value v1(42);
toml::value v2(3.14);
toml::value v3("foo");
{
const std::string pretty_error =
toml::format_error("[error] test error with two values",
v1, "this is the answer",
v2, "this is the pi",
v3, "this is a meta-syntactic variable");
std::cout << pretty_error << std::endl;
}
{
const std::string pretty_error =
toml::format_error("[error] test error with two values",
v1, "this is the answer",
v2, "this is the pi",
v3, "this is a meta-syntactic variable",
{"hint 1", "hint 2"});
std::cout << pretty_error << std::endl;
}
}

View File

@@ -1,172 +0,0 @@
#define BOOST_TEST_MODULE "test_from_toml"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <map>
#include <unordered_map>
#include <list>
#include <deque>
#include <array>
BOOST_AUTO_TEST_CASE(test_from_toml_exact)
{
toml::Boolean b(true);
toml::Integer i(42);
toml::Float f(3.14);
toml::String s("hoge");
toml::Datetime d(std::chrono::system_clock::now());
toml::Array a;
a.emplace_back(2);
a.emplace_back(7);
a.emplace_back(1);
a.emplace_back(8);
a.emplace_back(2);
toml::Table t;
t.emplace("val1", true);
t.emplace("val2", 42);
t.emplace("val3", 3.14);
t.emplace("val4", "piyo");
toml::value v1(b);
toml::value v2(i);
toml::value v3(f);
toml::value v4(s);
toml::value v5(d);
toml::value v6(a);
toml::value v7(t);
toml::Boolean u1;
toml::Integer u2;
toml::Float u3;
toml::String u4;
toml::Datetime u5;
toml::Array u6;
toml::Table u7;
toml::from_toml(u1, v1);
toml::from_toml(u2, v2);
toml::from_toml(u3, v3);
toml::from_toml(u4, v4);
toml::from_toml(u5, v5);
toml::from_toml(u6, v6);
toml::from_toml(u7, v7);
BOOST_CHECK_EQUAL(u1, b);
BOOST_CHECK_EQUAL(u2, i);
BOOST_CHECK_EQUAL(u3, f);
BOOST_CHECK_EQUAL(u4, s);
BOOST_CHECK_EQUAL(u6.at(0).cast<toml::value_t::Integer>(), a.at(0).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u6.at(1).cast<toml::value_t::Integer>(), a.at(1).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u6.at(2).cast<toml::value_t::Integer>(), a.at(2).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u6.at(3).cast<toml::value_t::Integer>(), a.at(3).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u6.at(4).cast<toml::value_t::Integer>(), a.at(4).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u7.at("val1").cast<toml::value_t::Boolean>(), true);
BOOST_CHECK_EQUAL(u7.at("val2").cast<toml::value_t::Integer>(), 42);
BOOST_CHECK_CLOSE_FRACTION(u7.at("val3").cast<toml::value_t::Float>(),3.14, 1e-3);
BOOST_CHECK_EQUAL(u7.at("val4").cast<toml::value_t::String>(), "piyo");
}
BOOST_AUTO_TEST_CASE(test_from_toml_cast)
{
toml::Integer i(42);
toml::Float f(3.14);
toml::Array a{2, 7, 1, 8, 2};
toml::Table t{{"val1", true}, {"val2", 42}, {"val3", 3.14}, {"val4", "piyo"}};
toml::value vi(i);
toml::value vf(f);
toml::value va(a);
toml::value vt(t);
int u1;
std::size_t u2;
float u3;
std::list<int> u4;
std::deque<std::size_t> u5;
std::array<long, 5> u6;
std::map<std::string, toml::value> u7;
std::list<int> expect_list{2,7,1,8,2};
std::deque<std::size_t> expect_deque{2,7,1,8,2};
std::array<long, 5> expect_array{{2,7,1,8,2}};
toml::from_toml(u1, vi);
toml::from_toml(u2, vi);
toml::from_toml(u3, vf);
toml::from_toml(u4, va);
toml::from_toml(u5, va);
toml::from_toml(u6, va);
toml::from_toml(u7, vt);
BOOST_CHECK_EQUAL(u1, 42);
BOOST_CHECK_EQUAL(u2, 42ul);
BOOST_CHECK_CLOSE_FRACTION(u3, 3.14, 1e-3);
const bool same_list = (u4 == expect_list);
const bool same_deque = (u5 == expect_deque);
const bool same_array = (u6 == expect_array);
BOOST_CHECK(same_list);
BOOST_CHECK(same_deque);
BOOST_CHECK(same_array);
BOOST_CHECK_EQUAL(u7["val1"].cast<toml::value_t::Boolean>(), true);
BOOST_CHECK_EQUAL(u7["val2"].cast<toml::value_t::Integer>(), 42);
BOOST_CHECK_CLOSE_FRACTION(u7["val3"].cast<toml::value_t::Float>(), 3.14, 1e-3);
BOOST_CHECK_EQUAL(u7["val4"].cast<toml::value_t::String >(), "piyo");
}
BOOST_AUTO_TEST_CASE(test_from_toml_tie)
{
toml::Boolean b(42);
toml::Integer i(42);
toml::Float f(3.14);
toml::Array a;
a.emplace_back(2);
a.emplace_back(7);
a.emplace_back(1);
a.emplace_back(8);
a.emplace_back(2);
toml::Table t;
t.emplace("val1", true);
t.emplace("val2", 42);
t.emplace("val3", 3.14);
t.emplace("val4", "piyo");
toml::value vb(b);
toml::value vi(i);
toml::value vf(f);
toml::value va(a);
toml::value vt(t);
bool ub;
int ui;
float uf;
std::deque<int> ua;
std::map<std::string, toml::value> ut;
toml::from_toml(std::tie(ub, ui, uf, ua, ut), vb);
toml::from_toml(std::tie(ub, ui, uf, ua, ut), vi);
toml::from_toml(std::tie(ub, ui, uf, ua, ut), vf);
toml::from_toml(std::tie(ub, ui, uf, ua, ut), va);
toml::from_toml(std::tie(ub, ui, uf, ua, ut), va);
toml::from_toml(std::tie(ub, ui, uf, ua, ut), vt);
BOOST_CHECK_EQUAL(ub, true);
BOOST_CHECK_EQUAL(ui, 42);
BOOST_CHECK_CLOSE_FRACTION(uf, 3.14, 1e-3);
BOOST_CHECK_EQUAL(ua.at(0), 2);
BOOST_CHECK_EQUAL(ua.at(1), 7);
BOOST_CHECK_EQUAL(ua.at(2), 1);
BOOST_CHECK_EQUAL(ua.at(3), 8);
BOOST_CHECK_EQUAL(ua.at(4), 2);
BOOST_CHECK_EQUAL(ut["val1"].cast<toml::value_t::Boolean>(), true);
BOOST_CHECK_EQUAL(ut["val2"].cast<toml::value_t::Integer>(), 42);
BOOST_CHECK_CLOSE_FRACTION(ut["val3"].cast<toml::value_t::Float>(), 3.14, 1e-3);
BOOST_CHECK_EQUAL(ut["val4"].cast<toml::value_t::String >(), "piyo");
}

View File

@@ -11,102 +11,499 @@
#include <list>
#include <deque>
#include <array>
#include <tuple>
#if __cplusplus >= 201703L
#include <string_view>
#endif
using test_value_types = std::tuple<
toml::value,
toml::basic_value<toml::preserve_comments>,
toml::basic_value<toml::discard_comments, std::map, std::deque>,
toml::basic_value<toml::preserve_comments, std::map, std::deque>
>;
BOOST_AUTO_TEST_CASE(test_get_exact)
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_exact, value_type, test_value_types)
{
toml::Boolean b(true);
toml::Integer i(42);
toml::Float f(3.14);
toml::String s("hoge");
toml::Array a;
a.emplace_back(2);
a.emplace_back(7);
a.emplace_back(1);
a.emplace_back(8);
a.emplace_back(2);
toml::Table t;
t.emplace("val1", true);
t.emplace("val2", 42);
t.emplace("val3", 3.14);
t.emplace("val4", "piyo");
{
value_type v(true);
BOOST_TEST(true == toml::get<toml::boolean>(v));
toml::value v1(b);
toml::value v2(i);
toml::value v3(f);
toml::value v4(s);
toml::value v6(a);
toml::value v7(t);
toml::get<toml::boolean>(v) = false;
BOOST_TEST(false == toml::get<toml::boolean>(v));
toml::Boolean u1 = toml::get<toml::Boolean >(v1);
toml::Integer u2 = toml::get<toml::Integer >(v2);
toml::Float u3 = toml::get<toml::Float >(v3);
toml::String u4 = toml::get<toml::String >(v4);
toml::Array u6 = toml::get<toml::Array >(v6);
toml::Table u7 = toml::get<toml::Table >(v7);
toml::boolean x = toml::get<toml::boolean>(std::move(v));
BOOST_TEST(false == x);
}
{
value_type v(42);
BOOST_TEST(toml::integer(42) == toml::get<toml::integer>(v));
BOOST_CHECK_EQUAL(u1, b);
BOOST_CHECK_EQUAL(u2, i);
BOOST_CHECK_EQUAL(u3, f);
BOOST_CHECK_EQUAL(u4, s);
BOOST_CHECK_EQUAL(u6.at(0).cast<toml::value_t::Integer>(), a.at(0).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u6.at(1).cast<toml::value_t::Integer>(), a.at(1).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u6.at(2).cast<toml::value_t::Integer>(), a.at(2).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u6.at(3).cast<toml::value_t::Integer>(), a.at(3).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u6.at(4).cast<toml::value_t::Integer>(), a.at(4).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u7.at("val1").cast<toml::value_t::Boolean>(), true);
BOOST_CHECK_EQUAL(u7.at("val2").cast<toml::value_t::Integer>(), 42);
BOOST_CHECK_CLOSE_FRACTION(u7.at("val3").cast<toml::value_t::Float>(),3.14, 1e-3);
BOOST_CHECK_EQUAL(u7.at("val4").cast<toml::value_t::String>(), "piyo");
toml::get<toml::integer>(v) = 54;
BOOST_TEST(toml::integer(54) == toml::get<toml::integer>(v));
toml::integer x = toml::get<toml::integer>(std::move(v));
BOOST_TEST(toml::integer(54) == x);
}
{
value_type v(3.14);
BOOST_TEST(toml::floating(3.14) == toml::get<toml::floating>(v));
toml::get<toml::floating>(v) = 2.71;
BOOST_TEST(toml::floating(2.71) == toml::get<toml::floating>(v));
toml::floating x = toml::get<toml::floating>(std::move(v));
BOOST_TEST(toml::floating(2.71) == x);
}
{
value_type v("foo");
BOOST_TEST(toml::string("foo", toml::string_t::basic) ==
toml::get<toml::string>(v));
toml::get<toml::string>(v).str += "bar";
BOOST_TEST(toml::string("foobar", toml::string_t::basic) ==
toml::get<toml::string>(v));
toml::string x = toml::get<toml::string>(std::move(v));
BOOST_TEST(toml::string("foobar") == x);
}
{
value_type v("foo", toml::string_t::literal);
BOOST_TEST(toml::string("foo", toml::string_t::literal) ==
toml::get<toml::string>(v));
toml::get<toml::string>(v).str += "bar";
BOOST_TEST(toml::string("foobar", toml::string_t::literal) ==
toml::get<toml::string>(v));
toml::string x = toml::get<toml::string>(std::move(v));
BOOST_TEST(toml::string("foobar", toml::string_t::literal) == x);
}
{
toml::local_date d(2018, toml::month_t::Apr, 22);
value_type v(d);
BOOST_TEST(d == toml::get<toml::local_date>(v));
toml::get<toml::local_date>(v).year = 2017;
d.year = 2017;
BOOST_TEST(d == toml::get<toml::local_date>(v));
toml::local_date x = toml::get<toml::local_date>(std::move(v));
BOOST_TEST(d == x);
}
{
toml::local_time t(12, 30, 45);
value_type v(t);
BOOST_TEST(t == toml::get<toml::local_time>(v));
toml::get<toml::local_time>(v).hour = 9;
t.hour = 9;
BOOST_TEST(t == toml::get<toml::local_time>(v));
toml::local_time x = toml::get<toml::local_time>(std::move(v));
BOOST_TEST(t == x);
}
{
toml::local_datetime dt(toml::local_date(2018, toml::month_t::Apr, 22),
toml::local_time(12, 30, 45));
value_type v(dt);
BOOST_TEST(dt == toml::get<toml::local_datetime>(v));
toml::get<toml::local_datetime>(v).date.year = 2017;
dt.date.year = 2017;
BOOST_TEST(dt == toml::get<toml::local_datetime>(v));
toml::local_datetime x = toml::get<toml::local_datetime>(std::move(v));
BOOST_TEST(dt == x);
}
{
toml::offset_datetime dt(toml::local_datetime(
toml::local_date(2018, toml::month_t::Apr, 22),
toml::local_time(12, 30, 45)), toml::time_offset(9, 0));
value_type v(dt);
BOOST_TEST(dt == toml::get<toml::offset_datetime>(v));
toml::get<toml::offset_datetime>(v).date.year = 2017;
dt.date.year = 2017;
BOOST_TEST(dt == toml::get<toml::offset_datetime>(v));
toml::offset_datetime x = toml::get<toml::offset_datetime>(std::move(v));
BOOST_TEST(dt == x);
}
{
using array_type = typename value_type::array_type;
array_type vec;
vec.push_back(value_type(42));
vec.push_back(value_type(54));
value_type v(vec);
BOOST_TEST(vec == toml::get<array_type>(v));
toml::get<array_type>(v).push_back(value_type(123));
vec.push_back(value_type(123));
BOOST_TEST(vec == toml::get<array_type>(v));
array_type x = toml::get<array_type>(std::move(v));
BOOST_TEST(vec == x);
}
{
using table_type = typename value_type::table_type;
table_type tab;
tab["key1"] = value_type(42);
tab["key2"] = value_type(3.14);
value_type v(tab);
BOOST_TEST(tab == toml::get<table_type>(v));
toml::get<table_type>(v)["key3"] = value_type(123);
tab["key3"] = value_type(123);
BOOST_TEST(tab == toml::get<table_type>(v));
table_type x = toml::get<table_type>(std::move(v));
BOOST_TEST(tab == x);
}
{
value_type v1(42);
BOOST_TEST(v1 == toml::get<value_type>(v1));
value_type v2(54);
toml::get<value_type>(v1) = v2;
BOOST_TEST(v2 == toml::get<value_type>(v1));
value_type x = toml::get<value_type>(std::move(v1));
BOOST_TEST(v2 == x);
}
}
BOOST_AUTO_TEST_CASE(test_get_cast)
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_integer_type, value_type, test_value_types)
{
toml::Integer i(42);
toml::Float f(3.14);
toml::String s("hoge");
toml::Datetime d(std::chrono::system_clock::now());
toml::Array a;
a.emplace_back(2);
a.emplace_back(7);
a.emplace_back(1);
a.emplace_back(8);
a.emplace_back(2);
toml::Table t;
t.emplace("val1", true);
t.emplace("val2", 42);
t.emplace("val3", 3.14);
t.emplace("val4", "piyo");
{
value_type v(42);
BOOST_TEST(int(42) == toml::get<int >(v));
BOOST_TEST(short(42) == toml::get<short >(v));
BOOST_TEST(char(42) == toml::get<char >(v));
BOOST_TEST(unsigned(42) == toml::get<unsigned >(v));
BOOST_TEST(long(42) == toml::get<long >(v));
BOOST_TEST(std::int64_t(42) == toml::get<std::int64_t >(v));
BOOST_TEST(std::uint64_t(42) == toml::get<std::uint64_t>(v));
BOOST_TEST(std::int16_t(42) == toml::get<std::int16_t >(v));
BOOST_TEST(std::uint16_t(42) == toml::get<std::uint16_t>(v));
toml::value v2(i);
toml::value v3(f);
toml::value v4(s);
toml::value v5(d);
toml::value v6(a);
toml::value v7(t);
const auto u2 = toml::get<std::size_t>(v2);
const auto u3 = toml::get<float>(v3);
const auto u4 = toml::get<std::deque<int>>(v6);
const auto u5 = toml::get<std::list<int> >(v6);
const auto u6 = toml::get<std::array<int,5>>(v6);
std::map<std::string, toml::value> u7 = toml::get<std::map<std::string, toml::value>>(v7);
std::deque<int> r4{2,7,1,8,2};
std::list<int> r5{2,7,1,8,2};
std::array<int, 5> r6{{2,7,1,8,2}};
BOOST_CHECK_EQUAL(u2, 42ul);
BOOST_CHECK_CLOSE_FRACTION(u3, 3.14, 1e-3);
const bool dq = r4 == u4;
const bool ls = r5 == u5;
const bool ar = r6 == u6;
BOOST_CHECK(dq);
BOOST_CHECK(ls);
BOOST_CHECK(ar);
BOOST_CHECK_EQUAL(u7.at("val1").cast<toml::value_t::Boolean>(), true);
BOOST_CHECK_EQUAL(u7.at("val2").cast<toml::value_t::Integer>(), 42);
BOOST_CHECK_CLOSE_FRACTION(u7.at("val3").cast<toml::value_t::Float>(),3.14, 1e-3);
BOOST_CHECK_EQUAL(u7.at("val4").cast<toml::value_t::String>(), "piyo");
BOOST_TEST(std::uint16_t(42) == toml::get<std::uint16_t>(std::move(v)));
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_floating_type, value_type, test_value_types)
{
{
value_type v(3.14);
const double ref(3.14);
BOOST_TEST(static_cast<float >(ref) == toml::get<float >(v));
BOOST_TEST( ref == toml::get<double >(v));
BOOST_TEST(static_cast<long double>(ref) == toml::get<long double>(v));
BOOST_TEST(static_cast<float >(ref) == toml::get<float>(std::move(v)));
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_string_type, value_type, test_value_types)
{
{
value_type v("foo", toml::string_t::basic);
BOOST_TEST("foo" == toml::get<std::string>(v));
toml::get<std::string>(v) += "bar";
BOOST_TEST("foobar" == toml::get<std::string>(v));
const auto x = toml::get<std::string>(std::move(v));
BOOST_TEST("foobar" == x);
}
{
value_type v("foo", toml::string_t::literal);
BOOST_TEST("foo" == toml::get<std::string>(v));
toml::get<std::string>(v) += "bar";
BOOST_TEST("foobar" == toml::get<std::string>(v));
const auto x = toml::get<std::string>(std::move(v));
BOOST_TEST("foobar" == x);
}
#if __cplusplus >= 201703L
{
value_type v("foo", toml::string_t::basic);
BOOST_TEST("foo" == toml::get<std::string_view>(v));
}
{
value_type v("foo", toml::string_t::literal);
BOOST_TEST("foo" == toml::get<std::string_view>(v));
}
#endif
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_toml_array, value_type, test_value_types)
{
{
const value_type v{42, 54, 69, 72};
const std::vector<int> vec = toml::get<std::vector<int>>(v);
const std::list<short> lst = toml::get<std::list<short>>(v);
const std::deque<std::int64_t> deq = toml::get<std::deque<std::int64_t>>(v);
BOOST_TEST(42 == vec.at(0));
BOOST_TEST(54 == vec.at(1));
BOOST_TEST(69 == vec.at(2));
BOOST_TEST(72 == vec.at(3));
std::list<short>::const_iterator iter = lst.begin();
BOOST_TEST(static_cast<short>(42) == *(iter++));
BOOST_TEST(static_cast<short>(54) == *(iter++));
BOOST_TEST(static_cast<short>(69) == *(iter++));
BOOST_TEST(static_cast<short>(72) == *(iter++));
BOOST_TEST(static_cast<std::int64_t>(42) == deq.at(0));
BOOST_TEST(static_cast<std::int64_t>(54) == deq.at(1));
BOOST_TEST(static_cast<std::int64_t>(69) == deq.at(2));
BOOST_TEST(static_cast<std::int64_t>(72) == deq.at(3));
std::array<int, 4> ary = toml::get<std::array<int, 4>>(v);
BOOST_TEST(42 == ary.at(0));
BOOST_TEST(54 == ary.at(1));
BOOST_TEST(69 == ary.at(2));
BOOST_TEST(72 == ary.at(3));
std::tuple<int, short, unsigned, long> tpl =
toml::get<std::tuple<int, short, unsigned, long>>(v);
BOOST_TEST( 42 == std::get<0>(tpl));
BOOST_TEST(static_cast<short >(54) == std::get<1>(tpl));
BOOST_TEST(static_cast<unsigned>(69) == std::get<2>(tpl));
BOOST_TEST(static_cast<long >(72) == std::get<3>(tpl));
const value_type p{3.14, 2.71};
std::pair<double, double> pr = toml::get<std::pair<double, double> >(p);
BOOST_TEST(3.14 == pr.first);
BOOST_TEST(2.71 == pr.second);
}
{
value_type v{42, 54, 69, 72};
const std::vector<int> vec = toml::get<std::vector<int>>(std::move(v));
BOOST_TEST(42 == vec.at(0));
BOOST_TEST(54 == vec.at(1));
BOOST_TEST(69 == vec.at(2));
BOOST_TEST(72 == vec.at(3));
}
{
value_type v{42, 54, 69, 72};
const std::deque<int> deq = toml::get<std::deque<int>>(std::move(v));
BOOST_TEST(42 == deq.at(0));
BOOST_TEST(54 == deq.at(1));
BOOST_TEST(69 == deq.at(2));
BOOST_TEST(72 == deq.at(3));
}
{
value_type v{42, 54, 69, 72};
const std::list<int> lst = toml::get<std::list<int>>(std::move(v));
std::list<int>::const_iterator iter = lst.begin();
BOOST_TEST(42 == *(iter++));
BOOST_TEST(54 == *(iter++));
BOOST_TEST(69 == *(iter++));
BOOST_TEST(72 == *(iter++));
}
{
value_type v{42, 54, 69, 72};
std::array<int, 4> ary = toml::get<std::array<int, 4>>(std::move(v));
BOOST_TEST(42 == ary.at(0));
BOOST_TEST(54 == ary.at(1));
BOOST_TEST(69 == ary.at(2));
BOOST_TEST(72 == ary.at(3));
}
{
value_type v{42, 54, 69, 72};
std::tuple<int, short, unsigned, long> tpl =
toml::get<std::tuple<int, short, unsigned, long>>(std::move(v));
BOOST_TEST( 42 == std::get<0>(tpl));
BOOST_TEST(static_cast<short >(54) == std::get<1>(tpl));
BOOST_TEST(static_cast<unsigned>(69) == std::get<2>(tpl));
BOOST_TEST(static_cast<long >(72) == std::get<3>(tpl));
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_toml_array_of_array, value_type, test_value_types)
{
{
const value_type v1{42, 54, 69, 72};
const value_type v2{"foo", "bar", "baz"};
const value_type v{v1, v2};
std::pair<std::vector<int>, std::vector<std::string>> p =
toml::get<std::pair<std::vector<int>, std::vector<std::string>>>(v);
BOOST_TEST(p.first.size() == 4u);
BOOST_TEST(p.first.at(0) == 42);
BOOST_TEST(p.first.at(1) == 54);
BOOST_TEST(p.first.at(2) == 69);
BOOST_TEST(p.first.at(3) == 72);
BOOST_TEST(p.second.size() == 3u);
BOOST_TEST(p.second.at(0) == "foo");
BOOST_TEST(p.second.at(1) == "bar");
BOOST_TEST(p.second.at(2) == "baz");
std::tuple<std::vector<int>, std::vector<std::string>> t =
toml::get<std::tuple<std::vector<int>, std::vector<std::string>>>(v);
BOOST_TEST(std::get<0>(t).at(0) == 42);
BOOST_TEST(std::get<0>(t).at(1) == 54);
BOOST_TEST(std::get<0>(t).at(2) == 69);
BOOST_TEST(std::get<0>(t).at(3) == 72);
BOOST_TEST(std::get<1>(t).at(0) == "foo");
BOOST_TEST(std::get<1>(t).at(1) == "bar");
BOOST_TEST(std::get<1>(t).at(2) == "baz");
}
{
const value_type v1{42, 54, 69, 72};
const value_type v2{"foo", "bar", "baz"};
value_type v{v1, v2};
std::pair<std::vector<int>, std::vector<std::string>> p =
toml::get<std::pair<std::vector<int>, std::vector<std::string>>>(std::move(v));
BOOST_TEST(p.first.size() == 4u);
BOOST_TEST(p.first.at(0) == 42);
BOOST_TEST(p.first.at(1) == 54);
BOOST_TEST(p.first.at(2) == 69);
BOOST_TEST(p.first.at(3) == 72);
BOOST_TEST(p.second.size() == 3u);
BOOST_TEST(p.second.at(0) == "foo");
BOOST_TEST(p.second.at(1) == "bar");
BOOST_TEST(p.second.at(2) == "baz");
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_toml_table, value_type, test_value_types)
{
{
const value_type v1{
{"key1", 1},
{"key2", 2},
{"key3", 3},
{"key4", 4}
};
const auto v = toml::get<std::map<std::string, int>>(v1);
BOOST_TEST(v.at("key1") == 1);
BOOST_TEST(v.at("key2") == 2);
BOOST_TEST(v.at("key3") == 3);
BOOST_TEST(v.at("key4") == 4);
}
{
value_type v1{
{"key1", 1},
{"key2", 2},
{"key3", 3},
{"key4", 4}
};
const auto v = toml::get<std::map<std::string, int>>(std::move(v1));
BOOST_TEST(v.at("key1") == 1);
BOOST_TEST(v.at("key2") == 2);
BOOST_TEST(v.at("key3") == 3);
BOOST_TEST(v.at("key4") == 4);
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_toml_local_date, value_type, test_value_types)
{
value_type v1(toml::local_date{2018, toml::month_t::Apr, 1});
const auto date = std::chrono::system_clock::to_time_t(
toml::get<std::chrono::system_clock::time_point>(v1));
std::tm t;
t.tm_year = 2018 - 1900;
t.tm_mon = 4 - 1;
t.tm_mday = 1;
t.tm_hour = 0;
t.tm_min = 0;
t.tm_sec = 0;
t.tm_isdst = -1;
const auto c = std::mktime(&t);
BOOST_TEST(c == date);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_toml_local_time, value_type, test_value_types)
{
value_type v1(toml::local_time{12, 30, 45});
const auto time = toml::get<std::chrono::seconds>(v1);
const bool result = time == std::chrono::hours(12) +
std::chrono::minutes(30) +
std::chrono::seconds(45);
BOOST_TEST(result);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_toml_local_datetime, value_type, test_value_types)
{
value_type v1(toml::local_datetime(
toml::local_date{2018, toml::month_t::Apr, 1},
toml::local_time{12, 30, 45}));
const auto date = std::chrono::system_clock::to_time_t(
toml::get<std::chrono::system_clock::time_point>(v1));
std::tm t;
t.tm_year = 2018 - 1900;
t.tm_mon = 4 - 1;
t.tm_mday = 1;
t.tm_hour = 12;
t.tm_min = 30;
t.tm_sec = 45;
t.tm_isdst = -1;
const auto c = std::mktime(&t);
BOOST_TEST(c == date);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_toml_offset_datetime, value_type, test_value_types)
{
{
value_type v1(toml::offset_datetime(
toml::local_date{2018, toml::month_t::Apr, 1},
toml::local_time{12, 30, 0},
toml::time_offset{9, 0}));
// 2018-04-01T12:30:00+09:00
// == 2018-04-01T03:30:00Z
const auto date = toml::get<std::chrono::system_clock::time_point>(v1);
const auto timet = std::chrono::system_clock::to_time_t(date);
// get time_t as gmtime (2018-04-01T03:30:00Z)
const auto tmp = std::gmtime(std::addressof(timet)); // XXX not threadsafe!
BOOST_TEST(tmp);
const auto tm = *tmp;
BOOST_TEST(tm.tm_year + 1900 == 2018);
BOOST_TEST(tm.tm_mon + 1 == 4);
BOOST_TEST(tm.tm_mday == 1);
BOOST_TEST(tm.tm_hour == 3);
BOOST_TEST(tm.tm_min == 30);
BOOST_TEST(tm.tm_sec == 0);
}
{
value_type v1(toml::offset_datetime(
toml::local_date{2018, toml::month_t::Apr, 1},
toml::local_time{12, 30, 0},
toml::time_offset{-8, 0}));
// 2018-04-01T12:30:00-08:00
// == 2018-04-01T20:30:00Z
const auto date = toml::get<std::chrono::system_clock::time_point>(v1);
const auto timet = std::chrono::system_clock::to_time_t(date);
// get time_t as gmtime (2018-04-01T03:30:00Z)
const auto tmp = std::gmtime(std::addressof(timet)); // XXX not threadsafe!
BOOST_TEST(tmp);
const auto tm = *tmp;
BOOST_TEST(tm.tm_year + 1900 == 2018);
BOOST_TEST(tm.tm_mon + 1 == 4);
BOOST_TEST(tm.tm_mday == 1);
BOOST_TEST(tm.tm_hour == 20);
BOOST_TEST(tm.tm_min == 30);
BOOST_TEST(tm.tm_sec == 0);
}
}

View File

@@ -11,78 +11,442 @@
#include <list>
#include <deque>
#include <array>
#include <tuple>
#if __cplusplus >= 201703L
#include <string_view>
#endif
using test_value_types = std::tuple<
toml::value,
toml::basic_value<toml::preserve_comments>,
toml::basic_value<toml::discard_comments, std::map, std::deque>,
toml::basic_value<toml::preserve_comments, std::map, std::deque>
>;
BOOST_AUTO_TEST_CASE(test_get_or_exist)
namespace test
{
toml::Boolean raw_v1(true);
toml::Integer raw_v2(42);
toml::Float raw_v3(3.14);
toml::String raw_v4("hoge");
toml::Array raw_v5{2,7,1,8,2};
toml::Table raw_v6{{"key", 42}};
// to compare result values in BOOST_TEST().
//
// BOOST_TEST outputs the expected and actual values. Thus it includes the
// output stream operator inside. To compile it, we need operator<<s for
// containers to compare.
template<typename charT, typename traits, typename T, typename Alloc>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const std::vector<T, Alloc>& v)
{
os << "[ ";
for(const auto& i : v) {os << i << ' ';}
os << ']';
return os;
}
template<typename charT, typename traits, typename T, typename Alloc>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const std::deque<T, Alloc>& v)
{
os << "[ ";
for(const auto& i : v) {os << i << ' ';}
os << ']';
return os;
}
template<typename charT, typename traits, typename T, typename Alloc>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const std::list<T, Alloc>& v)
{
os << "[ ";
for(const auto& i : v) {os << i << ' ';}
os << ']';
return os;
}
template<typename charT, typename traits,
typename Key, typename Value, typename Comp, typename Alloc>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os,
const std::map<Key, Value, Comp, Alloc>& v)
{
os << "[ ";
for(const auto& i : v) {os << '{' << i.first << ", " << i.second << "} ";}
os << ']';
return os;
}
template<typename charT, typename traits,
typename Key, typename Value, typename Hash, typename Eq, typename Alloc>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os,
const std::unordered_map<Key, Value, Hash, Eq, Alloc>& v)
{
os << "[ ";
for(const auto& i : v) {os << '{' << i.first << ", " << i.second << "} ";}
os << ']';
return os;
}
} // test
toml::value v1(raw_v1);
toml::value v2(raw_v2);
toml::value v3(raw_v3);
toml::value v4(raw_v4);
toml::value v5(raw_v5);
toml::value v6(raw_v6);
#define TOML11_TEST_GET_OR_EXACT(toml_type, init_expr, opt_expr)\
{ \
using namespace test; \
const toml::toml_type init init_expr ; \
const toml::toml_type opt opt_expr ; \
const value_type v(init); \
BOOST_TEST(init != opt); \
BOOST_TEST(init == toml::get_or(v, opt)); \
} \
/**/
toml::Table table{
{"value1", v1},
{"value2", v2},
{"value3", v3},
{"value4", v4},
{"value5", v5},
{"value6", v6}
};
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_or_exact, value_type, test_value_types)
{
TOML11_TEST_GET_OR_EXACT(boolean, ( true), (false))
TOML11_TEST_GET_OR_EXACT(integer, ( 42), ( 54))
TOML11_TEST_GET_OR_EXACT(floating, ( 3.14), ( 2.71))
TOML11_TEST_GET_OR_EXACT(string, ("foo"), ("bar"))
TOML11_TEST_GET_OR_EXACT(local_time, (12, 30, 45), (6, 0, 30))
TOML11_TEST_GET_OR_EXACT(local_date, (2019, toml::month_t::Apr, 1),
(1999, toml::month_t::Jan, 2))
TOML11_TEST_GET_OR_EXACT(local_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30))
)
TOML11_TEST_GET_OR_EXACT(offset_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45), toml::time_offset( 9, 0)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30), toml::time_offset(-3, 0))
)
{
const typename value_type::array_type init{1,2,3,4,5};
const typename value_type::array_type opt {6,7,8,9,10};
const value_type v(init);
BOOST_TEST(init != opt);
BOOST_TEST(init == toml::get_or(v, opt));
}
{
const typename value_type::table_type init{{"key1", 42}, {"key2", "foo"}};
const typename value_type::table_type opt {{"key1", 54}, {"key2", "bar"}};
const value_type v(init);
BOOST_TEST(init != opt);
BOOST_TEST(init == toml::get_or(v, opt));
}
}
#undef TOML11_TEST_GET_OR_EXACT
toml::Boolean u1 = toml::get_or(table, "value1", raw_v1);
toml::Integer u2 = toml::get_or(table, "value2", raw_v2);
toml::Float u3 = toml::get_or(table, "value3", raw_v3);
toml::String u4 = toml::get_or(table, "value4", raw_v4);
toml::Array u5 = toml::get_or(table, "value5", raw_v5);
toml::Table u6 = toml::get_or(table, "value6", raw_v6);
#define TOML11_TEST_GET_OR_MOVE_EXACT(toml_type, init_expr, opt_expr)\
{ \
using namespace test; \
const toml::toml_type init init_expr ; \
toml::toml_type opt opt_expr ; \
value_type v(init); \
BOOST_TEST(init != opt); \
const auto opt_ = toml::get_or(std::move(v), std::move(opt));\
BOOST_TEST(init == opt_); \
} \
/**/
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_or_move, value_type, test_value_types)
{
TOML11_TEST_GET_OR_MOVE_EXACT(boolean, ( true), (false))
TOML11_TEST_GET_OR_MOVE_EXACT(integer, ( 42), ( 54))
TOML11_TEST_GET_OR_MOVE_EXACT(floating, ( 3.14), ( 2.71))
TOML11_TEST_GET_OR_MOVE_EXACT(string, ("foo"), ("bar"))
TOML11_TEST_GET_OR_MOVE_EXACT(local_time, (12, 30, 45), (6, 0, 30))
TOML11_TEST_GET_OR_MOVE_EXACT(local_date, (2019, toml::month_t::Apr, 1),
(1999, toml::month_t::Jan, 2))
TOML11_TEST_GET_OR_MOVE_EXACT(local_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30))
)
TOML11_TEST_GET_OR_MOVE_EXACT(offset_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45), toml::time_offset( 9, 0)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30), toml::time_offset(-3, 0))
)
{
const typename value_type::array_type init{1,2,3,4,5};
typename value_type::array_type opt {6,7,8,9,10};
value_type v(init);
BOOST_TEST(init != opt);
const auto opt_ = toml::get_or(std::move(v), std::move(opt));
BOOST_TEST(init == opt_);
}
{
const typename value_type::table_type init{{"key1", 42}, {"key2", "foo"}};
typename value_type::table_type opt {{"key1", 54}, {"key2", "bar"}};
value_type v(init);
BOOST_TEST(init != opt);
const auto opt_ = toml::get_or(std::move(v), std::move(opt));
BOOST_TEST(init == opt_);
}
}
#undef TOML11_TEST_GET_OR_MOVE_EXACT
#define TOML11_TEST_GET_OR_MODIFY(toml_type, init_expr, opt_expr)\
{ \
using namespace test; \
const toml::toml_type init init_expr ; \
toml::toml_type opt1 opt_expr ; \
toml::toml_type opt2 opt_expr ; \
value_type v(init); \
BOOST_TEST(init != opt1); \
toml::get_or(v, opt2) = opt1; \
BOOST_TEST(opt1 == toml::get<toml::toml_type>(v)); \
} \
/**/
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_or_modify, value_type, test_value_types)
{
TOML11_TEST_GET_OR_MODIFY(boolean, ( true), (false))
TOML11_TEST_GET_OR_MODIFY(integer, ( 42), ( 54))
TOML11_TEST_GET_OR_MODIFY(floating, ( 3.14), ( 2.71))
TOML11_TEST_GET_OR_MODIFY(string, ("foo"), ("bar"))
TOML11_TEST_GET_OR_MODIFY(local_time, (12, 30, 45), (6, 0, 30))
TOML11_TEST_GET_OR_MODIFY(local_date, (2019, toml::month_t::Apr, 1),
(1999, toml::month_t::Jan, 2))
TOML11_TEST_GET_OR_MODIFY(local_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30))
)
TOML11_TEST_GET_OR_MODIFY(offset_datetime,
(toml::local_date(2019, toml::month_t::Apr, 1), toml::local_time(12, 30, 45), toml::time_offset( 9, 0)),
(toml::local_date(1999, toml::month_t::Jan, 2), toml::local_time( 6, 0, 30), toml::time_offset(-3, 0))
)
{
typename value_type::array_type init{1,2,3,4,5};
typename value_type::array_type opt1{6,7,8,9,10};
typename value_type::array_type opt2{6,7,8,9,10};
BOOST_TEST(init != opt1);
value_type v(init);
toml::get_or(v, opt2) = opt1;
BOOST_TEST(opt1 == toml::get<typename value_type::array_type>(v));
}
{
typename value_type::table_type init{{"key1", 42}, {"key2", "foo"}};
typename value_type::table_type opt1{{"key1", 54}, {"key2", "bar"}};
typename value_type::table_type opt2{{"key1", 54}, {"key2", "bar"}};
value_type v(init);
BOOST_TEST(init != opt1);
toml::get_or(v, opt2) = opt1;
BOOST_TEST(opt1 == toml::get<typename value_type::table_type>(v));
}
}
#undef TOML11_TEST_GET_OR_MODIFY
#define TOML11_TEST_GET_OR_FALLBACK(init_type, opt_type) \
{ \
using namespace test; \
value_type v(init_type); \
BOOST_TEST(opt_type == toml::get_or(v, opt_type));\
} \
/**/
BOOST_AUTO_TEST_CASE_TEMPLATE(test_get_or_fallback, value_type, test_value_types)
{
const toml::boolean boolean (true);
const toml::integer integer (42);
const toml::floating floating (3.14);
const toml::string string ("foo");
const toml::local_time local_time (12, 30, 45);
const toml::local_date local_date (2019, toml::month_t::Apr, 1);
const toml::local_datetime local_datetime (
toml::local_date(2019, toml::month_t::Apr, 1),
toml::local_time(12, 30, 45));
const toml::offset_datetime offset_datetime(
toml::local_date(2019, toml::month_t::Apr, 1),
toml::local_time(12, 30, 45), toml::time_offset( 9, 0));
using array_type = typename value_type::array_type;
using table_type = typename value_type::table_type;
const array_type array{1, 2, 3, 4, 5};
const table_type table{{"key1", 42}, {"key2", "foo"}};
TOML11_TEST_GET_OR_FALLBACK(boolean, integer );
TOML11_TEST_GET_OR_FALLBACK(boolean, floating );
TOML11_TEST_GET_OR_FALLBACK(boolean, string );
TOML11_TEST_GET_OR_FALLBACK(boolean, local_time );
TOML11_TEST_GET_OR_FALLBACK(boolean, local_date );
TOML11_TEST_GET_OR_FALLBACK(boolean, local_datetime );
TOML11_TEST_GET_OR_FALLBACK(boolean, offset_datetime);
TOML11_TEST_GET_OR_FALLBACK(boolean, array );
TOML11_TEST_GET_OR_FALLBACK(boolean, table );
TOML11_TEST_GET_OR_FALLBACK(integer, boolean );
TOML11_TEST_GET_OR_FALLBACK(integer, floating );
TOML11_TEST_GET_OR_FALLBACK(integer, string );
TOML11_TEST_GET_OR_FALLBACK(integer, local_time );
TOML11_TEST_GET_OR_FALLBACK(integer, local_date );
TOML11_TEST_GET_OR_FALLBACK(integer, local_datetime );
TOML11_TEST_GET_OR_FALLBACK(integer, offset_datetime);
TOML11_TEST_GET_OR_FALLBACK(integer, array );
TOML11_TEST_GET_OR_FALLBACK(integer, table );
TOML11_TEST_GET_OR_FALLBACK(floating, boolean );
TOML11_TEST_GET_OR_FALLBACK(floating, integer );
TOML11_TEST_GET_OR_FALLBACK(floating, string );
TOML11_TEST_GET_OR_FALLBACK(floating, local_time );
TOML11_TEST_GET_OR_FALLBACK(floating, local_date );
TOML11_TEST_GET_OR_FALLBACK(floating, local_datetime );
TOML11_TEST_GET_OR_FALLBACK(floating, offset_datetime);
TOML11_TEST_GET_OR_FALLBACK(floating, array );
TOML11_TEST_GET_OR_FALLBACK(floating, table );
TOML11_TEST_GET_OR_FALLBACK(string, boolean );
TOML11_TEST_GET_OR_FALLBACK(string, integer );
TOML11_TEST_GET_OR_FALLBACK(string, floating );
TOML11_TEST_GET_OR_FALLBACK(string, local_time );
TOML11_TEST_GET_OR_FALLBACK(string, local_date );
TOML11_TEST_GET_OR_FALLBACK(string, local_datetime );
TOML11_TEST_GET_OR_FALLBACK(string, offset_datetime);
TOML11_TEST_GET_OR_FALLBACK(string, array );
TOML11_TEST_GET_OR_FALLBACK(string, table );
TOML11_TEST_GET_OR_FALLBACK(local_time, boolean );
TOML11_TEST_GET_OR_FALLBACK(local_time, integer );
TOML11_TEST_GET_OR_FALLBACK(local_time, floating );
TOML11_TEST_GET_OR_FALLBACK(local_time, string );
TOML11_TEST_GET_OR_FALLBACK(local_time, local_date );
TOML11_TEST_GET_OR_FALLBACK(local_time, local_datetime );
TOML11_TEST_GET_OR_FALLBACK(local_time, offset_datetime);
TOML11_TEST_GET_OR_FALLBACK(local_time, array );
TOML11_TEST_GET_OR_FALLBACK(local_time, table );
TOML11_TEST_GET_OR_FALLBACK(local_date, boolean );
TOML11_TEST_GET_OR_FALLBACK(local_date, integer );
TOML11_TEST_GET_OR_FALLBACK(local_date, floating );
TOML11_TEST_GET_OR_FALLBACK(local_date, string );
TOML11_TEST_GET_OR_FALLBACK(local_date, local_time );
TOML11_TEST_GET_OR_FALLBACK(local_date, local_datetime );
TOML11_TEST_GET_OR_FALLBACK(local_date, offset_datetime);
TOML11_TEST_GET_OR_FALLBACK(local_date, array );
TOML11_TEST_GET_OR_FALLBACK(local_date, table );
TOML11_TEST_GET_OR_FALLBACK(local_datetime, boolean );
TOML11_TEST_GET_OR_FALLBACK(local_datetime, integer );
TOML11_TEST_GET_OR_FALLBACK(local_datetime, floating );
TOML11_TEST_GET_OR_FALLBACK(local_datetime, string );
TOML11_TEST_GET_OR_FALLBACK(local_datetime, local_time );
TOML11_TEST_GET_OR_FALLBACK(local_datetime, local_date );
TOML11_TEST_GET_OR_FALLBACK(local_datetime, offset_datetime);
TOML11_TEST_GET_OR_FALLBACK(local_datetime, array );
TOML11_TEST_GET_OR_FALLBACK(local_datetime, table );
TOML11_TEST_GET_OR_FALLBACK(offset_datetime, boolean );
TOML11_TEST_GET_OR_FALLBACK(offset_datetime, integer );
TOML11_TEST_GET_OR_FALLBACK(offset_datetime, floating );
TOML11_TEST_GET_OR_FALLBACK(offset_datetime, string );
TOML11_TEST_GET_OR_FALLBACK(offset_datetime, local_time );
TOML11_TEST_GET_OR_FALLBACK(offset_datetime, local_date );
TOML11_TEST_GET_OR_FALLBACK(offset_datetime, local_datetime );
TOML11_TEST_GET_OR_FALLBACK(offset_datetime, array );
TOML11_TEST_GET_OR_FALLBACK(offset_datetime, table );
TOML11_TEST_GET_OR_FALLBACK(array, boolean );
TOML11_TEST_GET_OR_FALLBACK(array, integer );
TOML11_TEST_GET_OR_FALLBACK(array, floating );
TOML11_TEST_GET_OR_FALLBACK(array, string );
TOML11_TEST_GET_OR_FALLBACK(array, local_time );
TOML11_TEST_GET_OR_FALLBACK(array, local_date );
TOML11_TEST_GET_OR_FALLBACK(array, local_datetime );
TOML11_TEST_GET_OR_FALLBACK(array, offset_datetime);
TOML11_TEST_GET_OR_FALLBACK(array, table );
TOML11_TEST_GET_OR_FALLBACK(table, boolean );
TOML11_TEST_GET_OR_FALLBACK(table, integer );
TOML11_TEST_GET_OR_FALLBACK(table, floating );
TOML11_TEST_GET_OR_FALLBACK(table, string );
TOML11_TEST_GET_OR_FALLBACK(table, local_time );
TOML11_TEST_GET_OR_FALLBACK(table, local_date );
TOML11_TEST_GET_OR_FALLBACK(table, local_datetime );
TOML11_TEST_GET_OR_FALLBACK(table, offset_datetime);
TOML11_TEST_GET_OR_FALLBACK(table, array );
}
#undef TOML11_TEST_GET_OR_FALLBACK
BOOST_AUTO_TEST_CASE(test_get_or_integer)
{
{
toml::value v1(42);
toml::value v2(3.14);
BOOST_TEST(42u == toml::get_or(v1, 0u));
BOOST_TEST(0u == toml::get_or(v2, 0u));
}
{
toml::value v1(42);
toml::value v2(3.14);
BOOST_TEST(42u == toml::get_or(std::move(v1), 0u));
BOOST_TEST(0u == toml::get_or(std::move(v2), 0u));
}
BOOST_CHECK_EQUAL(u1, raw_v1);
BOOST_CHECK_EQUAL(u2, raw_v2);
BOOST_CHECK_EQUAL(u3, raw_v3);
BOOST_CHECK_EQUAL(u4, raw_v4);
BOOST_CHECK_EQUAL(u5.at(0).cast<toml::value_t::Integer>(), raw_v5.at(0).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u5.at(1).cast<toml::value_t::Integer>(), raw_v5.at(1).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u5.at(2).cast<toml::value_t::Integer>(), raw_v5.at(2).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u5.at(3).cast<toml::value_t::Integer>(), raw_v5.at(3).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u5.at(4).cast<toml::value_t::Integer>(), raw_v5.at(4).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u6.at("key").cast<toml::value_t::Integer>(), 42);
}
BOOST_AUTO_TEST_CASE(test_get_or_empty)
BOOST_AUTO_TEST_CASE(test_get_or_floating)
{
toml::Boolean raw_v1(true);
toml::Integer raw_v2(42);
toml::Float raw_v3(3.14);
toml::String raw_v4("hoge");
toml::Array raw_v5{2,7,1,8,2};
toml::Table raw_v6{{"key", 42}};
toml::Table table; // empty!
toml::Boolean u1 = toml::get_or(table, std::string("value1"), raw_v1);
toml::Integer u2 = toml::get_or(table, std::string("value2"), raw_v2);
toml::Float u3 = toml::get_or(table, std::string("value3"), raw_v3);
toml::String u4 = toml::get_or(table, std::string("value4"), raw_v4);
toml::Array u5 = toml::get_or(table, std::string("value5"), raw_v5);
toml::Table u6 = toml::get_or(table, std::string("value6"), raw_v6);
BOOST_CHECK_EQUAL(u1, raw_v1);
BOOST_CHECK_EQUAL(u2, raw_v2);
BOOST_CHECK_EQUAL(u3, raw_v3);
BOOST_CHECK_EQUAL(u4, raw_v4);
BOOST_CHECK_EQUAL(u5.at(0).cast<toml::value_t::Integer>(), raw_v5.at(0).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u5.at(1).cast<toml::value_t::Integer>(), raw_v5.at(1).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u5.at(2).cast<toml::value_t::Integer>(), raw_v5.at(2).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u5.at(3).cast<toml::value_t::Integer>(), raw_v5.at(3).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u5.at(4).cast<toml::value_t::Integer>(), raw_v5.at(4).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(u6.at("key").cast<toml::value_t::Integer>(), 42);
{
toml::value v1(42);
toml::value v2(3.14);
BOOST_TEST(2.71f == toml::get_or(v1, 2.71f));
BOOST_TEST(static_cast<float>(v2.as_floating()) == toml::get_or(v2, 2.71f));
}
{
toml::value v1(42);
toml::value v2(3.14);
BOOST_TEST(2.71f == toml::get_or(std::move(v1), 2.71f));
BOOST_TEST(static_cast<float>(3.14) == toml::get_or(std::move(v2), 2.71f));
}
}
BOOST_AUTO_TEST_CASE(test_get_or_string)
{
{
toml::value v1("foobar");
toml::value v2(42);
std::string s1("bazqux");
const std::string s2("bazqux");
BOOST_TEST("foobar" == toml::get_or(v1, s1));
BOOST_TEST("bazqux" == toml::get_or(v2, s1));
std::string& v1r = toml::get_or(v1, s1);
std::string& s1r = toml::get_or(v2, s1);
BOOST_TEST("foobar" == v1r);
BOOST_TEST("bazqux" == s1r);
BOOST_TEST("foobar" == toml::get_or(v1, s2));
BOOST_TEST("bazqux" == toml::get_or(v2, s2));
BOOST_TEST("foobar" == toml::get_or(v1, std::move(s1)));
BOOST_TEST("bazqux" == toml::get_or(v2, std::move(s1)));
}
{
toml::value v1("foobar");
toml::value v2(42);
std::string s1("bazqux");
const std::string s2("bazqux");
BOOST_TEST("foobar" == toml::get_or(std::move(v1), s1));
BOOST_TEST("bazqux" == toml::get_or(std::move(v2), s1));
}
{
toml::value v1("foobar");
toml::value v2(42);
BOOST_TEST("foobar" == toml::get_or(v1, "bazqux"));
BOOST_TEST("bazqux" == toml::get_or(v2, "bazqux"));
const char* lit = "bazqux";
BOOST_TEST("foobar" == toml::get_or(v1, lit));
BOOST_TEST("bazqux" == toml::get_or(v2, lit));
}
{
toml::value v1("foobar");
toml::value v2(42);
BOOST_TEST("foobar" == toml::get_or(std::move(v1), "bazqux"));
BOOST_TEST("bazqux" == toml::get_or(std::move(v2), "bazqux"));
}
{
toml::value v1("foobar");
toml::value v2(42);
const char* lit = "bazqux";
BOOST_TEST("foobar" == toml::get_or(v1, lit));
BOOST_TEST("bazqux" == toml::get_or(v2, lit));
}
}

36
tests/test_lex_aux.hpp Normal file
View File

@@ -0,0 +1,36 @@
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <toml/region.hpp>
#include <toml/result.hpp>
#define TOML11_TEST_LEX_ACCEPT(lxr, tkn, expct) \
do { \
const std::string token (tkn); \
const std::string expected(expct); \
toml::detail::location<std::string> loc("test", token); \
const auto result = lxr::invoke(loc); \
BOOST_TEST(result.is_ok()); \
if(result.is_ok()){ \
const auto region = result.unwrap(); \
BOOST_TEST(region.str() == expected); \
BOOST_TEST(region.str().size() == expected.size()); \
BOOST_TEST(static_cast<std::size_t>(std::distance( \
loc.begin(), loc.iter())) == region.size()); \
} else { \
std::cerr << "lexer failed with input `"; \
std::cerr << token << "`. expected `" << expected << "`\n"; \
std::cerr << "reason: " << result.unwrap_err() << '\n'; \
} \
} while(false); \
/**/
#define TOML11_TEST_LEX_REJECT(lxr, tkn) \
do { \
const std::string token (tkn); \
toml::detail::location<std::string> loc("test", token); \
const auto result = lxr::invoke(loc); \
BOOST_TEST(result.is_err()); \
const bool loc_same = (loc.begin() == loc.iter()); \
BOOST_TEST(loc_same); \
} while(false); /**/

View File

@@ -0,0 +1,23 @@
#define BOOST_TEST_MODULE "test_lex_boolean"
#include <boost/test/unit_test.hpp>
#include <toml/lexer.hpp>
#include "test_lex_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_correct)
{
TOML11_TEST_LEX_ACCEPT(lex_boolean, "true", "true");
TOML11_TEST_LEX_ACCEPT(lex_boolean, "false", "false");
TOML11_TEST_LEX_ACCEPT(lex_boolean, "true # trailing", "true");
TOML11_TEST_LEX_ACCEPT(lex_boolean, "false # trailing", "false");
}
BOOST_AUTO_TEST_CASE(test_invalid)
{
TOML11_TEST_LEX_REJECT(lex_boolean, "TRUE");
TOML11_TEST_LEX_REJECT(lex_boolean, "FALSE");
TOML11_TEST_LEX_REJECT(lex_boolean, "True");
TOML11_TEST_LEX_REJECT(lex_boolean, "False");
}

View File

@@ -0,0 +1,57 @@
#define BOOST_TEST_MODULE "test_lex_datetime"
#include <boost/test/unit_test.hpp>
#include <toml/lexer.hpp>
#include "test_lex_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_offset_datetime)
{
TOML11_TEST_LEX_ACCEPT(lex_offset_date_time,
"1979-05-27T07:32:00Z",
"1979-05-27T07:32:00Z");
TOML11_TEST_LEX_ACCEPT(lex_offset_date_time,
"1979-05-27T07:32:00-07:00",
"1979-05-27T07:32:00-07:00");
TOML11_TEST_LEX_ACCEPT(lex_offset_date_time,
"1979-05-27T07:32:00.999999-07:00",
"1979-05-27T07:32:00.999999-07:00");
TOML11_TEST_LEX_ACCEPT(lex_offset_date_time,
"1979-05-27 07:32:00Z",
"1979-05-27 07:32:00Z");
TOML11_TEST_LEX_ACCEPT(lex_offset_date_time,
"1979-05-27 07:32:00-07:00",
"1979-05-27 07:32:00-07:00");
TOML11_TEST_LEX_ACCEPT(lex_offset_date_time,
"1979-05-27 07:32:00.999999-07:00",
"1979-05-27 07:32:00.999999-07:00");
}
BOOST_AUTO_TEST_CASE(test_local_datetime)
{
TOML11_TEST_LEX_ACCEPT(lex_local_date_time,
"1979-05-27T07:32:00",
"1979-05-27T07:32:00");
TOML11_TEST_LEX_ACCEPT(lex_local_date_time,
"1979-05-27T07:32:00.999999",
"1979-05-27T07:32:00.999999");
TOML11_TEST_LEX_ACCEPT(lex_local_date_time,
"1979-05-27 07:32:00",
"1979-05-27 07:32:00");
TOML11_TEST_LEX_ACCEPT(lex_local_date_time,
"1979-05-27 07:32:00.999999",
"1979-05-27 07:32:00.999999");
}
BOOST_AUTO_TEST_CASE(test_local_date)
{
TOML11_TEST_LEX_ACCEPT(lex_local_date, "1979-05-27", "1979-05-27");
}
BOOST_AUTO_TEST_CASE(test_local_time)
{
TOML11_TEST_LEX_ACCEPT(lex_local_time, "07:32:00", "07:32:00");
TOML11_TEST_LEX_ACCEPT(lex_local_time, "07:32:00.999999", "07:32:00.999999");
}

106
tests/test_lex_floating.cpp Normal file
View File

@@ -0,0 +1,106 @@
#define BOOST_TEST_MODULE "test_lex_floating"
#include <boost/test/unit_test.hpp>
#include <toml/lexer.hpp>
#include <limits>
#include "test_lex_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_fractional_valid)
{
TOML11_TEST_LEX_ACCEPT(lex_float, "1.0", "1.0" );
TOML11_TEST_LEX_ACCEPT(lex_float, "0.1", "0.1" );
TOML11_TEST_LEX_ACCEPT(lex_float, "0.001", "0.001" );
TOML11_TEST_LEX_ACCEPT(lex_float, "0.100", "0.100" );
TOML11_TEST_LEX_ACCEPT(lex_float, "+3.14", "+3.14" );
TOML11_TEST_LEX_ACCEPT(lex_float, "-3.14", "-3.14" );
TOML11_TEST_LEX_ACCEPT(lex_float, "3.1415_9265_3589", "3.1415_9265_3589" );
TOML11_TEST_LEX_ACCEPT(lex_float, "+3.1415_9265_3589", "+3.1415_9265_3589");
TOML11_TEST_LEX_ACCEPT(lex_float, "-3.1415_9265_3589", "-3.1415_9265_3589");
TOML11_TEST_LEX_ACCEPT(lex_float, "123_456.789", "123_456.789" );
TOML11_TEST_LEX_ACCEPT(lex_float, "+123_456.789", "+123_456.789" );
TOML11_TEST_LEX_ACCEPT(lex_float, "-123_456.789", "-123_456.789" );
}
BOOST_AUTO_TEST_CASE(test_fractional_invalid)
{
TOML11_TEST_LEX_REJECT(lex_float, "0.");
TOML11_TEST_LEX_REJECT(lex_float, ".0");
TOML11_TEST_LEX_REJECT(lex_float, "01.0");
TOML11_TEST_LEX_REJECT(lex_float, "3,14");
TOML11_TEST_LEX_REJECT(lex_float, "+-1.0");
TOML11_TEST_LEX_REJECT(lex_float, "1._0");
}
BOOST_AUTO_TEST_CASE(test_exponential_valid)
{
TOML11_TEST_LEX_ACCEPT(lex_float, "1e10", "1e10");
TOML11_TEST_LEX_ACCEPT(lex_float, "1e+10", "1e+10");
TOML11_TEST_LEX_ACCEPT(lex_float, "1e-10", "1e-10");
TOML11_TEST_LEX_ACCEPT(lex_float, "+1e10", "+1e10");
TOML11_TEST_LEX_ACCEPT(lex_float, "+1e+10", "+1e+10");
TOML11_TEST_LEX_ACCEPT(lex_float, "+1e-10", "+1e-10");
TOML11_TEST_LEX_ACCEPT(lex_float, "-1e10", "-1e10");
TOML11_TEST_LEX_ACCEPT(lex_float, "-1e+10", "-1e+10");
TOML11_TEST_LEX_ACCEPT(lex_float, "-1e-10", "-1e-10");
TOML11_TEST_LEX_ACCEPT(lex_float, "123e-10", "123e-10");
TOML11_TEST_LEX_ACCEPT(lex_float, "1E10", "1E10");
TOML11_TEST_LEX_ACCEPT(lex_float, "1E+10", "1E+10");
TOML11_TEST_LEX_ACCEPT(lex_float, "1E-10", "1E-10");
TOML11_TEST_LEX_ACCEPT(lex_float, "123E-10", "123E-10");
TOML11_TEST_LEX_ACCEPT(lex_float, "1_2_3E-10", "1_2_3E-10");
TOML11_TEST_LEX_ACCEPT(lex_float, "1_2_3E-1_0", "1_2_3E-1_0");
#ifdef TOML11_USE_UNRELEASED_TOML_FEATURES
BOOST_TEST_MESSAGE("testing an unreleased toml feature: leading zeroes in float exponent part");
// toml-lang/toml master permits leading 0s in exp part (unreleased)
TOML11_TEST_LEX_ACCEPT(lex_float, "1_2_3E-01", "1_2_3E-01");
TOML11_TEST_LEX_ACCEPT(lex_float, "1_2_3E-0_1", "1_2_3E-0_1");
#endif
}
BOOST_AUTO_TEST_CASE(test_exponential_invalid)
{
// accept partially
TOML11_TEST_LEX_ACCEPT(lex_float, "1e1E0", "1e1");
TOML11_TEST_LEX_ACCEPT(lex_float, "1E1e0", "1E1");
}
BOOST_AUTO_TEST_CASE(test_both_valid)
{
TOML11_TEST_LEX_ACCEPT(lex_float, "6.02e23", "6.02e23");
TOML11_TEST_LEX_ACCEPT(lex_float, "6.02e+23", "6.02e+23");
TOML11_TEST_LEX_ACCEPT(lex_float, "1.112_650_06e-17", "1.112_650_06e-17");
#ifdef TOML11_USE_UNRELEASED_TOML_FEATURES
BOOST_TEST_MESSAGE("testing an unreleased toml feature: leading zeroes in float exponent part");
// toml-lang/toml master permits leading 0s in exp part (unreleased)
TOML11_TEST_LEX_ACCEPT(lex_float, "1.0e-07", "1.0e-07");
#endif
}
BOOST_AUTO_TEST_CASE(test_both_invalid)
{
TOML11_TEST_LEX_REJECT(lex_float, "01e1.0");
// accept partially
TOML11_TEST_LEX_ACCEPT(lex_float, "1e1.0", "1e1");
#ifdef TOML11_USE_UNRELEASED_TOML_FEATURES
BOOST_TEST_MESSAGE("testing an unreleased toml feature: leading zeroes in float exponent part");
// toml-lang/toml master permits leading 0s in exp part (unreleased)
TOML11_TEST_LEX_ACCEPT(lex_float, "1.0e_01", "1.0");
TOML11_TEST_LEX_ACCEPT(lex_float, "1.0e0__1", "1.0e0");
#endif
}
BOOST_AUTO_TEST_CASE(test_special_floating_point)
{
TOML11_TEST_LEX_ACCEPT(lex_float, "inf", "inf");
TOML11_TEST_LEX_ACCEPT(lex_float, "+inf", "+inf");
TOML11_TEST_LEX_ACCEPT(lex_float, "-inf", "-inf");
TOML11_TEST_LEX_ACCEPT(lex_float, "nan", "nan");
TOML11_TEST_LEX_ACCEPT(lex_float, "+nan", "+nan");
TOML11_TEST_LEX_ACCEPT(lex_float, "-nan", "-nan");
}

101
tests/test_lex_integer.cpp Normal file
View File

@@ -0,0 +1,101 @@
#define BOOST_TEST_MODULE "test_lex_integer"
#include <boost/test/unit_test.hpp>
#include <toml/lexer.hpp>
#include "test_lex_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_decimal_correct)
{
TOML11_TEST_LEX_ACCEPT(lex_integer, "1234", "1234" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "+1234", "+1234" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "-1234", "-1234" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0", "0" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "1_2_3_4", "1_2_3_4" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "+1_2_3_4", "+1_2_3_4" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "-1_2_3_4", "-1_2_3_4" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "123_456_789", "123_456_789");
}
BOOST_AUTO_TEST_CASE(test_decimal_invalid)
{
TOML11_TEST_LEX_ACCEPT(lex_integer, "123+45", "123");
TOML11_TEST_LEX_ACCEPT(lex_integer, "123-45", "123");
TOML11_TEST_LEX_ACCEPT(lex_integer, "01234", "0");
TOML11_TEST_LEX_ACCEPT(lex_integer, "123__45", "123");
TOML11_TEST_LEX_REJECT(lex_integer, "_1234");
}
BOOST_AUTO_TEST_CASE(test_hex_correct)
{
TOML11_TEST_LEX_ACCEPT(lex_integer, "0xDEADBEEF", "0xDEADBEEF" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0xdeadbeef", "0xdeadbeef" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0xDEADbeef", "0xDEADbeef" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0xDEAD_BEEF", "0xDEAD_BEEF");
TOML11_TEST_LEX_ACCEPT(lex_integer, "0xdead_beef", "0xdead_beef");
TOML11_TEST_LEX_ACCEPT(lex_integer, "0xdead_BEEF", "0xdead_BEEF");
TOML11_TEST_LEX_ACCEPT(lex_integer, "0xFF", "0xFF" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0x00FF", "0x00FF" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0x0000FF", "0x0000FF");
}
BOOST_AUTO_TEST_CASE(test_hex_invalid)
{
TOML11_TEST_LEX_ACCEPT(lex_integer, "0xAPPLE", "0xA");
TOML11_TEST_LEX_ACCEPT(lex_integer, "0xDEAD+BEEF", "0xDEAD");
TOML11_TEST_LEX_ACCEPT(lex_integer, "0xDEAD__BEEF", "0xDEAD");
TOML11_TEST_LEX_REJECT(lex_hex_int, "0x_DEADBEEF");
TOML11_TEST_LEX_REJECT(lex_hex_int, "0x+DEADBEEF");
TOML11_TEST_LEX_REJECT(lex_hex_int, "-0xFF" );
TOML11_TEST_LEX_REJECT(lex_hex_int, "-0x00FF" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0x_DEADBEEF", "0" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0x+DEADBEEF", "0" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "-0xFF" , "-0" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "-0x00FF" , "-0" );
}
BOOST_AUTO_TEST_CASE(test_oct_correct)
{
TOML11_TEST_LEX_ACCEPT(lex_integer, "0o777", "0o777" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0o7_7_7", "0o7_7_7");
TOML11_TEST_LEX_ACCEPT(lex_integer, "0o007", "0o007" );
}
BOOST_AUTO_TEST_CASE(test_oct_invalid)
{
TOML11_TEST_LEX_ACCEPT(lex_integer, "0o77+7", "0o77");
TOML11_TEST_LEX_ACCEPT(lex_integer, "0o1__0", "0o1");
TOML11_TEST_LEX_REJECT(lex_oct_int, "0o800" );
TOML11_TEST_LEX_REJECT(lex_oct_int, "-0o777");
TOML11_TEST_LEX_REJECT(lex_oct_int, "0o+777");
TOML11_TEST_LEX_REJECT(lex_oct_int, "0o_10" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0o800", "0");
TOML11_TEST_LEX_ACCEPT(lex_integer, "-0o777", "-0");
TOML11_TEST_LEX_ACCEPT(lex_integer, "0o+777", "0");
TOML11_TEST_LEX_ACCEPT(lex_integer, "0o_10", "0");
}
BOOST_AUTO_TEST_CASE(test_bin_correct)
{
TOML11_TEST_LEX_ACCEPT(lex_integer, "0b10000", "0b10000" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0b010000", "0b010000" );
TOML11_TEST_LEX_ACCEPT(lex_integer, "0b01_00_00", "0b01_00_00");
TOML11_TEST_LEX_ACCEPT(lex_integer, "0b111111", "0b111111" );
}
BOOST_AUTO_TEST_CASE(test_bin_invalid)
{
TOML11_TEST_LEX_ACCEPT(lex_bin_int, "0b11__11", "0b11");
TOML11_TEST_LEX_ACCEPT(lex_bin_int, "0b11+11" , "0b11");
TOML11_TEST_LEX_REJECT(lex_bin_int, "-0b10000");
TOML11_TEST_LEX_REJECT(lex_bin_int, "0b_1111" );
}

View File

@@ -0,0 +1,53 @@
#define BOOST_TEST_MODULE "lex_key_comment_test"
#include <boost/test/unit_test.hpp>
#include <toml/lexer.hpp>
#include "test_lex_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_bare_key)
{
TOML11_TEST_LEX_ACCEPT(lex_key, "barekey", "barekey");
TOML11_TEST_LEX_ACCEPT(lex_key, "bare-key", "bare-key");
TOML11_TEST_LEX_ACCEPT(lex_key, "bare_key", "bare_key");
TOML11_TEST_LEX_ACCEPT(lex_key, "1234", "1234");
}
BOOST_AUTO_TEST_CASE(test_quoted_key)
{
TOML11_TEST_LEX_ACCEPT(lex_key, "\"127.0.0.1\"", "\"127.0.0.1\"");
TOML11_TEST_LEX_ACCEPT(lex_key, "\"character encoding\"", "\"character encoding\"");
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
TOML11_TEST_LEX_ACCEPT(lex_key, "\"\xCA\x8E\xC7\x9D\xCA\x9E\"",
"\"\xCA\x8E\xC7\x9D\xCA\x9E\"");
#else
TOML11_TEST_LEX_ACCEPT(lex_key, u8"\"ʎǝʞ\"", u8"\"ʎǝʞ\"");
#endif
TOML11_TEST_LEX_ACCEPT(lex_key, "'key2'", "'key2'");
TOML11_TEST_LEX_ACCEPT(lex_key, "'quoted \"value\"'", "'quoted \"value\"'");
}
BOOST_AUTO_TEST_CASE(test_dotted_key)
{
TOML11_TEST_LEX_ACCEPT(lex_key, "physical.color", "physical.color");
TOML11_TEST_LEX_ACCEPT(lex_key, "physical.shape", "physical.shape");
TOML11_TEST_LEX_ACCEPT(lex_key, "x.y", "x.y");
TOML11_TEST_LEX_ACCEPT(lex_key, "x . y", "x . y");
TOML11_TEST_LEX_ACCEPT(lex_key, "x.y.z", "x.y.z");
TOML11_TEST_LEX_ACCEPT(lex_key, "x. y .z", "x. y .z");
TOML11_TEST_LEX_ACCEPT(lex_key, "x .y. z", "x .y. z");
TOML11_TEST_LEX_ACCEPT(lex_key, "x . y . z", "x . y . z");
TOML11_TEST_LEX_ACCEPT(lex_key, "x.y.z.w", "x.y.z.w");
TOML11_TEST_LEX_ACCEPT(lex_key, "x. y .z. w", "x. y .z. w");
TOML11_TEST_LEX_ACCEPT(lex_key, "x . y . z . w", "x . y . z . w");
TOML11_TEST_LEX_ACCEPT(lex_key, "site.\"google.com\"", "site.\"google.com\"");
}
BOOST_AUTO_TEST_CASE(test_comment)
{
TOML11_TEST_LEX_ACCEPT(lex_comment, "# hoge", "# hoge");
TOML11_TEST_LEX_ACCEPT(lex_comment, "# \n", "# ");
TOML11_TEST_LEX_ACCEPT(lex_comment, "# \r\n", "# ");
TOML11_TEST_LEX_ACCEPT(lex_comment, "# # \n", "# # ");
}

114
tests/test_lex_string.cpp Normal file
View File

@@ -0,0 +1,114 @@
#define BOOST_TEST_MODULE "test_lex_string"
#include <boost/test/unit_test.hpp>
#include <toml/lexer.hpp>
#include "test_lex_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_string)
{
TOML11_TEST_LEX_ACCEPT(lex_string,
"\"The quick brown fox jumps over the lazy dog\"",
"\"The quick brown fox jumps over the lazy dog\"");
TOML11_TEST_LEX_ACCEPT(lex_string,
"\'The quick brown fox jumps over the lazy dog\'",
"\'The quick brown fox jumps over the lazy dog\'");
TOML11_TEST_LEX_ACCEPT(lex_ml_basic_string,
"\"\"\"The quick brown fox \\\njumps over the lazy dog\"\"\"",
"\"\"\"The quick brown fox \\\njumps over the lazy dog\"\"\"");
TOML11_TEST_LEX_ACCEPT(lex_ml_literal_string,
"'''The quick brown fox \njumps over the lazy dog'''",
"'''The quick brown fox \njumps over the lazy dog'''");
}
BOOST_AUTO_TEST_CASE(test_basic_string)
{
TOML11_TEST_LEX_ACCEPT(lex_string,
"\"GitHub Cofounder & CEO\\nLikes tater tots and beer.\"",
"\"GitHub Cofounder & CEO\\nLikes tater tots and beer.\"");
TOML11_TEST_LEX_ACCEPT(lex_string,
"\"192.168.1.1\"",
"\"192.168.1.1\"");
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
TOML11_TEST_LEX_ACCEPT(lex_string,
"\"\xE4\xB8\xAD\xE5\x9B\xBD\"",
"\"\xE4\xB8\xAD\xE5\x9B\xBD\"");
#else
TOML11_TEST_LEX_ACCEPT(lex_string,
u8"\"中国\"",
u8"\"中国\"");
#endif
TOML11_TEST_LEX_ACCEPT(lex_string,
"\"You'll hate me after this - #\"",
"\"You'll hate me after this - #\"");
TOML11_TEST_LEX_ACCEPT(lex_string,
"\" And when \\\"'s are in the string, along with # \\\"\"",
"\" And when \\\"'s are in the string, along with # \\\"\"");
}
BOOST_AUTO_TEST_CASE(test_ml_basic_string)
{
TOML11_TEST_LEX_ACCEPT(lex_string,
"\"\"\"\nThe quick brown \\\n\n fox jumps over \\\n the lazy dog.\"\"\"",
"\"\"\"\nThe quick brown \\\n\n fox jumps over \\\n the lazy dog.\"\"\"");
TOML11_TEST_LEX_ACCEPT(lex_string,
"\"\"\"\\\n The quick brown \\\n\n fox jumps over \\\n the lazy dog.\\\n \"\"\"",
"\"\"\"\\\n The quick brown \\\n\n fox jumps over \\\n the lazy dog.\\\n \"\"\"");
TOML11_TEST_LEX_ACCEPT(lex_string,
"\"\"\"Here are two quotation marks: \"\". Simple enough.\"\"\"",
"\"\"\"Here are two quotation marks: \"\". Simple enough.\"\"\"");
TOML11_TEST_LEX_ACCEPT(lex_string,
"\"\"\"Here are three quotation marks: \"\"\\\".\"\"\"",
"\"\"\"Here are three quotation marks: \"\"\\\".\"\"\"");
TOML11_TEST_LEX_ACCEPT(lex_string,
"\"\"\"Here are fifteen quotation marks: \"\"\\\"\"\"\\\"\"\"\\\"\"\"\\\"\"\"\\\".\"\"\"",
"\"\"\"Here are fifteen quotation marks: \"\"\\\"\"\"\\\"\"\"\\\"\"\"\\\"\"\"\\\".\"\"\"");
TOML11_TEST_LEX_ACCEPT(lex_string,
"\"\"\"\"This,\" she said, \"is just a pointless statement.\"\"\"\"",
"\"\"\"\"This,\" she said, \"is just a pointless statement.\"\"\"\"");
}
BOOST_AUTO_TEST_CASE(test_literal_string)
{
TOML11_TEST_LEX_ACCEPT(lex_string,
"'C:\\Users\\nodejs\\templates'",
"'C:\\Users\\nodejs\\templates'");
TOML11_TEST_LEX_ACCEPT(lex_string,
"'\\\\ServerX\\admin$\\system32\\'",
"'\\\\ServerX\\admin$\\system32\\'");
TOML11_TEST_LEX_ACCEPT(lex_string,
"'Tom \"Dubs\" Preston-Werner'",
"'Tom \"Dubs\" Preston-Werner'");
TOML11_TEST_LEX_ACCEPT(lex_string,
"'<\\i\\c*\\s*>'",
"'<\\i\\c*\\s*>'");
}
BOOST_AUTO_TEST_CASE(test_ml_literal_string)
{
TOML11_TEST_LEX_ACCEPT(lex_string,
"'''I [dw]on't need \\d{2} apples'''",
"'''I [dw]on't need \\d{2} apples'''");
TOML11_TEST_LEX_ACCEPT(lex_string,
"'''\nThe first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n'''",
"'''\nThe first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n'''");
TOML11_TEST_LEX_ACCEPT(lex_string,
"''''That's still pointless', she said.'''",
"''''That's still pointless', she said.'''");
TOML11_TEST_LEX_ACCEPT(lex_string,
"'''Here are fifteen quotation marks: \"\"\"\"\"\"\"\"\"\"\"\"\"\"\".'''",
"'''Here are fifteen quotation marks: \"\"\"\"\"\"\"\"\"\"\"\"\"\"\".'''");
TOML11_TEST_LEX_ACCEPT(lex_string,
"''''This,' she said, 'is just a pointless statement.''''",
"''''This,' she said, 'is just a pointless statement.''''");
}

173
tests/test_literals.cpp Normal file
View File

@@ -0,0 +1,173 @@
#define BOOST_TEST_MODULE "test_literals"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <map>
BOOST_AUTO_TEST_CASE(test_file_as_literal)
{
using namespace toml::literals::toml_literals;
{
const toml::value r{{"a", 42}, {"b", "baz"}};
const toml::value v = u8R"(
a = 42
b = "baz"
)"_toml;
BOOST_TEST(r == v);
}
{
const toml::value r{
{"c", 3.14},
{"table", toml::table{{"a", 42}, {"b", "baz"}}}
};
const toml::value v = u8R"(
c = 3.14
[table]
a = 42
b = "baz"
)"_toml;
BOOST_TEST(r == v);
}
{
const toml::value r{
{"table", toml::table{{"a", 42}, {"b", "baz"}}}
};
const toml::value v = u8R"(
[table]
a = 42
b = "baz"
)"_toml;
BOOST_TEST(r == v);
}
{
const toml::value r{
{"array_of_tables", toml::array{toml::table{}}}
};
const toml::value v = u8R"(
[[array_of_tables]]
)"_toml;
BOOST_TEST(r == v);
}
}
BOOST_AUTO_TEST_CASE(test_value_as_literal)
{
using namespace toml::literals::toml_literals;
{
const toml::value v1 = u8"true"_toml;
const toml::value v2 = u8"false"_toml;
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v2.is_boolean());
BOOST_TEST(toml::get<bool>(v1));
BOOST_TEST(!toml::get<bool>(v2));
}
{
const toml::value v1 = u8"123_456"_toml;
const toml::value v2 = u8"0b0010"_toml;
const toml::value v3 = u8"0xDEADBEEF"_toml;
BOOST_TEST(v1.is_integer());
BOOST_TEST(v2.is_integer());
BOOST_TEST(v3.is_integer());
BOOST_TEST(toml::get<toml::integer>(v1) == 123456);
BOOST_TEST(toml::get<toml::integer>(v2) == 2);
BOOST_TEST(toml::get<toml::integer>(v3) == 0xDEADBEEF);
}
{
const toml::value v1 = u8"3.1415"_toml;
const toml::value v2 = u8"6.02e+23"_toml;
BOOST_TEST(v1.is_floating());
BOOST_TEST(v2.is_floating());
BOOST_TEST(toml::get<double>(v1) == 3.1415, boost::test_tools::tolerance(0.00001));
BOOST_TEST(toml::get<double>(v2) == 6.02e23, boost::test_tools::tolerance(0.0001));
}
{
const toml::value v1 = u8R"("foo")"_toml;
const toml::value v2 = u8R"('foo')"_toml;
const toml::value v3 = u8R"("""foo""")"_toml;
const toml::value v4 = u8R"('''foo''')"_toml;
BOOST_TEST(v1.is_string());
BOOST_TEST(v2.is_string());
BOOST_TEST(v3.is_string());
BOOST_TEST(v4.is_string());
BOOST_TEST(toml::get<std::string>(v1) == "foo");
BOOST_TEST(toml::get<std::string>(v2) == "foo");
BOOST_TEST(toml::get<std::string>(v3) == "foo");
BOOST_TEST(toml::get<std::string>(v4) == "foo");
}
{
{
const toml::value v1 = u8R"([1,2,3])"_toml;
BOOST_TEST(v1.is_array());
const bool result = (toml::get<std::vector<int>>(v1) == std::vector<int>{1,2,3});
BOOST_TEST(result);
}
{
const toml::value v2 = u8R"([1,])"_toml;
BOOST_TEST(v2.is_array());
const bool result = (toml::get<std::vector<int>>(v2) == std::vector<int>{1});
BOOST_TEST(result);
}
{
const toml::value v3 = u8R"([[1,]])"_toml;
BOOST_TEST(v3.is_array());
const bool result = (toml::get<std::vector<int>>(toml::get<toml::array>(v3).front()) == std::vector<int>{1});
BOOST_TEST(result);
}
{
const toml::value v4 = u8R"([[1],])"_toml;
BOOST_TEST(v4.is_array());
const bool result = (toml::get<std::vector<int>>(toml::get<toml::array>(v4).front()) == std::vector<int>{1});
BOOST_TEST(result);
}
}
{
const toml::value v1 = u8R"({a = 42})"_toml;
BOOST_TEST(v1.is_table());
const bool result = toml::get<std::map<std::string,int>>(v1) ==
std::map<std::string,int>{{"a", 42}};
BOOST_TEST(result);
}
{
const toml::value v1 = u8"1979-05-27"_toml;
BOOST_TEST(v1.is_local_date());
BOOST_TEST(toml::get<toml::local_date>(v1) ==
toml::local_date(1979, toml::month_t::May, 27));
}
{
const toml::value v1 = u8"12:00:00"_toml;
BOOST_TEST(v1.is_local_time());
const bool result = toml::get<std::chrono::hours>(v1) == std::chrono::hours(12);
BOOST_TEST(result);
}
{
const toml::value v1 = u8"1979-05-27T07:32:00"_toml;
BOOST_TEST(v1.is_local_datetime());
BOOST_TEST(toml::get<toml::local_datetime>(v1) ==
toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0)));
}
{
const toml::value v1 = "1979-05-27T07:32:00Z"_toml;
BOOST_TEST(v1.is_offset_datetime());
BOOST_TEST(toml::get<toml::offset_datetime>(v1) ==
toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0), toml::time_offset(0, 0)));
}
}

View File

@@ -0,0 +1,11 @@
#include <toml.hpp>
int read_a(const toml::table&);
int main()
{
const std::string content("a = 0");
std::istringstream iss(content);
const auto data = toml::parse(iss, "test_multiple_translation_unit.toml");
return read_a(toml::get<toml::table>(data));
}

View File

@@ -0,0 +1,6 @@
#include <toml.hpp>
int read_a(const toml::table& t)
{
return toml::get<int>(t.at("a"));
}

174
tests/test_parse_array.cpp Normal file
View File

@@ -0,0 +1,174 @@
#define BOOST_TEST_MODULE "parse_array<toml::value>_test"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/parser.hpp>
#include "test_parse_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_oneline_array)
{
TOML11_TEST_PARSE_EQUAL(parse_array<toml::value>, "[]", array());
{
array a(5);
a[0] = toml::value(3); a[1] = toml::value(1); a[2] = toml::value(4);
a[3] = toml::value(1); a[4] = toml::value(5);
TOML11_TEST_PARSE_EQUAL(parse_array<toml::value>, "[3,1,4,1,5]", a);
}
{
array a(3);
a[0] = toml::value("foo"); a[1] = toml::value("bar");
a[2] = toml::value("baz");
TOML11_TEST_PARSE_EQUAL(parse_array<toml::value>, "[\"foo\", \"bar\", \"baz\"]", a);
}
{
array a(5);
a[0] = toml::value(3); a[1] = toml::value(1); a[2] = toml::value(4);
a[3] = toml::value(1); a[4] = toml::value(5);
TOML11_TEST_PARSE_EQUAL(parse_array<toml::value>, "[3,1,4,1,5,]", a);
}
{
array a(3);
a[0] = toml::value("foo"); a[1] = toml::value("bar");
a[2] = toml::value("baz");
TOML11_TEST_PARSE_EQUAL(parse_array<toml::value>, "[\"foo\", \"bar\", \"baz\",]", a);
}
}
BOOST_AUTO_TEST_CASE(test_oneline_array_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[]", toml::value(array()));
{
array a(5);
a[0] = toml::value(3); a[1] = toml::value(1); a[2] = toml::value(4);
a[3] = toml::value(1); a[4] = toml::value(5);
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[3,1,4,1,5]", toml::value(a));
}
{
array a(3);
a[0] = toml::value("foo"); a[1] = toml::value("bar");
a[2] = toml::value("baz");
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[\"foo\", \"bar\", \"baz\"]", toml::value(a));
}
{
array a(5);
a[0] = toml::value(3); a[1] = toml::value(1); a[2] = toml::value(4);
a[3] = toml::value(1); a[4] = toml::value(5);
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[3,1,4,1,5,]", toml::value(a));
}
{
array a(3);
a[0] = toml::value("foo"); a[1] = toml::value("bar");
a[2] = toml::value("baz");
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[\"foo\", \"bar\", \"baz\",]", toml::value(a));
}
}
BOOST_AUTO_TEST_CASE(test_multiline_array)
{
TOML11_TEST_PARSE_EQUAL(parse_array<toml::value>, "[\n#comment\n]", array());
{
array a(5);
a[0] = toml::value(3); a[1] = toml::value(1); a[2] = toml::value(4);
a[3] = toml::value(1); a[4] = toml::value(5);
TOML11_TEST_PARSE_EQUAL(parse_array<toml::value>, "[3,\n1,\n4,\n1,\n5]", a);
}
{
array a(3);
a[0] = toml::value("foo"); a[1] = toml::value("bar");
a[2] = toml::value("baz");
TOML11_TEST_PARSE_EQUAL(parse_array<toml::value>, "[\"foo\",\n\"bar\",\n\"baz\"]", a);
}
{
array a(5);
a[0] = toml::value(3); a[1] = toml::value(1); a[2] = toml::value(4);
a[3] = toml::value(1); a[4] = toml::value(5);
TOML11_TEST_PARSE_EQUAL(parse_array<toml::value>, "[3,#comment\n1,#comment\n4,#comment\n1,#comment\n5]", a);
}
{
array a(3);
a[0] = toml::value("foo"); a[1] = toml::value("b#r");
a[2] = toml::value("b#z");
TOML11_TEST_PARSE_EQUAL(parse_array<toml::value>, "[\"foo\",#comment\n\"b#r\",#comment\n\"b#z\"#comment\n]", a);
}
}
BOOST_AUTO_TEST_CASE(test_multiline_array_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[\n#comment\n]", toml::value(array()));
{
array a(5);
a[0] = toml::value(3); a[1] = toml::value(1); a[2] = toml::value(4);
a[3] = toml::value(1); a[4] = toml::value(5);
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[3,\n1,\n4,\n1,\n5]", toml::value(a));
}
{
array a(3);
a[0] = toml::value("foo"); a[1] = toml::value("bar");
a[2] = toml::value("baz");
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[\"foo\",\n\"bar\",\n\"baz\"]", toml::value(a));
}
{
array a(5);
a[0] = toml::value(3); a[1] = toml::value(1); a[2] = toml::value(4);
a[3] = toml::value(1); a[4] = toml::value(5);
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[3,#comment\n1,#comment\n4,#comment\n1,#comment\n5]", toml::value(a));
}
{
array a(3);
a[0] = toml::value("foo"); a[1] = toml::value("b#r");
a[2] = toml::value("b#z");
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[\"foo\",#comment\n\"b#r\",#comment\n\"b#z\"#comment\n]", toml::value(a));
}
}
BOOST_AUTO_TEST_CASE(test_heterogeneous_array)
{
#ifndef TOML11_USE_UNRELEASED_TOML_FEATURES
BOOST_TEST_MESSAGE("In strict TOML v0.5.0, heterogeneous arrays are not allowed.");
#else
{
array a(5);
a[0] = toml::value("foo");
a[1] = toml::value(3.14);
a[2] = toml::value(42);
a[3] = toml::value{toml::value("array"), toml::value("of"), toml::value("hetero-array"), toml::value(1)};
a[4] = toml::value{{"key", "value"}};
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[\"foo\", 3.14, 42, [\"array\", \"of\", \"hetero-array\", 1], {key = \"value\"}]", toml::value(a));
}
{
array a(5);
a[0] = toml::value("foo");
a[1] = toml::value(3.14);
a[2] = toml::value(42);
a[3] = toml::value{toml::value("array"), toml::value("of"), toml::value("hetero-array"), toml::value(1)};
a[4] = toml::value{{"key", "value"}};
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[\"foo\",\n 3.14,\n 42,\n [\"array\", \"of\", \"hetero-array\", 1],\n {key = \"value\"},\n]", toml::value(a));
}
{
array a(5);
a[0] = toml::value("foo");
a[1] = toml::value(3.14);
a[2] = toml::value(42);
a[3] = toml::value{toml::value("array"), toml::value("of"), toml::value("hetero-array"), toml::value(1)};
a[4] = toml::value{{"key", "value"}};
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[\"foo\",#comment\n 3.14,#comment\n 42,#comment\n [\"array\", \"of\", \"hetero-array\", 1],#comment\n {key = \"value\"},#comment\n]#comment", toml::value(a));
}
{
array a(5);
a[0] = toml::value("foo");
a[1] = toml::value(3.14);
a[2] = toml::value(42);
a[3] = toml::value{toml::value("array"), toml::value("of"), toml::value("hetero-array"), toml::value(1)};
a[4] = toml::value{{"key", "value"}};
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "[\"foo\",\n 3.14,\n 42,\n [\"array\",\n \"of\",\n \"hetero-array\",\n 1],\n {key = \"value\"},\n]", toml::value(a));
}
#endif
}

37
tests/test_parse_aux.hpp Normal file
View File

@@ -0,0 +1,37 @@
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <toml.hpp>
// some of the parsers returns not only a value but also a region.
#define TOML11_TEST_PARSE_EQUAL(psr, tkn, expct) \
do { \
const std::string token(tkn); \
toml::detail::location<std::string> loc("test", token); \
const auto result = psr(loc); \
BOOST_TEST(result.is_ok()); \
if(result.is_ok()){ \
BOOST_TEST(result.unwrap().first == expct); \
} else { \
std::cerr << "parser " << #psr << " failed with input `"; \
std::cerr << token << "`.\n"; \
std::cerr << "reason: " << result.unwrap_err() << '\n'; \
} \
} while(false); \
/**/
#define TOML11_TEST_PARSE_EQUAL_VALUE(psr, tkn, expct) \
do { \
const std::string token(tkn); \
toml::detail::location<std::string> loc("test", token); \
const auto result = psr(loc); \
BOOST_TEST(result.is_ok()); \
if(result.is_ok()){ \
BOOST_TEST(result.unwrap() == expct); \
} else { \
std::cerr << "parse_value failed with input `"; \
std::cerr << token << "`.\n"; \
std::cerr << "reason: " << result.unwrap_err() << '\n'; \
} \
} while(false); \
/**/

View File

@@ -0,0 +1,24 @@
#define BOOST_TEST_MODULE "test_parse_boolean"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/parser.hpp>
#include "test_parse_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_boolean)
{
TOML11_TEST_PARSE_EQUAL(parse_boolean, "true", true);
TOML11_TEST_PARSE_EQUAL(parse_boolean, "false", false);
}
BOOST_AUTO_TEST_CASE(test_boolean_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "true", toml::value( true));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "false", toml::value(false));
}

View File

@@ -0,0 +1,133 @@
#define BOOST_TEST_MODULE "parse_datetime_test"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/parser.hpp>
#include "test_parse_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_time)
{
TOML11_TEST_PARSE_EQUAL(parse_local_time, "07:32:00", toml::local_time(7, 32, 0));
TOML11_TEST_PARSE_EQUAL(parse_local_time, "07:32:00.99", toml::local_time(7, 32, 0, 990, 0));
TOML11_TEST_PARSE_EQUAL(parse_local_time, "07:32:00.999", toml::local_time(7, 32, 0, 999, 0));
TOML11_TEST_PARSE_EQUAL(parse_local_time, "07:32:00.999999", toml::local_time(7, 32, 0, 999, 999));
}
BOOST_AUTO_TEST_CASE(test_time_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "07:32:00", toml::value(toml::local_time(7, 32, 0)));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "07:32:00.99", toml::value(toml::local_time(7, 32, 0, 990, 0)));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "07:32:00.999", toml::value(toml::local_time(7, 32, 0, 999, 0)));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "07:32:00.999999", toml::value(toml::local_time(7, 32, 0, 999, 999)));
}
BOOST_AUTO_TEST_CASE(test_date)
{
TOML11_TEST_PARSE_EQUAL(parse_local_date, "1979-05-27",
toml::local_date(1979, toml::month_t::May, 27));
}
BOOST_AUTO_TEST_CASE(test_date_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27",
value(toml::local_date(1979, toml::month_t::May, 27)));
}
BOOST_AUTO_TEST_CASE(test_datetime)
{
TOML11_TEST_PARSE_EQUAL(parse_local_datetime, "1979-05-27T07:32:00",
toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0)));
TOML11_TEST_PARSE_EQUAL(parse_local_datetime, "1979-05-27T07:32:00.99",
toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 990, 0)));
TOML11_TEST_PARSE_EQUAL(parse_local_datetime, "1979-05-27T07:32:00.999999",
toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 999, 999)));
TOML11_TEST_PARSE_EQUAL(parse_local_datetime, "1979-05-27t07:32:00",
toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0)));
TOML11_TEST_PARSE_EQUAL(parse_local_datetime, "1979-05-27t07:32:00.99",
toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 990, 0)));
TOML11_TEST_PARSE_EQUAL(parse_local_datetime, "1979-05-27t07:32:00.999999",
toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 999, 999)));
TOML11_TEST_PARSE_EQUAL(parse_local_datetime, "1979-05-27 07:32:00",
toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0)));
TOML11_TEST_PARSE_EQUAL(parse_local_datetime, "1979-05-27 07:32:00.99",
toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 990, 0)));
TOML11_TEST_PARSE_EQUAL(parse_local_datetime, "1979-05-27 07:32:00.999999",
toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 999, 999)));
}
BOOST_AUTO_TEST_CASE(test_datetime_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27T07:32:00",
toml::value(toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27T07:32:00.99",
toml::value(toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 990, 0))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27T07:32:00.999999",
toml::value(toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 999, 999))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27t07:32:00",
toml::value(toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27t07:32:00.99",
toml::value(toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 990, 0))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27t07:32:00.999999",
toml::value(toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 999, 999))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27 07:32:00",
toml::value(toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27 07:32:00.99",
toml::value(toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 990, 0))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27 07:32:00.999999",
toml::value(toml::local_datetime(toml::local_date(1979, toml::month_t::May, 27), toml::local_time(7, 32, 0, 999, 999))));
}
BOOST_AUTO_TEST_CASE(test_offset_datetime)
{
TOML11_TEST_PARSE_EQUAL(parse_offset_datetime, "1979-05-27T07:32:00Z",
toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0), toml::time_offset(0, 0)));
TOML11_TEST_PARSE_EQUAL(parse_offset_datetime, "1979-05-27T07:32:00.99Z",
toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0, 990, 0), toml::time_offset(0, 0)));
TOML11_TEST_PARSE_EQUAL(parse_offset_datetime, "1979-05-27T07:32:00.999999Z",
toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0, 999, 999), toml::time_offset(0, 0)));
TOML11_TEST_PARSE_EQUAL(parse_offset_datetime, "1979-05-27T07:32:00+09:00",
toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0), toml::time_offset(9, 0)));
TOML11_TEST_PARSE_EQUAL(parse_offset_datetime, "1979-05-27T07:32:00.99+09:00",
toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0, 990, 0), toml::time_offset(9, 0)));
TOML11_TEST_PARSE_EQUAL(parse_offset_datetime, "1979-05-27T07:32:00.999999+09:00",
toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0, 999, 999), toml::time_offset(9, 0)));
}
BOOST_AUTO_TEST_CASE(test_offset_datetime_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27T07:32:00Z",
toml::value(toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0), toml::time_offset(0, 0))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27T07:32:00.99Z",
toml::value(toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0, 990, 0), toml::time_offset(0, 0))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27T07:32:00.999999Z",
toml::value(toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0, 999, 999), toml::time_offset(0, 0))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27T07:32:00+09:00",
toml::value(toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0), toml::time_offset(9, 0))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27T07:32:00.99+09:00",
toml::value(toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0, 990, 0), toml::time_offset(9, 0))));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1979-05-27T07:32:00.999999+09:00",
toml::value(toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0, 999, 999), toml::time_offset(9, 0))));
}

View File

@@ -8,187 +8,884 @@
#include <toml.hpp>
#include <iostream>
#include <fstream>
#include <map>
#include <deque>
BOOST_AUTO_TEST_CASE(test_example)
{
const auto data = toml::parse("toml/tests/example.toml");
BOOST_CHECK_EQUAL(toml::get<std::string>(data.at("title")), "TOML Example");
toml::Table owner = toml::get<toml::Table>(data.at("owner"));
BOOST_TEST(toml::find<std::string>(data, "title") == "TOML Example");
const auto& owner = toml::find(data, "owner");
{
BOOST_CHECK_EQUAL(toml::get<std::string>(owner.at("name")), "Tom Preston-Werner");
BOOST_CHECK_EQUAL(toml::get<std::string>(owner.at("organization")), "GitHub");
BOOST_CHECK_EQUAL(toml::get<std::string>(owner.at("bio")),
BOOST_TEST(toml::find<std::string>(owner, "name") == "Tom Preston-Werner");
BOOST_TEST(toml::find<std::string>(owner, "organization") == "GitHub");
BOOST_TEST(toml::find<std::string>(owner, "bio") ==
"GitHub Cofounder & CEO\nLikes tater tots and beer.");
BOOST_CHECK_EQUAL(toml::get<toml::Datetime>(owner.at("dob")),
toml::Datetime(1979, 5, 27, 7, 32, 0, 0, 0, 0, 0));
BOOST_TEST(toml::find<toml::offset_datetime>(owner, "dob") ==
toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0), toml::time_offset(0, 0)));
}
toml::Table database = toml::get<toml::Table>(data.at("database"));
const auto& database = toml::find(data, "database");
{
BOOST_CHECK_EQUAL(toml::get<std::string>(database.at("server")), "192.168.1.1");
BOOST_TEST(toml::find<std::string>(database, "server") == "192.168.1.1");
const std::vector<int> expected_ports{8001, 8001, 8002};
BOOST_CHECK(toml::get<std::vector<int>>(database.at("ports")) == expected_ports);
BOOST_CHECK_EQUAL(toml::get<int>(database.at("connection_max")), 5000);
BOOST_CHECK_EQUAL(toml::get<bool>(database.at("enabled")), true);
BOOST_CHECK(toml::find<std::vector<int>>(database, "ports") == expected_ports);
BOOST_TEST(toml::find<int >(database, "connection_max") == 5000);
BOOST_TEST(toml::find<bool>(database, "enabled") == true);
}
toml::Table servers = toml::get<toml::Table>(data.at("servers"));
const auto& servers = toml::find(data, "servers");
{
toml::Table alpha = toml::get<toml::Table>(servers.at("alpha"));
BOOST_CHECK_EQUAL(toml::get<std::string>(alpha.at("ip")), "10.0.0.1");
BOOST_CHECK_EQUAL(toml::get<std::string>(alpha.at("dc")), "eqdc10");
toml::table alpha = toml::find<toml::table>(servers, "alpha");
BOOST_TEST(toml::get<std::string>(alpha.at("ip")) == "10.0.0.1");
BOOST_TEST(toml::get<std::string>(alpha.at("dc")) == "eqdc10");
toml::Table beta = toml::get<toml::Table>(servers.at("beta"));
BOOST_CHECK_EQUAL(toml::get<std::string>(beta.at("ip")), "10.0.0.2");
BOOST_CHECK_EQUAL(toml::get<std::string>(beta.at("dc")), "eqdc10");
BOOST_CHECK_EQUAL(toml::get<std::string>(beta.at("country")), "\xE4\xB8\xAD\xE5\x9B\xBD");
toml::table beta = toml::find<toml::table>(servers, "beta");
BOOST_TEST(toml::get<std::string>(beta.at("ip")) == "10.0.0.2");
BOOST_TEST(toml::get<std::string>(beta.at("dc")) == "eqdc10");
BOOST_TEST(toml::get<std::string>(beta.at("country")) == "\xE4\xB8\xAD\xE5\x9B\xBD");
}
toml::Table clients = toml::get<toml::Table>(data.at("clients"));
const auto& clients = toml::find(data, "clients");
{
toml::Array clients_data = toml::get<toml::Array>(clients.at("data"));
toml::array clients_data = toml::find<toml::array>(clients, "data");
std::vector<std::string> expected_name{"gamma", "delta"};
BOOST_CHECK(toml::get<std::vector<std::string>>(clients_data.at(0)) ==
expected_name);
BOOST_CHECK(toml::get<std::vector<std::string>>(clients_data.at(0)) == expected_name);
std::vector<int> expected_number{1, 2};
BOOST_CHECK(toml::get<std::vector<int>>(clients_data.at(1)) ==
expected_number);
BOOST_CHECK(toml::get<std::vector<int>>(clients_data.at(1)) == expected_number);
std::vector<std::string> expected_hosts{"alpha", "omega"};
BOOST_CHECK(toml::get<std::vector<std::string>>(clients.at("hosts")) ==
expected_hosts);
BOOST_CHECK(toml::find<std::vector<std::string>>(clients, "hosts") == expected_hosts);
}
std::vector<toml::Table> products =
toml::get<std::vector<toml::Table>>(data.at("products"));
std::vector<toml::table> products =
toml::find<std::vector<toml::table>>(data, "products");
{
BOOST_CHECK_EQUAL(toml::get<std::string>(products.at(0).at("name")),
"Hammer");
BOOST_CHECK_EQUAL(toml::get<std::int64_t>(products.at(0).at("sku")),
738594937);
BOOST_TEST(toml::get<std::string>(products.at(0).at("name")) == "Hammer");
BOOST_TEST(toml::get<std::int64_t>(products.at(0).at("sku")) == 738594937);
BOOST_CHECK_EQUAL(toml::get<std::string>(products.at(1).at("name")),
"Nail");
BOOST_CHECK_EQUAL(toml::get<std::int64_t>(products.at(1).at("sku")),
284758393);
BOOST_CHECK_EQUAL(toml::get<std::string>(products.at(1).at("color")),
"gray");
BOOST_TEST(toml::get<std::string>(products.at(1).at("name")) == "Nail");
BOOST_TEST(toml::get<std::int64_t>(products.at(1).at("sku")) == 284758393);
BOOST_TEST(toml::get<std::string>(products.at(1).at("color")) == "gray");
}
}
BOOST_AUTO_TEST_CASE(test_example_stream)
{
std::ifstream ifs("toml/tests/example.toml");
std::ifstream ifs("toml/tests/example.toml", std::ios::binary);
const auto data = toml::parse(ifs);
BOOST_CHECK_EQUAL(toml::get<std::string>(data.at("title")), "TOML Example");
toml::Table owner = toml::get<toml::Table>(data.at("owner"));
BOOST_TEST(toml::find<std::string>(data, "title") == "TOML Example");
const auto& owner = toml::find(data, "owner");
{
BOOST_CHECK_EQUAL(toml::get<std::string>(owner.at("name")), "Tom Preston-Werner");
BOOST_CHECK_EQUAL(toml::get<std::string>(owner.at("organization")), "GitHub");
BOOST_CHECK_EQUAL(toml::get<std::string>(owner.at("bio")),
BOOST_TEST(toml::find<std::string>(owner, "name") == "Tom Preston-Werner");
BOOST_TEST(toml::find<std::string>(owner, "organization") == "GitHub");
BOOST_TEST(toml::find<std::string>(owner, "bio") ==
"GitHub Cofounder & CEO\nLikes tater tots and beer.");
BOOST_CHECK_EQUAL(toml::get<toml::Datetime>(owner.at("dob")),
toml::Datetime(1979, 5, 27, 7, 32, 0, 0, 0, 0, 0));
BOOST_TEST(toml::find<toml::offset_datetime>(owner, "dob") ==
toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0), toml::time_offset(0, 0)));
}
toml::Table database = toml::get<toml::Table>(data.at("database"));
const auto& database = toml::find(data, "database");
{
BOOST_CHECK_EQUAL(toml::get<std::string>(database.at("server")), "192.168.1.1");
BOOST_TEST(toml::find<std::string>(database, "server") == "192.168.1.1");
const std::vector<int> expected_ports{8001, 8001, 8002};
BOOST_CHECK(toml::get<std::vector<int>>(database.at("ports")) == expected_ports);
BOOST_CHECK_EQUAL(toml::get<int>(database.at("connection_max")), 5000);
BOOST_CHECK_EQUAL(toml::get<bool>(database.at("enabled")), true);
BOOST_CHECK(toml::find<std::vector<int>>(database, "ports") == expected_ports);
BOOST_TEST(toml::find<int >(database, "connection_max") == 5000);
BOOST_TEST(toml::find<bool>(database, "enabled") == true);
}
toml::Table servers = toml::get<toml::Table>(data.at("servers"));
const auto& servers = toml::find(data, "servers");
{
toml::Table alpha = toml::get<toml::Table>(servers.at("alpha"));
BOOST_CHECK_EQUAL(toml::get<std::string>(alpha.at("ip")), "10.0.0.1");
BOOST_CHECK_EQUAL(toml::get<std::string>(alpha.at("dc")), "eqdc10");
toml::table alpha = toml::find<toml::table>(servers, "alpha");
BOOST_TEST(toml::get<std::string>(alpha.at("ip")) == "10.0.0.1");
BOOST_TEST(toml::get<std::string>(alpha.at("dc")) == "eqdc10");
toml::Table beta = toml::get<toml::Table>(servers.at("beta"));
BOOST_CHECK_EQUAL(toml::get<std::string>(beta.at("ip")), "10.0.0.2");
BOOST_CHECK_EQUAL(toml::get<std::string>(beta.at("dc")), "eqdc10");
BOOST_CHECK_EQUAL(toml::get<std::string>(beta.at("country")), "\xE4\xB8\xAD\xE5\x9B\xBD");
toml::table beta = toml::find<toml::table>(servers, "beta");
BOOST_TEST(toml::get<std::string>(beta.at("ip")) == "10.0.0.2");
BOOST_TEST(toml::get<std::string>(beta.at("dc")) == "eqdc10");
BOOST_TEST(toml::get<std::string>(beta.at("country")) == "\xE4\xB8\xAD\xE5\x9B\xBD");
}
toml::Table clients = toml::get<toml::Table>(data.at("clients"));
const auto& clients = toml::find(data, "clients");
{
toml::Array clients_data = toml::get<toml::Array>(clients.at("data"));
toml::array clients_data = toml::find<toml::array>(clients, "data");
std::vector<std::string> expected_name{"gamma", "delta"};
BOOST_CHECK(toml::get<std::vector<std::string>>(clients_data.at(0)) ==
expected_name);
BOOST_CHECK(toml::get<std::vector<std::string>>(clients_data.at(0)) == expected_name);
std::vector<int> expected_number{1, 2};
BOOST_CHECK(toml::get<std::vector<int>>(clients_data.at(1)) ==
expected_number);
BOOST_CHECK(toml::get<std::vector<int>>(clients_data.at(1)) == expected_number);
std::vector<std::string> expected_hosts{"alpha", "omega"};
BOOST_CHECK(toml::get<std::vector<std::string>>(clients.at("hosts")) ==
expected_hosts);
BOOST_CHECK(toml::find<std::vector<std::string>>(clients, "hosts") == expected_hosts);
}
std::vector<toml::Table> products =
toml::get<std::vector<toml::Table>>(data.at("products"));
std::vector<toml::table> products =
toml::find<std::vector<toml::table>>(data, "products");
{
BOOST_CHECK_EQUAL(toml::get<std::string>(products.at(0).at("name")),
BOOST_TEST(toml::get<std::string>(products.at(0).at("name")) ==
"Hammer");
BOOST_CHECK_EQUAL(toml::get<std::int64_t>(products.at(0).at("sku")),
BOOST_TEST(toml::get<std::int64_t>(products.at(0).at("sku")) ==
738594937);
BOOST_CHECK_EQUAL(toml::get<std::string>(products.at(1).at("name")),
BOOST_TEST(toml::get<std::string>(products.at(1).at("name")) ==
"Nail");
BOOST_CHECK_EQUAL(toml::get<std::int64_t>(products.at(1).at("sku")),
BOOST_TEST(toml::get<std::int64_t>(products.at(1).at("sku")) ==
284758393);
BOOST_CHECK_EQUAL(toml::get<std::string>(products.at(1).at("color")),
BOOST_TEST(toml::get<std::string>(products.at(1).at("color")) ==
"gray");
}
}
BOOST_AUTO_TEST_CASE(test_fruit)
{
const auto data = toml::parse("toml/tests/fruit.toml");
const auto blah = toml::get<std::vector<toml::Table>>(
toml::get<toml::Table>(data.at("fruit")).at("blah"));
BOOST_CHECK_EQUAL(toml::get<std::string>(blah.at(0).at("name")), "apple");
BOOST_CHECK_EQUAL(toml::get<std::string>(blah.at(1).at("name")), "banana");
const auto blah = toml::find<toml::array>(toml::find(data, "fruit"), "blah");
BOOST_TEST(toml::find<std::string>(blah.at(0), "name") == "apple");
BOOST_TEST(toml::find<std::string>(blah.at(1), "name") == "banana");
{
const auto physical = toml::get<toml::Table>(blah.at(0).at("physical"));
BOOST_CHECK_EQUAL(toml::get<std::string>(physical.at("color")), "red");
BOOST_CHECK_EQUAL(toml::get<std::string>(physical.at("shape")), "round");
const auto physical = toml::find(blah.at(0), "physical");
BOOST_TEST(toml::find<std::string>(physical, "color") == "red");
BOOST_TEST(toml::find<std::string>(physical, "shape") == "round");
}
{
const auto physical = toml::get<toml::Table>(blah.at(1).at("physical"));
BOOST_CHECK_EQUAL(toml::get<std::string>(physical.at("color")), "yellow");
BOOST_CHECK_EQUAL(toml::get<std::string>(physical.at("shape")), "bent");
const auto physical = toml::find(blah.at(1), "physical");
BOOST_TEST(toml::find<std::string>(physical, "color") == "yellow");
BOOST_TEST(toml::find<std::string>(physical, "shape") == "bent");
}
}
BOOST_AUTO_TEST_CASE(test_hard_example)
{
const auto data = toml::parse("toml/tests/hard_example.toml");
const auto the = toml::get<toml::Table>(data.at("the"));
BOOST_CHECK_EQUAL(toml::get<std::string>(the.at("test_string")),
const auto the = toml::find(data, "the");
BOOST_TEST(toml::find<std::string>(the, "test_string") ==
"You'll hate me after this - #");
const auto hard = toml::get<toml::Table>(the.at("hard"));
const auto hard = toml::find(the, "hard");
const std::vector<std::string> expected_the_hard_test_array{"] ", " # "};
BOOST_CHECK(toml::get<std::vector<std::string>>(hard.at("test_array")) ==
BOOST_CHECK(toml::find<std::vector<std::string>>(hard, "test_array") ==
expected_the_hard_test_array);
const std::vector<std::string> expected_the_hard_test_array2{
"Test #11 ]proved that", "Experiment #9 was a success"};
BOOST_CHECK(toml::get<std::vector<std::string>>(hard.at("test_array2")) ==
BOOST_CHECK(toml::find<std::vector<std::string>>(hard, "test_array2") ==
expected_the_hard_test_array2);
BOOST_CHECK_EQUAL(toml::get<std::string>(hard.at("another_test_string")),
BOOST_TEST(toml::find<std::string>(hard, "another_test_string") ==
" Same thing, but with a string #");
BOOST_CHECK_EQUAL(toml::get<std::string>(hard.at("harder_test_string")),
BOOST_TEST(toml::find<std::string>(hard, "harder_test_string") ==
" And when \"'s are in the string, along with # \"");
const auto bit = toml::get<toml::Table>(hard.at("bit#"));
BOOST_CHECK_EQUAL(toml::get<std::string>(bit.at("what?")),
const auto bit = toml::find(hard, "bit#");
BOOST_TEST(toml::find<std::string>(bit, "what?") ==
"You don't think some user won't do that?");
const std::vector<std::string> expected_multi_line_array{"]"};
BOOST_CHECK(toml::get<std::vector<std::string>>(bit.at("multi_line_array")) ==
BOOST_CHECK(toml::find<std::vector<std::string>>(bit, "multi_line_array") ==
expected_multi_line_array);
}
BOOST_AUTO_TEST_CASE(test_hard_example_comment)
{
const auto data = toml::parse<toml::preserve_comments>("toml/tests/hard_example.toml");
const auto the = toml::find(data, "the");
BOOST_TEST(toml::find<std::string>(the, "test_string") ==
"You'll hate me after this - #");
const auto hard = toml::find(the, "hard");
const std::vector<std::string> expected_the_hard_test_array{"] ", " # "};
BOOST_CHECK(toml::find<std::vector<std::string>>(hard, "test_array") ==
expected_the_hard_test_array);
const std::vector<std::string> expected_the_hard_test_array2{
"Test #11 ]proved that", "Experiment #9 was a success"};
BOOST_CHECK(toml::find<std::vector<std::string>>(hard, "test_array2") ==
expected_the_hard_test_array2);
BOOST_TEST(toml::find<std::string>(hard, "another_test_string") ==
" Same thing, but with a string #");
BOOST_TEST(toml::find<std::string>(hard, "harder_test_string") ==
" And when \"'s are in the string, along with # \"");
const auto bit = toml::find(hard, "bit#");
BOOST_TEST(toml::find<std::string>(bit, "what?") ==
"You don't think some user won't do that?");
const std::vector<std::string> expected_multi_line_array{"]"};
BOOST_CHECK(toml::find<std::vector<std::string>>(bit, "multi_line_array") ==
expected_multi_line_array);
}
BOOST_AUTO_TEST_CASE(test_example_preserve_comment)
{
const auto data = toml::parse<toml::preserve_comments>("toml/tests/example.toml");
BOOST_TEST(toml::find<std::string>(data, "title") == "TOML Example");
const auto& owner = toml::find(data, "owner");
{
BOOST_TEST(toml::find<std::string>(owner, "name") == "Tom Preston-Werner");
BOOST_TEST(toml::find<std::string>(owner, "organization") == "GitHub");
BOOST_TEST(toml::find<std::string>(owner, "bio") ==
"GitHub Cofounder & CEO\nLikes tater tots and beer.");
BOOST_TEST(toml::find<toml::offset_datetime>(owner, "dob") ==
toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0), toml::time_offset(0, 0)));
BOOST_TEST(toml::find(owner, "dob").comments().at(0) ==
" First class dates? Why not?");
}
const auto& database = toml::find(data, "database");
{
BOOST_TEST(toml::find<std::string>(database, "server") == "192.168.1.1");
const std::vector<int> expected_ports{8001, 8001, 8002};
BOOST_CHECK(toml::find<std::vector<int>>(database, "ports") == expected_ports);
BOOST_TEST(toml::find<int >(database, "connection_max") == 5000);
BOOST_TEST(toml::find<bool>(database, "enabled") == true);
}
const auto& servers = toml::find(data, "servers");
{
const auto& alpha = toml::find(servers, "alpha");
BOOST_TEST(alpha.comments().at(0) ==
" You can indent as you please. Tabs or spaces. TOML don't care.");
BOOST_TEST(toml::find<std::string>(alpha, "ip") == "10.0.0.1");
BOOST_TEST(toml::find<std::string>(alpha, "dc") == "eqdc10");
const auto& beta = toml::find(servers, "beta");
BOOST_TEST(toml::find<std::string>(beta, "ip") == "10.0.0.2");
BOOST_TEST(toml::find<std::string>(beta, "dc") == "eqdc10");
BOOST_TEST(toml::find<std::string>(beta, "country") ==
"\xE4\xB8\xAD\xE5\x9B\xBD");
BOOST_TEST(toml::find(beta, "country").comments().at(0) ==
" This should be parsed as UTF-8");
}
const auto& clients = toml::find(data, "clients");
{
BOOST_TEST(toml::find(clients, "data").comments().at(0) ==
" just an update to make sure parsers support it");
toml::array clients_data = toml::find<toml::array>(clients, "data");
std::vector<std::string> expected_name{"gamma", "delta"};
BOOST_CHECK(toml::get<std::vector<std::string>>(clients_data.at(0)) ==
expected_name);
std::vector<int> expected_number{1, 2};
BOOST_CHECK(toml::get<std::vector<int>>(clients_data.at(1)) ==
expected_number);
std::vector<std::string> expected_hosts{"alpha", "omega"};
BOOST_CHECK(toml::find<std::vector<std::string>>(clients, "hosts") ==
expected_hosts);
BOOST_TEST(toml::find(clients, "hosts").comments().at(0) ==
" Line breaks are OK when inside arrays");
}
std::vector<toml::table> products =
toml::find<std::vector<toml::table>>(data, "products");
{
BOOST_TEST(toml::get<std::string>(products.at(0).at("name")) ==
"Hammer");
BOOST_TEST(toml::get<std::int64_t>(products.at(0).at("sku")) ==
738594937);
BOOST_TEST(toml::get<std::string>(products.at(1).at("name")) ==
"Nail");
BOOST_TEST(toml::get<std::int64_t>(products.at(1).at("sku")) ==
284758393);
BOOST_TEST(toml::get<std::string>(products.at(1).at("color")) ==
"gray");
}
}
BOOST_AUTO_TEST_CASE(test_example_preserve_stdmap_stddeque)
{
const auto data = toml::parse<toml::preserve_comments, std::map, std::deque
>("toml/tests/example.toml");
static_assert(std::is_same<typename decltype(data)::table_type,
std::map<toml::key, typename std::remove_cv<decltype(data)>::type>
>::value, "");
static_assert(std::is_same<typename decltype(data)::array_type,
std::deque<typename std::remove_cv<decltype(data)>::type>
>::value, "");
BOOST_TEST(toml::find<std::string>(data, "title") == "TOML Example");
const auto& owner = toml::find(data, "owner");
{
BOOST_TEST(toml::find<std::string>(owner, "name") == "Tom Preston-Werner");
BOOST_TEST(toml::find<std::string>(owner, "organization") == "GitHub");
BOOST_TEST(toml::find<std::string>(owner, "bio") ==
"GitHub Cofounder & CEO\nLikes tater tots and beer.");
BOOST_TEST(toml::find<toml::offset_datetime>(owner, "dob") ==
toml::offset_datetime(toml::local_date(1979, toml::month_t::May, 27),
toml::local_time(7, 32, 0), toml::time_offset(0, 0)));
BOOST_TEST(toml::find(owner, "dob").comments().at(0) ==
" First class dates? Why not?");
}
const auto& database = toml::find(data, "database");
{
BOOST_TEST(toml::find<std::string>(database, "server") == "192.168.1.1");
const std::vector<int> expected_ports{8001, 8001, 8002};
BOOST_CHECK(toml::find<std::vector<int>>(database, "ports") == expected_ports);
BOOST_TEST(toml::find<int >(database, "connection_max") == 5000);
BOOST_TEST(toml::find<bool>(database, "enabled") == true);
}
const auto& servers = toml::find(data, "servers");
{
const auto& alpha = toml::find(servers, "alpha");
BOOST_TEST(alpha.comments().at(0) ==
" You can indent as you please. Tabs or spaces. TOML don't care.");
BOOST_TEST(toml::find<std::string>(alpha, "ip") == "10.0.0.1");
BOOST_TEST(toml::find<std::string>(alpha, "dc") == "eqdc10");
const auto& beta = toml::find(servers, "beta");
BOOST_TEST(toml::find<std::string>(beta, "ip") == "10.0.0.2");
BOOST_TEST(toml::find<std::string>(beta, "dc") == "eqdc10");
BOOST_TEST(toml::find<std::string>(beta, "country") ==
"\xE4\xB8\xAD\xE5\x9B\xBD");
BOOST_TEST(toml::find(beta, "country").comments().at(0) ==
" This should be parsed as UTF-8");
}
const auto& clients = toml::find(data, "clients");
{
BOOST_TEST(toml::find(clients, "data").comments().at(0) ==
" just an update to make sure parsers support it");
toml::array clients_data = toml::find<toml::array>(clients, "data");
std::vector<std::string> expected_name{"gamma", "delta"};
BOOST_CHECK(toml::get<std::vector<std::string>>(clients_data.at(0)) ==
expected_name);
std::vector<int> expected_number{1, 2};
BOOST_CHECK(toml::get<std::vector<int>>(clients_data.at(1)) ==
expected_number);
std::vector<std::string> expected_hosts{"alpha", "omega"};
BOOST_CHECK(toml::find<std::vector<std::string>>(clients, "hosts") ==
expected_hosts);
BOOST_TEST(toml::find(clients, "hosts").comments().at(0) ==
" Line breaks are OK when inside arrays");
}
std::vector<toml::table> products =
toml::find<std::vector<toml::table>>(data, "products");
{
BOOST_TEST(toml::get<std::string>(products.at(0).at("name")) ==
"Hammer");
BOOST_TEST(toml::get<std::int64_t>(products.at(0).at("sku")) ==
738594937);
BOOST_TEST(toml::get<std::string>(products.at(1).at("name")) ==
"Nail");
BOOST_TEST(toml::get<std::int64_t>(products.at(1).at("sku")) ==
284758393);
BOOST_TEST(toml::get<std::string>(products.at(1).at("color")) ==
"gray");
}
}
// ---------------------------------------------------------------------------
// after here, the test codes generate the content of a file.
BOOST_AUTO_TEST_CASE(test_file_with_BOM)
{
{
const std::string table(
"\xEF\xBB\xBF" // BOM
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss, "test_file_with_BOM.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"\xEF\xBB\xBF" // BOM
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
);
{
std::ofstream ofs("tmp.toml");
ofs << table;
}
const auto data = toml::parse("tmp.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"\xEF\xBB\xBF" // BOM
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss, "test_file_with_BOM_CRLF.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"\xEF\xBB\xBF" // BOM
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
);
{
// with text-mode, "\n" is converted to "\r\n" and the resulting
// value will be "\r\r\n". To avoid the additional "\r", use binary
// mode.
std::ofstream ofs("tmp.toml", std::ios_base::binary);
ofs.write(table.data(), static_cast<std::streamsize>(table.size()));
}
const auto data = toml::parse("tmp.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
}
BOOST_AUTO_TEST_CASE(test_file_without_newline_at_the_end_of_file)
{
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\""
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_file_without_newline_at_the_end_of_file.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\""
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_file_without_newline_at_the_end_of_file_CRLF.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\" # comment"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_file_without_newline_at_the_end_of_file_comment.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\" # comment"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_file_without_newline_at_the_end_of_file_comment.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\" \t"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_file_without_newline_at_the_end_of_file_ws.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\" \t"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_file_without_newline_at_the_end_of_file_ws.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
}
BOOST_AUTO_TEST_CASE(test_files_end_with_comment)
{
// comment w/o newline
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
"# comment"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_comment.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
"# comment\n"
"# one more comment"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_comment.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
// comment w/ newline
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
"# comment\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_comment.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
"# comment\n"
"# one more comment\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_comment.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
// CRLF version
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
"# comment"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_comment.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
"# comment\r\n"
"# one more comment"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_comment.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
"# comment\r\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_comment.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
"# comment\r\n"
"# one more comment\r\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_comment.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
}
BOOST_AUTO_TEST_CASE(test_files_end_with_empty_lines)
{
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
"\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
"\n"
"\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
// with whitespaces
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
" \n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
" \n"
" \n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
"\n"
" \n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
" \n"
"\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
// with whitespaces but no newline
{
const std::string table(
"key = \"value\"\n"
"[table]\n"
"key = \"value\"\n"
" "
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
// CRLF
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
"\r\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
"\r\n"
"\r\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
// with whitespaces
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
" \r\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
"\r\n"
" \r\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
" \r\n"
"\r\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
" \r\n"
" \r\n"
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
{
const std::string table(
"key = \"value\"\r\n"
"[table]\r\n"
"key = \"value\"\r\n"
" "
);
std::istringstream iss(table);
const auto data = toml::parse(iss,
"test_files_end_with_newline.toml");
BOOST_TEST(toml::find<std::string>(data, "key") == "value");
BOOST_TEST(toml::find<std::string>(toml::find(data, "table"), "key") == "value");
}
}

View File

@@ -0,0 +1,178 @@
#define BOOST_TEST_MODULE "parse_floating_test"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/parser.hpp>
#include <cmath>
#include "test_parse_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_fractional)
{
TOML11_TEST_PARSE_EQUAL(parse_floating, "1.0", 1.0);
TOML11_TEST_PARSE_EQUAL(parse_floating, "0.1", 0.1);
TOML11_TEST_PARSE_EQUAL(parse_floating, "0.001", 0.001);
TOML11_TEST_PARSE_EQUAL(parse_floating, "0.100", 0.1);
TOML11_TEST_PARSE_EQUAL(parse_floating, "+3.14", 3.14);
TOML11_TEST_PARSE_EQUAL(parse_floating, "-3.14", -3.14);
TOML11_TEST_PARSE_EQUAL(parse_floating, "3.1415_9265_3589", 3.141592653589);
TOML11_TEST_PARSE_EQUAL(parse_floating, "+3.1415_9265_3589", 3.141592653589);
TOML11_TEST_PARSE_EQUAL(parse_floating, "-3.1415_9265_3589", -3.141592653589);
TOML11_TEST_PARSE_EQUAL(parse_floating, "123_456.789", 123456.789);
TOML11_TEST_PARSE_EQUAL(parse_floating, "+123_456.789", 123456.789);
TOML11_TEST_PARSE_EQUAL(parse_floating, "-123_456.789", -123456.789);
TOML11_TEST_PARSE_EQUAL(parse_floating, "+0.0", 0.0);
TOML11_TEST_PARSE_EQUAL(parse_floating, "-0.0", -0.0);
}
BOOST_AUTO_TEST_CASE(test_fractional_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1.0", value( 1.0));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0.1", value( 0.1));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0.001", value( 0.001));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0.100", value( 0.1));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "+3.14", value( 3.14));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "-3.14", value(-3.14));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "3.1415_9265_3589", value( 3.141592653589));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "+3.1415_9265_3589", value( 3.141592653589));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "-3.1415_9265_3589", value(-3.141592653589));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "123_456.789", value( 123456.789));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "+123_456.789", value( 123456.789));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "-123_456.789", value(-123456.789));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "+0.0", value( 0.0));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "-0.0", value(-0.0));
}
BOOST_AUTO_TEST_CASE(test_exponential)
{
TOML11_TEST_PARSE_EQUAL(parse_floating, "1e10", 1e10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "1e+10", 1e10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "1e-10", 1e-10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "+1e10", 1e10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "+1e+10", 1e10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "+1e-10", 1e-10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "-1e10", -1e10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "-1e+10", -1e10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "-1e-10", -1e-10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "123e-10", 123e-10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "1E10", 1e10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "1E+10", 1e10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "1E-10", 1e-10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "123E-10", 123e-10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "1_2_3E-10", 123e-10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "1_2_3E-1_0", 123e-10);
TOML11_TEST_PARSE_EQUAL(parse_floating, "+0e0", 0.0);
TOML11_TEST_PARSE_EQUAL(parse_floating, "-0e0", -0.0);
#ifdef TOML11_USE_UNRELEASED_TOML_FEATURES
BOOST_TEST_MESSAGE("testing an unreleased toml feature: leading zeroes in float exponent part");
// toml-lang/toml master permits leading 0s in exp part (unreleased)
TOML11_TEST_PARSE_EQUAL(parse_floating, "1_2_3E-01", 123e-1);
TOML11_TEST_PARSE_EQUAL(parse_floating, "1_2_3E-0_1", 123e-1);
#endif
}
BOOST_AUTO_TEST_CASE(test_exponential_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1e10", value(1e10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1e+10", value(1e10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1e-10", value(1e-10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "+1e10", value(1e10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "+1e+10", value(1e10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "+1e-10", value(1e-10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "-1e10", value(-1e10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "-1e+10", value(-1e10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "-1e-10", value(-1e-10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "123e-10", value(123e-10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1E10", value(1e10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1E+10", value(1e10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1E-10", value(1e-10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "123E-10", value(123e-10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1_2_3E-10", value(123e-10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1_2_3E-1_0", value(123e-10));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "+0e0", value( 0.0));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "-0e0", value(-0.0));
#ifdef TOML11_USE_UNRELEASED_TOML_FEATURES
BOOST_TEST_MESSAGE("testing an unreleased toml feature: leading zeroes in float exponent part");
// toml-lang/toml master permits leading 0s in exp part (unreleased)
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1_2_3E-01", value(123e-1));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1_2_3E-0_1", value(123e-1));
#endif
}
BOOST_AUTO_TEST_CASE(test_fe)
{
TOML11_TEST_PARSE_EQUAL(parse_floating, "6.02e23", 6.02e23);
TOML11_TEST_PARSE_EQUAL(parse_floating, "6.02e+23", 6.02e23);
TOML11_TEST_PARSE_EQUAL(parse_floating, "1.112_650_06e-17", 1.11265006e-17);
}
BOOST_AUTO_TEST_CASE(test_fe_vaule)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "6.02e23", value(6.02e23));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "6.02e+23", value(6.02e23));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1.112_650_06e-17", value(1.11265006e-17));
#ifdef TOML11_USE_UNRELEASED_TOML_FEATURES
BOOST_TEST_MESSAGE("testing an unreleased toml feature: leading zeroes in float exponent part");
// toml-lang/toml master permits leading 0s in exp part (unreleased)
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "3.141_5e-01", value(3.1415e-1));
#endif
}
BOOST_AUTO_TEST_CASE(test_inf)
{
{
const std::string token("inf");
toml::detail::location<std::string> loc("test", token);
const auto r = parse_floating(loc);
BOOST_CHECK(r.is_ok());
BOOST_CHECK(std::isinf(r.unwrap().first));
BOOST_CHECK(r.unwrap().first > 0.0);
}
{
const std::string token("+inf");
toml::detail::location<std::string> loc("test", token);
const auto r = parse_floating(loc);
BOOST_CHECK(r.is_ok());
BOOST_CHECK(std::isinf(r.unwrap().first));
BOOST_CHECK(r.unwrap().first > 0.0);
}
{
const std::string token("-inf");
toml::detail::location<std::string> loc("test", token);
const auto r = parse_floating(loc);
BOOST_CHECK(r.is_ok());
BOOST_CHECK(std::isinf(r.unwrap().first));
BOOST_CHECK(r.unwrap().first < 0.0);
}
}
BOOST_AUTO_TEST_CASE(test_nan)
{
{
const std::string token("nan");
toml::detail::location<std::string> loc("test", token);
const auto r = parse_floating(loc);
BOOST_CHECK(r.is_ok());
BOOST_CHECK(std::isnan(r.unwrap().first));
}
{
const std::string token("+nan");
toml::detail::location<std::string> loc("test", token);
const auto r = parse_floating(loc);
BOOST_CHECK(r.is_ok());
BOOST_CHECK(std::isnan(r.unwrap().first));
}
{
const std::string token("-nan");
toml::detail::location<std::string> loc("test", token);
const auto r = parse_floating(loc);
BOOST_CHECK(r.is_ok());
BOOST_CHECK(std::isnan(r.unwrap().first));
}
}

View File

@@ -0,0 +1,64 @@
#define BOOST_TEST_MODULE "parse_inline_table_test"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/parser.hpp>
#include "test_parse_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_inline_table)
{
TOML11_TEST_PARSE_EQUAL(parse_inline_table<toml::value>, "{}", table());
{
table t;
t["foo"] = toml::value(42);
t["bar"] = toml::value("baz");
TOML11_TEST_PARSE_EQUAL(parse_inline_table<toml::value>, "{foo = 42, bar = \"baz\"}", t);
}
{
table t;
table t_sub;
t_sub["name"] = toml::value("pug");
t["type"] = toml::value(t_sub);
TOML11_TEST_PARSE_EQUAL(parse_inline_table<toml::value>, "{type.name = \"pug\"}", t);
}
}
BOOST_AUTO_TEST_CASE(test_inline_table_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "{}", value(table()));
{
table t;
t["foo"] = toml::value(42);
t["bar"] = toml::value("baz");
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "{foo = 42, bar = \"baz\"}", value(t));
}
{
table t;
table t_sub;
t_sub["name"] = toml::value("pug");
t["type"] = toml::value(t_sub);
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "{type.name = \"pug\"}", value(t));
}
}
BOOST_AUTO_TEST_CASE(test_inline_table_immutability)
{
{
std::istringstream stream(std::string(
"a = {b = 1}\n"
"a.c = 2\n"));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
}
{
std::istringstream stream(std::string(
"a = {b = {c = 1}}\n"
"a.b.d = 2\n"));
BOOST_CHECK_THROW(toml::parse(stream), toml::syntax_error);
}
}

View File

@@ -0,0 +1,92 @@
#define BOOST_TEST_MODULE "parse_integer_test"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/parser.hpp>
#include "test_parse_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_decimal)
{
TOML11_TEST_PARSE_EQUAL(parse_integer, "1234", 1234);
TOML11_TEST_PARSE_EQUAL(parse_integer, "+1234", 1234);
TOML11_TEST_PARSE_EQUAL(parse_integer, "-1234", -1234);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0", 0);
TOML11_TEST_PARSE_EQUAL(parse_integer, "1_2_3_4", 1234);
TOML11_TEST_PARSE_EQUAL(parse_integer, "+1_2_3_4", +1234);
TOML11_TEST_PARSE_EQUAL(parse_integer, "-1_2_3_4", -1234);
TOML11_TEST_PARSE_EQUAL(parse_integer, "123_456_789", 123456789);
}
BOOST_AUTO_TEST_CASE(test_decimal_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1234", toml::value( 1234));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "+1234", toml::value( 1234));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "-1234", toml::value( -1234));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0", toml::value( 0));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "1_2_3_4", toml::value( 1234));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "+1_2_3_4", toml::value( +1234));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "-1_2_3_4", toml::value( -1234));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "123_456_789", toml::value(123456789));
}
BOOST_AUTO_TEST_CASE(test_hex)
{
TOML11_TEST_PARSE_EQUAL(parse_integer, "0xDEADBEEF", 0xDEADBEEF);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0xdeadbeef", 0xDEADBEEF);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0xDEADbeef", 0xDEADBEEF);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0xDEAD_BEEF", 0xDEADBEEF);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0xdead_beef", 0xDEADBEEF);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0xdead_BEEF", 0xDEADBEEF);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0xFF", 0xFF);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0x00FF", 0xFF);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0x0000FF", 0xFF);
}
BOOST_AUTO_TEST_CASE(test_hex_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0xDEADBEEF", value(0xDEADBEEF));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0xdeadbeef", value(0xDEADBEEF));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0xDEADbeef", value(0xDEADBEEF));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0xDEAD_BEEF", value(0xDEADBEEF));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0xdead_beef", value(0xDEADBEEF));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0xdead_BEEF", value(0xDEADBEEF));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0xFF", value(0xFF));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0x00FF", value(0xFF));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0x0000FF", value(0xFF));
}
BOOST_AUTO_TEST_CASE(test_oct)
{
TOML11_TEST_PARSE_EQUAL(parse_integer, "0o777", 64*7+8*7+7);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0o7_7_7", 64*7+8*7+7);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0o007", 7);
}
BOOST_AUTO_TEST_CASE(test_oct_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0o777", value(64*7+8*7+7));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0o7_7_7", value(64*7+8*7+7));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0o007", value(7));
}
BOOST_AUTO_TEST_CASE(test_bin)
{
TOML11_TEST_PARSE_EQUAL(parse_integer, "0b10000", 16);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0b010000", 16);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0b01_00_00", 16);
TOML11_TEST_PARSE_EQUAL(parse_integer, "0b111111", 63);
}
BOOST_AUTO_TEST_CASE(test_bin_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0b10000", value(16));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0b010000", value(16));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0b01_00_00", value(16));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>, "0b111111", value(63));
}

63
tests/test_parse_key.cpp Normal file
View File

@@ -0,0 +1,63 @@
#define BOOST_TEST_MODULE "parse_key_test"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/parser.hpp>
#include "test_parse_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_bare_key)
{
TOML11_TEST_PARSE_EQUAL(parse_key, "barekey", std::vector<key>(1, "barekey"));
TOML11_TEST_PARSE_EQUAL(parse_key, "bare-key", std::vector<key>(1, "bare-key"));
TOML11_TEST_PARSE_EQUAL(parse_key, "bare_key", std::vector<key>(1, "bare_key"));
TOML11_TEST_PARSE_EQUAL(parse_key, "1234", std::vector<key>(1, "1234"));
}
BOOST_AUTO_TEST_CASE(test_quoted_key)
{
TOML11_TEST_PARSE_EQUAL(parse_key, "\"127.0.0.1\"", std::vector<key>(1, "127.0.0.1" ));
TOML11_TEST_PARSE_EQUAL(parse_key, "\"character encoding\"", std::vector<key>(1, "character encoding"));
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
TOML11_TEST_PARSE_EQUAL(parse_key, "\"\xCA\x8E\xC7\x9D\xCA\x9E\"", std::vector<key>(1, "\xCA\x8E\xC7\x9D\xCA\x9E"));
#else
TOML11_TEST_PARSE_EQUAL(parse_key, "\"ʎǝʞ\"", std::vector<key>(1, "ʎǝʞ" ));
#endif
TOML11_TEST_PARSE_EQUAL(parse_key, "'key2'", std::vector<key>(1, "key2" ));
TOML11_TEST_PARSE_EQUAL(parse_key, "'quoted \"value\"'", std::vector<key>(1, "quoted \"value\"" ));
}
BOOST_AUTO_TEST_CASE(test_dotted_key)
{
{
std::vector<key> keys(2);
keys[0] = "physical";
keys[1] = "color";
TOML11_TEST_PARSE_EQUAL(parse_key, "physical.color", keys);
}
{
std::vector<key> keys(2);
keys[0] = "physical";
keys[1] = "shape";
TOML11_TEST_PARSE_EQUAL(parse_key, "physical.shape", keys);
}
{
std::vector<key> keys(4);
keys[0] = "x";
keys[1] = "y";
keys[2] = "z";
keys[3] = "w";
TOML11_TEST_PARSE_EQUAL(parse_key, "x.y.z.w", keys);
}
{
std::vector<key> keys(2);
keys[0] = "site";
keys[1] = "google.com";
TOML11_TEST_PARSE_EQUAL(parse_key, "site.\"google.com\"", keys);
}
}

237
tests/test_parse_string.cpp Normal file
View File

@@ -0,0 +1,237 @@
#define BOOST_TEST_MODULE "parse_string_test"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/parser.hpp>
#include "test_parse_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_string)
{
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"The quick brown fox jumps over the lazy dog\"",
string("The quick brown fox jumps over the lazy dog", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\'The quick brown fox jumps over the lazy dog\'",
string("The quick brown fox jumps over the lazy dog", string_t::literal));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\"\"The quick brown fox \\\njumps over the lazy dog\"\"\"",
string("The quick brown fox jumps over the lazy dog", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"'''The quick brown fox \njumps over the lazy dog'''",
string("The quick brown fox \njumps over the lazy dog", string_t::literal));
}
BOOST_AUTO_TEST_CASE(test_string_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"The quick brown fox jumps over the lazy dog\"",
toml::value("The quick brown fox jumps over the lazy dog", string_t::basic));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\'The quick brown fox jumps over the lazy dog\'",
toml::value("The quick brown fox jumps over the lazy dog", string_t::literal));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"\"\"The quick brown fox \\\njumps over the lazy dog\"\"\"",
toml::value("The quick brown fox jumps over the lazy dog", string_t::basic));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"'''The quick brown fox \njumps over the lazy dog'''",
toml::value("The quick brown fox \njumps over the lazy dog", string_t::literal));
}
BOOST_AUTO_TEST_CASE(test_basic_string)
{
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"GitHub Cofounder & CEO\\nLikes tater tots and beer.\"",
string("GitHub Cofounder & CEO\nLikes tater tots and beer.", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"192.168.1.1\"",
string("192.168.1.1", string_t::basic));
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\xE4\xB8\xAD\xE5\x9B\xBD\"",
string("\xE4\xB8\xAD\xE5\x9B\xBD", string_t::basic));
#else
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"中国\"",
string("中国", string_t::basic));
#endif
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"You'll hate me after this - #\"",
string("You'll hate me after this - #", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\" And when \\\"'s are in the along with # \\\"\"",
string(" And when \"'s are in the along with # \"", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"Here are fifteen apostrophes: '''''''''''''''\"",
string("Here are fifteen apostrophes: '''''''''''''''", string_t::basic));
}
BOOST_AUTO_TEST_CASE(test_basic_string_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"GitHub Cofounder & CEO\\nLikes tater tots and beer.\"",
value("GitHub Cofounder & CEO\nLikes tater tots and beer.", string_t::basic));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"192.168.1.1\"",
value("192.168.1.1", string_t::basic));
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"\xE4\xB8\xAD\xE5\x9B\xBD\"",
value("\xE4\xB8\xAD\xE5\x9B\xBD", string_t::basic));
#else
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"中国\"",
value("中国", string_t::basic));
#endif
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"You'll hate me after this - #\"",
value("You'll hate me after this - #", string_t::basic));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\" And when \\\"'s are in the along with # \\\"\"",
value(" And when \"'s are in the along with # \"", string_t::basic));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"Here are fifteen apostrophes: '''''''''''''''\"",
value("Here are fifteen apostrophes: '''''''''''''''", string_t::basic));
}
BOOST_AUTO_TEST_CASE(test_ml_basic_string)
{
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\"\"\nThe quick brown \\\n\n fox jumps over \\\n the lazy dog.\"\"\"",
string("The quick brown fox jumps over the lazy dog.", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\"\"\\\n The quick brown \\\n\n fox jumps over \\\n the lazy dog.\\\n \"\"\"",
string("The quick brown fox jumps over the lazy dog.", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\"\"Here are two quotation marks: \"\". Simple enough.\"\"\"",
string("Here are two quotation marks: \"\". Simple enough.", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\"\"Here are three quotation marks: \"\"\\\".\"\"\"",
string("Here are three quotation marks: \"\"\".", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\"\"Here are fifteen quotation marks: \"\"\\\"\"\"\\\"\"\"\\\"\"\"\\\"\"\"\\\".\"\"\"",
string("Here are fifteen quotation marks: \"\"\"\"\"\"\"\"\"\"\"\"\"\"\".", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\"\"\"This,\" she said, \"is just a pointless statement.\"\"\"\"",
string("\"This,\" she said, \"is just a pointless statement.\"", string_t::basic));
}
BOOST_AUTO_TEST_CASE(test_ml_basic_string_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"\"\"\nThe quick brown \\\n\n fox jumps over \\\n the lazy dog.\"\"\"",
value("The quick brown fox jumps over the lazy dog.", string_t::basic));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"\"\"\\\n The quick brown \\\n\n fox jumps over \\\n the lazy dog.\\\n \"\"\"",
value("The quick brown fox jumps over the lazy dog.", string_t::basic));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"\"\"Here are two quotation marks: \"\". Simple enough.\"\"\"",
value("Here are two quotation marks: \"\". Simple enough.", string_t::basic));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"\"\"Here are three quotation marks: \"\"\\\".\"\"\"",
value("Here are three quotation marks: \"\"\".", string_t::basic));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"\"\"Here are fifteen quotation marks: \"\"\\\"\"\"\\\"\"\"\\\"\"\"\\\"\"\"\\\".\"\"\"",
value("Here are fifteen quotation marks: \"\"\"\"\"\"\"\"\"\"\"\"\"\"\".", string_t::basic));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"\"\"\"\"This,\" she said, \"is just a pointless statement.\"\"\"\"",
value("\"This,\" she said, \"is just a pointless statement.\"", string_t::basic));
}
BOOST_AUTO_TEST_CASE(test_literal_string)
{
TOML11_TEST_PARSE_EQUAL(parse_string,
"'C:\\Users\\nodejs\\templates'",
string("C:\\Users\\nodejs\\templates", string_t::literal));
TOML11_TEST_PARSE_EQUAL(parse_string,
"'\\\\ServerX\\admin$\\system32\\'",
string("\\\\ServerX\\admin$\\system32\\", string_t::literal));
TOML11_TEST_PARSE_EQUAL(parse_string,
"'Tom \"Dubs\" Preston-Werner'",
string("Tom \"Dubs\" Preston-Werner", string_t::literal));
TOML11_TEST_PARSE_EQUAL(parse_string,
"'<\\i\\c*\\s*>'",
string("<\\i\\c*\\s*>", string_t::literal));
}
BOOST_AUTO_TEST_CASE(test_literal_string_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"'C:\\Users\\nodejs\\templates'",
value("C:\\Users\\nodejs\\templates", string_t::literal));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"'\\\\ServerX\\admin$\\system32\\'",
value("\\\\ServerX\\admin$\\system32\\", string_t::literal));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"'Tom \"Dubs\" Preston-Werner'",
value("Tom \"Dubs\" Preston-Werner", string_t::literal));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"'<\\i\\c*\\s*>'",
value("<\\i\\c*\\s*>", string_t::literal));
}
BOOST_AUTO_TEST_CASE(test_ml_literal_string)
{
TOML11_TEST_PARSE_EQUAL(parse_string,
"'''I [dw]on't need \\d{2} apples'''",
string("I [dw]on't need \\d{2} apples", string_t::literal));
TOML11_TEST_PARSE_EQUAL(parse_string,
"'''\nThe first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n'''",
string("The first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n", string_t::literal));
TOML11_TEST_PARSE_EQUAL(parse_string,
"''''That's still pointless', she said.'''",
string("'That's still pointless', she said.", string_t::literal));
TOML11_TEST_PARSE_EQUAL(parse_string,
"'''Here are fifteen quotation marks: \"\"\"\"\"\"\"\"\"\"\"\"\"\"\".'''",
string("Here are fifteen quotation marks: \"\"\"\"\"\"\"\"\"\"\"\"\"\"\".", string_t::literal));
TOML11_TEST_PARSE_EQUAL(parse_string,
"''''This,' she said, 'is just a pointless statement.''''",
string("'This,' she said, 'is just a pointless statement.'", string_t::literal));
}
BOOST_AUTO_TEST_CASE(test_ml_literal_string_value)
{
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"'''I [dw]on't need \\d{2} apples'''",
value("I [dw]on't need \\d{2} apples", string_t::literal));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"'''\nThe first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n'''",
value("The first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n", string_t::literal));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"''''That's still pointless', she said.'''",
value("'That's still pointless', she said.", string_t::literal));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"'''Here are fifteen quotation marks: \"\"\"\"\"\"\"\"\"\"\"\"\"\"\".'''",
value("Here are fifteen quotation marks: \"\"\"\"\"\"\"\"\"\"\"\"\"\"\".", string_t::literal));
TOML11_TEST_PARSE_EQUAL_VALUE(parse_value<toml::value>,
"''''This,' she said, 'is just a pointless statement.''''",
value("'This,' she said, 'is just a pointless statement.'", string_t::literal));
}
BOOST_AUTO_TEST_CASE(test_unicode_escape_sequence)
{
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\\u03B1\\u03B2\\u03B3\"",
string("\xCE\xB1\xCE\xB2\xCE\xB3", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\\U0001D7AA\"",
string("\xF0\x9D\x9E\xAA", string_t::basic));
#else
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\\u03B1\\u03B2\\u03B3\"",
string("αβγ", string_t::basic));
TOML11_TEST_PARSE_EQUAL(parse_string,
"\"\\U0001D7AA\"",
string("𝞪", string_t::basic));
#endif
}

View File

@@ -0,0 +1,50 @@
#define BOOST_TEST_MODULE "parse_table_test"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/parser.hpp>
#include <toml/get.hpp>
#include "test_parse_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_normal_table)
{
std::string table(
"key1 = \"value\"\n"
"key2 = 42\n"
"key3 = 3.14\n"
);
location<std::string> loc("test", table);
const auto result = toml::detail::parse_ml_table<toml::value>(loc);
BOOST_TEST(result.is_ok());
const auto data = result.unwrap();
BOOST_TEST(toml::get<std::string >(data.at("key1")) == "value");
BOOST_TEST(toml::get<std::int64_t>(data.at("key2")) == 42);
BOOST_TEST(toml::get<double >(data.at("key3")) == 3.14);
}
BOOST_AUTO_TEST_CASE(test_nested_table)
{
std::string table(
"a.b = \"value\"\n"
"a.c.d = 42\n"
);
location<std::string> loc("test", table);
const auto result = toml::detail::parse_ml_table<toml::value>(loc);
BOOST_TEST(result.is_ok());
const auto data = result.unwrap();
const auto a = toml::get<toml::table>(data.at("a"));
const auto c = toml::get<toml::table>(a.at("c"));
BOOST_TEST(toml::get<std::string >(a.at("b")) == "value");
BOOST_TEST(toml::get<std::int64_t>(c.at("d")) == 42);
}

View File

@@ -0,0 +1,117 @@
#define BOOST_TEST_MODULE "parse_table_key_test"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/parser.hpp>
#include "test_parse_aux.hpp"
using namespace toml;
using namespace detail;
BOOST_AUTO_TEST_CASE(test_table_bare_key)
{
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[barekey]", std::vector<key>(1, "barekey"));
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[bare-key]", std::vector<key>(1, "bare-key"));
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[bare_key]", std::vector<key>(1, "bare_key"));
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[1234]", std::vector<key>(1, "1234"));
}
BOOST_AUTO_TEST_CASE(test_table_quoted_key)
{
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[\"127.0.0.1\"]", std::vector<key>(1, "127.0.0.1" ));
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[\"character encoding\"]", std::vector<key>(1, "character encoding"));
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[\"ʎǝʞ\"]", std::vector<key>(1, "ʎǝʞ" ));
TOML11_TEST_PARSE_EQUAL(parse_table_key, "['key2']", std::vector<key>(1, "key2" ));
TOML11_TEST_PARSE_EQUAL(parse_table_key, "['quoted \"value\"']", std::vector<key>(1, "quoted \"value\"" ));
}
BOOST_AUTO_TEST_CASE(test_table_dotted_key)
{
{
std::vector<key> keys(2);
keys[0] = "physical";
keys[1] = "color";
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[physical.color]", keys);
}
{
std::vector<key> keys(2);
keys[0] = "physical";
keys[1] = "shape";
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[physical.shape]", keys);
}
{
std::vector<key> keys(4);
keys[0] = "x";
keys[1] = "y";
keys[2] = "z";
keys[3] = "w";
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x.y.z.w]", keys);
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x . y . z . w]", keys);
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x. y .z. w]", keys);
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[x .y. z .w]", keys);
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[ x. y .z . w ]", keys);
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[ x . y . z . w ]", keys);
}
{
std::vector<key> keys(2);
keys[0] = "site";
keys[1] = "google.com";
TOML11_TEST_PARSE_EQUAL(parse_table_key, "[site.\"google.com\"]", keys);
}
}
BOOST_AUTO_TEST_CASE(test_array_of_table_bare_key)
{
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[barekey]]", std::vector<key>(1, "barekey"));
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[bare-key]]", std::vector<key>(1, "bare-key"));
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[bare_key]]", std::vector<key>(1, "bare_key"));
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[1234]]", std::vector<key>(1, "1234"));
}
BOOST_AUTO_TEST_CASE(test_array_of_table_quoted_key)
{
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[\"127.0.0.1\"]]", std::vector<key>(1, "127.0.0.1" ));
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[\"character encoding\"]]", std::vector<key>(1, "character encoding"));
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[\"ʎǝʞ\"]]", std::vector<key>(1, "ʎǝʞ" ));
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[['key2']]", std::vector<key>(1, "key2" ));
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[['quoted \"value\"']]", std::vector<key>(1, "quoted \"value\"" ));
}
BOOST_AUTO_TEST_CASE(test_array_of_table_dotted_key)
{
{
std::vector<key> keys(2);
keys[0] = "physical";
keys[1] = "color";
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[physical.color]]", keys);
}
{
std::vector<key> keys(2);
keys[0] = "physical";
keys[1] = "shape";
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[physical.shape]]", keys);
}
{
std::vector<key> keys(4);
keys[0] = "x";
keys[1] = "y";
keys[2] = "z";
keys[3] = "w";
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[x.y.z.w]]", keys);
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[x . y . z . w]]", keys);
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[x. y .z. w]]", keys);
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[x .y. z .w]]", keys);
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[ x. y .z . w ]]", keys);
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[ x . y . z . w ]]", keys);
}
{
std::vector<key> keys(2);
keys[0] = "site";
keys[1] = "google.com";
TOML11_TEST_PARSE_EQUAL(parse_array_table_key, "[[site.\"google.com\"]]", keys);
}
}

View File

@@ -14,11 +14,11 @@ BOOST_AUTO_TEST_CASE(test_hard_example_unicode)
{
const auto data = toml::parse("toml/tests/hard_example_unicode.toml");
const auto the = toml::get<toml::Table>(data.at("the"));
BOOST_CHECK_EQUAL(toml::get<std::string>(the.at("test_string")),
const auto the = toml::find<toml::table>(data, "the");
BOOST_TEST(toml::get<std::string>(the.at("test_string")) ==
std::string("\xC3\x9D\xC3\xB4\xC3\xBA\x27\xE2\x84\x93\xE2\x84\x93\x20\xCE\xBB\xC3\xA1\xC6\xAD\xC3\xA8\x20\xE2\x82\xA5\xC3\xA8\x20\xC3\xA1\xC6\x92\xC6\xAD\xC3\xA8\xC5\x99\x20\xC6\xAD\xCE\xBB\xC3\xAF\xC6\xA8\x20\x2D\x20\x23"));
const auto hard = toml::get<toml::Table>(the.at("hard"));
const auto hard = toml::get<toml::table>(the.at("hard"));
const std::vector<std::string> expected_the_hard_test_array{"] ", " # "};
BOOST_CHECK(toml::get<std::vector<std::string>>(hard.at("test_array")) ==
expected_the_hard_test_array);
@@ -28,13 +28,13 @@ BOOST_AUTO_TEST_CASE(test_hard_example_unicode)
};
BOOST_CHECK(toml::get<std::vector<std::string>>(hard.at("test_array2")) ==
expected_the_hard_test_array2);
BOOST_CHECK_EQUAL(toml::get<std::string>(hard.at("another_test_string")),
BOOST_TEST(toml::get<std::string>(hard.at("another_test_string")) ==
std::string("\xC2\xA7\xC3\xA1\xE2\x82\xA5\xC3\xA8\x20\xC6\xAD\xCE\xBB\xC3\xAF\xC3\xB1\xCF\xB1\x2C\x20\xCE\xB2\xC3\xBA\xC6\xAD\x20\xCF\x89\xC3\xAF\xC6\xAD\xCE\xBB\x20\xC3\xA1\x20\xC6\xA8\xC6\xAD\xC5\x99\xC3\xAF\xC3\xB1\xCF\xB1\x20\x23"));
BOOST_CHECK_EQUAL(toml::get<std::string>(hard.at("harder_test_string")),
BOOST_TEST(toml::get<std::string>(hard.at("harder_test_string")) ==
std::string("\x20\xC3\x82\xC3\xB1\xCE\xB4\x20\xCF\x89\xCE\xBB\xC3\xA8\xC3\xB1\x20\x22\x27\xC6\xA8\x20\xC3\xA1\xC5\x99\xC3\xA8\x20\xC3\xAF\xC3\xB1\x20\xC6\xAD\xCE\xBB\xC3\xA8\x20\xC6\xA8\xC6\xAD\xC5\x99\xC3\xAF\xC3\xB1\xCF\xB1\x2C\x20\xC3\xA1\xE2\x84\x93\xC3\xB4\xC3\xB1\xCF\xB1\x20\xCF\x89\xC3\xAF\xC6\xAD\xCE\xBB\x20\x23\x20\x22"));
//
const auto bit = toml::get<toml::Table>(hard.at(std::string("\xCE\xB2\xC3\xAF\xC6\xAD\x23")));
BOOST_CHECK_EQUAL(toml::get<std::string>(bit.at(std::string("\xCF\x89\xCE\xBB\xC3\xA1\xC6\xAD\x3F"))),
const auto bit = toml::get<toml::table>(hard.at(std::string("\xCE\xB2\xC3\xAF\xC6\xAD\x23")));
BOOST_TEST(toml::get<std::string>(bit.at(std::string("\xCF\x89\xCE\xBB\xC3\xA1\xC6\xAD\x3F"))) ==
std::string("\xC3\x9D\xC3\xB4\xC3\xBA\x20\xCE\xB4\xC3\xB4\xC3\xB1\x27\xC6\xAD\x20\xC6\xAD\xCE\xBB\xC3\xAF\xC3\xB1\xC6\x99\x20\xC6\xA8\xC3\xB4\xE2\x82\xA5\xC3\xA8\x20\xC3\xBA\xC6\xA8\xC3\xA8\xC5\x99\x20\xCF\x89\xC3\xB4\xC3\xB1\x27\xC6\xAD\x20\xCE\xB4\xC3\xB4\x20\xC6\xAD\xCE\xBB\xC3\xA1\xC6\xAD\x3F"));
const std::vector<std::string> expected_multi_line_array{"]"};
BOOST_CHECK(toml::get<std::vector<std::string>>(bit.at("multi_line_array")) ==
@@ -45,11 +45,11 @@ BOOST_AUTO_TEST_CASE(test_hard_example_unicode)
{
const auto data = toml::parse("toml/tests/hard_example_unicode.toml");
const auto the = toml::get<toml::Table>(data.at("the"));
BOOST_CHECK_EQUAL(toml::get<std::string>(the.at("test_string")),
const auto the = toml::find<toml::table>(data, "the");
BOOST_TEST(toml::get<std::string>(the.at("test_string")) ==
std::string(u8"Ýôú' λáƭè ₥è áƒƭèř ƭλïƨ - #"));
const auto hard = toml::get<toml::Table>(the.at("hard"));
const auto hard = toml::get<toml::table>(the.at("hard"));
const std::vector<std::string> expected_the_hard_test_array{"] ", " # "};
BOOST_CHECK(toml::get<std::vector<std::string>>(hard.at("test_array")) ==
expected_the_hard_test_array);
@@ -58,13 +58,13 @@ BOOST_AUTO_TEST_CASE(test_hard_example_unicode)
std::string(u8"Éжƥèřï₥èñƭ #9 ωáƨ á ƨúççèƨƨ")};
BOOST_CHECK(toml::get<std::vector<std::string>>(hard.at("test_array2")) ==
expected_the_hard_test_array2);
BOOST_CHECK_EQUAL(toml::get<std::string>(hard.at("another_test_string")),
BOOST_TEST(toml::get<std::string>(hard.at("another_test_string")) ==
std::string(u8"§á₥è ƭλïñϱ, βúƭ ωïƭλ á ƨƭřïñϱ #"));
BOOST_CHECK_EQUAL(toml::get<std::string>(hard.at("harder_test_string")),
BOOST_TEST(toml::get<std::string>(hard.at("harder_test_string")) ==
std::string(u8" Âñδ ωλèñ \"'ƨ ářè ïñ ƭλè ƨƭřïñϱ, áℓôñϱ ωïƭλ # \""));
const auto bit = toml::get<toml::Table>(hard.at(std::string(u8"βïƭ#")));
BOOST_CHECK_EQUAL(toml::get<std::string>(bit.at(std::string(u8"ωλáƭ?"))),
const auto bit = toml::get<toml::table>(hard.at(std::string(u8"βïƭ#")));
BOOST_TEST(toml::get<std::string>(bit.at(std::string(u8"ωλáƭ?"))) ==
std::string(u8"Ýôú δôñ'ƭ ƭλïñƙ ƨô₥è úƨèř ωôñ'ƭ δô ƭλáƭ?"));
const std::vector<std::string> expected_multi_line_array{"]"};
BOOST_CHECK(toml::get<std::vector<std::string>>(bit.at("multi_line_array")) ==

View File

@@ -1,935 +0,0 @@
#define BOOST_TEST_MODULE "test_parser"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml/acceptor.hpp>
#include <toml/parser.hpp>
#include <toml/from_toml.hpp>
#include <iostream>
BOOST_AUTO_TEST_CASE(test_parse_basic_inline_string)
{
typedef toml::parse_basic_inline_string parser;
typedef toml::is_basic_inline_string<toml::character> acceptor;
{
const std::string source("\"simple\"");
const std::string expected("simple");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("\"I'm a string. \\\"You can quote me\\\". Name\\tJos\\u00E9\\nLocation\\tSF.\"");
const std::string expected("I'm a string. \"You can quote me\". Name\tJosé\nLocation\tSF.");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("dummy");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_basic_multiline_string)
{
typedef toml::parse_basic_multiline_string parser;
typedef toml::is_basic_multiline_string<toml::character> acceptor;
{
//XXX ifdef windows platform
const std::string source("\"\"\"\nRoses are red\nViolets are blue\"\"\"");
const std::string expected("Roses are red\nViolets are blue");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("\"\"\"\nThe quick brown \\\n\n fox jumps over \\\n the lazy dog.\"\"\"");
const std::string expected("The quick brown fox jumps over the lazy dog.");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("\"\"\"\nThe quick brown \\\n fox jumps over \\\n the lazy dog.\\\n \"\"\"");
const std::string expected("The quick brown fox jumps over the lazy dog.");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("dummy");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_literal_inline_string)
{
typedef toml::parse_literal_inline_string parser;
typedef toml::is_literal_inline_string<toml::character> acceptor;
{
const std::string source("'C:\\Users\\nodejs\\templates'");
const std::string expected("C:\\Users\\nodejs\\templates");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("'\\\\ServerX\\admin$\\system32\\'");
const std::string expected("\\\\ServerX\\admin$\\system32\\");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("'Tom \"Dubs\" Preston-Werner'");
const std::string expected("Tom \"Dubs\" Preston-Werner");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("'<\\i\\c*\\s*>'");
const std::string expected("<\\i\\c*\\s*>");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("dummy");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_literal_multiline_string)
{
typedef toml::parse_literal_multiline_string parser;
typedef toml::is_literal_multiline_string<toml::character> acceptor;
{
const std::string source("'''I [dw]on't need \\d{2} apples'''");
const std::string expected("I [dw]on't need \\d{2} apples");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("'''\nThe first newline is \ntrimmed in raw strings.\n All other whitespace\n is preserved.'''");
const std::string expected("The first newline is \ntrimmed in raw strings.\n All other whitespace\n is preserved.");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("dummy");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_string)
{
typedef toml::parse_string parser;
typedef toml::is_string<toml::character> acceptor;
{
const std::string source("\"string\"");
const std::string expected("string");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("\"\"\"string\"\"\"");
const std::string expected("string");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("'string'");
const std::string expected("string");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("'''string'''");
const std::string expected("string");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("dummy");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_integer)
{
typedef toml::parse_integer parser;
typedef toml::is_integer<toml::character> acceptor;
{
const std::string source("42");
const toml::Integer expected(42);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("+42");
const toml::Integer expected(42);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("-42");
const toml::Integer expected(-42);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("-4_2");
const toml::Integer expected(-42);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("dummy");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_float)
{
typedef toml::parse_float parser;
typedef toml::is_float<toml::character> acceptor;
{
const std::string source("42.0");
const toml::Float expected(42.0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("+42.0");
const toml::Float expected(42.0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("-42.0");
const toml::Float expected(-42.0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("-4_2.0");
const toml::Float expected(-42.0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("-42e0");
const toml::Float expected(-42.0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("-42.0e0");
const toml::Float expected(-42.0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("dummy");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
{
const std::string source("42");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_boolean)
{
typedef toml::parse_boolean parser;
typedef toml::is_boolean<toml::character> acceptor;
{
const std::string source("true");
const toml::Boolean expected(true);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("false");
const toml::Boolean expected(false);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("dummy");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_local_time)
{
typedef toml::parse_local_time parser;
typedef toml::is_local_time<toml::character> acceptor;
{
const std::string source("12:34:56");
const toml::Datetime expected(12, 34, 56, 0, 0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("12:34:56.7");
const toml::Datetime expected(12, 34, 56, 700, 0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("12:34:56.7891");
const toml::Datetime expected(12, 34, 56, 789, 100);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("10");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_local_date)
{
typedef toml::parse_local_date parser;
typedef toml::is_local_date<toml::character> acceptor;
{
const std::string source("1979-09-27");
const toml::Datetime expected(1979, 9, 27);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("10");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_local_date_time)
{
typedef toml::parse_local_date_time parser;
typedef toml::is_local_date_time<toml::character> acceptor;
{
const std::string source("1979-09-27T12:34:56");
const toml::Datetime expected(1979, 9, 27, 12, 34, 56, 0, 0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("1979-09-27T12:34:56.789000");
const toml::Datetime expected(1979, 9, 27, 12, 34, 56, 789, 0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("1000-11-11");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_offset_date_time)
{
typedef toml::parse_offset_date_time parser;
typedef toml::is_offset_date_time<toml::character> acceptor;
{
const std::string source("1979-09-27T12:34:56Z");
const toml::Datetime expected(1979, 9, 27, 12, 34, 56, 0, 0, 0, 0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("1979-09-27T12:34:56.789000Z");
const toml::Datetime expected(1979, 9, 27, 12, 34, 56, 789, 0, 0, 0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("1979-09-27T12:34:56+07:30");
const toml::Datetime expected(1979, 9, 27, 12, 34, 56, 0, 0, 7, 30);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("1979-09-27T12:34:56.789000+07:30");
const toml::Datetime expected(1979, 9, 27, 12, 34, 56, 789, 0, 7, 30);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("1979-09-27T12:34:56-07:30");
const toml::Datetime expected(1979, 9, 27, 12, 34, 56, 0, 0, -7, -30);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("1979-09-27T12:34:56.789000-07:30");
const toml::Datetime expected(1979, 9, 27, 12, 34, 56, 789, 0, -7, -30);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("1000-11-11");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_datetime)
{
typedef toml::parse_datetime parser;
typedef toml::is_datetime<toml::character> acceptor;
{
const std::string source("1979-09-27T12:34:56Z");
const toml::Datetime expected(1979, 9, 27, 12, 34, 56, 0, 0, 0, 0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("1979-09-27T12:34:56");
const toml::Datetime expected(1979, 9, 27, 12, 34, 56, 0, 0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("1979-09-27");
const toml::Datetime expected(1979, 9, 27);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("12:34:56");
const toml::Datetime expected(12, 34, 56, 0, 0);
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK_EQUAL(result.first.get(), expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("12");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_array)
{
typedef toml::parse_array<toml::character> parser;
typedef toml::is_array<toml::character> acceptor;
{
const std::string source("[1,2,3]");
const toml::Array expected{1, 2, 3};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[1, 2, 3]");
const toml::Array expected{1, 2, 3};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[ 1,2,3 ]");
const toml::Array expected{1, 2, 3};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[ 1 , 2 , 3 ]");
const toml::Array expected{1, 2, 3};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[ 1 \n,#comment\n 2 ,\n 3\n ]");
const toml::Array expected{1, 2, 3};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[ # empty array\n ]");
const toml::Array expected{};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[ \"] \", ' # ', \n']', # ] \n]");
const toml::Array expected{"] ", " # ", "]"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[ \"Test #11 ]proved that\", 'Experiment #9 was a success' ]");
const toml::Array expected{"Test #11 ]proved that", "Experiment #9 was a success"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[ \"Test #11 ]proved that\", 'Experiment #9 was a success' ]");
const toml::Array expected{"Test #11 ]proved that", "Experiment #9 was a success"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[ [1,2,3] , ['a', 'b', 'c'] ]");
const toml::Array expected{{1,2,3}, {"a", "b", "c"}};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[ {foo=1}, {foo=1, bar=2.0}, {foo=1, bar=2.0, baz='str'} ]");
const toml::Array expected{{{"foo", 1}}, {{"foo", 1}, {"bar", 2.0}}, {{"foo", 1}, {"bar", 2.0}, {"baz", "str"}}};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[dummy]");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_inline_table)
{
typedef toml::parse_inline_table<toml::character> parser;
typedef toml::is_inline_table<toml::character> acceptor;
{
const std::string source("{foo=1,bar=2.0,baz='str'}");
const toml::Table expected{{"foo", 1}, {"bar", 2.0}, {"baz", "str"}};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("{ foo=1, bar=2.0, baz='str' }");
const toml::Table expected{{"foo", 1}, {"bar", 2.0}, {"baz", "str"}};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("{ foo = 1, bar = 2.0, baz = 'str' }");
const toml::Table expected{{"foo", 1}, {"bar", 2.0}, {"baz", "str"}};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("{b=true, i=1, f=2.0, d=1907-03-02T07:32:00, s='str', a=[1,2,3], t={foo=1}}");
const toml::Table expected{{"b", true}, {"i", 1}, {"f", 2.0},
{"d", toml::Datetime(1907,3,2,7,32,0,0,0)},
{"s", "str"}, {"a", {1, 2, 3}},
{"t", {{"foo", 1}}}};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("{dummy}");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(!result.first.ok());
BOOST_CHECK(result.second == source.begin());
}
}
BOOST_AUTO_TEST_CASE(test_parse_barekey)
{
typedef toml::parse_barekey parser;
typedef toml::is_barekey<toml::character> acceptor;
{
const std::string source("hoge");
const toml::key expected("hoge");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("bare-key");
const toml::key expected("bare-key");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("bare_key");
const toml::key expected("bare_key");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("42");
const toml::key expected("42");
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
}
BOOST_AUTO_TEST_CASE(test_key_value_pair)
{
typedef toml::parse_key_value_pair<char> parser;
typedef toml::is_key_value_pair<char> acceptor;
{
const std::string source("key=1");
const std::pair<toml::key, toml::value> expected{"key", 1};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("key =\t1");
const std::pair<toml::key, toml::value> expected{"key", 1};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("key = true");
const std::pair<toml::key, toml::value> expected{"key", true};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("key = -42");
const std::pair<toml::key, toml::value> expected{"key", -42};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("key = -42.0");
const std::pair<toml::key, toml::value> expected{"key", -42.};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("key = \"string\"");
const std::pair<toml::key, toml::value> expected{"key", "string"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("key = 1901-01-01T00:00:00");
const std::pair<toml::key, toml::value> expected{"key", toml::Datetime(1901, 1,1,0,0,0,0,0)};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("key = [1,2,3]");
const std::pair<toml::key, toml::value> expected{"key", {1,2,3}};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("key = {foo=1,bar=2.0,baz='3'}");
const std::pair<toml::key, toml::value> expected{"key",
{{"foo", 1}, {"bar", 2.0}, {"baz", "3"}}};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
}
BOOST_AUTO_TEST_CASE(test_table_definition)
{
typedef toml::parse_table_definition parser;
typedef toml::is_table_definition<char> acceptor;
{
const std::string source("[foo]");
const std::vector<toml::key> expected{"foo"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[foo.bar.baz]");
const std::vector<toml::key> expected{"foo", "bar", "baz"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[foo . bar. baz]");
const std::vector<toml::key> expected{"foo", "bar", "baz"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[foo . \"bar\" . baz]");
const std::vector<toml::key> expected{"foo", "bar", "baz"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[foo . \"b\\tar\" . baz]");
const std::vector<toml::key> expected{"foo", "b\tar", "baz"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
}
BOOST_AUTO_TEST_CASE(test_array_of_table_definition)
{
typedef toml::parse_array_of_table_definition parser;
typedef toml::is_array_of_table_definition<char> acceptor;
{
const std::string source("[[foo]]");
const std::vector<toml::key> expected{"foo"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[[foo.bar.baz]]");
const std::vector<toml::key> expected{"foo", "bar", "baz"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[[foo . bar. baz]]");
const std::vector<toml::key> expected{"foo", "bar", "baz"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[[foo . \"bar\" . baz]]");
const std::vector<toml::key> expected{"foo", "bar", "baz"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
{
const std::string source("[[foo . \"b\\tar\" . baz]]");
const std::vector<toml::key> expected{"foo", "b\tar", "baz"};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result.first.ok());
BOOST_CHECK(result.first.get() == expected);
BOOST_CHECK(result.second == acceptor::invoke(source.begin(), source.end()));
}
}
BOOST_AUTO_TEST_CASE(test_parse_data)
{
typedef toml::parse_data parser;
{
const std::string source("#hogehoge");
const toml::Table expected{};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result == expected);
}
{
const std::string source("key = 'value'");
const toml::Table expected{{"key", "value"}};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result == expected);
}
{
const std::string source("key = 'value' #hoge");
const toml::Table expected{{"key", "value"}};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result == expected);
}
{
const std::string source("[table]\nkey = 'value' #hoge");
const toml::Table expected{{"table", {{"key", "value"}} }};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result == expected);
}
{
const std::string source("[table]\n\tkey = 'value'\n\t#hoge");
const toml::Table expected{{"table", {{"key", "value"}} }};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result == expected);
}
{
const std::string source("[table]\n\tkey = 'value'\n\t#hoge");
const toml::Table expected{{"table", {{"key", "value"}} }};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result == expected);
}
{
const std::string source("[nested.table]\n\tkey = 'value'\n\t#hoge");
const toml::Table expected{{"nested", {{"table", {{"key", "value"}}}}}};
const auto result = parser::invoke(source.cbegin(), source.cend());
BOOST_CHECK(result == expected);
}
}

441
tests/test_result.cpp Normal file
View File

@@ -0,0 +1,441 @@
#define BOOST_TEST_MODULE "test_result"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <toml/result.hpp>
BOOST_AUTO_TEST_CASE(test_construct)
{
{
auto s = toml::ok(42);
toml::result<int, std::string> result(s);
BOOST_TEST(!!result);
BOOST_TEST(result.is_ok());
BOOST_TEST(!result.is_err());
BOOST_TEST(result.unwrap() == 42);
}
{
const auto s = toml::ok(42);
toml::result<int, std::string> result(s);
BOOST_TEST(!!result);
BOOST_TEST(result.is_ok());
BOOST_TEST(!result.is_err());
BOOST_TEST(result.unwrap() == 42);
}
{
toml::result<int, std::string> result(toml::ok(42));
BOOST_TEST(!!result);
BOOST_TEST(result.is_ok());
BOOST_TEST(!result.is_err());
BOOST_TEST(result.unwrap() == 42);
}
{
auto f = toml::err<std::string>("foobar");
toml::result<int, std::string> result(f);
BOOST_TEST(!result);
BOOST_TEST(!result.is_ok());
BOOST_TEST(result.is_err());
BOOST_TEST(result.unwrap_err() == "foobar");
}
{
const auto f = toml::err<std::string>("foobar");
toml::result<int, std::string> result(f);
BOOST_TEST(!result);
BOOST_TEST(!result.is_ok());
BOOST_TEST(result.is_err());
BOOST_TEST(result.unwrap_err() == "foobar");
}
{
toml::result<int, std::string> result(toml::err<std::string>("foobar"));
BOOST_TEST(!result);
BOOST_TEST(!result.is_ok());
BOOST_TEST(result.is_err());
BOOST_TEST(result.unwrap_err() == "foobar");
}
}
BOOST_AUTO_TEST_CASE(test_assignment)
{
{
toml::result<int, std::string> result(toml::err<std::string>("foobar"));
result = toml::ok(42);
BOOST_TEST(!!result);
BOOST_TEST(result.is_ok());
BOOST_TEST(!result.is_err());
BOOST_TEST(result.unwrap() == 42);
}
{
toml::result<int, std::string> result(toml::err<std::string>("foobar"));
auto s = toml::ok(42);
result = s;
BOOST_TEST(!!result);
BOOST_TEST(result.is_ok());
BOOST_TEST(!result.is_err());
BOOST_TEST(result.unwrap() == 42);
}
{
toml::result<int, std::string> result(toml::err<std::string>("foobar"));
const auto s = toml::ok(42);
result = s;
BOOST_TEST(!!result);
BOOST_TEST(result.is_ok());
BOOST_TEST(!result.is_err());
BOOST_TEST(result.unwrap() == 42);
}
{
toml::result<int, std::string> result(toml::err<std::string>("foobar"));
result = toml::err<std::string>("hoge");
BOOST_TEST(!result);
BOOST_TEST(!result.is_ok());
BOOST_TEST(result.is_err());
BOOST_TEST(result.unwrap_err() == "hoge");
}
{
toml::result<int, std::string> result(toml::err<std::string>("foobar"));
auto f = toml::err<std::string>("hoge");
result = f;
BOOST_TEST(!result);
BOOST_TEST(!result.is_ok());
BOOST_TEST(result.is_err());
BOOST_TEST(result.unwrap_err() == "hoge");
}
{
toml::result<int, std::string> result(toml::err<std::string>("foobar"));
const auto f = toml::err<std::string>("hoge");
result = f;
BOOST_TEST(!result);
BOOST_TEST(!result.is_ok());
BOOST_TEST(result.is_err());
BOOST_TEST(result.unwrap_err() == "hoge");
}
}
BOOST_AUTO_TEST_CASE(test_map)
{
{
const toml::result<int, std::string> result(toml::ok(42));
const auto mapped = result.map(
[](const int i) -> int {
return i * 2;
});
BOOST_TEST(!!mapped);
BOOST_TEST(mapped.is_ok());
BOOST_TEST(!mapped.is_err());
BOOST_TEST(mapped.unwrap() == 42 * 2);
}
{
toml::result<std::unique_ptr<int>, std::string>
result(toml::ok(std::unique_ptr<int>(new int(42))));
const auto mapped = std::move(result).map(
[](std::unique_ptr<int> i) -> int {
return *i;
});
BOOST_TEST(!!mapped);
BOOST_TEST(mapped.is_ok());
BOOST_TEST(!mapped.is_err());
BOOST_TEST(mapped.unwrap() == 42);
}
{
const toml::result<int, std::string> result(toml::err<std::string>("hoge"));
const auto mapped = result.map(
[](const int i) -> int {
return i * 2;
});
BOOST_TEST(!mapped);
BOOST_TEST(!mapped.is_ok());
BOOST_TEST(mapped.is_err());
BOOST_TEST(mapped.unwrap_err() == "hoge");
}
{
toml::result<std::unique_ptr<int>, std::string>
result(toml::err<std::string>("hoge"));
const auto mapped = std::move(result).map(
[](std::unique_ptr<int> i) -> int {
return *i;
});
BOOST_TEST(!mapped);
BOOST_TEST(!mapped.is_ok());
BOOST_TEST(mapped.is_err());
BOOST_TEST(mapped.unwrap_err() == "hoge");
}
}
BOOST_AUTO_TEST_CASE(test_map_err)
{
{
const toml::result<int, std::string> result(toml::ok(42));
const auto mapped = result.map_err(
[](const std::string s) -> std::string {
return s + s;
});
BOOST_TEST(!!mapped);
BOOST_TEST(mapped.is_ok());
BOOST_TEST(!mapped.is_err());
BOOST_TEST(mapped.unwrap() == 42);
}
{
toml::result<std::unique_ptr<int>, std::string>
result(toml::ok(std::unique_ptr<int>(new int(42))));
const auto mapped = std::move(result).map_err(
[](const std::string s) -> std::string {
return s + s;
});
BOOST_TEST(!!mapped);
BOOST_TEST(mapped.is_ok());
BOOST_TEST(!mapped.is_err());
BOOST_TEST(*(mapped.unwrap()) == 42);
}
{
const toml::result<int, std::string> result(toml::err<std::string>("hoge"));
const auto mapped = result.map_err(
[](const std::string s) -> std::string {
return s + s;
});
BOOST_TEST(!mapped);
BOOST_TEST(!mapped.is_ok());
BOOST_TEST(mapped.is_err());
BOOST_TEST(mapped.unwrap_err() == "hogehoge");
}
{
toml::result<int, std::unique_ptr<std::string>>
result(toml::err(std::unique_ptr<std::string>(new std::string("hoge"))));
const auto mapped = std::move(result).map_err(
[](std::unique_ptr<std::string> p) -> std::string {
return *p;
});
BOOST_TEST(!mapped);
BOOST_TEST(!mapped.is_ok());
BOOST_TEST(mapped.is_err());
BOOST_TEST(mapped.unwrap_err() == "hoge");
}
}
BOOST_AUTO_TEST_CASE(test_map_or_else)
{
{
const toml::result<int, std::string> result(toml::ok(42));
const auto mapped = result.map_or_else(
[](const int i) -> int {
return i * 2;
}, 54);
BOOST_TEST(mapped == 42 * 2);
}
{
toml::result<std::unique_ptr<int>, std::string>
result(toml::ok(std::unique_ptr<int>(new int(42))));
const auto mapped = std::move(result).map_or_else(
[](std::unique_ptr<int> i) -> int {
return *i;
}, 54);
BOOST_TEST(mapped == 42);
}
{
const toml::result<int, std::string> result(toml::err<std::string>("hoge"));
const auto mapped = result.map_or_else(
[](const int i) -> int {
return i * 2;
}, 54);
BOOST_TEST(mapped == 54);
}
{
toml::result<std::unique_ptr<int>, std::string>
result(toml::err<std::string>("hoge"));
const auto mapped = std::move(result).map_or_else(
[](std::unique_ptr<int> i) -> int {
return *i;
}, 54);
BOOST_TEST(mapped == 54);
}
}
BOOST_AUTO_TEST_CASE(test_map_err_or_else)
{
{
const toml::result<int, std::string> result(toml::ok(42));
const auto mapped = result.map_err_or_else(
[](const std::string i) -> std::string {
return i + i;
}, "foobar");
BOOST_TEST(mapped == "foobar");
}
{
toml::result<std::unique_ptr<int>, std::string>
result(toml::ok(std::unique_ptr<int>(new int(42))));
const auto mapped = std::move(result).map_err_or_else(
[](const std::string i) -> std::string {
return i + i;
}, "foobar");
BOOST_TEST(mapped == "foobar");
}
{
const toml::result<int, std::string> result(toml::err<std::string>("hoge"));
const auto mapped = result.map_err_or_else(
[](const std::string i) -> std::string {
return i + i;
}, "foobar");
BOOST_TEST(mapped == "hogehoge");
}
{
toml::result<std::unique_ptr<int>, std::string>
result(toml::err<std::string>("hoge"));
const auto mapped = result.map_err_or_else(
[](const std::string i) -> std::string {
return i + i;
}, "foobar");
BOOST_TEST(mapped == "hogehoge");
}
}
BOOST_AUTO_TEST_CASE(test_and_then)
{
{
const toml::result<int, std::string> result(toml::ok(42));
const auto mapped = result.and_then(
[](const int i) -> toml::result<int, std::string> {
return toml::ok(i * 2);
});
BOOST_TEST(!!mapped);
BOOST_TEST(mapped.is_ok());
BOOST_TEST(!mapped.is_err());
BOOST_TEST(mapped.unwrap() == 42 * 2);
}
{
toml::result<std::unique_ptr<int>, std::string>
result(toml::ok(std::unique_ptr<int>(new int(42))));
const auto mapped = std::move(result).and_then(
[](std::unique_ptr<int> i) -> toml::result<int, std::string> {
return toml::ok(*i);
});
BOOST_TEST(!!mapped);
BOOST_TEST(mapped.is_ok());
BOOST_TEST(!mapped.is_err());
BOOST_TEST(mapped.unwrap() == 42);
}
{
const toml::result<int, std::string> result(toml::err<std::string>("hoge"));
const auto mapped = result.and_then(
[](const int i) -> toml::result<int, std::string> {
return toml::ok(i * 2);
});
BOOST_TEST(!mapped);
BOOST_TEST(!mapped.is_ok());
BOOST_TEST(mapped.is_err());
BOOST_TEST(mapped.unwrap_err() == "hoge");
}
{
toml::result<std::unique_ptr<int>, std::string>
result(toml::err<std::string>("hoge"));
const auto mapped = std::move(result).and_then(
[](std::unique_ptr<int> i) -> toml::result<int, std::string> {
return toml::ok(*i);
});
BOOST_TEST(!mapped);
BOOST_TEST(!mapped.is_ok());
BOOST_TEST(mapped.is_err());
BOOST_TEST(mapped.unwrap_err() == "hoge");
}
}
BOOST_AUTO_TEST_CASE(test_or_else)
{
{
const toml::result<int, std::string> result(toml::ok(42));
const auto mapped = result.or_else(
[](const std::string& s) -> toml::result<int, std::string> {
return toml::err(s + s);
});
BOOST_TEST(!!mapped);
BOOST_TEST(mapped.is_ok());
BOOST_TEST(!mapped.is_err());
BOOST_TEST(mapped.unwrap() == 42);
}
{
toml::result<std::unique_ptr<int>, std::string>
result(toml::ok(std::unique_ptr<int>(new int(42))));
const auto mapped = std::move(result).or_else(
[](const std::string& s) -> toml::result<std::unique_ptr<int>, std::string> {
return toml::err(s + s);
});
BOOST_TEST(!!mapped);
BOOST_TEST(mapped.is_ok());
BOOST_TEST(!mapped.is_err());
BOOST_TEST(*mapped.unwrap() == 42);
}
{
const toml::result<int, std::string> result(toml::err<std::string>("hoge"));
const auto mapped = result.or_else(
[](const std::string& s) -> toml::result<int, std::string> {
return toml::err(s + s);
});
BOOST_TEST(!mapped);
BOOST_TEST(!mapped.is_ok());
BOOST_TEST(mapped.is_err());
BOOST_TEST(mapped.unwrap_err() == "hogehoge");
}
{
toml::result<std::unique_ptr<int>, std::string>
result(toml::err<std::string>("hoge"));
const auto mapped = std::move(result).or_else(
[](const std::string& s) -> toml::result<std::unique_ptr<int>, std::string> {
return toml::err(s + s);
});
BOOST_TEST(!mapped);
BOOST_TEST(!mapped.is_ok());
BOOST_TEST(mapped.is_err());
BOOST_TEST(mapped.unwrap_err() == "hogehoge");
}
}
BOOST_AUTO_TEST_CASE(test_and_or_other)
{
{
const toml::result<int, std::string> r1(toml::ok(42));
const toml::result<int, std::string> r2(toml::err<std::string>("foo"));
BOOST_TEST(r1 == r1.or_other(r2));
BOOST_TEST(r2 == r1.and_other(r2));
BOOST_TEST(42 == r1.or_other(r2).unwrap());
BOOST_TEST("foo" == r1.and_other(r2).unwrap_err());
}
{
auto r1_gen = []() -> toml::result<int, std::string> {
return toml::ok(42);
};
auto r2_gen = []() -> toml::result<int, std::string> {
return toml::err<std::string>("foo");
};
const auto r3 = r1_gen();
const auto r4 = r2_gen();
BOOST_TEST(r3 == r1_gen().or_other (r2_gen()));
BOOST_TEST(r4 == r1_gen().and_other(r2_gen()));
BOOST_TEST(42 == r1_gen().or_other (r2_gen()).unwrap());
BOOST_TEST("foo" == r1_gen().and_other(r2_gen()).unwrap_err());
}
}

View File

@@ -0,0 +1,305 @@
#define BOOST_TEST_MODULE "test_serialize_file"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <deque>
#include <map>
#include <iostream>
#include <fstream>
template<typename Comment,
template<typename ...> class Table,
template<typename ...> class Array>
bool has_comment_inside(const toml::basic_value<Comment, Table, Array>& v)
{
if(!v.comments().empty())
{
return false;
}
// v itself does not have a comment.
if(v.is_array())
{
for(const auto& x : v.as_array())
{
if(has_comment_inside(x))
{
return false;
}
}
}
if(v.is_table())
{
for(const auto& x : v.as_table())
{
if(has_comment_inside(x.second))
{
return false;
}
}
}
return true;
}
BOOST_AUTO_TEST_CASE(test_example)
{
const auto data = toml::parse("toml/tests/example.toml");
{
std::ofstream ofs("tmp1.toml");
ofs << std::setw(80) << data;
}
auto serialized = toml::parse("tmp1.toml");
{
auto& owner = toml::find(serialized, "owner");
auto& bio = toml::find<std::string>(owner, "bio");
const auto CR = std::find(bio.begin(), bio.end(), '\r');
if(CR != bio.end())
{
bio.erase(CR);
}
}
BOOST_TEST(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_example_map_dq)
{
const auto data = toml::parse<toml::discard_comments, std::map, std::deque>(
"toml/tests/example.toml");
{
std::ofstream ofs("tmp1_map_dq.toml");
ofs << std::setw(80) << data;
}
auto serialized = toml::parse<toml::discard_comments, std::map, std::deque>(
"tmp1_map_dq.toml");
{
auto& owner = toml::find(serialized, "owner");
auto& bio = toml::find<std::string>(owner, "bio");
const auto CR = std::find(bio.begin(), bio.end(), '\r');
if(CR != bio.end())
{
bio.erase(CR);
}
}
BOOST_TEST(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_example_with_comment)
{
const auto data = toml::parse<toml::preserve_comments>("toml/tests/example.toml");
{
std::ofstream ofs("tmp1_com.toml");
ofs << std::setw(80) << data;
}
auto serialized = toml::parse<toml::preserve_comments>("tmp1_com.toml");
{
auto& owner = toml::find(serialized, "owner");
auto& bio = toml::find<std::string>(owner, "bio");
const auto CR = std::find(bio.begin(), bio.end(), '\r');
if(CR != bio.end())
{
bio.erase(CR);
}
}
BOOST_TEST(data == serialized);
{
std::ofstream ofs("tmp1_com1.toml");
ofs << std::setw(80) << serialized;
}
}
BOOST_AUTO_TEST_CASE(test_example_with_comment_nocomment)
{
{
const auto data = toml::parse<toml::preserve_comments>("toml/tests/example.toml");
{
std::ofstream ofs("tmp1_com_nocomment.toml");
ofs << std::setw(80) << toml::nocomment << data;
}
const auto serialized = toml::parse<toml::preserve_comments>("tmp1_com_nocomment.toml");
// check no comment exist
BOOST_TEST(!has_comment_inside(serialized));
}
{
const auto data_nocomment = toml::parse("toml/tests/example.toml");
auto serialized = toml::parse("tmp1_com_nocomment.toml");
{
auto& owner = toml::find(serialized, "owner");
auto& bio = toml::find<std::string>(owner, "bio");
const auto CR = std::find(bio.begin(), bio.end(), '\r');
if(CR != bio.end())
{
bio.erase(CR);
}
}
// check collectly serialized
BOOST_TEST(data_nocomment == serialized);
}
}
BOOST_AUTO_TEST_CASE(test_example_with_comment_map_dq)
{
const auto data = toml::parse<toml::preserve_comments, std::map, std::deque>(
"toml/tests/example.toml");
{
std::ofstream ofs("tmp1_com_map_dq.toml");
ofs << std::setw(80) << data;
}
auto serialized = toml::parse<toml::preserve_comments, std::map, std::deque>(
"tmp1_com_map_dq.toml");
{
auto& owner = toml::find(serialized, "owner");
auto& bio = toml::find<std::string>(owner, "bio");
const auto CR = std::find(bio.begin(), bio.end(), '\r');
if(CR != bio.end())
{
bio.erase(CR);
}
}
BOOST_TEST(data == serialized);
{
std::ofstream ofs("tmp1_com1_map_dq.toml");
ofs << std::setw(80) << serialized;
}
}
BOOST_AUTO_TEST_CASE(test_example_with_comment_map_dq_nocomment)
{
{
const auto data = toml::parse<toml::preserve_comments, std::map, std::deque>("toml/tests/example.toml");
{
std::ofstream ofs("tmp1_com_map_dq_nocomment.toml");
ofs << std::setw(80) << toml::nocomment << data;
}
const auto serialized = toml::parse<toml::preserve_comments, std::map, std::deque>("tmp1_com_map_dq_nocomment.toml");
BOOST_TEST(!has_comment_inside(serialized));
}
{
const auto data_nocomment = toml::parse("toml/tests/example.toml");
auto serialized = toml::parse("tmp1_com_map_dq_nocomment.toml");
{
auto& owner = toml::find(serialized, "owner");
auto& bio = toml::find<std::string>(owner, "bio");
const auto CR = std::find(bio.begin(), bio.end(), '\r');
if(CR != bio.end())
{
bio.erase(CR);
}
}
BOOST_TEST(data_nocomment == serialized);
}
}
BOOST_AUTO_TEST_CASE(test_fruit)
{
const auto data = toml::parse("toml/tests/fruit.toml");
{
std::ofstream ofs("tmp2.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse("tmp2.toml");
BOOST_TEST(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_fruit_map_dq)
{
const auto data = toml::parse<toml::discard_comments, std::map, std::deque>(
"toml/tests/fruit.toml");
{
std::ofstream ofs("tmp2.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse<toml::discard_comments, std::map, std::deque>(
"tmp2.toml");
BOOST_TEST(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_fruit_with_comments)
{
const auto data = toml::parse<toml::preserve_comments>("toml/tests/fruit.toml");
{
std::ofstream ofs("tmp2_com.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse<toml::preserve_comments>("tmp2_com.toml");
BOOST_TEST(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_fruit_with_comments_map_dq)
{
const auto data = toml::parse<toml::preserve_comments, std::map, std::deque>(
"toml/tests/fruit.toml");
{
std::ofstream ofs("tmp2_com.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse<toml::preserve_comments, std::map, std::deque>("tmp2_com.toml");
BOOST_TEST(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_hard_example)
{
const auto data = toml::parse("toml/tests/hard_example.toml");
{
std::ofstream ofs("tmp3.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse("tmp3.toml");
BOOST_TEST(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_hard_example_map_dq)
{
const auto data = toml::parse<toml::discard_comments, std::map, std::deque>(
"toml/tests/hard_example.toml");
{
std::ofstream ofs("tmp3.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse<toml::discard_comments, std::map, std::deque>(
"tmp3.toml");
BOOST_TEST(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_hard_example_with_comment)
{
const auto data = toml::parse<toml::preserve_comments, std::map, std::deque>(
"toml/tests/hard_example.toml");
{
std::ofstream ofs("tmp3_com.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse<toml::preserve_comments, std::map, std::deque>(
"tmp3_com.toml");
{
std::ofstream ofs("tmp3_com1.toml");
ofs << std::setw(80) << serialized;
}
BOOST_TEST(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_format_key)
{
{
const toml::key key("normal_bare-key");
BOOST_TEST("normal_bare-key" == toml::format_key(key));
}
{
const toml::key key("key.include.dots");
BOOST_TEST("\"key.include.dots\"" == toml::format_key(key));
}
{
const toml::key key("key-include-unicode-\xE3\x81\x82");
BOOST_TEST("\"key-include-unicode-\xE3\x81\x82\"" == toml::format_key(key));
}
{
const toml::key key("special-chars-\\-\"-\b-\f-\r-\n-\t");
BOOST_TEST("\"special-chars-\\\\-\\\"-\\b-\\f-\\r-\\n-\\t\"" == toml::format_key(key));
}
}

154
tests/test_string.cpp Normal file
View File

@@ -0,0 +1,154 @@
#define BOOST_TEST_MODULE "test_string"
#include <boost/test/unit_test.hpp>
#include <toml.hpp>
BOOST_AUTO_TEST_CASE(test_basic_string)
{
{
const toml::string str("basic string");
std::ostringstream oss;
oss << str;
BOOST_TEST(oss.str() == "\"basic string\"");
}
{
const std::string s1 ("basic string");
const toml::string str(s1);
std::ostringstream oss;
oss << str;
BOOST_TEST(oss.str() == "\"basic string\"");
}
{
const toml::string str("basic string", toml::string_t::basic);
std::ostringstream oss;
oss << str;
BOOST_TEST(oss.str() == "\"basic string\"");
}
{
const std::string s1 ("basic string");
const toml::string str(s1, toml::string_t::basic);
std::ostringstream oss;
oss << str;
BOOST_TEST(oss.str() == "\"basic string\"");
}
}
BOOST_AUTO_TEST_CASE(test_basic_ml_string)
{
{
const toml::string str("basic\nstring");
std::ostringstream oss1;
oss1 << str;
std::ostringstream oss2;
oss2 << "\"\"\"\nbasic\nstring\\\n\"\"\"";
BOOST_TEST(oss1.str() == oss2.str());
}
{
const std::string s1 ("basic\nstring");
const toml::string str(s1);
std::ostringstream oss1;
oss1 << str;
std::ostringstream oss2;
oss2 << "\"\"\"\nbasic\nstring\\\n\"\"\"";
BOOST_TEST(oss1.str() == oss2.str());
}
{
const toml::string str("basic\nstring", toml::string_t::basic);
std::ostringstream oss1;
oss1 << str;
std::ostringstream oss2;
oss2 << "\"\"\"\nbasic\nstring\\\n\"\"\"";
BOOST_TEST(oss1.str() == oss2.str());
}
{
const std::string s1 ("basic\nstring");
const toml::string str(s1, toml::string_t::basic);
std::ostringstream oss1;
oss1 << str;
std::ostringstream oss2;
oss2 << "\"\"\"\nbasic\nstring\\\n\"\"\"";
BOOST_TEST(oss1.str() == oss2.str());
}
}
BOOST_AUTO_TEST_CASE(test_literal_string)
{
{
const toml::string str("literal string", toml::string_t::literal);
std::ostringstream oss;
oss << str;
BOOST_TEST(oss.str() == "'literal string'");
}
{
const std::string s1 ("literal string");
const toml::string str(s1, toml::string_t::literal);
std::ostringstream oss;
oss << str;
BOOST_TEST(oss.str() == "'literal string'");
}
}
BOOST_AUTO_TEST_CASE(test_literal_ml_string)
{
{
const toml::string str("literal\nstring", toml::string_t::literal);
std::ostringstream oss1;
oss1 << str;
std::ostringstream oss2;
oss2 << "'''\nliteral\nstring'''";
BOOST_TEST(oss1.str() == oss2.str());
}
{
const std::string s1 ("literal\nstring");
const toml::string str(s1, toml::string_t::literal);
std::ostringstream oss1;
oss1 << str;
std::ostringstream oss2;
oss2 << "'''\nliteral\nstring'''";
BOOST_TEST(oss1.str() == oss2.str());
}
}
BOOST_AUTO_TEST_CASE(test_string_add_assign)
{
// string literal
{
toml::string str("foo");
str += "bar";
BOOST_TEST(str.str == "foobar");
}
// std::string
{
toml::string str("foo");
std::string str2("bar");
str += str2;
BOOST_TEST(str.str == "foobar");
}
// toml::string
{
toml::string str("foo");
toml::string str2("bar");
str += str2;
BOOST_TEST(str.str == "foobar");
}
#if __cplusplus >= 201703L
// std::string_view
{
toml::string str("foo");
str += std::string_view("bar");
BOOST_TEST(str == "foobar");
}
#endif
// std::string += toml::string
{
std::string str("foo");
toml::string str2("bar");
str += str2;
BOOST_TEST(str == "foobar");
}
}

View File

@@ -1,105 +0,0 @@
#define BOOST_TEST_MODULE "test_to_toml"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <map>
#include <list>
BOOST_AUTO_TEST_CASE(test_to_toml_exact)
{
toml::Boolean b(true);
toml::Integer i(42);
toml::Float f(3.14);
toml::String s("hoge");
toml::Datetime d(std::chrono::system_clock::now());
toml::Array a;
a.emplace_back(2);
a.emplace_back(7);
a.emplace_back(1);
a.emplace_back(8);
a.emplace_back(2);
toml::Table t;
t.emplace("val1", true);
t.emplace("val2", 42);
t.emplace("val3", 3.14);
t.emplace("val4", "piyo");
auto v1 = toml::to_toml(b);
auto v2 = toml::to_toml(i);
auto v3 = toml::to_toml(f);
auto v4 = toml::to_toml(s);
auto v5 = toml::to_toml(d);
auto v6 = toml::to_toml(a);
auto v7 = toml::to_toml(t);
BOOST_CHECK_EQUAL(v1.type(), toml::value_t::Boolean);
BOOST_CHECK_EQUAL(v2.type(), toml::value_t::Integer);
BOOST_CHECK_EQUAL(v3.type(), toml::value_t::Float);
BOOST_CHECK_EQUAL(v4.type(), toml::value_t::String);
BOOST_CHECK_EQUAL(v5.type(), toml::value_t::Datetime);
BOOST_CHECK_EQUAL(v6.type(), toml::value_t::Array);
BOOST_CHECK_EQUAL(v7.type(), toml::value_t::Table);
BOOST_CHECK_EQUAL(v1.cast<toml::value_t::Boolean >(), b);
BOOST_CHECK_EQUAL(v2.cast<toml::value_t::Integer >(), i);
BOOST_CHECK_EQUAL(v3.cast<toml::value_t::Float >(), f);
BOOST_CHECK_EQUAL(v4.cast<toml::value_t::String >(), s);
const auto& ar = v6.cast<toml::value_t::Array>();
BOOST_CHECK_EQUAL(ar.at(0).cast<toml::value_t::Integer>(), a.at(0).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(ar.at(1).cast<toml::value_t::Integer>(), a.at(1).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(ar.at(2).cast<toml::value_t::Integer>(), a.at(2).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(ar.at(3).cast<toml::value_t::Integer>(), a.at(3).cast<toml::value_t::Integer>());
BOOST_CHECK_EQUAL(ar.at(4).cast<toml::value_t::Integer>(), a.at(4).cast<toml::value_t::Integer>());
}
BOOST_AUTO_TEST_CASE(test_to_toml_castable)
{
auto v1 = toml::to_toml(true);
auto v2 = toml::to_toml(42ul);
auto v3 = toml::to_toml(3.14f);
auto v4 = toml::to_toml("hoge");
BOOST_CHECK_EQUAL(v1.type(), toml::value_t::Boolean);
BOOST_CHECK_EQUAL(v2.type(), toml::value_t::Integer);
BOOST_CHECK_EQUAL(v3.type(), toml::value_t::Float);
BOOST_CHECK_EQUAL(v4.type(), toml::value_t::String);
BOOST_CHECK_EQUAL(v1.cast<toml::value_t::Boolean >(), true);
BOOST_CHECK_EQUAL(v2.cast<toml::value_t::Integer >(), 42);
BOOST_CHECK_CLOSE_FRACTION(v3.cast<toml::value_t::Float >(), 3.14, 1e-5);
BOOST_CHECK_EQUAL(v4.cast<toml::value_t::String >(), "hoge");
}
BOOST_AUTO_TEST_CASE(test_to_toml_initializer_list)
{
toml::value v1 = toml::to_toml({3,1,4,1,5});
toml::value v2 = toml::to_toml({{"hoge", 1}, {"piyo", 3.14}, {"fuga", "string"}});
BOOST_CHECK_EQUAL(v1.type(), toml::value_t::Array);
BOOST_CHECK_EQUAL(v2.type(), toml::value_t::Table);
const auto& ar = v1.cast<toml::value_t::Array>();
BOOST_CHECK_EQUAL(ar.at(0).cast<toml::value_t::Integer>(), 3);
BOOST_CHECK_EQUAL(ar.at(1).cast<toml::value_t::Integer>(), 1);
BOOST_CHECK_EQUAL(ar.at(2).cast<toml::value_t::Integer>(), 4);
BOOST_CHECK_EQUAL(ar.at(3).cast<toml::value_t::Integer>(), 1);
BOOST_CHECK_EQUAL(ar.at(4).cast<toml::value_t::Integer>(), 5);
const auto& tb = v2.cast<toml::value_t::Table>();
BOOST_CHECK_EQUAL(tb.at("hoge").type(), toml::value_t::Integer);
BOOST_CHECK_EQUAL(tb.at("piyo").type(), toml::value_t::Float);
BOOST_CHECK_EQUAL(tb.at("fuga").type(), toml::value_t::String);
BOOST_CHECK_EQUAL(tb.at("hoge").cast<toml::value_t::Integer>(), 1);
BOOST_CHECK_CLOSE_FRACTION(tb.at("piyo").cast<toml::value_t::Float>(), 3.14, 1e-3);
BOOST_CHECK_EQUAL(tb.at("fuga").cast<toml::value_t::String>(), "string");
}

View File

@@ -5,7 +5,7 @@
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <toml/types.hpp>
#include <list>
#include <forward_list>
@@ -37,53 +37,48 @@ typedef std::unordered_map<std::string, dummy_type> std_unordered_map_type;
BOOST_AUTO_TEST_CASE(test_has_xxx)
{
BOOST_CHECK(toml::detail::has_iterator<std::list<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_iterator<std::forward_list<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_iterator<std::deque<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_iterator<std::vector<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_iterator<std::set<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_iterator<std::unordered_set<std::string>>::value);
BOOST_CHECK(toml::detail::has_iterator<std_array_type>::value);
BOOST_CHECK(toml::detail::has_iterator<std_map_type>::value);
BOOST_CHECK(toml::detail::has_iterator<std_unordered_map_type>::value);
BOOST_CHECK(toml::detail::has_iterator<dummy_container<dummy_type>>::value);
BOOST_TEST(toml::detail::has_iterator<std::list<dummy_type>>::value);
BOOST_TEST(toml::detail::has_iterator<std::forward_list<dummy_type>>::value);
BOOST_TEST(toml::detail::has_iterator<std::deque<dummy_type>>::value);
BOOST_TEST(toml::detail::has_iterator<std::vector<dummy_type>>::value);
BOOST_TEST(toml::detail::has_iterator<std::set<dummy_type>>::value);
BOOST_TEST(toml::detail::has_iterator<std::unordered_set<std::string>>::value);
BOOST_TEST(toml::detail::has_iterator<std_array_type>::value);
BOOST_TEST(toml::detail::has_iterator<std_map_type>::value);
BOOST_TEST(toml::detail::has_iterator<std_unordered_map_type>::value);
BOOST_TEST(toml::detail::has_iterator<dummy_container<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_value_type<std::list<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_value_type<std::forward_list<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_value_type<std::deque<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_value_type<std::vector<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_value_type<std_array_type>::value);
BOOST_CHECK(toml::detail::has_value_type<std::set<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_value_type<std::unordered_set<std::string>>::value);
BOOST_CHECK(toml::detail::has_value_type<std_map_type>::value);
BOOST_CHECK(toml::detail::has_value_type<std_unordered_map_type>::value);
BOOST_CHECK(toml::detail::has_value_type<dummy_container<dummy_type>>::value);
BOOST_TEST(toml::detail::has_value_type<std::list<dummy_type>>::value);
BOOST_TEST(toml::detail::has_value_type<std::forward_list<dummy_type>>::value);
BOOST_TEST(toml::detail::has_value_type<std::deque<dummy_type>>::value);
BOOST_TEST(toml::detail::has_value_type<std::vector<dummy_type>>::value);
BOOST_TEST(toml::detail::has_value_type<std_array_type>::value);
BOOST_TEST(toml::detail::has_value_type<std::set<dummy_type>>::value);
BOOST_TEST(toml::detail::has_value_type<std::unordered_set<std::string>>::value);
BOOST_TEST(toml::detail::has_value_type<std_map_type>::value);
BOOST_TEST(toml::detail::has_value_type<std_unordered_map_type>::value);
BOOST_TEST(toml::detail::has_value_type<dummy_container<dummy_type>>::value);
BOOST_CHECK(toml::detail::has_key_type<std_map_type>::value);
BOOST_CHECK(toml::detail::has_key_type<std_unordered_map_type>::value);
BOOST_CHECK(toml::detail::has_mapped_type<std_map_type>::value);
BOOST_CHECK(toml::detail::has_mapped_type<std_unordered_map_type>::value);
BOOST_TEST(toml::detail::has_key_type<std_map_type>::value);
BOOST_TEST(toml::detail::has_key_type<std_unordered_map_type>::value);
BOOST_TEST(toml::detail::has_mapped_type<std_map_type>::value);
BOOST_TEST(toml::detail::has_mapped_type<std_unordered_map_type>::value);
}
BOOST_AUTO_TEST_CASE(test_is_xxx)
{
BOOST_CHECK(toml::detail::is_container<std::list<dummy_type>>::value);
BOOST_CHECK(toml::detail::is_container<std::forward_list<dummy_type>>::value);
BOOST_CHECK(toml::detail::is_container<std::deque<dummy_type>>::value);
BOOST_CHECK(toml::detail::is_container<std::vector<dummy_type>>::value);
BOOST_CHECK(toml::detail::is_container<std_array_type>::value);
BOOST_CHECK(toml::detail::is_container<std::set<dummy_type>>::value);
BOOST_CHECK(toml::detail::is_container<std::unordered_set<std::string>>::value);
BOOST_CHECK(toml::detail::is_container<std_map_type>::value);
BOOST_CHECK(toml::detail::is_container<std_unordered_map_type>::value);
BOOST_CHECK(toml::detail::is_container<dummy_container<dummy_type>>::value);
BOOST_TEST(toml::detail::is_container<std::list<dummy_type>>::value);
BOOST_TEST(toml::detail::is_container<std::forward_list<dummy_type>>::value);
BOOST_TEST(toml::detail::is_container<std::deque<dummy_type>>::value);
BOOST_TEST(toml::detail::is_container<std::vector<dummy_type>>::value);
BOOST_TEST(toml::detail::is_container<std_array_type>::value);
BOOST_TEST(toml::detail::is_container<std::set<dummy_type>>::value);
BOOST_TEST(toml::detail::is_container<std::unordered_set<std::string>>::value);
BOOST_TEST(toml::detail::is_container<dummy_container<dummy_type>>::value);
BOOST_CHECK(toml::detail::is_map<std_map_type>::value);
BOOST_CHECK(toml::detail::is_map<std_unordered_map_type>::value);
BOOST_TEST(!toml::detail::is_container<std_map_type>::value);
BOOST_TEST(!toml::detail::is_container<std_unordered_map_type>::value);
BOOST_CHECK(toml::detail::is_key_convertible<std_map_type>::value);
BOOST_CHECK(toml::detail::is_key_convertible<std_unordered_map_type>::value);
BOOST_TEST(toml::detail::is_map<std_map_type>::value);
BOOST_TEST(toml::detail::is_map<std_unordered_map_type>::value);
}

View File

@@ -9,56 +9,41 @@
#include <vector>
#include <array>
BOOST_AUTO_TEST_CASE(test_resize)
BOOST_AUTO_TEST_CASE(test_try_reserve)
{
{
typedef std::vector<int> resizable_type;
typedef std::array<int,1> non_resizable_type;
BOOST_CHECK(toml::detail::has_resize_method<resizable_type>::value);
BOOST_CHECK(!toml::detail::has_resize_method<non_resizable_type>::value);
// since BOOST_TEST is a macro, it cannot handle commas correctly.
// When toml::detail::has_reserve_method<std::array<int, 1>>::value
// is passed to a macro, C preprocessor considers
// toml::detail::has_reserve_method<std::array<int as the first argument
// and 1>>::value as the second argument. We need an alias to avoid
// this problem.
using reservable_type = std::vector<int> ;
using nonreservable_type = std::array<int, 1>;
BOOST_TEST( toml::detail::has_reserve_method<reservable_type >::value);
BOOST_TEST(!toml::detail::has_reserve_method<nonreservable_type>::value);
}
{
bool thrown = false;
std::vector<int> v;
try
{
toml::resize(v, 10);
}
catch(std::exception& ex)
{
thrown = true;
}
BOOST_CHECK(!thrown);
BOOST_CHECK_EQUAL(v.size(), 10);
}
{
bool thrown = false;
std::array<int, 15> a;
try
{
toml::resize(a, 10);
}
catch(std::exception& ex)
{
thrown = true;
}
BOOST_CHECK(!thrown);
BOOST_CHECK_EQUAL(a.size(), 15);
}
{
bool thrown = false;
std::array<int, 15> a;
try
{
toml::resize(a, 20);
}
catch(std::exception& ex)
{
thrown = true;
}
BOOST_CHECK(thrown);
toml::try_reserve(v, 100);
BOOST_TEST(v.capacity() == 100u);
}
}
BOOST_AUTO_TEST_CASE(test_concat_to_string)
{
const std::string cat = toml::concat_to_string("foo", "bar", 42);
BOOST_TEST(cat == "foobar42");
}
BOOST_AUTO_TEST_CASE(test_from_string)
{
{
const std::string str("123");
BOOST_TEST(toml::from_string<int>(str, 0) == 123);
}
{
const std::string str("01");
BOOST_TEST(toml::from_string<int>(str, 0) == 1);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,98 +0,0 @@
#define BOOST_TEST_MODULE "test_value_operator"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <map>
#include <list>
BOOST_AUTO_TEST_CASE(test_value_equal)
{
toml::Boolean b(true);
toml::Integer i(42);
toml::Float f(3.14);
toml::String s("hoge");
toml::Datetime d(std::chrono::system_clock::now());
toml::Array a;
a.emplace_back(2);
a.emplace_back(7);
a.emplace_back(1);
a.emplace_back(8);
a.emplace_back(2);
toml::Table t;
t.emplace("val1", true);
t.emplace("val2", 42);
t.emplace("val3", 3.14);
t.emplace("val4", "piyo");
toml::value v1(b);
toml::value v2(i);
toml::value v3(f);
toml::value v4(s);
toml::value v5(d);
toml::value v6(a);
toml::value v7(t);
toml::value u1(b);
toml::value u2(i);
toml::value u3(f);
toml::value u4(s);
toml::value u5(d);
toml::value u6(a);
toml::value u7(t);
const bool b1 = v1 == u1;
const bool b2 = v2 == u2;
const bool b3 = v3 == u3;
const bool b4 = v4 == u4;
const bool b5 = v5 == u5;
const bool b6 = v6 == u6;
const bool b7 = v7 == u7;
BOOST_CHECK(b1);
BOOST_CHECK(b2);
BOOST_CHECK(b3);
BOOST_CHECK(b4);
BOOST_CHECK(b5);
BOOST_CHECK(b6);
BOOST_CHECK(b7);
{
const bool n1 = v1 != u1;
const bool n2 = v2 != u2;
const bool n3 = v3 != u3;
const bool n4 = v4 != u4;
const bool n5 = v5 != u5;
const bool n6 = v6 != u6;
const bool n7 = v7 != u7;
BOOST_CHECK(!n1);
BOOST_CHECK(!n2);
BOOST_CHECK(!n3);
BOOST_CHECK(!n4);
BOOST_CHECK(!n5);
BOOST_CHECK(!n6);
BOOST_CHECK(!n7);
}
{
const bool n1 = v1 == u2;
const bool n2 = v2 == u3;
const bool n3 = v3 == u4;
const bool n4 = v4 == u5;
const bool n5 = v5 == u6;
const bool n6 = v6 == u7;
const bool n7 = v7 == u1;
BOOST_CHECK(!n1);
BOOST_CHECK(!n2);
BOOST_CHECK(!n3);
BOOST_CHECK(!n4);
BOOST_CHECK(!n5);
BOOST_CHECK(!n6);
BOOST_CHECK(!n7);
}
}

12
tests/test_windows.cpp Normal file
View File

@@ -0,0 +1,12 @@
#include <windows.h>
#include <toml.hpp>
#include <iostream>
int main()
{
using namespace toml::literals::toml_literals;
const auto data = u8R"(windows = "defines min and max as a macro")"_toml;
std::cout << toml::find<std::string>(data, "windows") << std::endl;
return 0;
}

View File

@@ -33,9 +33,13 @@
# error "toml11 requires C++11 or later."
#endif
#define TOML11_VERSION_MAJOR 3
#define TOML11_VERSION_MINOR 5
#define TOML11_VERSION_PATCH 0
#include "toml/parser.hpp"
#include "toml/to_toml.hpp"
#include "toml/from_toml.hpp"
#include "toml/literal.hpp"
#include "toml/serializer.hpp"
#include "toml/get.hpp"
#endif// TOML_FOR_MODERN_CPP

View File

@@ -1,777 +0,0 @@
#ifndef TOML11_ACCEPTOR
#define TOML11_ACCEPTOR
#include <type_traits>
#include <iterator>
#include <limits>
#include "exception.hpp"
namespace toml
{
template<typename charT, charT c>
struct is_character
{
typedef charT value_type;
constexpr static value_type target = c;
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
constexpr static Iterator invoke(Iterator iter, Iterator end)
{
return iter == end ? iter : *iter == c ? std::next(iter) : iter;
}
};
template<typename charT, charT lw, charT up>
struct is_in_range
{
typedef charT value_type;
constexpr static value_type upper = up;
constexpr static value_type lower = lw;
static_assert(lower <= upper, "lower <= upper");
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
constexpr static Iterator invoke(Iterator iter, Iterator end)
{
return iter == end ? iter :
(lower <= *iter && *iter <= upper) ? std::next(iter) : iter;
}
};
template<typename headT, typename ... condT>
struct is_one_of
{
typedef typename headT::value_type value_type;
static_assert(
std::is_same<value_type, typename is_one_of<condT...>::value_type>::value,
"different value_type");
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end)
{
const Iterator tmp = headT::invoke(iter, end);
return (tmp != iter) ? tmp : is_one_of<condT...>::invoke(iter, end);
}
};
template<typename tailT>
struct is_one_of<tailT>
{
typedef typename tailT::value_type value_type;
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end)
{
const Iterator tmp = tailT::invoke(iter, end);
return (tmp != iter) ? tmp : iter;
}
};
// just a wrapper for maybe_ignored
template<typename condT>
struct is_ignorable
{
typedef typename condT::value_type value_type;
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end)
{
const Iterator tmp = condT::invoke(iter, end);
return (tmp != iter) ? tmp : iter;
}
};
template<typename condT>
struct maybe_ignored : std::false_type{};
template<typename condT>
struct maybe_ignored<is_ignorable<condT>> : std::true_type{};
template<typename headT, typename ... condT>
struct is_chain_of_impl
{
typedef typename headT::value_type value_type;
static_assert(std::is_same<value_type,
typename is_chain_of_impl<condT...>::value_type>::value,
"different value_type");
constexpr static bool ignorable = maybe_ignored<headT>::value;
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end, Iterator rollback)
{
const Iterator tmp = headT::invoke(iter, end);
return (tmp == iter && !ignorable) ? rollback :
is_chain_of_impl<condT...>::invoke(tmp, end, rollback);
}
};
template<typename tailT>
struct is_chain_of_impl<tailT>
{
typedef typename tailT::value_type value_type;
constexpr static bool ignorable = maybe_ignored<tailT>::value;
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end, Iterator rollback)
{
const Iterator tmp = tailT::invoke(iter, end);
return (tmp == iter) ? (ignorable ? iter : rollback) : tmp;
}
};
template<typename headT, typename ...condT>
struct is_chain_of
{
typedef typename is_chain_of_impl<headT, condT...>::value_type value_type;
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end)
{
return is_chain_of_impl<headT, condT...>::invoke(iter, end, iter);
}
};
constexpr inline std::size_t repeat_infinite(){return 0ul;}
template<typename condT, std::size_t N>
struct is_repeat_of
{
typedef typename condT::value_type value_type;
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end)
{
const Iterator rollback = iter;
Iterator tmp;
for(auto i=0ul; i<N; ++i)
{
tmp = condT::invoke(iter, end);
if(tmp == iter) return rollback;
iter = tmp;
}
return iter;
}
};
template<typename condT>
struct is_repeat_of<condT, 0>
{
typedef typename condT::value_type value_type;
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end)
{
Iterator tmp = condT::invoke(iter, end);
while(tmp != iter)
{
iter = tmp;
tmp = condT::invoke(iter, end);
}
return iter;
}
};
template<typename headT, typename ... tailT>
struct is_none_of
{
typedef typename headT::value_type value_type;
static_assert(
std::is_same<value_type, typename is_one_of<tailT...>::value_type>::value,
"different value_type");
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end)
{
const Iterator tmp = headT::invoke(iter, end);
return (tmp != iter) ? iter : is_none_of<tailT...>::invoke(iter, end);
}
};
template<typename tailT>
struct is_none_of<tailT>
{
typedef typename tailT::value_type value_type;
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end)
{
const Iterator tmp = tailT::invoke(iter, end);
return (tmp != iter) ? iter : std::next(iter);
}
};
template<typename notT, typename butT>
struct is_not_but
{
typedef typename notT::value_type value_type;
static_assert(
std::is_same<value_type, typename butT::value_type>::value,
"different value type");
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end)
{
return (iter != notT::invoke(iter, end)) ? iter : butT::invoke(iter, end);
}
};
template<typename charT>
using is_space = is_character<charT, ' '>;
template<typename charT>
using is_tab = is_character<charT, '\t'>;
template<typename charT>
using is_number = is_in_range<charT, '0', '9'>;
template<typename charT>
using is_lowercase = is_in_range<charT, 'a', 'z'>;
template<typename charT>
using is_uppercase = is_in_range<charT, 'A', 'Z'>;
template<typename charT>
using is_alphabet = is_one_of<is_lowercase<charT>, is_uppercase<charT>>;
template<typename charT>
using is_hex = is_one_of<is_number<charT>, is_in_range<charT, 'a', 'f'>,
is_in_range<charT, 'A', 'F'>>;
template<typename charT>
using is_whitespace = is_one_of<is_space<charT>, is_tab<charT>>;
template<typename charT>
using is_any_num_of_ws =
is_ignorable<is_repeat_of<is_whitespace<charT>, repeat_infinite()>>;
template<typename charT>
using is_newline = is_one_of<is_character<charT, '\n'>,
is_chain_of<is_character<charT, '\r'>, is_character<charT, '\n'>>>;
template<typename charT>
using is_barekey_component = is_one_of<is_alphabet<charT>, is_number<charT>,
is_character<charT, '_'>, is_character<charT, '-'>>;
template<typename charT>
using is_barekey = is_repeat_of<is_barekey_component<charT>, repeat_infinite()>;
template<typename charT>
using is_comment =
is_chain_of<
is_character<charT, '#'>,
is_repeat_of<is_none_of<is_newline<charT>>, repeat_infinite()>,
is_newline<charT>
>;
template<typename charT>
using is_basic_inline_string_component =
is_one_of<
is_none_of< is_in_range<charT, '\0', '\31'>, is_character<charT, '\"'>,
is_character<charT, '\\'>, is_newline<charT>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, '\"'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, '\\'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'b'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 't'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'n'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'f'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'r'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'u'>,
is_repeat_of<is_hex<charT>, 4>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'U'>,
is_repeat_of<is_hex<charT>, 8>>
>;
template<typename charT>
using is_basic_inline_string =
is_not_but<
is_repeat_of<is_character<charT, '\"'>, 3>, // not multiline
is_chain_of<
is_character<charT, '\"'>,
is_ignorable<is_repeat_of<is_basic_inline_string_component<charT>,
repeat_infinite()>>,
is_character<charT, '\"'>
>
>;
template<typename charT>
using is_basic_multiline_string_component =
is_one_of<
is_none_of< is_in_range<charT, '\0', '\31'>,
is_repeat_of<is_character<charT, '\"'>, 3>,
is_character<charT, '\\'>>,
is_newline<charT>,
is_chain_of<is_character<charT, '\\'>, is_newline<charT>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, '\"'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, '\\'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'b'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 't'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'n'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'f'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'r'>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'u'>,
is_repeat_of<is_hex<charT>, 4>>,
is_chain_of<is_character<charT, '\\'>, is_character<charT, 'U'>,
is_repeat_of<is_hex<charT>, 8>>
>;
template<typename charT>
using is_basic_multiline_string =
is_chain_of<
is_repeat_of<is_character<charT, '\"'>, 3>,
is_ignorable<is_repeat_of<is_basic_multiline_string_component<charT>,
repeat_infinite()>>,
is_repeat_of<is_character<charT, '\"'>, 3>
>;
template<typename charT>
using is_literal_inline_string_component =
is_none_of<is_in_range<charT, '\0', '\31'>, is_character<charT, '\''>>;
template<typename charT>
using is_literal_inline_string =
is_not_but<
is_repeat_of<is_character<charT, '\''>, 3>,
is_chain_of<
is_character<charT, '\''>,
is_ignorable<is_repeat_of<is_literal_inline_string_component<charT>,
repeat_infinite()>>,
is_character<charT, '\''>
>
>;
template<typename charT>
using is_literal_multiline_string_component =
is_one_of<
is_none_of<is_in_range<charT, '\0', '\31'>,
is_repeat_of<is_character<charT, '\''>, 3>>,
is_newline<charT>
>;
template<typename charT>
using is_literal_multiline_string =
is_chain_of<
is_repeat_of<is_character<charT, '\''>, 3>,
is_ignorable<is_repeat_of<is_literal_multiline_string_component<charT>,
repeat_infinite()>>,
is_repeat_of<is_character<charT, '\''>, 3>
>;
template<typename charT>
using is_string =
is_one_of<
is_basic_inline_string<charT>,
is_basic_multiline_string<charT>,
is_literal_inline_string<charT>,
is_literal_multiline_string<charT>
>;
template<typename charT>
using is_sign = is_one_of<is_character<charT, '+'>, is_character<charT, '-'>>;
template<typename charT>
using is_nonzero_number = is_in_range<charT, '1', '9'>;
template<typename charT>
using is_integer_component =
is_not_but<
is_repeat_of<is_character<charT, '_'>, 2>,
is_one_of<
is_character<charT, '_'>, is_number<charT>
>
>;
template<typename charT>
using is_integer =
is_chain_of<
is_ignorable<is_sign<charT>>,
is_one_of<
is_character<charT, '0'>,
is_chain_of<
is_nonzero_number<charT>,
is_ignorable<is_repeat_of<is_integer_component<charT>,
repeat_infinite()>
>
>
>
>;
template<typename charT>
using is_fractional_part =
is_chain_of<
is_character<charT, '.'>,
is_repeat_of<is_integer_component<charT>, repeat_infinite()>
>;
template<typename charT>
using is_exponent_part =
is_chain_of<
is_one_of<is_character<charT, 'e'>, is_character<charT, 'E'>>,
is_integer<charT>
>;
template<typename charT>
using is_float =
is_one_of<
is_chain_of<
is_integer<charT>,
is_fractional_part<charT>,
is_exponent_part<charT>
>,
is_chain_of<
is_integer<charT>,
is_fractional_part<charT>
>,
is_chain_of<
is_integer<charT>,
is_exponent_part<charT>
>
>;
template<typename charT>
using is_boolean =
is_one_of<
is_chain_of<
is_character<charT, 't'>,
is_character<charT, 'r'>,
is_character<charT, 'u'>,
is_character<charT, 'e'>
>,
is_chain_of<
is_character<charT, 'f'>,
is_character<charT, 'a'>,
is_character<charT, 'l'>,
is_character<charT, 's'>,
is_character<charT, 'e'>
>
>;
template<typename charT>
using is_local_time =
is_chain_of<
is_repeat_of<is_number<charT>, 2>,
is_character<charT, ':'>,
is_repeat_of<is_number<charT>, 2>,
is_character<charT, ':'>,
is_repeat_of<is_number<charT>, 2>,
is_ignorable<
is_chain_of<
is_character<charT, '.'>,
is_repeat_of<is_number<charT>, repeat_infinite()>
>
>
>;
template<typename charT>
using is_local_date =
is_chain_of<
is_repeat_of<is_number<charT>, 4>,
is_character<charT, '-'>,
is_repeat_of<is_number<charT>, 2>,
is_character<charT, '-'>,
is_repeat_of<is_number<charT>, 2>
>;
template<typename charT>
using is_local_date_time =
is_chain_of<
is_local_date<charT>,
is_character<charT, 'T'>,
is_local_time<charT>
>;
template<typename charT>
using is_offset =
is_one_of<
is_character<charT, 'Z'>,
is_chain_of<
is_sign<charT>,
is_repeat_of<is_number<charT>, 2>,
is_character<charT, ':'>,
is_repeat_of<is_number<charT>, 2>
>
>;
template<typename charT>
using is_offset_date_time =
is_chain_of<
is_local_date_time<charT>,
is_offset<charT>
>;
template<typename charT>
using is_datetime =
is_one_of<
is_offset_date_time<charT>,
is_local_date_time<charT>,
is_local_date<charT>,
is_local_time<charT>
>;
template<typename charT>
using is_fundamental_type =
is_one_of<
is_basic_inline_string<charT>,
is_basic_multiline_string<charT>,
is_literal_inline_string<charT>,
is_literal_multiline_string<charT>,
is_offset_date_time<charT>,
is_local_date_time<charT>,
is_local_date<charT>,
is_local_time<charT>,
is_boolean<charT>,
is_float<charT>,
is_integer<charT>
>;
template<typename charT>
using is_skippable_in_array =
is_repeat_of<
is_one_of<is_whitespace<charT>, is_newline<charT>, is_comment<charT>>,
repeat_infinite()
>;
template<typename charT>
struct is_inline_table;
template<typename charT>
using is_key =
is_one_of<
is_barekey<charT>,
is_string<charT>
>;
template<typename charT, typename is_array_component>
using is_fixed_type_array =
is_chain_of<
is_character<charT, '['>,
is_ignorable<
is_repeat_of<
is_chain_of<
is_ignorable<is_skippable_in_array<charT>>,
is_array_component,
is_ignorable<is_skippable_in_array<charT>>,
is_character<charT, ','>
>,
repeat_infinite()
>
>,
is_ignorable<
is_chain_of<
is_ignorable<is_skippable_in_array<charT>>,
is_array_component,
is_ignorable<is_skippable_in_array<charT>>,
is_ignorable<is_character<charT, ','>>
>
>,
is_ignorable<is_skippable_in_array<charT>>,
is_character<charT, ']'>
>;
template<typename charT>
struct is_array
{
typedef charT value_type;
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end)
{
return is_one_of<
is_fixed_type_array<charT, is_boolean<charT>>,
is_fixed_type_array<charT, is_integer<charT>>,
is_fixed_type_array<charT, is_float<charT>>,
is_fixed_type_array<charT, is_string<charT>>,
is_fixed_type_array<charT, is_datetime<charT>>,
is_fixed_type_array<charT, is_array<charT>>,
is_fixed_type_array<charT, is_inline_table<charT>>
>::invoke(iter, end);
}
};
template<typename charT>
struct is_inline_table
{
typedef charT value_type;
template<typename Iterator, class = typename std::enable_if<
std::is_same<typename std::iterator_traits<Iterator>::value_type,
value_type>::value>::type>
static Iterator invoke(Iterator iter, Iterator end)
{
typedef is_one_of<is_fundamental_type<charT>,
is_array<charT>, is_inline_table<charT>> is_component;
typedef is_chain_of<
is_any_num_of_ws<charT>,
is_key<charT>,
is_any_num_of_ws<charT>,
is_character<charT, '='>,
is_any_num_of_ws<charT>,
is_component,
is_any_num_of_ws<charT>
> is_inline_key_value_pair;
typedef is_chain_of<
is_character<charT, '{'>,
is_ignorable<
is_repeat_of<
is_chain_of<
is_any_num_of_ws<charT>,
is_inline_key_value_pair,
is_any_num_of_ws<charT>,
is_character<charT, ','>
>,
repeat_infinite()
>
>,
is_ignorable<
is_chain_of<
is_any_num_of_ws<charT>,
is_inline_key_value_pair,
is_any_num_of_ws<charT>,
is_ignorable<is_character<charT, ','>>
>
>,
is_any_num_of_ws<charT>,
is_character<charT, '}'>
> entity;
return entity::invoke(iter, end);
}
};
template<typename charT>
using is_value =
is_one_of<is_fundamental_type<charT>, is_array<charT>, is_inline_table<charT>>;
// []
template<typename charT>
using is_table_definition =
is_chain_of<
is_any_num_of_ws<charT>,
is_character<charT, '['>,
is_any_num_of_ws<charT>,
is_key<charT>,
is_ignorable<
is_repeat_of<
is_chain_of<
is_any_num_of_ws<charT>,
is_character<charT, '.'>,
is_any_num_of_ws<charT>,
is_key<charT>,
is_any_num_of_ws<charT>
>,
repeat_infinite()>
>,
is_character<charT, ']'>
>;
template<typename charT>
using is_array_of_table_definition =
is_chain_of<
is_any_num_of_ws<charT>,
is_repeat_of<is_character<charT, '['>, 2>,
is_any_num_of_ws<charT>,
is_key<charT>,
is_ignorable<
is_repeat_of<
is_chain_of<
is_any_num_of_ws<charT>,
is_character<charT, '.'>,
is_any_num_of_ws<charT>,
is_key<charT>,
is_any_num_of_ws<charT>
>,
repeat_infinite()>
>,
is_repeat_of<is_character<charT, ']'>, 2>
>;
template<typename charT>
using is_key_value_pair =
is_chain_of<
is_any_num_of_ws<charT>,
is_key<charT>,
is_any_num_of_ws<charT>,
is_character<charT, '='>,
is_any_num_of_ws<charT>,
is_value<charT>,
is_any_num_of_ws<charT>
>;
template<typename charT>
using is_empty_line =
is_chain_of<
is_any_num_of_ws<charT>,
is_one_of<is_comment<charT>, is_newline<charT>>
>;
template<typename charT>
using is_empty_lines =
is_repeat_of<
is_chain_of<
is_any_num_of_ws<charT>,
is_one_of<is_comment<charT>, is_newline<charT>>
>,
repeat_infinite()
>;
template<typename charT>
using is_table_contents =
is_repeat_of<
is_one_of<
is_empty_lines<charT>,
is_chain_of<
is_key_value_pair<charT>,
is_one_of<
is_comment<charT>,
is_newline<charT>
>
>
>,
repeat_infinite()
>;
template<typename charT>
using is_standard_table =
is_chain_of<
is_table_definition<charT>,
is_any_num_of_ws<charT>,
is_one_of<is_comment<charT>, is_newline<charT>>,
is_table_contents<charT>
>;
template<typename charT>
using is_array_of_table =
is_chain_of<
is_array_of_table_definition<charT>,
is_any_num_of_ws<charT>,
is_one_of<is_comment<charT>, is_newline<charT>>,
is_table_contents<charT>
>;
template<typename charT>
using is_toml_data =
is_chain_of<
is_ignorable<is_table_contents<charT>>,
is_ignorable<
is_repeat_of<
is_one_of<
is_standard_table<charT>,
is_array_of_table<charT>
>,
repeat_infinite()
>
>
>;
}//toml
#endif// TOML11_ACCEPTOR

64
toml/color.hpp Normal file
View File

@@ -0,0 +1,64 @@
#ifndef TOML11_COLOR_HPP
#define TOML11_COLOR_HPP
#include <cstdint>
#include <ostream>
#ifdef TOML11_COLORIZE_ERROR_MESSAGE
#define TOML11_ERROR_MESSAGE_COLORIZED true
#else
#define TOML11_ERROR_MESSAGE_COLORIZED false
#endif
namespace toml
{
// put ANSI escape sequence to ostream
namespace color_ansi
{
namespace detail
{
inline int colorize_index()
{
static const int index = std::ios_base::xalloc();
return index;
}
} // detail
inline std::ostream& colorize(std::ostream& os)
{
// by default, it is zero.
os.iword(detail::colorize_index()) = 1;
return os;
}
inline std::ostream& nocolorize(std::ostream& os)
{
os.iword(detail::colorize_index()) = 0;
return os;
}
inline std::ostream& reset (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[00m";} return os;}
inline std::ostream& bold (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[01m";} return os;}
inline std::ostream& grey (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[30m";} return os;}
inline std::ostream& red (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[31m";} return os;}
inline std::ostream& green (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[32m";} return os;}
inline std::ostream& yellow (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[33m";} return os;}
inline std::ostream& blue (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[34m";} return os;}
inline std::ostream& magenta(std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[35m";} return os;}
inline std::ostream& cyan (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[36m";} return os;}
inline std::ostream& white (std::ostream& os)
{if(os.iword(detail::colorize_index()) == 1) {os << "\033[37m";} return os;}
} // color_ansi
// ANSI escape sequence is the only and default colorization method currently
namespace color = color_ansi;
} // toml
#endif// TOML11_COLOR_HPP

336
toml/combinator.hpp Normal file
View File

@@ -0,0 +1,336 @@
// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_COMBINATOR_HPP
#define TOML11_COMBINATOR_HPP
#include <cassert>
#include <cctype>
#include <cstdio>
#include <array>
#include <iomanip>
#include <iterator>
#include <limits>
#include <type_traits>
#include "region.hpp"
#include "result.hpp"
#include "traits.hpp"
#include "utility.hpp"
// they scans characters and returns region if it matches to the condition.
// when they fail, it does not change the location.
// in lexer.hpp, these are used.
namespace toml
{
namespace detail
{
// to output character as an error message.
inline std::string show_char(const char c)
{
// It supress an error that occurs only in Debug mode of MSVC++ on Windows.
// I'm not completely sure but they check the value of char to be in the
// range [0, 256) and some of the COMPLETELY VALID utf-8 character sometimes
// has negative value (if char has sign). So here it re-interprets c as
// unsigned char through pointer. In general, converting pointer to a
// pointer that has different type cause UB, but `(signed|unsigned)?char`
// are one of the exceptions. Converting pointer only to char and std::byte
// (c++17) are valid.
if(std::isgraph(*reinterpret_cast<unsigned char const*>(std::addressof(c))))
{
return std::string(1, c);
}
else
{
std::array<char, 5> buf;
buf.fill('\0');
const auto r = std::snprintf(
buf.data(), buf.size(), "0x%02x", static_cast<int>(c) & 0xFF);
(void) r; // Unused variable warning
assert(r == static_cast<int>(buf.size()) - 1);
return std::string(buf.data());
}
}
template<char C>
struct character
{
static constexpr char target = C;
template<typename Cont>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc)
{
static_assert(std::is_same<char, typename Cont::value_type>::value,
"internal error: container::value_type should be `char`.");
if(loc.iter() == loc.end()) {return none();}
const auto first = loc.iter();
const char c = *(loc.iter());
if(c != target)
{
return none();
}
loc.advance(); // update location
return ok(region<Cont>(loc, first, loc.iter()));
}
};
template<char C>
constexpr char character<C>::target;
// closed interval [Low, Up]. both Low and Up are included.
template<char Low, char Up>
struct in_range
{
// assuming ascii part of UTF-8...
static_assert(Low <= Up, "lower bound should be less than upper bound.");
static constexpr char upper = Up;
static constexpr char lower = Low;
template<typename Cont>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc)
{
static_assert(std::is_same<char, typename Cont::value_type>::value,
"internal error: container::value_type should be `char`.");
if(loc.iter() == loc.end()) {return none();}
const auto first = loc.iter();
const char c = *(loc.iter());
if(c < lower || upper < c)
{
return none();
}
loc.advance();
return ok(region<Cont>(loc, first, loc.iter()));
}
};
template<char L, char U> constexpr char in_range<L, U>::upper;
template<char L, char U> constexpr char in_range<L, U>::lower;
// keep iterator if `Combinator` matches. otherwise, increment `iter` by 1 char.
// for detecting invalid characters, like control sequences in toml string.
template<typename Combinator>
struct exclude
{
template<typename Cont>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc)
{
static_assert(std::is_same<char, typename Cont::value_type>::value,
"internal error: container::value_type should be `char`.");
if(loc.iter() == loc.end()) {return none();}
auto first = loc.iter();
auto rslt = Combinator::invoke(loc);
if(rslt.is_ok())
{
loc.reset(first);
return none();
}
loc.reset(std::next(first)); // XXX maybe loc.advance() is okay but...
return ok(region<Cont>(loc, first, loc.iter()));
}
};
// increment `iter`, if matches. otherwise, just return empty string.
template<typename Combinator>
struct maybe
{
template<typename Cont>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc)
{
static_assert(std::is_same<char, typename Cont::value_type>::value,
"internal error: container::value_type should be `char`.");
const auto rslt = Combinator::invoke(loc);
if(rslt.is_ok())
{
return rslt;
}
return ok(region<Cont>(loc));
}
};
template<typename ... Ts>
struct sequence;
template<typename Head, typename ... Tail>
struct sequence<Head, Tail...>
{
template<typename Cont>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc)
{
static_assert(std::is_same<char, typename Cont::value_type>::value,
"internal error: container::value_type should be `char`.");
const auto first = loc.iter();
const auto rslt = Head::invoke(loc);
if(rslt.is_err())
{
loc.reset(first);
return none();
}
return sequence<Tail...>::invoke(loc, std::move(rslt.unwrap()), first);
}
// called from the above function only, recursively.
template<typename Cont, typename Iterator>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc, region<Cont> reg, Iterator first)
{
const auto rslt = Head::invoke(loc);
if(rslt.is_err())
{
loc.reset(first);
return none();
}
reg += rslt.unwrap(); // concat regions
return sequence<Tail...>::invoke(loc, std::move(reg), first);
}
};
template<typename Head>
struct sequence<Head>
{
// would be called from sequence<T ...>::invoke only.
template<typename Cont, typename Iterator>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc, region<Cont> reg, Iterator first)
{
const auto rslt = Head::invoke(loc);
if(rslt.is_err())
{
loc.reset(first);
return none();
}
reg += rslt.unwrap(); // concat regions
return ok(reg);
}
};
template<typename ... Ts>
struct either;
template<typename Head, typename ... Tail>
struct either<Head, Tail...>
{
template<typename Cont>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc)
{
static_assert(std::is_same<char, typename Cont::value_type>::value,
"internal error: container::value_type should be `char`.");
const auto rslt = Head::invoke(loc);
if(rslt.is_ok()) {return rslt;}
return either<Tail...>::invoke(loc);
}
};
template<typename Head>
struct either<Head>
{
template<typename Cont>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc)
{
static_assert(std::is_same<char, typename Cont::value_type>::value,
"internal error: container::value_type should be `char`.");
return Head::invoke(loc);
}
};
template<typename T, typename N>
struct repeat;
template<std::size_t N> struct exactly{};
template<std::size_t N> struct at_least{};
struct unlimited{};
template<typename T, std::size_t N>
struct repeat<T, exactly<N>>
{
template<typename Cont>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc)
{
region<Cont> retval(loc);
const auto first = loc.iter();
for(std::size_t i=0; i<N; ++i)
{
auto rslt = T::invoke(loc);
if(rslt.is_err())
{
loc.reset(first);
return none();
}
retval += rslt.unwrap();
}
return ok(std::move(retval));
}
};
template<typename T, std::size_t N>
struct repeat<T, at_least<N>>
{
template<typename Cont>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc)
{
region<Cont> retval(loc);
const auto first = loc.iter();
for(std::size_t i=0; i<N; ++i)
{
auto rslt = T::invoke(loc);
if(rslt.is_err())
{
loc.reset(first);
return none();
}
retval += rslt.unwrap();
}
while(true)
{
auto rslt = T::invoke(loc);
if(rslt.is_err())
{
return ok(std::move(retval));
}
retval += rslt.unwrap();
}
}
};
template<typename T>
struct repeat<T, unlimited>
{
template<typename Cont>
static result<region<Cont>, none_t>
invoke(location<Cont>& loc)
{
region<Cont> retval(loc);
while(true)
{
auto rslt = T::invoke(loc);
if(rslt.is_err())
{
return ok(std::move(retval));
}
retval += rslt.unwrap();
}
}
};
} // detail
} // toml
#endif// TOML11_COMBINATOR_HPP

465
toml/comments.hpp Normal file
View File

@@ -0,0 +1,465 @@
// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_COMMENTS_HPP
#define TOML11_COMMENTS_HPP
#include <initializer_list>
#include <iterator>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
// This file provides mainly two classes, `preserve_comments` and `discard_comments`.
// Those two are a container that have the same interface as `std::vector<std::string>`
// but bahaves in the opposite way. `preserve_comments` is just the same as
// `std::vector<std::string>` and each `std::string` corresponds to a comment line.
// Conversely, `discard_comments` discards all the strings and ignores everything
// assigned in it. `discard_comments` is always empty and you will encounter an
// error whenever you access to the element.
namespace toml
{
struct discard_comments; // forward decl
// use it in the following way
//
// const toml::basic_value<toml::preserve_comments> data =
// toml::parse<toml::preserve_comments>("example.toml");
//
// the interface is almost the same as std::vector<std::string>.
struct preserve_comments
{
// `container_type` is not provided in discard_comments.
// do not use this inner-type in a generic code.
using container_type = std::vector<std::string>;
using size_type = container_type::size_type;
using difference_type = container_type::difference_type;
using value_type = container_type::value_type;
using reference = container_type::reference;
using const_reference = container_type::const_reference;
using pointer = container_type::pointer;
using const_pointer = container_type::const_pointer;
using iterator = container_type::iterator;
using const_iterator = container_type::const_iterator;
using reverse_iterator = container_type::reverse_iterator;
using const_reverse_iterator = container_type::const_reverse_iterator;
preserve_comments() = default;
~preserve_comments() = default;
preserve_comments(preserve_comments const&) = default;
preserve_comments(preserve_comments &&) = default;
preserve_comments& operator=(preserve_comments const&) = default;
preserve_comments& operator=(preserve_comments &&) = default;
explicit preserve_comments(const std::vector<std::string>& c): comments(c){}
explicit preserve_comments(std::vector<std::string>&& c)
: comments(std::move(c))
{}
preserve_comments& operator=(const std::vector<std::string>& c)
{
comments = c;
return *this;
}
preserve_comments& operator=(std::vector<std::string>&& c)
{
comments = std::move(c);
return *this;
}
explicit preserve_comments(const discard_comments&) {}
explicit preserve_comments(size_type n): comments(n) {}
preserve_comments(size_type n, const std::string& x): comments(n, x) {}
preserve_comments(std::initializer_list<std::string> x): comments(x) {}
template<typename InputIterator>
preserve_comments(InputIterator first, InputIterator last)
: comments(first, last)
{}
template<typename InputIterator>
void assign(InputIterator first, InputIterator last) {comments.assign(first, last);}
void assign(std::initializer_list<std::string> ini) {comments.assign(ini);}
void assign(size_type n, const std::string& val) {comments.assign(n, val);}
// Related to the issue #97.
//
// It is known that `std::vector::insert` and `std::vector::erase` in
// the standard library implementation included in GCC 4.8.5 takes
// `std::vector::iterator` instead of `std::vector::const_iterator`.
// Because of the const-correctness, we cannot convert a `const_iterator` to
// an `iterator`. It causes compilation error in GCC 4.8.5.
#if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && !defined(__clang__)
# if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) <= 40805
# define TOML11_WORKAROUND_GCC_4_8_X_STANDARD_LIBRARY_IMPLEMENTATION
# endif
#endif
#ifdef TOML11_WORKAROUND_GCC_4_8_X_STANDARD_LIBRARY_IMPLEMENTATION
iterator insert(iterator p, const std::string& x)
{
return comments.insert(p, x);
}
iterator insert(iterator p, std::string&& x)
{
return comments.insert(p, std::move(x));
}
void insert(iterator p, size_type n, const std::string& x)
{
return comments.insert(p, n, x);
}
template<typename InputIterator>
void insert(iterator p, InputIterator first, InputIterator last)
{
return comments.insert(p, first, last);
}
void insert(iterator p, std::initializer_list<std::string> ini)
{
return comments.insert(p, ini);
}
template<typename ... Ts>
iterator emplace(iterator p, Ts&& ... args)
{
return comments.emplace(p, std::forward<Ts>(args)...);
}
iterator erase(iterator pos) {return comments.erase(pos);}
iterator erase(iterator first, iterator last)
{
return comments.erase(first, last);
}
#else
iterator insert(const_iterator p, const std::string& x)
{
return comments.insert(p, x);
}
iterator insert(const_iterator p, std::string&& x)
{
return comments.insert(p, std::move(x));
}
iterator insert(const_iterator p, size_type n, const std::string& x)
{
return comments.insert(p, n, x);
}
template<typename InputIterator>
iterator insert(const_iterator p, InputIterator first, InputIterator last)
{
return comments.insert(p, first, last);
}
iterator insert(const_iterator p, std::initializer_list<std::string> ini)
{
return comments.insert(p, ini);
}
template<typename ... Ts>
iterator emplace(const_iterator p, Ts&& ... args)
{
return comments.emplace(p, std::forward<Ts>(args)...);
}
iterator erase(const_iterator pos) {return comments.erase(pos);}
iterator erase(const_iterator first, const_iterator last)
{
return comments.erase(first, last);
}
#endif
void swap(preserve_comments& other) {comments.swap(other.comments);}
void push_back(const std::string& v) {comments.push_back(v);}
void push_back(std::string&& v) {comments.push_back(std::move(v));}
void pop_back() {comments.pop_back();}
template<typename ... Ts>
void emplace_back(Ts&& ... args) {comments.emplace_back(std::forward<Ts>(args)...);}
void clear() {comments.clear();}
size_type size() const noexcept {return comments.size();}
size_type max_size() const noexcept {return comments.max_size();}
size_type capacity() const noexcept {return comments.capacity();}
bool empty() const noexcept {return comments.empty();}
void reserve(size_type n) {comments.reserve(n);}
void resize(size_type n) {comments.resize(n);}
void resize(size_type n, const std::string& c) {comments.resize(n, c);}
void shrink_to_fit() {comments.shrink_to_fit();}
reference operator[](const size_type n) noexcept {return comments[n];}
const_reference operator[](const size_type n) const noexcept {return comments[n];}
reference at(const size_type n) {return comments.at(n);}
const_reference at(const size_type n) const {return comments.at(n);}
reference front() noexcept {return comments.front();}
const_reference front() const noexcept {return comments.front();}
reference back() noexcept {return comments.back();}
const_reference back() const noexcept {return comments.back();}
pointer data() noexcept {return comments.data();}
const_pointer data() const noexcept {return comments.data();}
iterator begin() noexcept {return comments.begin();}
iterator end() noexcept {return comments.end();}
const_iterator begin() const noexcept {return comments.begin();}
const_iterator end() const noexcept {return comments.end();}
const_iterator cbegin() const noexcept {return comments.cbegin();}
const_iterator cend() const noexcept {return comments.cend();}
reverse_iterator rbegin() noexcept {return comments.rbegin();}
reverse_iterator rend() noexcept {return comments.rend();}
const_reverse_iterator rbegin() const noexcept {return comments.rbegin();}
const_reverse_iterator rend() const noexcept {return comments.rend();}
const_reverse_iterator crbegin() const noexcept {return comments.crbegin();}
const_reverse_iterator crend() const noexcept {return comments.crend();}
friend bool operator==(const preserve_comments&, const preserve_comments&);
friend bool operator!=(const preserve_comments&, const preserve_comments&);
friend bool operator< (const preserve_comments&, const preserve_comments&);
friend bool operator<=(const preserve_comments&, const preserve_comments&);
friend bool operator> (const preserve_comments&, const preserve_comments&);
friend bool operator>=(const preserve_comments&, const preserve_comments&);
friend void swap(preserve_comments&, std::vector<std::string>&);
friend void swap(std::vector<std::string>&, preserve_comments&);
private:
container_type comments;
};
inline bool operator==(const preserve_comments& lhs, const preserve_comments& rhs) {return lhs.comments == rhs.comments;}
inline bool operator!=(const preserve_comments& lhs, const preserve_comments& rhs) {return lhs.comments != rhs.comments;}
inline bool operator< (const preserve_comments& lhs, const preserve_comments& rhs) {return lhs.comments < rhs.comments;}
inline bool operator<=(const preserve_comments& lhs, const preserve_comments& rhs) {return lhs.comments <= rhs.comments;}
inline bool operator> (const preserve_comments& lhs, const preserve_comments& rhs) {return lhs.comments > rhs.comments;}
inline bool operator>=(const preserve_comments& lhs, const preserve_comments& rhs) {return lhs.comments >= rhs.comments;}
inline void swap(preserve_comments& lhs, preserve_comments& rhs)
{
lhs.swap(rhs);
return;
}
inline void swap(preserve_comments& lhs, std::vector<std::string>& rhs)
{
lhs.comments.swap(rhs);
return;
}
inline void swap(std::vector<std::string>& lhs, preserve_comments& rhs)
{
lhs.swap(rhs.comments);
return;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const preserve_comments& com)
{
for(const auto& c : com)
{
os << '#' << c << '\n';
}
return os;
}
namespace detail
{
// To provide the same interface with `preserve_comments`, `discard_comments`
// should have an iterator. But it does not contain anything, so we need to
// add an iterator that points nothing.
//
// It always points null, so DO NOT unwrap this iterator. It always crashes
// your program.
template<typename T, bool is_const>
struct empty_iterator
{
using value_type = T;
using reference_type = typename std::conditional<is_const, T const&, T&>::type;
using pointer_type = typename std::conditional<is_const, T const*, T*>::type;
using difference_type = std::ptrdiff_t;
using iterator_category = std::random_access_iterator_tag;
empty_iterator() = default;
~empty_iterator() = default;
empty_iterator(empty_iterator const&) = default;
empty_iterator(empty_iterator &&) = default;
empty_iterator& operator=(empty_iterator const&) = default;
empty_iterator& operator=(empty_iterator &&) = default;
// DO NOT call these operators.
reference_type operator*() const noexcept {std::terminate();}
pointer_type operator->() const noexcept {return nullptr;}
reference_type operator[](difference_type) const noexcept {return this->operator*();}
// These operators do nothing.
empty_iterator& operator++() noexcept {return *this;}
empty_iterator operator++(int) noexcept {return *this;}
empty_iterator& operator--() noexcept {return *this;}
empty_iterator operator--(int) noexcept {return *this;}
empty_iterator& operator+=(difference_type) noexcept {return *this;}
empty_iterator& operator-=(difference_type) noexcept {return *this;}
empty_iterator operator+(difference_type) const noexcept {return *this;}
empty_iterator operator-(difference_type) const noexcept {return *this;}
};
template<typename T, bool C>
bool operator==(const empty_iterator<T, C>&, const empty_iterator<T, C>&) noexcept {return true;}
template<typename T, bool C>
bool operator!=(const empty_iterator<T, C>&, const empty_iterator<T, C>&) noexcept {return false;}
template<typename T, bool C>
bool operator< (const empty_iterator<T, C>&, const empty_iterator<T, C>&) noexcept {return false;}
template<typename T, bool C>
bool operator<=(const empty_iterator<T, C>&, const empty_iterator<T, C>&) noexcept {return true;}
template<typename T, bool C>
bool operator> (const empty_iterator<T, C>&, const empty_iterator<T, C>&) noexcept {return false;}
template<typename T, bool C>
bool operator>=(const empty_iterator<T, C>&, const empty_iterator<T, C>&) noexcept {return true;}
template<typename T, bool C>
typename empty_iterator<T, C>::difference_type
operator-(const empty_iterator<T, C>&, const empty_iterator<T, C>&) noexcept {return 0;}
template<typename T, bool C>
empty_iterator<T, C>
operator+(typename empty_iterator<T, C>::difference_type, const empty_iterator<T, C>& rhs) noexcept {return rhs;}
template<typename T, bool C>
empty_iterator<T, C>
operator+(const empty_iterator<T, C>& lhs, typename empty_iterator<T, C>::difference_type) noexcept {return lhs;}
} // detail
// The default comment type. It discards all the comments. It requires only one
// byte to contain, so the memory footprint is smaller than preserve_comments.
//
// It just ignores `push_back`, `insert`, `erase`, and any other modifications.
// IT always returns size() == 0, the iterator taken by `begin()` is always the
// same as that of `end()`, and accessing through `operator[]` or iterators
// always causes a segmentation fault. DO NOT access to the element of this.
//
// Why this is chose as the default type is because the last version (2.x.y)
// does not contain any comments in a value. To minimize the impact on the
// efficiency, this is choosed as a default.
//
// To reduce the memory footprint, later we can try empty base optimization (EBO).
struct discard_comments
{
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using value_type = std::string;
using reference = std::string&;
using const_reference = std::string const&;
using pointer = std::string*;
using const_pointer = std::string const*;
using iterator = detail::empty_iterator<std::string, false>;
using const_iterator = detail::empty_iterator<std::string, true>;
using reverse_iterator = detail::empty_iterator<std::string, false>;
using const_reverse_iterator = detail::empty_iterator<std::string, true>;
discard_comments() = default;
~discard_comments() = default;
discard_comments(discard_comments const&) = default;
discard_comments(discard_comments &&) = default;
discard_comments& operator=(discard_comments const&) = default;
discard_comments& operator=(discard_comments &&) = default;
explicit discard_comments(const std::vector<std::string>&) noexcept {}
explicit discard_comments(std::vector<std::string>&&) noexcept {}
discard_comments& operator=(const std::vector<std::string>&) noexcept {return *this;}
discard_comments& operator=(std::vector<std::string>&&) noexcept {return *this;}
explicit discard_comments(const preserve_comments&) noexcept {}
explicit discard_comments(size_type) noexcept {}
discard_comments(size_type, const std::string&) noexcept {}
discard_comments(std::initializer_list<std::string>) noexcept {}
template<typename InputIterator>
discard_comments(InputIterator, InputIterator) noexcept {}
template<typename InputIterator>
void assign(InputIterator, InputIterator) noexcept {}
void assign(std::initializer_list<std::string>) noexcept {}
void assign(size_type, const std::string&) noexcept {}
iterator insert(const_iterator, const std::string&) {return iterator{};}
iterator insert(const_iterator, std::string&&) {return iterator{};}
iterator insert(const_iterator, size_type, const std::string&) {return iterator{};}
template<typename InputIterator>
iterator insert(const_iterator, InputIterator, InputIterator) {return iterator{};}
iterator insert(const_iterator, std::initializer_list<std::string>) {return iterator{};}
template<typename ... Ts>
iterator emplace(const_iterator, Ts&& ...) {return iterator{};}
iterator erase(const_iterator) {return iterator{};}
iterator erase(const_iterator, const_iterator) {return iterator{};}
void swap(discard_comments&) {return;}
void push_back(const std::string&) {return;}
void push_back(std::string&& ) {return;}
void pop_back() {return;}
template<typename ... Ts>
void emplace_back(Ts&& ...) {return;}
void clear() {return;}
size_type size() const noexcept {return 0;}
size_type max_size() const noexcept {return 0;}
size_type capacity() const noexcept {return 0;}
bool empty() const noexcept {return true;}
void reserve(size_type) {return;}
void resize(size_type) {return;}
void resize(size_type, const std::string&) {return;}
void shrink_to_fit() {return;}
// DO NOT access to the element of this container. This container is always
// empty, so accessing through operator[], front/back, data causes address
// error.
reference operator[](const size_type) noexcept {return *data();}
const_reference operator[](const size_type) const noexcept {return *data();}
reference at(const size_type) {throw std::out_of_range("toml::discard_comment is always empty.");}
const_reference at(const size_type) const {throw std::out_of_range("toml::discard_comment is always empty.");}
reference front() noexcept {return *data();}
const_reference front() const noexcept {return *data();}
reference back() noexcept {return *data();}
const_reference back() const noexcept {return *data();}
pointer data() noexcept {return nullptr;}
const_pointer data() const noexcept {return nullptr;}
iterator begin() noexcept {return iterator{};}
iterator end() noexcept {return iterator{};}
const_iterator begin() const noexcept {return const_iterator{};}
const_iterator end() const noexcept {return const_iterator{};}
const_iterator cbegin() const noexcept {return const_iterator{};}
const_iterator cend() const noexcept {return const_iterator{};}
reverse_iterator rbegin() noexcept {return iterator{};}
reverse_iterator rend() noexcept {return iterator{};}
const_reverse_iterator rbegin() const noexcept {return const_iterator{};}
const_reverse_iterator rend() const noexcept {return const_iterator{};}
const_reverse_iterator crbegin() const noexcept {return const_iterator{};}
const_reverse_iterator crend() const noexcept {return const_iterator{};}
};
inline bool operator==(const discard_comments&, const discard_comments&) noexcept {return true;}
inline bool operator!=(const discard_comments&, const discard_comments&) noexcept {return false;}
inline bool operator< (const discard_comments&, const discard_comments&) noexcept {return false;}
inline bool operator<=(const discard_comments&, const discard_comments&) noexcept {return true;}
inline bool operator> (const discard_comments&, const discard_comments&) noexcept {return false;}
inline bool operator>=(const discard_comments&, const discard_comments&) noexcept {return true;}
inline void swap(const discard_comments&, const discard_comments&) noexcept {return;}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const discard_comments&)
{
return os;
}
} // toml11
#endif// TOML11_COMMENTS_HPP

View File

@@ -1,231 +1,631 @@
#ifndef TOML11_DATETIME
#define TOML11_DATETIME
// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_DATETIME_HPP
#define TOML11_DATETIME_HPP
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <array>
#include <chrono>
#include <iomanip>
#include <ctime>
#include <ostream>
#include <tuple>
namespace toml
{
template<typename unsignedT, typename intT>
struct basic_datetime
// To avoid non-threadsafe std::localtime. In C11 (not C++11!), localtime_s is
// provided in the absolutely same purpose, but C++11 is actually not compatible
// with C11. We need to dispatch the function depending on the OS.
namespace detail
{
typedef unsignedT number_type;
typedef intT offset_type;
constexpr static unsignedT undef = std::numeric_limits<unsignedT>::max();
constexpr static intT nooffset = std::numeric_limits<intT>::max();
// TODO: find more sophisticated way to handle this
#if (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 1) || defined(_XOPEN_SOURCE) || defined(_BSD_SOURCE) || defined(_SVID_SOURCE) || defined(_POSIX_SOURCE)
inline std::tm localtime_s(const std::time_t* src)
{
std::tm dst;
const auto result = ::localtime_r(src, &dst);
if (!result) { throw std::runtime_error("localtime_r failed."); }
return dst;
}
inline std::tm gmtime_s(const std::time_t* src)
{
std::tm dst;
const auto result = ::gmtime_r(src, &dst);
if (!result) { throw std::runtime_error("gmtime_r failed."); }
return dst;
}
#elif defined(_MSC_VER)
inline std::tm localtime_s(const std::time_t* src)
{
std::tm dst;
const auto result = ::localtime_s(&dst, src);
if (result) { throw std::runtime_error("localtime_s failed."); }
return dst;
}
inline std::tm gmtime_s(const std::time_t* src)
{
std::tm dst;
const auto result = ::gmtime_s(&dst, src);
if (result) { throw std::runtime_error("gmtime_s failed."); }
return dst;
}
#else // fallback. not threadsafe
inline std::tm localtime_s(const std::time_t* src)
{
const auto result = std::localtime(src);
if (!result) { throw std::runtime_error("localtime failed."); }
return *result;
}
inline std::tm gmtime_s(const std::time_t* src)
{
const auto result = std::gmtime(src);
if (!result) { throw std::runtime_error("gmtime failed."); }
return *result;
}
#endif
} // detail
unsignedT year;
unsignedT month;
unsignedT day;
unsignedT hour;
unsignedT minute;
unsignedT second;
unsignedT millisecond;
unsignedT microsecond;
intT offset_hour;
intT offset_minute;
enum class month_t : std::uint8_t
{
Jan = 0,
Feb = 1,
Mar = 2,
Apr = 3,
May = 4,
Jun = 5,
Jul = 6,
Aug = 7,
Sep = 8,
Oct = 9,
Nov = 10,
Dec = 11
};
basic_datetime() = default;
~basic_datetime() = default;
basic_datetime(const basic_datetime&) = default;
basic_datetime(basic_datetime&&) = default;
basic_datetime& operator=(const basic_datetime&) = default;
basic_datetime& operator=(basic_datetime&&) = default;
struct local_date
{
std::int16_t year; // A.D. (like, 2018)
std::uint8_t month; // [0, 11]
std::uint8_t day; // [1, 31]
basic_datetime(unsignedT y, unsignedT m, unsignedT d)
: year(y), month(m), day(d), hour(undef), minute(undef), second(undef),
millisecond(undef), microsecond(undef),
offset_hour(nooffset), offset_minute(nooffset)
{}
basic_datetime(unsignedT h, unsignedT m, unsignedT s,
unsignedT ms, unsignedT us)
: year(undef), month(undef), day(undef), hour(h), minute(m), second(s),
millisecond(ms), microsecond(us),
offset_hour(nooffset), offset_minute(nooffset)
{}
basic_datetime(unsignedT y, unsignedT mth, unsignedT d,
unsignedT h, unsignedT min, unsignedT s,
unsignedT ms, unsignedT us)
: year(y), month(mth), day(d), hour(h), minute(min), second(s),
millisecond(ms), microsecond(us),
offset_hour(nooffset), offset_minute(nooffset)
{}
basic_datetime(unsignedT y, unsignedT mth, unsignedT d,
unsignedT h, unsignedT min, unsignedT s,
unsignedT ss, unsignedT us, intT oh, intT om)
: year(y), month(mth), day(d), hour(h), minute(min), second(s),
millisecond(ss), microsecond(us), offset_hour(oh), offset_minute(om)
local_date(int y, month_t m, int d)
: year (static_cast<std::int16_t>(y)),
month(static_cast<std::uint8_t>(m)),
day (static_cast<std::uint8_t>(d))
{}
basic_datetime(std::chrono::system_clock::time_point tp);
basic_datetime(std::time_t t);
explicit local_date(const std::tm& t)
: year (static_cast<std::int16_t>(t.tm_year + 1900)),
month(static_cast<std::uint8_t>(t.tm_mon)),
day (static_cast<std::uint8_t>(t.tm_mday))
{}
explicit local_date(const std::chrono::system_clock::time_point& tp)
{
const auto t = std::chrono::system_clock::to_time_t(tp);
const auto time = detail::localtime_s(&t);
*this = local_date(time);
}
explicit local_date(const std::time_t t)
: local_date(std::chrono::system_clock::from_time_t(t))
{}
operator std::chrono::system_clock::time_point() const
{
std::tm time;
if(this->year == undef || this->month == undef || this->day == undef)
{
const auto now = std::chrono::system_clock::now();
const auto t = std::chrono::system_clock::to_time_t(now);
std::tm* t_ = std::localtime(&t);
time.tm_year = t_->tm_year;
time.tm_mon = t_->tm_mon;
time.tm_mday = t_->tm_mday;
}
else
{
time.tm_year = this->year - 1900;
time.tm_mon = this->month - 1;
time.tm_mday = this->day;
}
time.tm_hour = (this->hour == undef) ? 0 : this->hour;
time.tm_min = (this->minute == undef) ? 0 : this->minute;
time.tm_sec = (this->second == undef) ? 0 : this->second;
auto tp = std::chrono::system_clock::from_time_t(std::mktime(&time));
tp += std::chrono::milliseconds(this->millisecond);
tp += std::chrono::microseconds(this->microsecond);
// mktime regards the tm struct as localtime. so adding offset is not needed.
return tp;
// std::mktime returns date as local time zone. no conversion needed
std::tm t;
t.tm_sec = 0;
t.tm_min = 0;
t.tm_hour = 0;
t.tm_mday = static_cast<int>(this->day);
t.tm_mon = static_cast<int>(this->month);
t.tm_year = static_cast<int>(this->year) - 1900;
t.tm_wday = 0; // the value will be ignored
t.tm_yday = 0; // the value will be ignored
t.tm_isdst = -1;
return std::chrono::system_clock::from_time_t(std::mktime(&t));
}
operator std::time_t() const
{
return std::chrono::system_clock::to_time_t(
std::chrono::system_clock::time_point(*this));
std::chrono::system_clock::time_point(*this));
}
local_date() = default;
~local_date() = default;
local_date(local_date const&) = default;
local_date(local_date&&) = default;
local_date& operator=(local_date const&) = default;
local_date& operator=(local_date&&) = default;
};
template<typename uT, typename iT>
basic_datetime<uT, iT>::basic_datetime(std::chrono::system_clock::time_point tp)
inline bool operator==(const local_date& lhs, const local_date& rhs)
{
const auto t = std::chrono::system_clock::to_time_t(tp);
std::tm *time = std::localtime(&t);
this->year = time->tm_year + 1900;
this->month = time->tm_mon + 1;
this->day = time->tm_mday;
this->hour = time->tm_hour;
this->minute = time->tm_min;
this->second = time->tm_sec;
auto t_ = std::chrono::system_clock::from_time_t(std::mktime(time));
auto diff = tp - t_;
this->millisecond = std::chrono::duration_cast<std::chrono::milliseconds
>(diff).count() % 1000;
this->microsecond = std::chrono::duration_cast<std::chrono::microseconds
>(diff).count() % 1000;
std::tm *utc = std::gmtime(&t);
int total_offset = (this->hour - utc->tm_hour) * 60 +
(this->minute - utc->tm_min);
if(total_offset > 720) total_offset -= 1440;
else if(total_offset < -720) total_offset += 1440;
offset_hour = total_offset / 60;
offset_minute = total_offset - (offset_hour * 60);
return std::make_tuple(lhs.year, lhs.month, lhs.day) ==
std::make_tuple(rhs.year, rhs.month, rhs.day);
}
inline bool operator!=(const local_date& lhs, const local_date& rhs)
{
return !(lhs == rhs);
}
inline bool operator< (const local_date& lhs, const local_date& rhs)
{
return std::make_tuple(lhs.year, lhs.month, lhs.day) <
std::make_tuple(rhs.year, rhs.month, rhs.day);
}
inline bool operator<=(const local_date& lhs, const local_date& rhs)
{
return (lhs < rhs) || (lhs == rhs);
}
inline bool operator> (const local_date& lhs, const local_date& rhs)
{
return !(lhs <= rhs);
}
inline bool operator>=(const local_date& lhs, const local_date& rhs)
{
return !(lhs < rhs);
}
template<typename uT, typename iT>
basic_datetime<uT, iT>::basic_datetime(std::time_t t)
{
*this = basic_datetime(std::chrono::system_clock::from_time_t(t));
}
template<typename charT, typename traits, typename uT, typename iT>
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, basic_datetime<uT, iT> const& dt)
operator<<(std::basic_ostream<charT, traits>& os, const local_date& date)
{
bool date = false;
if(dt.year != basic_datetime<uT, iT>::undef &&
dt.month != basic_datetime<uT, iT>::undef &&
dt.day != basic_datetime<uT, iT>::undef)
os << std::setfill('0') << std::setw(4) << static_cast<int>(date.year ) << '-';
os << std::setfill('0') << std::setw(2) << static_cast<int>(date.month) + 1 << '-';
os << std::setfill('0') << std::setw(2) << static_cast<int>(date.day ) ;
return os;
}
struct local_time
{
std::uint8_t hour; // [0, 23]
std::uint8_t minute; // [0, 59]
std::uint8_t second; // [0, 60]
std::uint16_t millisecond; // [0, 999]
std::uint16_t microsecond; // [0, 999]
std::uint16_t nanosecond; // [0, 999]
local_time(int h, int m, int s,
int ms = 0, int us = 0, int ns = 0)
: hour (static_cast<std::uint8_t>(h)),
minute(static_cast<std::uint8_t>(m)),
second(static_cast<std::uint8_t>(s)),
millisecond(static_cast<std::uint16_t>(ms)),
microsecond(static_cast<std::uint16_t>(us)),
nanosecond (static_cast<std::uint16_t>(ns))
{}
explicit local_time(const std::tm& t)
: hour (static_cast<std::uint8_t>(t.tm_hour)),
minute(static_cast<std::uint8_t>(t.tm_min)),
second(static_cast<std::uint8_t>(t.tm_sec)),
millisecond(0), microsecond(0), nanosecond(0)
{}
template<typename Rep, typename Period>
explicit local_time(const std::chrono::duration<Rep, Period>& t)
{
os << std::setfill('0') << std::setw(4) << dt.year << '-'
<< std::setfill('0') << std::setw(2) << dt.month << '-'
<< std::setfill('0') << std::setw(2) << dt.day;
date = true;
const auto h = std::chrono::duration_cast<std::chrono::hours>(t);
this->hour = static_cast<std::uint8_t>(h.count());
const auto t2 = t - h;
const auto m = std::chrono::duration_cast<std::chrono::minutes>(t2);
this->minute = static_cast<std::uint8_t>(m.count());
const auto t3 = t2 - m;
const auto s = std::chrono::duration_cast<std::chrono::seconds>(t3);
this->second = static_cast<std::uint8_t>(s.count());
const auto t4 = t3 - s;
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(t4);
this->millisecond = static_cast<std::uint16_t>(ms.count());
const auto t5 = t4 - ms;
const auto us = std::chrono::duration_cast<std::chrono::microseconds>(t5);
this->microsecond = static_cast<std::uint16_t>(us.count());
const auto t6 = t5 - us;
const auto ns = std::chrono::duration_cast<std::chrono::nanoseconds>(t6);
this->nanosecond = static_cast<std::uint16_t>(ns.count());
}
if(dt.hour != basic_datetime<uT, iT>::undef &&
dt.minute != basic_datetime<uT, iT>::undef &&
dt.second != basic_datetime<uT, iT>::undef)
operator std::chrono::nanoseconds() const
{
if(date) os << 'T';
os << std::setfill('0') << std::setw(2) << dt.hour << ':'
<< std::setfill('0') << std::setw(2) << dt.minute << ':'
<< std::setfill('0') << std::setw(2) << dt.second << '.'
<< std::setfill('0') << std::setw(3) << dt.millisecond
<< std::setfill('0') << std::setw(3) << dt.microsecond;
return std::chrono::nanoseconds (this->nanosecond) +
std::chrono::microseconds(this->microsecond) +
std::chrono::milliseconds(this->millisecond) +
std::chrono::seconds(this->second) +
std::chrono::minutes(this->minute) +
std::chrono::hours(this->hour);
}
if(dt.offset_hour != basic_datetime<uT, iT>::nooffset &&
dt.offset_minute != basic_datetime<uT, iT>::nooffset)
local_time() = default;
~local_time() = default;
local_time(local_time const&) = default;
local_time(local_time&&) = default;
local_time& operator=(local_time const&) = default;
local_time& operator=(local_time&&) = default;
};
inline bool operator==(const local_time& lhs, const local_time& rhs)
{
return std::make_tuple(lhs.hour, lhs.minute, lhs.second, lhs.millisecond, lhs.microsecond, lhs.nanosecond) ==
std::make_tuple(rhs.hour, rhs.minute, rhs.second, rhs.millisecond, rhs.microsecond, rhs.nanosecond);
}
inline bool operator!=(const local_time& lhs, const local_time& rhs)
{
return !(lhs == rhs);
}
inline bool operator< (const local_time& lhs, const local_time& rhs)
{
return std::make_tuple(lhs.hour, lhs.minute, lhs.second, lhs.millisecond, lhs.microsecond, lhs.nanosecond) <
std::make_tuple(rhs.hour, rhs.minute, rhs.second, rhs.millisecond, rhs.microsecond, rhs.nanosecond);
}
inline bool operator<=(const local_time& lhs, const local_time& rhs)
{
return (lhs < rhs) || (lhs == rhs);
}
inline bool operator> (const local_time& lhs, const local_time& rhs)
{
return !(lhs <= rhs);
}
inline bool operator>=(const local_time& lhs, const local_time& rhs)
{
return !(lhs < rhs);
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const local_time& time)
{
os << std::setfill('0') << std::setw(2) << static_cast<int>(time.hour ) << ':';
os << std::setfill('0') << std::setw(2) << static_cast<int>(time.minute) << ':';
os << std::setfill('0') << std::setw(2) << static_cast<int>(time.second);
if(time.millisecond != 0 || time.microsecond != 0 || time.nanosecond != 0)
{
if(dt.offset_hour == 0 && dt.offset_minute == 0)
os << '.';
os << std::setfill('0') << std::setw(3) << static_cast<int>(time.millisecond);
if(time.microsecond != 0 || time.nanosecond != 0)
{
os << 'Z';
}
else
{
char sign = ' ';
iT oh = dt.offset_hour;
iT om = dt.offset_minute;
om += oh * 60;
if(om > 0) sign = '+'; else sign='-';
oh = om / 60;
om -= oh * 60;
os << sign << std::setfill('0') << std::setw(2) << std::abs(oh) << ':'
<< std::setfill('0') << std::setw(2) << std::abs(om);
os << std::setfill('0') << std::setw(3) << static_cast<int>(time.microsecond);
if(time.nanosecond != 0)
{
os << std::setfill('0') << std::setw(3) << static_cast<int>(time.nanosecond);
}
}
}
return os;
}
template<typename uT, typename iT>
inline bool
operator==(basic_datetime<uT, iT> const& lhs, basic_datetime<uT, iT> const& rhs)
struct time_offset
{
return lhs.year == rhs.year && lhs.month == rhs.month &&
lhs.day == rhs.day && lhs.minute == rhs.minute &&
lhs.second == rhs.second && lhs.millisecond == rhs.millisecond &&
lhs.microsecond == rhs.microsecond &&
lhs.offset_hour == rhs.offset_hour &&
lhs.offset_minute == rhs.offset_minute;
}
std::int8_t hour; // [-12, 12]
std::int8_t minute; // [-59, 59]
template<typename uT, typename iT>
inline bool
operator!=(basic_datetime<uT, iT> const& lhs, basic_datetime<uT, iT> const& rhs)
time_offset(int h, int m)
: hour (static_cast<std::int8_t>(h)),
minute(static_cast<std::int8_t>(m))
{}
operator std::chrono::minutes() const
{
return std::chrono::minutes(this->minute) +
std::chrono::hours(this->hour);
}
time_offset() = default;
~time_offset() = default;
time_offset(time_offset const&) = default;
time_offset(time_offset&&) = default;
time_offset& operator=(time_offset const&) = default;
time_offset& operator=(time_offset&&) = default;
};
inline bool operator==(const time_offset& lhs, const time_offset& rhs)
{
return std::make_tuple(lhs.hour, lhs.minute) ==
std::make_tuple(rhs.hour, rhs.minute);
}
inline bool operator!=(const time_offset& lhs, const time_offset& rhs)
{
return !(lhs == rhs);
}
template<typename uT, typename iT>
inline bool
operator<(basic_datetime<uT, iT> const& lhs, basic_datetime<uT, iT> const& rhs)
inline bool operator< (const time_offset& lhs, const time_offset& rhs)
{
return std::time_t(lhs) < std::time_t(rhs);
return std::make_tuple(lhs.hour, lhs.minute) <
std::make_tuple(rhs.hour, rhs.minute);
}
inline bool operator<=(const time_offset& lhs, const time_offset& rhs)
{
return (lhs < rhs) || (lhs == rhs);
}
inline bool operator> (const time_offset& lhs, const time_offset& rhs)
{
return !(lhs <= rhs);
}
inline bool operator>=(const time_offset& lhs, const time_offset& rhs)
{
return !(lhs < rhs);
}
template<typename uT, typename iT>
inline bool
operator<=(basic_datetime<uT, iT> const& lhs, basic_datetime<uT, iT> const& rhs)
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const time_offset& offset)
{
return std::time_t(lhs) <= std::time_t(rhs);
if(offset.hour == 0 && offset.minute == 0)
{
os << 'Z';
return os;
}
int minute = static_cast<int>(offset.hour) * 60 + offset.minute;
if(minute < 0){os << '-'; minute = std::abs(minute);} else {os << '+';}
os << std::setfill('0') << std::setw(2) << minute / 60 << ':';
os << std::setfill('0') << std::setw(2) << minute % 60;
return os;
}
template<typename uT, typename iT>
inline bool
operator>(basic_datetime<uT, iT> const& lhs, basic_datetime<uT, iT> const& rhs)
struct local_datetime
{
return std::time_t(lhs) > std::time_t(rhs);
local_date date;
local_time time;
local_datetime(local_date d, local_time t): date(d), time(t) {}
explicit local_datetime(const std::tm& t): date(t), time(t){}
explicit local_datetime(const std::chrono::system_clock::time_point& tp)
{
const auto t = std::chrono::system_clock::to_time_t(tp);
std::tm ltime = detail::localtime_s(&t);
this->date = local_date(ltime);
this->time = local_time(ltime);
// std::tm lacks subsecond information, so diff between tp and tm
// can be used to get millisecond & microsecond information.
const auto t_diff = tp -
std::chrono::system_clock::from_time_t(std::mktime(&ltime));
this->time.millisecond = static_cast<std::uint16_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(t_diff).count());
this->time.microsecond = static_cast<std::uint16_t>(
std::chrono::duration_cast<std::chrono::microseconds>(t_diff).count());
this->time.nanosecond = static_cast<std::uint16_t>(
std::chrono::duration_cast<std::chrono::nanoseconds >(t_diff).count());
}
explicit local_datetime(const std::time_t t)
: local_datetime(std::chrono::system_clock::from_time_t(t))
{}
operator std::chrono::system_clock::time_point() const
{
using internal_duration =
typename std::chrono::system_clock::time_point::duration;
// Normally DST begins at A.M. 3 or 4. If we re-use conversion operator
// of local_date and local_time independently, the conversion fails if
// it is the day when DST begins or ends. Since local_date considers the
// time is 00:00 A.M. and local_time does not consider DST because it
// does not have any date information. We need to consider both date and
// time information at the same time to convert it correctly.
std::tm t;
t.tm_sec = static_cast<int>(this->time.second);
t.tm_min = static_cast<int>(this->time.minute);
t.tm_hour = static_cast<int>(this->time.hour);
t.tm_mday = static_cast<int>(this->date.day);
t.tm_mon = static_cast<int>(this->date.month);
t.tm_year = static_cast<int>(this->date.year) - 1900;
t.tm_wday = 0; // the value will be ignored
t.tm_yday = 0; // the value will be ignored
t.tm_isdst = -1;
// std::mktime returns date as local time zone. no conversion needed
auto dt = std::chrono::system_clock::from_time_t(std::mktime(&t));
dt += std::chrono::duration_cast<internal_duration>(
std::chrono::milliseconds(this->time.millisecond) +
std::chrono::microseconds(this->time.microsecond) +
std::chrono::nanoseconds (this->time.nanosecond));
return dt;
}
operator std::time_t() const
{
return std::chrono::system_clock::to_time_t(
std::chrono::system_clock::time_point(*this));
}
local_datetime() = default;
~local_datetime() = default;
local_datetime(local_datetime const&) = default;
local_datetime(local_datetime&&) = default;
local_datetime& operator=(local_datetime const&) = default;
local_datetime& operator=(local_datetime&&) = default;
};
inline bool operator==(const local_datetime& lhs, const local_datetime& rhs)
{
return std::make_tuple(lhs.date, lhs.time) ==
std::make_tuple(rhs.date, rhs.time);
}
inline bool operator!=(const local_datetime& lhs, const local_datetime& rhs)
{
return !(lhs == rhs);
}
inline bool operator< (const local_datetime& lhs, const local_datetime& rhs)
{
return std::make_tuple(lhs.date, lhs.time) <
std::make_tuple(rhs.date, rhs.time);
}
inline bool operator<=(const local_datetime& lhs, const local_datetime& rhs)
{
return (lhs < rhs) || (lhs == rhs);
}
inline bool operator> (const local_datetime& lhs, const local_datetime& rhs)
{
return !(lhs <= rhs);
}
inline bool operator>=(const local_datetime& lhs, const local_datetime& rhs)
{
return !(lhs < rhs);
}
template<typename uT, typename iT>
inline bool
operator>=(basic_datetime<uT, iT> const& lhs, basic_datetime<uT, iT> const& rhs)
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const local_datetime& dt)
{
return std::time_t(lhs) >= std::time_t(rhs);
os << dt.date << 'T' << dt.time;
return os;
}
struct offset_datetime
{
local_date date;
local_time time;
time_offset offset;
offset_datetime(local_date d, local_time t, time_offset o)
: date(d), time(t), offset(o)
{}
offset_datetime(const local_datetime& dt, time_offset o)
: date(dt.date), time(dt.time), offset(o)
{}
explicit offset_datetime(const local_datetime& ld)
: date(ld.date), time(ld.time), offset(get_local_offset(nullptr))
// use the current local timezone offset
{}
explicit offset_datetime(const std::chrono::system_clock::time_point& tp)
: offset(0, 0) // use gmtime
{
const auto timet = std::chrono::system_clock::to_time_t(tp);
const auto tm = detail::gmtime_s(&timet);
this->date = local_date(tm);
this->time = local_time(tm);
}
explicit offset_datetime(const std::time_t& t)
: offset(0, 0) // use gmtime
{
const auto tm = detail::gmtime_s(&t);
this->date = local_date(tm);
this->time = local_time(tm);
}
explicit offset_datetime(const std::tm& t)
: offset(0, 0) // assume gmtime
{
this->date = local_date(t);
this->time = local_time(t);
}
operator std::chrono::system_clock::time_point() const
{
// get date-time
using internal_duration =
typename std::chrono::system_clock::time_point::duration;
// first, convert it to local date-time information in the same way as
// local_datetime does. later we will use time_t to adjust time offset.
std::tm t;
t.tm_sec = static_cast<int>(this->time.second);
t.tm_min = static_cast<int>(this->time.minute);
t.tm_hour = static_cast<int>(this->time.hour);
t.tm_mday = static_cast<int>(this->date.day);
t.tm_mon = static_cast<int>(this->date.month);
t.tm_year = static_cast<int>(this->date.year) - 1900;
t.tm_wday = 0; // the value will be ignored
t.tm_yday = 0; // the value will be ignored
t.tm_isdst = -1;
const std::time_t tp_loc = std::mktime(std::addressof(t));
auto tp = std::chrono::system_clock::from_time_t(tp_loc);
tp += std::chrono::duration_cast<internal_duration>(
std::chrono::milliseconds(this->time.millisecond) +
std::chrono::microseconds(this->time.microsecond) +
std::chrono::nanoseconds (this->time.nanosecond));
// Since mktime uses local time zone, it should be corrected.
// `12:00:00+09:00` means `03:00:00Z`. So mktime returns `03:00:00Z` if
// we are in `+09:00` timezone. To represent `12:00:00Z` there, we need
// to add `+09:00` to `03:00:00Z`.
// Here, it uses the time_t converted from date-time info to handle
// daylight saving time.
const auto ofs = get_local_offset(std::addressof(tp_loc));
tp += std::chrono::hours (ofs.hour);
tp += std::chrono::minutes(ofs.minute);
// We got `12:00:00Z` by correcting local timezone applied by mktime.
// Then we will apply the offset. Let's say `12:00:00-08:00` is given.
// And now, we have `12:00:00Z`. `12:00:00-08:00` means `20:00:00Z`.
// So we need to subtract the offset.
tp -= std::chrono::minutes(this->offset);
return tp;
}
operator std::time_t() const
{
return std::chrono::system_clock::to_time_t(
std::chrono::system_clock::time_point(*this));
}
offset_datetime() = default;
~offset_datetime() = default;
offset_datetime(offset_datetime const&) = default;
offset_datetime(offset_datetime&&) = default;
offset_datetime& operator=(offset_datetime const&) = default;
offset_datetime& operator=(offset_datetime&&) = default;
private:
static time_offset get_local_offset(const std::time_t* tp)
{
// get local timezone with the same date-time information as mktime
const auto t = detail::localtime_s(tp);
std::array<char, 6> buf;
const auto result = std::strftime(buf.data(), 6, "%z", &t); // +hhmm\0
if(result != 5)
{
throw std::runtime_error("toml::offset_datetime: cannot obtain "
"timezone information of current env");
}
const int ofs = std::atoi(buf.data());
const int ofs_h = ofs / 100;
const int ofs_m = ofs - (ofs_h * 100);
return time_offset(ofs_h, ofs_m);
}
};
inline bool operator==(const offset_datetime& lhs, const offset_datetime& rhs)
{
return std::make_tuple(lhs.date, lhs.time, lhs.offset) ==
std::make_tuple(rhs.date, rhs.time, rhs.offset);
}
inline bool operator!=(const offset_datetime& lhs, const offset_datetime& rhs)
{
return !(lhs == rhs);
}
inline bool operator< (const offset_datetime& lhs, const offset_datetime& rhs)
{
return std::make_tuple(lhs.date, lhs.time, lhs.offset) <
std::make_tuple(rhs.date, rhs.time, rhs.offset);
}
inline bool operator<=(const offset_datetime& lhs, const offset_datetime& rhs)
{
return (lhs < rhs) || (lhs == rhs);
}
inline bool operator> (const offset_datetime& lhs, const offset_datetime& rhs)
{
return !(lhs <= rhs);
}
inline bool operator>=(const offset_datetime& lhs, const offset_datetime& rhs)
{
return !(lhs < rhs);
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const offset_datetime& dt)
{
os << dt.date << 'T' << dt.time << dt.offset;
return os;
}
}//toml
#endif// TOML11_DATETIME

View File

@@ -1,23 +1,33 @@
#ifndef TOML11_EXCEPTION
#define TOML11_EXCEPTION
// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_EXCEPTION_HPP
#define TOML11_EXCEPTION_HPP
#include <stdexcept>
#include <string>
#include "source_location.hpp"
namespace toml
{
struct exception : public std::exception
{
public:
explicit exception(const source_location& loc): loc_(loc) {}
virtual ~exception() noexcept override = default;
virtual const char* what() const noexcept override {return "";}
virtual source_location const& location() const noexcept {return loc_;}
protected:
source_location loc_;
};
struct syntax_error : public toml::exception
{
public:
explicit syntax_error(const std::string& what_arg) : what_(what_arg){}
explicit syntax_error(const char* what_arg) : what_(what_arg){}
explicit syntax_error(const std::string& what_arg, const source_location& loc)
: exception(loc), what_(what_arg)
{}
virtual ~syntax_error() noexcept override = default;
virtual const char* what() const noexcept override {return what_.c_str();}
@@ -28,8 +38,9 @@ struct syntax_error : public toml::exception
struct type_error : public toml::exception
{
public:
explicit type_error(const std::string& what_arg) : what_(what_arg){}
explicit type_error(const char* what_arg) : what_(what_arg){}
explicit type_error(const std::string& what_arg, const source_location& loc)
: exception(loc), what_(what_arg)
{}
virtual ~type_error() noexcept override = default;
virtual const char* what() const noexcept override {return what_.c_str();}
@@ -40,10 +51,12 @@ struct type_error : public toml::exception
struct internal_error : public toml::exception
{
public:
explicit internal_error(const std::string& what_arg) : what_(what_arg){}
explicit internal_error(const char* what_arg) : what_(what_arg){}
explicit internal_error(const std::string& what_arg, const source_location& loc)
: exception(loc), what_(what_arg)
{}
virtual ~internal_error() noexcept override = default;
virtual const char* what() const noexcept override {return what_.c_str();}
protected:
std::string what_;
};

View File

@@ -1,386 +0,0 @@
#ifndef TOML11_FORMAT
#define TOML11_FORMAT
#include "value.hpp"
#include <type_traits>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <locale>
namespace toml
{
// synopsis
// toml::format("key", value, toml::make_inline(80))
// toml::format("key", value, toml::forceinline)
// std::cout << toml::make_inline(80) << value;
// std::cout << toml::forceinline << value;
template<typename traits = std::char_traits<toml::character>,
typename alloc = std::allocator<toml::character>>
std::basic_string<toml::character, traits, alloc>
format(const value& v);
template<typename traits = std::char_traits<toml::character>,
typename alloc = std::allocator<toml::character>>
std::basic_string<toml::character, traits, alloc>
format(const value& v, std::size_t mk);
template<typename traits = std::char_traits<toml::character>,
typename alloc = std::allocator<toml::character>>
std::basic_string<toml::character, traits, alloc>
format(const toml::key& k, const value& v);
template<typename traits = std::char_traits<toml::character>,
typename alloc = std::allocator<toml::character>>
std::basic_string<toml::character, traits, alloc>
format(const toml::key& k, const value& v, std::size_t mk);
template<value_t Type>
struct format_impl;
template<> struct format_impl<value_t::Boolean>
{
typedef detail::toml_default_type<value_t::Boolean>::type type;
std::basic_string<toml::character>
operator()(const type& val)
{
return val ? "true" : "false";
}
};
template<> struct format_impl<value_t::Integer>
{
typedef detail::toml_default_type<value_t::Integer>::type type;
std::basic_string<toml::character>
operator()(const type& val)
{
return std::to_string(val);
}
};
template<> struct format_impl<value_t::Float>
{
typedef detail::toml_default_type<value_t::Float>::type type;
std::basic_string<toml::character>
operator()(const type& val)
{
std::basic_ostringstream<toml::character> oss;
oss << std::showpoint << val;
if(oss.str().back() == '.') oss << '0';
return oss.str();
}
};
template<> struct format_impl<value_t::String>
{
typedef detail::toml_default_type<value_t::String>::type type;
std::size_t max_length;
format_impl() : max_length(80){}
format_impl(std::size_t mx) : max_length(mx){}
std::basic_string<toml::character>
operator()(const type& val)
{
auto tmp = make_inline(val);
if(max_length == std::numeric_limits<std::size_t>::max() ||
tmp.size() <= max_length) return tmp;
return convert_multiline(std::move(tmp));
}
private:
std::basic_string<toml::character>
make_inline(const std::basic_string<toml::character>& val)
{
std::basic_string<toml::character> str;
str += '"';
for(const auto& c : val)
{
if('\0' < c && c < '\31')
{
switch(c)
{
case '\b': str += "\\b"; break;
case '\t': str += "\\t"; break;
case '\n': str += "\\n"; break;
case '\f': str += "\\f"; break;
case '\r': str += "\\r"; break;
default:
{
str += 'u';
std::basic_ostringstream<toml::character> oss;
oss << std::setw(4) << std::setfill('0') << std::hex
<< static_cast<std::int8_t>(c);
auto hexdig = oss.str();
std::transform(hexdig.begin(), hexdig.end(), hexdig.begin(), ::toupper);
str += oss.str();
break;
}
}
}
else if(c == '"')
{
str += "\\\"";
}
else if(c == '\\')
{
str += "\\\\";
}
else
{
str += c;
}
}
str += '"';
return str;
}
std::basic_string<toml::character>
convert_multiline(std::basic_string<toml::character>&& val)
{
std::basic_string<toml::character> str; str.reserve(val.size() + 6);
str += "\"\"\"\n";
std::size_t current = 0;
for(auto iter = val.begin()+1; iter != val.end()-1; ++iter)
{
if(*iter != '\\')
{
if(current + 1 == max_length) str += "\\\n";
str += *iter; continue;
}
assert(std::next(iter) < val.end()-1);
if(*std::next(iter) == 'u')
{
if(current + 5 == max_length) str += "\\\n";
assert(iter + 5 < val.end()-1);
str += *iter; ++iter; // u
str += *iter; ++iter; // 0
str += *iter; ++iter; // 1
str += *iter; ++iter; // 2
str += *iter; continue;// 3
}
if(current + 2 == max_length) str += "\\\n";
str += *iter; ++iter; str += *iter;
}
str += "\"\"\"";
return str;
}
};
template<> struct format_impl<value_t::Datetime>
{
typedef detail::toml_default_type<value_t::Datetime>::type type;
std::basic_string<toml::character>
operator()(const type& val)
{
std::basic_ostringstream<toml::character> oss;
oss << val;
return oss.str();
}
};
// TODO max length!
template<> struct format_impl<value_t::Array>
{
typedef detail::toml_default_type<value_t::Array>::type type;
std::size_t max_length;
format_impl() : max_length(80){}
format_impl(std::size_t mx) : max_length(mx){}
std::basic_string<toml::character>
operator()(const type& val)
{
std::basic_string<toml::character> retval;
retval += '[';
for(const auto& item : val)
{
auto tmp = format(val, max_length - 1);
retval += tmp;
retval += ", ";
if(tmp.size() * 2 > max_length) retval += '\n';
}
retval += ']';
return retval;
}
};
// TODO max length && inline!
template<> struct format_impl<value_t::Table>
{
typedef detail::toml_default_type<value_t::Table>::type type;
std::size_t max_length;
format_impl() : max_length(80){}
format_impl(std::size_t mx) : max_length(mx){}
std::basic_string<toml::character>
operator()(const type& val)
{
std::basic_string<toml::character> retval;
for(const auto& item : val)
{
retval += item.first;
retval += " = ";
retval += format(item.second);
retval += '\n';
}
return retval;
}
};
template<typename traits, typename alloc>
std::basic_string<toml::character, traits, alloc>
format(const value& v)
{
switch(v.type())
{
case value_t::Boolean : return format_impl<value_t::Boolean >{}(v.template cast<value_t::Boolean >());
case value_t::Integer : return format_impl<value_t::Integer >{}(v.template cast<value_t::Integer >());
case value_t::Float : return format_impl<value_t::Float >{}(v.template cast<value_t::Float >());
case value_t::String : return format_impl<value_t::String >{}(v.template cast<value_t::String >());
case value_t::Datetime: return format_impl<value_t::Datetime>{}(v.template cast<value_t::Datetime>());
case value_t::Array : return format_impl<value_t::Array >{}(v.template cast<value_t::Array >());
case value_t::Table : return format_impl<value_t::Table >{}(v.template cast<value_t::Table >());
case value_t::Empty : throw std::runtime_error("toml::format: empty value");
case value_t::Unknown : throw std::runtime_error("toml::format: unknown value");
default: throw std::logic_error("toml::format: unknown enum value");
}
}
template<typename traits, typename alloc>
std::basic_string<toml::character, traits, alloc>
format(const value& v, std::size_t inl)
{
switch(v.type())
{
case value_t::Boolean : return format_impl<value_t::Boolean >{}(v.template cast<value_t::Boolean>());
case value_t::Integer : return format_impl<value_t::Integer >{}(v.template cast<value_t::Integer>());
case value_t::Float : return format_impl<value_t::Float >{}(v.template cast<value_t::Float>());
case value_t::String : return format_impl<value_t::String >{inl}(v.template cast<value_t::String>());
case value_t::Datetime: return format_impl<value_t::Datetime>{}(v.template cast<value_t::Datetime>());
case value_t::Array : return format_impl<value_t::Array >{inl}(v.template cast<value_t::Array>());
case value_t::Table : return format_impl<value_t::Table >{inl}(v.template cast<value_t::Table>());
case value_t::Empty : throw std::runtime_error("toml::format: empty value");
case value_t::Unknown : throw std::runtime_error("toml::format: unknown value");
default: throw std::logic_error("toml::format: unknown enum value");
}
}
template<typename traits, typename alloc>
std::basic_string<toml::character, traits, alloc>
format(std::basic_string<toml::character, traits, alloc> key, const value& val)
{
std::basic_string<toml::character, traits, alloc> retval(std::move(key));
retval += " = ";
retval += format(val);
return retval;
}
template<typename traits, typename alloc>
std::basic_string<toml::character, traits, alloc>
format(std::basic_string<toml::character, traits, alloc> key, const value& val, std::size_t mk)
{
std::basic_string<toml::character, traits, alloc> retval(std::move(key));
retval += " = ";
retval += format(val, mk);
return retval;
}
// ----------------------------- stream operators -----------------------------
namespace detail
{
template<typename T = std::size_t>
struct inline_limit
{
static_assert(std::is_same<T, std::size_t>::value, "do not instantiate this");
static const int index;
T limit;
inline_limit() = default;
~inline_limit() = default;
constexpr inline_limit(T i): limit(i){}
constexpr operator T() const {return limit;}
static void callback(std::ios_base::event ev, std::ios_base& ios, int idx)
{
void*& info = ios.pword(idx);
switch (ev)
{
case std::ios_base::erase_event:
{
delete static_cast<std::size_t*>(info);
break;
}
case std::ios_base::copyfmt_event:
{
info = new std::size_t(*static_cast<std::size_t*>(info));
break;
}
case std::ios_base::imbue_event:
{
break;
}
}
}
};
template<typename T>
const int inline_limit<T>::index = std::ios_base::xalloc();
} //detail
template<typename sizeT, typename traits = std::char_traits<toml::character>>
std::basic_ostream<toml::character, traits>&
operator<<(std::basic_ostream<toml::character, traits>& os,
const detail::inline_limit<sizeT>& inl)
{
void*& info = os.pword(detail::inline_limit<sizeT>::index);
if(!os.bad())
{
if(info == nullptr)
{
os.register_callback(detail::inline_limit<sizeT>::callback,
detail::inline_limit<sizeT>::index);
info = new std::size_t(inl.limit);
}
else
{
*static_cast<std::size_t*>(info) = inl.limit;
}
}
return os;
}
constexpr static detail::inline_limit<std::size_t> forceinline(
std::numeric_limits<std::size_t>::max());
inline detail::inline_limit<std::size_t> make_inline(std::size_t sz)
{
return detail::inline_limit<std::size_t>(sz);
}
template<typename T, typename traits = std::char_traits<toml::character>>
std::basic_ostream<toml::character, traits>&
operator<<(std::basic_ostream<toml::character, traits>& os,
const toml::value& v)
{
std::size_t* info =
static_cast<std::size_t*>(os.pword(detail::inline_limit<std::size_t>::index));
return os << (info == nullptr ? toml::format(v) : toml::format(v, *info));
}
}
#endif // TOML11_FORMAT

20
toml/from.hpp Normal file
View File

@@ -0,0 +1,20 @@
// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_FROM_HPP
#define TOML11_FROM_HPP
#include "traits.hpp"
namespace toml
{
template<typename T>
struct from;
// {
// static T from_toml(const toml::value& v)
// {
// // User-defined conversions ...
// }
// };
} // toml
#endif // TOML11_FROM_HPP

View File

@@ -1,121 +0,0 @@
#ifndef TOML11_FROM_TOML
#define TOML11_FROM_TOML
#include "value.hpp"
namespace toml
{
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT != toml::value_t::Unknown &&
vT != value_t::Empty), std::nullptr_t>::type = nullptr>
void from_toml(T& x, const toml::value& v)
{
if(v.type() != vT)
throw type_error("from_toml: value type: " + stringize(v.type()) +
std::string(" is not arguemnt type: ") + stringize(vT));
x = v.cast<vT>();
return;
}
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT == toml::value_t::Unknown) &&
(!toml::detail::is_map<T>::value) &&
toml::detail::is_container<T>::value, std::nullptr_t>::type = nullptr>
void from_toml(T& x, const toml::value& v)
{
// TODO the case of x is not dynamic container case
if(v.type() != value_t::Array)
throw type_error("from_toml: value type: " + stringize(v.type()) +
std::string(" is not argument type: Array"));
const auto& ar = v.cast<value_t::Array>();
try
{
toml::resize(x, ar.size());
}
catch(std::invalid_argument& iv)
{
throw toml::type_error("toml::from_toml: static array size is not enough");
}
auto iter = x.begin();
for(const auto& val : ar)
{
typename T::value_type v;
from_toml(v, val);
*iter = std::move(v);
++iter;
}
return;
}
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT == toml::value_t::Unknown) &&
toml::detail::is_map<T>::value, std::nullptr_t>::type = nullptr>
void from_toml(T& x, const toml::value& v)
{
if(v.type() != value_t::Table)
throw type_error("from_toml: value type: " + stringize(v.type()) +
std::string(" is not argument type: Table"));
x.clear();
const auto& tb = v.cast<value_t::Table>();
for(const auto& kv : tb)
{
x.insert(kv);
}
return;
}
namespace detail
{
template<typename T>
constexpr toml::value_t determine_castable_type()
{
return check_type<T>() != toml::value_t::Unknown ? check_type<T>() :
toml::detail::is_map<T>::value ? toml::value_t::Table :
toml::detail::is_container<T>::value ? toml::value_t::Array :
toml::value_t::Unknown;
}
template<std::size_t N, typename ... Ts>
struct from_toml_tie_impl
{
constexpr static std::size_t index = sizeof...(Ts) - N;
constexpr static toml::value_t type_index =
determine_castable_type<
typename std::tuple_element<index, std::tuple<Ts...>>::type>();
static void invoke(std::tuple<Ts& ...> tie, const toml::value& v)
{
// static_cast is needed because with intel c++ compiler, operator==
// is only defined when the two types are strictly equal, and type_index
// is const toml::value_t, while v.type() is toml::value_t.
if(static_cast<toml::value_t>(type_index) == v.type())
{
from_toml(std::get<index>(tie), v);
return;
}
return from_toml_tie_impl<N-1, Ts...>::invoke(tie, v);
}
};
template<typename ... Ts>
struct from_toml_tie_impl<0, Ts...>
{
static void invoke(std::tuple<Ts& ...> tie, const toml::value& v)
{
return;
}
};
} // detail
template<typename ... Ts>
void from_toml(std::tuple<Ts& ...> tie, const toml::value& v)
{
detail::from_toml_tie_impl<sizeof...(Ts), Ts...>::invoke(tie, v);
return;
}
} // toml
#endif // TOML11_FROM_TOML

File diff suppressed because it is too large Load Diff

20
toml/into.hpp Normal file
View File

@@ -0,0 +1,20 @@
// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_INTO_HPP
#define TOML11_INTO_HPP
#include "traits.hpp"
namespace toml
{
template<typename T>
struct into;
// {
// static toml::value into_toml(const T& user_defined_type)
// {
// // User-defined conversions ...
// }
// };
} // toml
#endif // TOML11_INTO_HPP

270
toml/lexer.hpp Normal file
View File

@@ -0,0 +1,270 @@
// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_LEXER_HPP
#define TOML11_LEXER_HPP
#include <istream>
#include <sstream>
#include <stdexcept>
#include <fstream>
#include "combinator.hpp"
namespace toml
{
namespace detail
{
// these scans contents from current location in a container of char
// and extract a region that matches their own pattern.
// to see the implementation of each component, see combinator.hpp.
using lex_wschar = either<character<' '>, character<'\t'>>;
using lex_ws = repeat<lex_wschar, at_least<1>>;
using lex_newline = either<character<'\n'>,
sequence<character<'\r'>, character<'\n'>>>;
using lex_lower = in_range<'a', 'z'>;
using lex_upper = in_range<'A', 'Z'>;
using lex_alpha = either<lex_lower, lex_upper>;
using lex_digit = in_range<'0', '9'>;
using lex_nonzero = in_range<'1', '9'>;
using lex_oct_dig = in_range<'0', '7'>;
using lex_bin_dig = in_range<'0', '1'>;
using lex_hex_dig = either<lex_digit, in_range<'A', 'F'>, in_range<'a', 'f'>>;
using lex_hex_prefix = sequence<character<'0'>, character<'x'>>;
using lex_oct_prefix = sequence<character<'0'>, character<'o'>>;
using lex_bin_prefix = sequence<character<'0'>, character<'b'>>;
using lex_underscore = character<'_'>;
using lex_plus = character<'+'>;
using lex_minus = character<'-'>;
using lex_sign = either<lex_plus, lex_minus>;
// digit | nonzero 1*(digit | _ digit)
using lex_unsigned_dec_int = either<sequence<lex_nonzero, repeat<
either<lex_digit, sequence<lex_underscore, lex_digit>>, at_least<1>>>,
lex_digit>;
// (+|-)? unsigned_dec_int
using lex_dec_int = sequence<maybe<lex_sign>, lex_unsigned_dec_int>;
// hex_prefix hex_dig *(hex_dig | _ hex_dig)
using lex_hex_int = sequence<lex_hex_prefix, sequence<lex_hex_dig, repeat<
either<lex_hex_dig, sequence<lex_underscore, lex_hex_dig>>, unlimited>>>;
// oct_prefix oct_dig *(oct_dig | _ oct_dig)
using lex_oct_int = sequence<lex_oct_prefix, sequence<lex_oct_dig, repeat<
either<lex_oct_dig, sequence<lex_underscore, lex_oct_dig>>, unlimited>>>;
// bin_prefix bin_dig *(bin_dig | _ bin_dig)
using lex_bin_int = sequence<lex_bin_prefix, sequence<lex_bin_dig, repeat<
either<lex_bin_dig, sequence<lex_underscore, lex_bin_dig>>, unlimited>>>;
// (dec_int | hex_int | oct_int | bin_int)
using lex_integer = either<lex_bin_int, lex_oct_int, lex_hex_int, lex_dec_int>;
// ===========================================================================
using lex_inf = sequence<character<'i'>, character<'n'>, character<'f'>>;
using lex_nan = sequence<character<'n'>, character<'a'>, character<'n'>>;
using lex_special_float = sequence<maybe<lex_sign>, either<lex_inf, lex_nan>>;
using lex_zero_prefixable_int = sequence<lex_digit, repeat<either<lex_digit,
sequence<lex_underscore, lex_digit>>, unlimited>>;
using lex_fractional_part = sequence<character<'.'>, lex_zero_prefixable_int>;
using lex_exponent_part = sequence<either<character<'e'>, character<'E'>>,
maybe<lex_sign>, lex_zero_prefixable_int>;
using lex_float = either<lex_special_float,
sequence<lex_dec_int, either<lex_exponent_part,
sequence<lex_fractional_part, maybe<lex_exponent_part>>>>>;
// ===========================================================================
using lex_true = sequence<character<'t'>, character<'r'>,
character<'u'>, character<'e'>>;
using lex_false = sequence<character<'f'>, character<'a'>, character<'l'>,
character<'s'>, character<'e'>>;
using lex_boolean = either<lex_true, lex_false>;
// ===========================================================================
using lex_date_fullyear = repeat<lex_digit, exactly<4>>;
using lex_date_month = repeat<lex_digit, exactly<2>>;
using lex_date_mday = repeat<lex_digit, exactly<2>>;
using lex_time_delim = either<character<'T'>, character<'t'>, character<' '>>;
using lex_time_hour = repeat<lex_digit, exactly<2>>;
using lex_time_minute = repeat<lex_digit, exactly<2>>;
using lex_time_second = repeat<lex_digit, exactly<2>>;
using lex_time_secfrac = sequence<character<'.'>,
repeat<lex_digit, at_least<1>>>;
using lex_time_numoffset = sequence<either<character<'+'>, character<'-'>>,
sequence<lex_time_hour, character<':'>,
lex_time_minute>>;
using lex_time_offset = either<character<'Z'>, character<'z'>,
lex_time_numoffset>;
using lex_partial_time = sequence<lex_time_hour, character<':'>,
lex_time_minute, character<':'>,
lex_time_second, maybe<lex_time_secfrac>>;
using lex_full_date = sequence<lex_date_fullyear, character<'-'>,
lex_date_month, character<'-'>,
lex_date_mday>;
using lex_full_time = sequence<lex_partial_time, lex_time_offset>;
using lex_offset_date_time = sequence<lex_full_date, lex_time_delim, lex_full_time>;
using lex_local_date_time = sequence<lex_full_date, lex_time_delim, lex_partial_time>;
using lex_local_date = lex_full_date;
using lex_local_time = lex_partial_time;
// ===========================================================================
using lex_quotation_mark = character<'"'>;
using lex_basic_unescaped = exclude<either<in_range<0x00, 0x08>, // 0x09 (tab)
in_range<0x0a, 0x1F>, // is allowed
character<0x22>, character<0x5C>,
character<0x7F>>>;
using lex_escape = character<'\\'>;
using lex_escape_unicode_short = sequence<character<'u'>,
repeat<lex_hex_dig, exactly<4>>>;
using lex_escape_unicode_long = sequence<character<'U'>,
repeat<lex_hex_dig, exactly<8>>>;
using lex_escape_seq_char = either<character<'"'>, character<'\\'>,
character<'b'>, character<'f'>,
character<'n'>, character<'r'>,
character<'t'>,
lex_escape_unicode_short,
lex_escape_unicode_long
>;
using lex_escaped = sequence<lex_escape, lex_escape_seq_char>;
using lex_basic_char = either<lex_basic_unescaped, lex_escaped>;
using lex_basic_string = sequence<lex_quotation_mark,
repeat<lex_basic_char, unlimited>,
lex_quotation_mark>;
// After toml post-v0.5.0, it is explicitly clarified how quotes in ml-strings
// are allowed to be used.
// After this, the following strings are *explicitly* allowed.
// - One or two `"`s in a multi-line basic string is allowed wherever it is.
// - Three consecutive `"`s in a multi-line basic string is considered as a delimiter.
// - One or two `"`s can appear just before or after the delimiter.
// ```toml
// str4 = """Here are two quotation marks: "". Simple enough."""
// str5 = """Here are three quotation marks: ""\"."""
// str6 = """Here are fifteen quotation marks: ""\"""\"""\"""\"""\"."""
// str7 = """"This," she said, "is just a pointless statement.""""
// ```
// In the current implementation (v3.3.0), it is difficult to parse `str7` in
// the above example. It is difficult to recognize `"` at the end of string body
// collectly. It will be misunderstood as a `"""` delimiter and an additional,
// invalid `"`. Like this:
// ```console
// what(): [error] toml::parse_table: invalid line format
// --> hoge.toml
// |
// 13 | str7 = """"This," she said, "is just a pointless statement.""""
// | ^- expected newline, but got '"'.
// ```
// As a quick workaround for this problem, `lex_ml_basic_string_delim` was
// splitted into two, `lex_ml_basic_string_open` and `lex_ml_basic_string_close`.
// `lex_ml_basic_string_open` allows only `"""`. `_close` allows 3-5 `"`s.
// In parse_ml_basic_string() function, the trailing `"`s will be attached to
// the string body.
//
using lex_ml_basic_string_delim = repeat<lex_quotation_mark, exactly<3>>;
using lex_ml_basic_string_open = lex_ml_basic_string_delim;
using lex_ml_basic_string_close = sequence<
repeat<lex_quotation_mark, exactly<3>>,
maybe<lex_quotation_mark>, maybe<lex_quotation_mark>
>;
using lex_ml_basic_unescaped = exclude<either<in_range<0x00, 0x08>, // 0x09
in_range<0x0a, 0x1F>, // is tab
character<0x5C>, // backslash
character<0x7F>, // DEL
lex_ml_basic_string_delim>>;
using lex_ml_basic_escaped_newline = sequence<
lex_escape, maybe<lex_ws>, lex_newline,
repeat<either<lex_ws, lex_newline>, unlimited>>;
using lex_ml_basic_char = either<lex_ml_basic_unescaped, lex_escaped>;
using lex_ml_basic_body = repeat<either<lex_ml_basic_char, lex_newline,
lex_ml_basic_escaped_newline>,
unlimited>;
using lex_ml_basic_string = sequence<lex_ml_basic_string_open,
lex_ml_basic_body,
lex_ml_basic_string_close>;
using lex_literal_char = exclude<either<in_range<0x00, 0x08>,
in_range<0x10, 0x19>, character<0x27>>>;
using lex_apostrophe = character<'\''>;
using lex_literal_string = sequence<lex_apostrophe,
repeat<lex_literal_char, unlimited>,
lex_apostrophe>;
// the same reason as above.
using lex_ml_literal_string_delim = repeat<lex_apostrophe, exactly<3>>;
using lex_ml_literal_string_open = lex_ml_literal_string_delim;
using lex_ml_literal_string_close = sequence<
repeat<lex_apostrophe, exactly<3>>,
maybe<lex_apostrophe>, maybe<lex_apostrophe>
>;
using lex_ml_literal_char = exclude<either<in_range<0x00, 0x08>,
in_range<0x10, 0x1F>,
character<0x7F>,
lex_ml_literal_string_delim>>;
using lex_ml_literal_body = repeat<either<lex_ml_literal_char, lex_newline>,
unlimited>;
using lex_ml_literal_string = sequence<lex_ml_literal_string_open,
lex_ml_literal_body,
lex_ml_literal_string_close>;
using lex_string = either<lex_ml_basic_string, lex_basic_string,
lex_ml_literal_string, lex_literal_string>;
// ===========================================================================
using lex_comment_start_symbol = character<'#'>;
using lex_non_eol = either<character<'\t'>, exclude<in_range<0x00, 0x19>>>;
using lex_comment = sequence<lex_comment_start_symbol,
repeat<lex_non_eol, unlimited>>;
using lex_dot_sep = sequence<maybe<lex_ws>, character<'.'>, maybe<lex_ws>>;
using lex_unquoted_key = repeat<either<lex_alpha, lex_digit,
character<'-'>, character<'_'>>,
at_least<1>>;
using lex_quoted_key = either<lex_basic_string, lex_literal_string>;
using lex_simple_key = either<lex_unquoted_key, lex_quoted_key>;
using lex_dotted_key = sequence<lex_simple_key,
repeat<sequence<lex_dot_sep, lex_simple_key>,
at_least<1>
>
>;
using lex_key = either<lex_dotted_key, lex_simple_key>;
using lex_keyval_sep = sequence<maybe<lex_ws>,
character<'='>,
maybe<lex_ws>>;
using lex_std_table_open = character<'['>;
using lex_std_table_close = character<']'>;
using lex_std_table = sequence<lex_std_table_open,
maybe<lex_ws>,
lex_key,
maybe<lex_ws>,
lex_std_table_close>;
using lex_array_table_open = sequence<lex_std_table_open, lex_std_table_open>;
using lex_array_table_close = sequence<lex_std_table_close, lex_std_table_close>;
using lex_array_table = sequence<lex_array_table_open,
maybe<lex_ws>,
lex_key,
maybe<lex_ws>,
lex_array_table_close>;
} // detail
} // toml
#endif // TOML_LEXER_HPP

87
toml/literal.hpp Normal file
View File

@@ -0,0 +1,87 @@
// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_LITERAL_HPP
#define TOML11_LITERAL_HPP
#include "parser.hpp"
namespace toml
{
inline namespace literals
{
inline namespace toml_literals
{
inline ::toml::value operator"" _toml(const char* str, std::size_t len)
{
::toml::detail::location<std::vector<char>>
loc(/* filename = */ std::string("TOML literal encoded in a C++ code"),
/* contents = */ std::vector<char>(str, str + len));
// if there are some comments or empty lines, skip them.
using skip_line = ::toml::detail::repeat<toml::detail::sequence<
::toml::detail::maybe<::toml::detail::lex_ws>,
::toml::detail::maybe<::toml::detail::lex_comment>,
::toml::detail::lex_newline
>, ::toml::detail::at_least<1>>;
skip_line::invoke(loc);
// if there are some whitespaces before a value, skip them.
using skip_ws = ::toml::detail::repeat<
::toml::detail::lex_ws, ::toml::detail::at_least<1>>;
skip_ws::invoke(loc);
// to distinguish arrays and tables, first check it is a table or not.
//
// "[1,2,3]"_toml; // this is an array
// "[table]"_toml; // a table that has an empty table named "table" inside.
// "[[1,2,3]]"_toml; // this is an array of arrays
// "[[table]]"_toml; // this is a table that has an array of tables inside.
//
// "[[1]]"_toml; // this can be both... (currently it becomes a table)
// "1 = [{}]"_toml; // this is a table that has an array of table named 1.
// "[[1,]]"_toml; // this is an array of arrays.
// "[[1],]"_toml; // this also.
const auto the_front = loc.iter();
const bool is_table_key = ::toml::detail::lex_std_table::invoke(loc);
loc.reset(the_front);
const bool is_aots_key = ::toml::detail::lex_array_table::invoke(loc);
loc.reset(the_front);
// If it is neither a table-key or a array-of-table-key, it may be a value.
if(!is_table_key && !is_aots_key)
{
if(auto data = ::toml::detail::parse_value<::toml::value>(loc))
{
return data.unwrap();
}
}
// Note that still it can be a table, because the literal might be something
// like the following.
// ```cpp
// R"( // c++11 raw string literals
// key = "value"
// int = 42
// )"_toml;
// ```
// It is a valid toml file.
// It should be parsed as if we parse a file with this content.
if(auto data = ::toml::detail::parse_toml_file<::toml::value>(loc))
{
return data.unwrap();
}
else // none of them.
{
throw ::toml::syntax_error(data.unwrap_err(),
source_location(std::addressof(loc)));
}
}
} // toml_literals
} // literals
} // toml
#endif//TOML11_LITERAL_HPP

File diff suppressed because it is too large Load Diff

525
toml/region.hpp Normal file
View File

@@ -0,0 +1,525 @@
// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_REGION_HPP
#define TOML11_REGION_HPP
#include <memory>
#include <vector>
#include <algorithm>
#include <initializer_list>
#include <iterator>
#include <iomanip>
#include <cassert>
#include "color.hpp"
namespace toml
{
namespace detail
{
// helper function to avoid std::string(0, 'c') or std::string(iter, iter)
template<typename Iterator>
std::string make_string(Iterator first, Iterator last)
{
if(first == last) {return "";}
return std::string(first, last);
}
inline std::string make_string(std::size_t len, char c)
{
if(len == 0) {return "";}
return std::string(len, c);
}
// region_base is a base class of location and region that are defined below.
// it will be used to generate better error messages.
struct region_base
{
region_base() = default;
virtual ~region_base() = default;
region_base(const region_base&) = default;
region_base(region_base&& ) = default;
region_base& operator=(const region_base&) = default;
region_base& operator=(region_base&& ) = default;
virtual bool is_ok() const noexcept {return false;}
virtual char front() const noexcept {return '\0';}
virtual std::string str() const {return std::string("unknown region");}
virtual std::string name() const {return std::string("unknown file");}
virtual std::string line() const {return std::string("unknown line");}
virtual std::string line_num() const {return std::string("?");}
// length of the region
virtual std::size_t size() const noexcept {return 0;}
// number of characters in the line before the region
virtual std::size_t before() const noexcept {return 0;}
// number of characters in the line after the region
virtual std::size_t after() const noexcept {return 0;}
virtual std::vector<std::string> comments() const {return {};}
// ```toml
// # comment_before
// key = "value" # comment_inline
// ```
};
// location represents a position in a container, which contains a file content.
// it can be considered as a region that contains only one character.
//
// it contains pointer to the file content and iterator that points the current
// location.
template<typename Container>
struct location final : public region_base
{
using const_iterator = typename Container::const_iterator;
using difference_type = typename const_iterator::difference_type;
using source_ptr = std::shared_ptr<const Container>;
static_assert(std::is_same<char, typename Container::value_type>::value,"");
static_assert(std::is_same<std::random_access_iterator_tag,
typename std::iterator_traits<const_iterator>::iterator_category>::value,
"container should be randomly accessible");
location(std::string name, Container cont)
: source_(std::make_shared<Container>(std::move(cont))), line_number_(1),
source_name_(std::move(name)), iter_(source_->cbegin())
{}
location(const location&) = default;
location(location&&) = default;
location& operator=(const location&) = default;
location& operator=(location&&) = default;
~location() = default;
bool is_ok() const noexcept override {return static_cast<bool>(source_);}
char front() const noexcept override {return *iter_;}
// this const prohibits codes like `++(loc.iter())`.
const const_iterator iter() const noexcept {return iter_;}
const_iterator begin() const noexcept {return source_->cbegin();}
const_iterator end() const noexcept {return source_->cend();}
// XXX `location::line_num()` used to be implemented using `std::count` to
// count a number of '\n'. But with a long toml file (typically, 10k lines),
// it becomes intolerably slow because each time it generates error messages,
// it counts '\n' from thousands of characters. To workaround it, I decided
// to introduce `location::line_number_` member variable and synchronize it
// to the location changes the point to look. So an overload of `iter()`
// which returns mutable reference is removed and `advance()`, `retrace()`
// and `reset()` is added.
void advance(difference_type n = 1) noexcept
{
this->line_number_ += static_cast<std::size_t>(
std::count(this->iter_, std::next(this->iter_, n), '\n'));
this->iter_ += n;
return;
}
void retrace(difference_type n = 1) noexcept
{
this->line_number_ -= static_cast<std::size_t>(
std::count(std::prev(this->iter_, n), this->iter_, '\n'));
this->iter_ -= n;
return;
}
void reset(const_iterator rollback) noexcept
{
// since c++11, std::distance works in both ways for random-access
// iterators and returns a negative value if `first > last`.
if(0 <= std::distance(rollback, this->iter_)) // rollback < iter
{
this->line_number_ -= static_cast<std::size_t>(
std::count(rollback, this->iter_, '\n'));
}
else // iter < rollback [[unlikely]]
{
this->line_number_ += static_cast<std::size_t>(
std::count(this->iter_, rollback, '\n'));
}
this->iter_ = rollback;
return;
}
std::string str() const override {return make_string(1, *this->iter());}
std::string name() const override {return source_name_;}
std::string line_num() const override
{
return std::to_string(this->line_number_);
}
std::string line() const override
{
return make_string(this->line_begin(), this->line_end());
}
const_iterator line_begin() const noexcept
{
using reverse_iterator = std::reverse_iterator<const_iterator>;
return std::find(reverse_iterator(this->iter()),
reverse_iterator(this->begin()), '\n').base();
}
const_iterator line_end() const noexcept
{
return std::find(this->iter(), this->end(), '\n');
}
// location is always points a character. so the size is 1.
std::size_t size() const noexcept override
{
return 1u;
}
std::size_t before() const noexcept override
{
const auto sz = std::distance(this->line_begin(), this->iter());
assert(sz >= 0);
return static_cast<std::size_t>(sz);
}
std::size_t after() const noexcept override
{
const auto sz = std::distance(this->iter(), this->line_end());
assert(sz >= 0);
return static_cast<std::size_t>(sz);
}
source_ptr const& source() const& noexcept {return source_;}
source_ptr&& source() && noexcept {return std::move(source_);}
private:
source_ptr source_;
std::size_t line_number_;
std::string source_name_;
const_iterator iter_;
};
// region represents a range in a container, which contains a file content.
//
// it contains pointer to the file content and iterator that points the first
// and last location.
template<typename Container>
struct region final : public region_base
{
using const_iterator = typename Container::const_iterator;
using source_ptr = std::shared_ptr<const Container>;
static_assert(std::is_same<char, typename Container::value_type>::value,"");
static_assert(std::is_same<std::random_access_iterator_tag,
typename std::iterator_traits<const_iterator>::iterator_category>::value,
"container should be randomly accessible");
// delete default constructor. source_ never be null.
region() = delete;
region(const location<Container>& loc)
: source_(loc.source()), source_name_(loc.name()),
first_(loc.iter()), last_(loc.iter())
{}
region(location<Container>&& loc)
: source_(loc.source()), source_name_(loc.name()),
first_(loc.iter()), last_(loc.iter())
{}
region(const location<Container>& loc, const_iterator f, const_iterator l)
: source_(loc.source()), source_name_(loc.name()), first_(f), last_(l)
{}
region(location<Container>&& loc, const_iterator f, const_iterator l)
: source_(loc.source()), source_name_(loc.name()), first_(f), last_(l)
{}
region(const region&) = default;
region(region&&) = default;
region& operator=(const region&) = default;
region& operator=(region&&) = default;
~region() = default;
region& operator+=(const region& other)
{
// different regions cannot be concatenated
assert(this->begin() == other.begin() && this->end() == other.end() &&
this->last_ == other.first_);
this->last_ = other.last_;
return *this;
}
bool is_ok() const noexcept override {return static_cast<bool>(source_);}
char front() const noexcept override {return *first_;}
std::string str() const override {return make_string(first_, last_);}
std::string line() const override
{
if(this->contain_newline())
{
return make_string(this->line_begin(),
std::find(this->line_begin(), this->last(), '\n'));
}
return make_string(this->line_begin(), this->line_end());
}
std::string line_num() const override
{
return std::to_string(1 + std::count(this->begin(), this->first(), '\n'));
}
std::size_t size() const noexcept override
{
const auto sz = std::distance(first_, last_);
assert(sz >= 0);
return static_cast<std::size_t>(sz);
}
std::size_t before() const noexcept override
{
const auto sz = std::distance(this->line_begin(), this->first());
assert(sz >= 0);
return static_cast<std::size_t>(sz);
}
std::size_t after() const noexcept override
{
const auto sz = std::distance(this->last(), this->line_end());
assert(sz >= 0);
return static_cast<std::size_t>(sz);
}
bool contain_newline() const noexcept
{
return std::find(this->first(), this->last(), '\n') != this->last();
}
const_iterator line_begin() const noexcept
{
using reverse_iterator = std::reverse_iterator<const_iterator>;
return std::find(reverse_iterator(this->first()),
reverse_iterator(this->begin()), '\n').base();
}
const_iterator line_end() const noexcept
{
return std::find(this->last(), this->end(), '\n');
}
const_iterator begin() const noexcept {return source_->cbegin();}
const_iterator end() const noexcept {return source_->cend();}
const_iterator first() const noexcept {return first_;}
const_iterator last() const noexcept {return last_;}
source_ptr const& source() const& noexcept {return source_;}
source_ptr&& source() && noexcept {return std::move(source_);}
std::string name() const override {return source_name_;}
std::vector<std::string> comments() const override
{
// assuming the current region (`*this`) points a value.
// ```toml
// a = "value"
// ^^^^^^^- this region
// ```
using rev_iter = std::reverse_iterator<const_iterator>;
std::vector<std::string> com{};
{
// find comments just before the current region.
// ```toml
// # this should be collected.
// # this also.
// a = value # not this.
// ```
// # this is a comment for `a`, not array elements.
// a = [1, 2, 3, 4, 5]
if(this->first() == std::find_if(this->line_begin(), this->first(),
[](const char c) noexcept -> bool {return c == '[' || c == '{';}))
{
auto iter = this->line_begin(); // points the first character
while(iter != this->begin())
{
iter = std::prev(iter);
// range [line_start, iter) represents the previous line
const auto line_start = std::find(
rev_iter(iter), rev_iter(this->begin()), '\n').base();
const auto comment_found = std::find(line_start, iter, '#');
if(comment_found == iter)
{
break; // comment not found.
}
// exclude the following case.
// > a = "foo" # comment // <-- this is not a comment for b but a.
// > b = "current value"
if(std::all_of(line_start, comment_found,
[](const char c) noexcept -> bool {
return c == ' ' || c == '\t';
}))
{
// unwrap the first '#' by std::next.
auto str = make_string(std::next(comment_found), iter);
if(str.back() == '\r') {str.pop_back();}
com.push_back(std::move(str));
}
else
{
break;
}
iter = line_start;
}
}
}
if(com.size() > 1)
{
std::reverse(com.begin(), com.end());
}
{
// find comments just after the current region.
// ```toml
// # not this.
// a = value # this one.
// a = [ # not this (technically difficult)
//
// ] # and this.
// ```
// The reason why it's difficult is that it requires parsing in the
// following case.
// ```toml
// a = [ 10 # this comment is for `10`. not for `a` but `a[0]`.
// # ...
// ] # this is apparently a comment for a.
//
// b = [
// 3.14 ] # there is no way to add a comment to `3.14` currently.
//
// c = [
// 3.14 # do this if you need a comment here.
// ]
// ```
const auto comment_found =
std::find(this->last(), this->line_end(), '#');
if(comment_found != this->line_end()) // '#' found
{
// table = {key = "value"} # what is this for?
// the above comment is not for "value", but {key="value"}.
if(comment_found == std::find_if(this->last(), comment_found,
[](const char c) noexcept -> bool {
return !(c == ' ' || c == '\t' || c == ',');
}))
{
// unwrap the first '#' by std::next.
auto str = make_string(std::next(comment_found), this->line_end());
if(str.back() == '\r') {str.pop_back();}
com.push_back(std::move(str));
}
}
}
return com;
}
private:
source_ptr source_;
std::string source_name_;
const_iterator first_, last_;
};
// to show a better error message.
inline std::string format_underline(const std::string& message,
const std::vector<std::pair<region_base const*, std::string>>& reg_com,
const std::vector<std::string>& helps = {},
const bool colorize = TOML11_ERROR_MESSAGE_COLORIZED)
{
assert(!reg_com.empty());
const auto line_num_width = static_cast<int>(std::max_element(
reg_com.begin(), reg_com.end(),
[](std::pair<region_base const*, std::string> const& lhs,
std::pair<region_base const*, std::string> const& rhs)
{
return lhs.first->line_num().size() < rhs.first->line_num().size();
}
)->first->line_num().size());
std::ostringstream retval;
if(colorize)
{
retval << color::colorize; // turn on ANSI color
}
// XXX
// Here, before `colorize` support, it does not output `[error]` prefix
// automatically. So some user may output it manually and this change may
// duplicate the prefix. To avoid it, check the first 7 characters and
// if it is "[error]", it removes that part from the message shown.
if(message.size() > 7 && message.substr(0, 7) == "[error]")
{
retval << color::bold << color::red << "[error]" << color::reset
<< color::bold << message.substr(7) << color::reset << '\n';
}
else
{
retval << color::bold << color::red << "[error] " << color::reset
<< color::bold << message << color::reset << '\n';
}
for(auto iter = reg_com.begin(); iter != reg_com.end(); ++iter)
{
// if the filenames are the same, print "..."
if(iter != reg_com.begin() &&
std::prev(iter)->first->name() == iter->first->name())
{
retval << color::bold << color::blue << "\n ...\n" << color::reset;
}
else // if filename differs, print " --> filename.toml"
{
if(iter != reg_com.begin()) {retval << '\n';}
retval << color::bold << color::blue << " --> " << color::reset
<< iter->first->name() << '\n';
// add one almost-empty line for readability
retval << make_string(static_cast<std::size_t>(line_num_width + 1), ' ')
<< color::bold << color::blue << " | " << color::reset << '\n';
}
const region_base* const reg = iter->first;
const std::string& comment = iter->second;
retval << ' ' << color::bold << color::blue << std::setw(line_num_width)
<< std::right << reg->line_num() << " | " << color::reset
<< reg->line() << '\n';
retval << make_string(static_cast<std::size_t>(line_num_width + 1), ' ')
<< color::bold << color::blue << " | " << color::reset
<< make_string(reg->before(), ' ');
if(reg->size() == 1)
{
// invalid
// ^------
retval << color::bold << color::red
<< '^' << make_string(reg->after(), '-') << color::reset;
}
else
{
// invalid
// ~~~~~~~
const auto underline_len = (std::min)(reg->size(), reg->line().size());
retval << color::bold << color::red
<< make_string(underline_len, '~') << color::reset;
}
retval << ' ';
retval << comment;
}
if(!helps.empty())
{
retval << '\n';
retval << make_string(static_cast<std::size_t>(line_num_width + 1), ' ');
retval << color::bold << color::blue << " | " << color::reset;
for(const auto& help : helps)
{
retval << color::bold << "\nHint: " << color::reset;
retval << help;
}
}
return retval.str();
}
} // detail
} // toml
#endif// TOML11_REGION_H

717
toml/result.hpp Normal file
View File

@@ -0,0 +1,717 @@
// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_RESULT_HPP
#define TOML11_RESULT_HPP
#include "traits.hpp"
#include <type_traits>
#include <stdexcept>
#include <utility>
#include <new>
#include <string>
#include <sstream>
#include <cassert>
namespace toml
{
template<typename T>
struct success
{
using value_type = T;
value_type value;
explicit success(const value_type& v)
noexcept(std::is_nothrow_copy_constructible<value_type>::value)
: value(v)
{}
explicit success(value_type&& v)
noexcept(std::is_nothrow_move_constructible<value_type>::value)
: value(std::move(v))
{}
template<typename U>
explicit success(U&& v): value(std::forward<U>(v)) {}
template<typename U>
explicit success(const success<U>& v): value(v.value) {}
template<typename U>
explicit success(success<U>&& v): value(std::move(v.value)) {}
~success() = default;
success(const success&) = default;
success(success&&) = default;
success& operator=(const success&) = default;
success& operator=(success&&) = default;
};
template<typename T>
struct failure
{
using value_type = T;
value_type value;
explicit failure(const value_type& v)
noexcept(std::is_nothrow_copy_constructible<value_type>::value)
: value(v)
{}
explicit failure(value_type&& v)
noexcept(std::is_nothrow_move_constructible<value_type>::value)
: value(std::move(v))
{}
template<typename U>
explicit failure(U&& v): value(std::forward<U>(v)) {}
template<typename U>
explicit failure(const failure<U>& v): value(v.value) {}
template<typename U>
explicit failure(failure<U>&& v): value(std::move(v.value)) {}
~failure() = default;
failure(const failure&) = default;
failure(failure&&) = default;
failure& operator=(const failure&) = default;
failure& operator=(failure&&) = default;
};
template<typename T>
success<typename std::remove_cv<typename std::remove_reference<T>::type>::type>
ok(T&& v)
{
return success<
typename std::remove_cv<typename std::remove_reference<T>::type>::type
>(std::forward<T>(v));
}
template<typename T>
failure<typename std::remove_cv<typename std::remove_reference<T>::type>::type>
err(T&& v)
{
return failure<
typename std::remove_cv<typename std::remove_reference<T>::type>::type
>(std::forward<T>(v));
}
inline success<std::string> ok(const char* literal)
{
return success<std::string>(std::string(literal));
}
inline failure<std::string> err(const char* literal)
{
return failure<std::string>(std::string(literal));
}
template<typename T, typename E>
struct result
{
using value_type = T;
using error_type = E;
using success_type = success<value_type>;
using failure_type = failure<error_type>;
result(const success_type& s): is_ok_(true)
{
auto tmp = ::new(std::addressof(this->succ)) success_type(s);
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
result(const failure_type& f): is_ok_(false)
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(f);
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
result(success_type&& s): is_ok_(true)
{
auto tmp = ::new(std::addressof(this->succ)) success_type(std::move(s));
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
result(failure_type&& f): is_ok_(false)
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(std::move(f));
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
template<typename U>
result(const success<U>& s): is_ok_(true)
{
auto tmp = ::new(std::addressof(this->succ)) success_type(s.value);
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
template<typename U>
result(const failure<U>& f): is_ok_(false)
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(f.value);
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
template<typename U>
result(success<U>&& s): is_ok_(true)
{
auto tmp = ::new(std::addressof(this->succ)) success_type(std::move(s.value));
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
template<typename U>
result(failure<U>&& f): is_ok_(false)
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(std::move(f.value));
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
result& operator=(const success_type& s)
{
this->cleanup();
this->is_ok_ = true;
auto tmp = ::new(std::addressof(this->succ)) success_type(s);
assert(tmp == std::addressof(this->succ));
(void)tmp;
return *this;
}
result& operator=(const failure_type& f)
{
this->cleanup();
this->is_ok_ = false;
auto tmp = ::new(std::addressof(this->fail)) failure_type(f);
assert(tmp == std::addressof(this->fail));
(void)tmp;
return *this;
}
result& operator=(success_type&& s)
{
this->cleanup();
this->is_ok_ = true;
auto tmp = ::new(std::addressof(this->succ)) success_type(std::move(s));
assert(tmp == std::addressof(this->succ));
(void)tmp;
return *this;
}
result& operator=(failure_type&& f)
{
this->cleanup();
this->is_ok_ = false;
auto tmp = ::new(std::addressof(this->fail)) failure_type(std::move(f));
assert(tmp == std::addressof(this->fail));
(void)tmp;
return *this;
}
template<typename U>
result& operator=(const success<U>& s)
{
this->cleanup();
this->is_ok_ = true;
auto tmp = ::new(std::addressof(this->succ)) success_type(s.value);
assert(tmp == std::addressof(this->succ));
(void)tmp;
return *this;
}
template<typename U>
result& operator=(const failure<U>& f)
{
this->cleanup();
this->is_ok_ = false;
auto tmp = ::new(std::addressof(this->fail)) failure_type(f.value);
assert(tmp == std::addressof(this->fail));
(void)tmp;
return *this;
}
template<typename U>
result& operator=(success<U>&& s)
{
this->cleanup();
this->is_ok_ = true;
auto tmp = ::new(std::addressof(this->succ)) success_type(std::move(s.value));
assert(tmp == std::addressof(this->succ));
(void)tmp;
return *this;
}
template<typename U>
result& operator=(failure<U>&& f)
{
this->cleanup();
this->is_ok_ = false;
auto tmp = ::new(std::addressof(this->fail)) failure_type(std::move(f.value));
assert(tmp == std::addressof(this->fail));
(void)tmp;
return *this;
}
~result() noexcept {this->cleanup();}
result(const result& other): is_ok_(other.is_ok())
{
if(other.is_ok())
{
auto tmp = ::new(std::addressof(this->succ)) success_type(other.as_ok());
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
else
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(other.as_err());
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
}
result(result&& other): is_ok_(other.is_ok())
{
if(other.is_ok())
{
auto tmp = ::new(std::addressof(this->succ)) success_type(std::move(other.as_ok()));
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
else
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(std::move(other.as_err()));
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
}
template<typename U, typename F>
result(const result<U, F>& other): is_ok_(other.is_ok())
{
if(other.is_ok())
{
auto tmp = ::new(std::addressof(this->succ)) success_type(other.as_ok());
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
else
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(other.as_err());
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
}
template<typename U, typename F>
result(result<U, F>&& other): is_ok_(other.is_ok())
{
if(other.is_ok())
{
auto tmp = ::new(std::addressof(this->succ)) success_type(std::move(other.as_ok()));
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
else
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(std::move(other.as_err()));
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
}
result& operator=(const result& other)
{
this->cleanup();
if(other.is_ok())
{
auto tmp = ::new(std::addressof(this->succ)) success_type(other.as_ok());
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
else
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(other.as_err());
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
is_ok_ = other.is_ok();
return *this;
}
result& operator=(result&& other)
{
this->cleanup();
if(other.is_ok())
{
auto tmp = ::new(std::addressof(this->succ)) success_type(std::move(other.as_ok()));
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
else
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(std::move(other.as_err()));
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
is_ok_ = other.is_ok();
return *this;
}
template<typename U, typename F>
result& operator=(const result<U, F>& other)
{
this->cleanup();
if(other.is_ok())
{
auto tmp = ::new(std::addressof(this->succ)) success_type(other.as_ok());
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
else
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(other.as_err());
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
is_ok_ = other.is_ok();
return *this;
}
template<typename U, typename F>
result& operator=(result<U, F>&& other)
{
this->cleanup();
if(other.is_ok())
{
auto tmp = ::new(std::addressof(this->succ)) success_type(std::move(other.as_ok()));
assert(tmp == std::addressof(this->succ));
(void)tmp;
}
else
{
auto tmp = ::new(std::addressof(this->fail)) failure_type(std::move(other.as_err()));
assert(tmp == std::addressof(this->fail));
(void)tmp;
}
is_ok_ = other.is_ok();
return *this;
}
bool is_ok() const noexcept {return is_ok_;}
bool is_err() const noexcept {return !is_ok_;}
operator bool() const noexcept {return is_ok_;}
value_type& unwrap() &
{
if(is_err())
{
throw std::runtime_error("toml::result: bad unwrap: " +
format_error(this->as_err()));
}
return this->succ.value;
}
value_type const& unwrap() const&
{
if(is_err())
{
throw std::runtime_error("toml::result: bad unwrap: " +
format_error(this->as_err()));
}
return this->succ.value;
}
value_type&& unwrap() &&
{
if(is_err())
{
throw std::runtime_error("toml::result: bad unwrap: " +
format_error(this->as_err()));
}
return std::move(this->succ.value);
}
value_type& unwrap_or(value_type& opt) &
{
if(is_err()) {return opt;}
return this->succ.value;
}
value_type const& unwrap_or(value_type const& opt) const&
{
if(is_err()) {return opt;}
return this->succ.value;
}
value_type unwrap_or(value_type opt) &&
{
if(is_err()) {return opt;}
return this->succ.value;
}
error_type& unwrap_err() &
{
if(is_ok()) {throw std::runtime_error("toml::result: bad unwrap_err");}
return this->fail.value;
}
error_type const& unwrap_err() const&
{
if(is_ok()) {throw std::runtime_error("toml::result: bad unwrap_err");}
return this->fail.value;
}
error_type&& unwrap_err() &&
{
if(is_ok()) {throw std::runtime_error("toml::result: bad unwrap_err");}
return std::move(this->fail.value);
}
value_type& as_ok() & noexcept {return this->succ.value;}
value_type const& as_ok() const& noexcept {return this->succ.value;}
value_type&& as_ok() && noexcept {return std::move(this->succ.value);}
error_type& as_err() & noexcept {return this->fail.value;}
error_type const& as_err() const& noexcept {return this->fail.value;}
error_type&& as_err() && noexcept {return std::move(this->fail.value);}
// prerequisities
// F: T -> U
// retval: result<U, E>
template<typename F>
result<detail::return_type_of_t<F, value_type&>, error_type>
map(F&& f) &
{
if(this->is_ok()){return ok(f(this->as_ok()));}
return err(this->as_err());
}
template<typename F>
result<detail::return_type_of_t<F, value_type const&>, error_type>
map(F&& f) const&
{
if(this->is_ok()){return ok(f(this->as_ok()));}
return err(this->as_err());
}
template<typename F>
result<detail::return_type_of_t<F, value_type &&>, error_type>
map(F&& f) &&
{
if(this->is_ok()){return ok(f(std::move(this->as_ok())));}
return err(std::move(this->as_err()));
}
// prerequisities
// F: E -> F
// retval: result<T, F>
template<typename F>
result<value_type, detail::return_type_of_t<F, error_type&>>
map_err(F&& f) &
{
if(this->is_err()){return err(f(this->as_err()));}
return ok(this->as_ok());
}
template<typename F>
result<value_type, detail::return_type_of_t<F, error_type const&>>
map_err(F&& f) const&
{
if(this->is_err()){return err(f(this->as_err()));}
return ok(this->as_ok());
}
template<typename F>
result<value_type, detail::return_type_of_t<F, error_type&&>>
map_err(F&& f) &&
{
if(this->is_err()){return err(f(std::move(this->as_err())));}
return ok(std::move(this->as_ok()));
}
// prerequisities
// F: T -> U
// retval: U
template<typename F, typename U>
detail::return_type_of_t<F, value_type&>
map_or_else(F&& f, U&& opt) &
{
if(this->is_err()){return std::forward<U>(opt);}
return f(this->as_ok());
}
template<typename F, typename U>
detail::return_type_of_t<F, value_type const&>
map_or_else(F&& f, U&& opt) const&
{
if(this->is_err()){return std::forward<U>(opt);}
return f(this->as_ok());
}
template<typename F, typename U>
detail::return_type_of_t<F, value_type&&>
map_or_else(F&& f, U&& opt) &&
{
if(this->is_err()){return std::forward<U>(opt);}
return f(std::move(this->as_ok()));
}
// prerequisities
// F: E -> U
// retval: U
template<typename F, typename U>
detail::return_type_of_t<F, error_type&>
map_err_or_else(F&& f, U&& opt) &
{
if(this->is_ok()){return std::forward<U>(opt);}
return f(this->as_err());
}
template<typename F, typename U>
detail::return_type_of_t<F, error_type const&>
map_err_or_else(F&& f, U&& opt) const&
{
if(this->is_ok()){return std::forward<U>(opt);}
return f(this->as_err());
}
template<typename F, typename U>
detail::return_type_of_t<F, error_type&&>
map_err_or_else(F&& f, U&& opt) &&
{
if(this->is_ok()){return std::forward<U>(opt);}
return f(std::move(this->as_err()));
}
// prerequisities:
// F: func T -> U
// toml::err(error_type) should be convertible to U.
// normally, type U is another result<S, F> and E is convertible to F
template<typename F>
detail::return_type_of_t<F, value_type&>
and_then(F&& f) &
{
if(this->is_ok()){return f(this->as_ok());}
return err(this->as_err());
}
template<typename F>
detail::return_type_of_t<F, value_type const&>
and_then(F&& f) const&
{
if(this->is_ok()){return f(this->as_ok());}
return err(this->as_err());
}
template<typename F>
detail::return_type_of_t<F, value_type&&>
and_then(F&& f) &&
{
if(this->is_ok()){return f(std::move(this->as_ok()));}
return err(std::move(this->as_err()));
}
// prerequisities:
// F: func E -> U
// toml::ok(value_type) should be convertible to U.
// normally, type U is another result<S, F> and T is convertible to S
template<typename F>
detail::return_type_of_t<F, error_type&>
or_else(F&& f) &
{
if(this->is_err()){return f(this->as_err());}
return ok(this->as_ok());
}
template<typename F>
detail::return_type_of_t<F, error_type const&>
or_else(F&& f) const&
{
if(this->is_err()){return f(this->as_err());}
return ok(this->as_ok());
}
template<typename F>
detail::return_type_of_t<F, error_type&&>
or_else(F&& f) &&
{
if(this->is_err()){return f(std::move(this->as_err()));}
return ok(std::move(this->as_ok()));
}
// if *this is error, returns *this. otherwise, returns other.
result and_other(const result& other) const&
{
return this->is_err() ? *this : other;
}
result and_other(result&& other) &&
{
return this->is_err() ? std::move(*this) : std::move(other);
}
// if *this is okay, returns *this. otherwise, returns other.
result or_other(const result& other) const&
{
return this->is_ok() ? *this : other;
}
result or_other(result&& other) &&
{
return this->is_ok() ? std::move(*this) : std::move(other);
}
void swap(result<T, E>& other)
{
result<T, E> tmp(std::move(*this));
*this = std::move(other);
other = std::move(tmp);
return ;
}
private:
static std::string format_error(std::exception const& excpt)
{
return std::string(excpt.what());
}
template<typename U, typename std::enable_if<!std::is_base_of<
std::exception, U>::value, std::nullptr_t>::type = nullptr>
static std::string format_error(U const& others)
{
std::ostringstream oss; oss << others;
return oss.str();
}
void cleanup() noexcept
{
if(this->is_ok_) {this->succ.~success_type();}
else {this->fail.~failure_type();}
return;
}
private:
bool is_ok_;
union
{
success_type succ;
failure_type fail;
};
};
template<typename T, typename E>
void swap(result<T, E>& lhs, result<T, E>& rhs)
{
lhs.swap(rhs);
return;
}
// this might be confusing because it eagerly evaluated, while in the other
// cases operator && and || are short-circuited.
//
// template<typename T, typename E>
// inline result<T, E>
// operator&&(const result<T, E>& lhs, const result<T, E>& rhs) noexcept
// {
// return lhs.is_ok() ? rhs : lhs;
// }
//
// template<typename T, typename E>
// inline result<T, E>
// operator||(const result<T, E>& lhs, const result<T, E>& rhs) noexcept
// {
// return lhs.is_ok() ? lhs : rhs;
// }
// ----------------------------------------------------------------------------
// re-use result<T, E> as a optional<T> with none_t
namespace detail
{
struct none_t {};
inline bool operator==(const none_t&, const none_t&) noexcept {return true;}
inline bool operator!=(const none_t&, const none_t&) noexcept {return false;}
inline bool operator< (const none_t&, const none_t&) noexcept {return false;}
inline bool operator<=(const none_t&, const none_t&) noexcept {return true;}
inline bool operator> (const none_t&, const none_t&) noexcept {return false;}
inline bool operator>=(const none_t&, const none_t&) noexcept {return true;}
template<typename charT, typename traitsT>
std::basic_ostream<charT, traitsT>&
operator<<(std::basic_ostream<charT, traitsT>& os, const none_t&)
{
os << "none";
return os;
}
inline failure<none_t> none() noexcept {return failure<none_t>{none_t{}};}
} // detail
} // toml11
#endif// TOML11_RESULT_H

788
toml/serializer.hpp Normal file
View File

@@ -0,0 +1,788 @@
// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_SERIALIZER_HPP
#define TOML11_SERIALIZER_HPP
#include <cstdio>
#include <limits>
#include "lexer.hpp"
#include "value.hpp"
namespace toml
{
// This function serialize a key. It checks a string is a bare key and
// escapes special characters if the string is not compatible to a bare key.
// ```cpp
// std::string k("non.bare.key"); // the key itself includes `.`s.
// std::string formatted = toml::format_key(k);
// assert(formatted == "\"non.bare.key\"");
// ```
//
// This function is exposed to make it easy to write a user-defined serializer.
// Since toml restricts characters available in a bare key, generally a string
// should be escaped. But checking whether a string needs to be surrounded by
// a `"` and escaping some special character is boring.
template<typename charT, typename traits, typename Alloc>
std::basic_string<charT, traits, Alloc>
format_key(const std::basic_string<charT, traits, Alloc>& key)
{
// check the key can be a bare (unquoted) key
detail::location<toml::key> loc(key, key);
detail::lex_unquoted_key::invoke(loc);
if(loc.iter() == loc.end())
{
return key; // all the tokens are consumed. the key is unquoted-key.
}
//if it includes special characters, then format it in a "quoted" key.
std::basic_string<charT, traits, Alloc> serialized("\"");
for(const char c : key)
{
switch(c)
{
case '\\': {serialized += "\\\\"; break;}
case '\"': {serialized += "\\\""; break;}
case '\b': {serialized += "\\b"; break;}
case '\t': {serialized += "\\t"; break;}
case '\f': {serialized += "\\f"; break;}
case '\n': {serialized += "\\n"; break;}
case '\r': {serialized += "\\r"; break;}
default : {serialized += c; break;}
}
}
serialized += "\"";
return serialized;
}
template<typename charT, typename traits, typename Alloc>
std::basic_string<charT, traits, Alloc>
format_keys(const std::vector<std::basic_string<charT, traits, Alloc>>& keys)
{
std::basic_string<charT, traits, Alloc> serialized;
if(keys.empty()) {return serialized;}
for(const auto& ky : keys)
{
serialized += format_key(ky);
serialized += charT('.');
}
serialized.pop_back(); // remove the last dot '.'
return serialized;
}
template<typename Value>
struct serializer
{
static_assert(detail::is_basic_value<Value>::value,
"toml::serializer is for toml::value and its variants, "
"toml::basic_value<...>.");
using value_type = Value;
using key_type = typename value_type::key_type ;
using comment_type = typename value_type::comment_type ;
using boolean_type = typename value_type::boolean_type ;
using integer_type = typename value_type::integer_type ;
using floating_type = typename value_type::floating_type ;
using string_type = typename value_type::string_type ;
using local_time_type = typename value_type::local_time_type ;
using local_date_type = typename value_type::local_date_type ;
using local_datetime_type = typename value_type::local_datetime_type ;
using offset_datetime_type = typename value_type::offset_datetime_type;
using array_type = typename value_type::array_type ;
using table_type = typename value_type::table_type ;
serializer(const std::size_t w = 80u,
const int float_prec = std::numeric_limits<toml::floating>::max_digits10,
const bool can_be_inlined = false,
const bool no_comment = false,
std::vector<toml::key> ks = {})
: can_be_inlined_(can_be_inlined), no_comment_(no_comment),
float_prec_(float_prec), width_(w), keys_(std::move(ks))
{}
~serializer() = default;
std::string operator()(const boolean_type& b) const
{
return b ? "true" : "false";
}
std::string operator()(const integer_type i) const
{
return std::to_string(i);
}
std::string operator()(const floating_type f) const
{
const auto fmt = "%.*g";
const auto bsz = std::snprintf(nullptr, 0, fmt, this->float_prec_, f);
// +1 for null character(\0)
std::vector<char> buf(static_cast<std::size_t>(bsz + 1), '\0');
std::snprintf(buf.data(), buf.size(), fmt, this->float_prec_, f);
std::string token(buf.begin(), std::prev(buf.end()));
if(token.back() == '.') // 1. => 1.0
{
token += '0';
}
const auto e = std::find_if(
token.cbegin(), token.cend(), [](const char c) noexcept -> bool {
return c == 'e' || c == 'E';
});
const auto has_exponent = (token.cend() != e);
const auto has_fraction = (token.cend() != std::find(
token.cbegin(), token.cend(), '.'));
if(!has_exponent && !has_fraction)
{
// the resulting value does not have any float specific part!
token += ".0";
}
return token;
}
std::string operator()(const string_type& s) const
{
if(s.kind == string_t::basic)
{
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend() ||
std::find(s.str.cbegin(), s.str.cend(), '\"') != s.str.cend())
{
// if linefeed or double-quote is contained,
// make it multiline basic string.
const auto escaped = this->escape_ml_basic_string(s.str);
std::string open("\"\"\"");
std::string close("\"\"\"");
if(escaped.find('\n') != std::string::npos ||
this->width_ < escaped.size() + 6)
{
// if the string body contains newline or is enough long,
// add newlines after and before delimiters.
open += "\n";
close = std::string("\\\n") + close;
}
return open + escaped + close;
}
// no linefeed. try to make it oneline-string.
std::string oneline = this->escape_basic_string(s.str);
if(oneline.size() + 2 < width_ || width_ < 2)
{
const std::string quote("\"");
return quote + oneline + quote;
}
// the line is too long compared to the specified width.
// split it into multiple lines.
std::string token("\"\"\"\n");
while(!oneline.empty())
{
if(oneline.size() < width_)
{
token += oneline;
oneline.clear();
}
else if(oneline.at(width_-2) == '\\')
{
token += oneline.substr(0, width_-2);
token += "\\\n";
oneline.erase(0, width_-2);
}
else
{
token += oneline.substr(0, width_-1);
token += "\\\n";
oneline.erase(0, width_-1);
}
}
return token + std::string("\\\n\"\"\"");
}
else // the string `s` is literal-string.
{
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend() ||
std::find(s.str.cbegin(), s.str.cend(), '\'') != s.str.cend() )
{
std::string open("'''");
if(this->width_ + 6 < s.str.size())
{
open += '\n'; // the first newline is ignored by TOML spec
}
const std::string close("'''");
return open + s.str + close;
}
else
{
const std::string quote("'");
return quote + s.str + quote;
}
}
}
std::string operator()(const local_date_type& d) const
{
std::ostringstream oss;
oss << d;
return oss.str();
}
std::string operator()(const local_time_type& t) const
{
std::ostringstream oss;
oss << t;
return oss.str();
}
std::string operator()(const local_datetime_type& dt) const
{
std::ostringstream oss;
oss << dt;
return oss.str();
}
std::string operator()(const offset_datetime_type& odt) const
{
std::ostringstream oss;
oss << odt;
return oss.str();
}
std::string operator()(const array_type& v) const
{
if(!v.empty() && v.front().is_table())// v is an array of tables
{
// if it's not inlined, we need to add `[[table.key]]`.
// but if it can be inlined,
// ```
// table.key = [
// {...},
// # comment
// {...},
// ]
// ```
if(this->can_be_inlined_)
{
std::string token;
if(!keys_.empty())
{
token += format_key(keys_.back());
token += " = ";
}
bool failed = false;
token += "[\n";
for(const auto& item : v)
{
// if an element of the table has a comment, the table
// cannot be inlined.
if(this->has_comment_inside(item.as_table()))
{
failed = true;
break;
}
if(!no_comment_)
{
for(const auto& c : item.comments())
{
token += '#';
token += c;
token += '\n';
}
}
const auto t = this->make_inline_table(item.as_table());
if(t.size() + 1 > width_ || // +1 for the last comma {...},
std::find(t.cbegin(), t.cend(), '\n') != t.cend())
{
failed = true;
break;
}
token += t;
token += ",\n";
}
if(!failed)
{
token += "]\n";
return token;
}
// if failed, serialize them as [[array.of.tables]].
}
std::string token;
for(const auto& item : v)
{
if(!no_comment_)
{
for(const auto& c : item.comments())
{
token += '#';
token += c;
token += '\n';
}
}
token += "[[";
token += format_keys(keys_);
token += "]]\n";
token += this->make_multiline_table(item.as_table());
}
return token;
}
if(v.empty())
{
return std::string("[]");
}
// not an array of tables. normal array.
// first, try to make it inline if none of the elements have a comment.
if(!this->has_comment_inside(v))
{
const auto inl = this->make_inline_array(v);
if(inl.size() < this->width_ &&
std::find(inl.cbegin(), inl.cend(), '\n') == inl.cend())
{
return inl;
}
}
// if the length exceeds this->width_, print multiline array.
// key = [
// # ...
// 42,
// ...
// ]
std::string token;
std::string current_line;
token += "[\n";
for(const auto& item : v)
{
if(!item.comments().empty() && !no_comment_)
{
// if comment exists, the element must be the only element in the line.
// e.g. the following is not allowed.
// ```toml
// array = [
// # comment for what?
// 1, 2, 3, 4, 5
// ]
// ```
if(!current_line.empty())
{
if(current_line.back() != '\n')
{
current_line += '\n';
}
token += current_line;
current_line.clear();
}
for(const auto& c : item.comments())
{
token += '#';
token += c;
token += '\n';
}
token += toml::visit(*this, item);
if(token.back() == '\n') {token.pop_back();}
token += ",\n";
continue;
}
std::string next_elem;
next_elem += toml::visit(*this, item);
// comma before newline.
if(next_elem.back() == '\n') {next_elem.pop_back();}
// if current line does not exceeds the width limit, continue.
if(current_line.size() + next_elem.size() + 1 < this->width_)
{
current_line += next_elem;
current_line += ',';
}
else if(current_line.empty())
{
// if current line was empty, force put the next_elem because
// next_elem is not splittable
token += next_elem;
token += ",\n";
// current_line is kept empty
}
else // reset current_line
{
assert(current_line.back() == ',');
token += current_line;
token += '\n';
current_line = next_elem;
current_line += ',';
}
}
if(!current_line.empty())
{
if(current_line.back() != '\n') {current_line += '\n';}
token += current_line;
}
token += "]\n";
return token;
}
// templatize for any table-like container
std::string operator()(const table_type& v) const
{
// if an element has a comment, then it can't be inlined.
// table = {# how can we write a comment for this? key = "value"}
if(this->can_be_inlined_ && !(this->has_comment_inside(v)))
{
std::string token;
if(!this->keys_.empty())
{
token += format_key(this->keys_.back());
token += " = ";
}
token += this->make_inline_table(v);
if(token.size() < this->width_ &&
token.end() == std::find(token.begin(), token.end(), '\n'))
{
return token;
}
}
std::string token;
if(!keys_.empty())
{
token += '[';
token += format_keys(keys_);
token += "]\n";
}
token += this->make_multiline_table(v);
return token;
}
private:
std::string escape_basic_string(const std::string& s) const
{
//XXX assuming `s` is a valid utf-8 sequence.
std::string retval;
for(const char c : s)
{
switch(c)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\\n"; break;}
case '\r': {retval += "\\r"; break;}
default : {retval += c; break;}
}
}
return retval;
}
std::string escape_ml_basic_string(const std::string& s) const
{
std::string retval;
for(auto i=s.cbegin(), e=s.cend(); i!=e; ++i)
{
switch(*i)
{
case '\\': {retval += "\\\\"; break;}
// One or two consecutive "s are allowed.
// Later we will check there are no three consecutive "s.
// case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\n"; break;}
case '\r':
{
if(std::next(i) != e && *std::next(i) == '\n')
{
retval += "\r\n";
++i;
}
else
{
retval += "\\r";
}
break;
}
default: {retval += *i; break;}
}
}
// Only 1 or 2 consecutive `"`s are allowed in multiline basic string.
// 3 consecutive `"`s are considered as a closing delimiter.
// We need to check if there are 3 or more consecutive `"`s and insert
// backslash to break them down into several short `"`s like the `str6`
// in the following example.
// ```toml
// str4 = """Here are two quotation marks: "". Simple enough."""
// # str5 = """Here are three quotation marks: """.""" # INVALID
// str5 = """Here are three quotation marks: ""\"."""
// str6 = """Here are fifteen quotation marks: ""\"""\"""\"""\"""\"."""
// ```
auto found_3_quotes = retval.find("\"\"\"");
while(found_3_quotes != std::string::npos)
{
retval.replace(found_3_quotes, 3, "\"\"\\\"");
found_3_quotes = retval.find("\"\"\"");
}
return retval;
}
// if an element of a table or an array has a comment, it cannot be inlined.
bool has_comment_inside(const array_type& a) const noexcept
{
// if no_comment is set, comments would not be written.
if(this->no_comment_) {return false;}
for(const auto& v : a)
{
if(!v.comments().empty()) {return true;}
}
return false;
}
bool has_comment_inside(const table_type& t) const noexcept
{
// if no_comment is set, comments would not be written.
if(this->no_comment_) {return false;}
for(const auto& kv : t)
{
if(!kv.second.comments().empty()) {return true;}
}
return false;
}
std::string make_inline_array(const array_type& v) const
{
assert(!has_comment_inside(v));
std::string token;
token += '[';
bool is_first = true;
for(const auto& item : v)
{
if(is_first) {is_first = false;} else {token += ',';}
token += visit(serializer((std::numeric_limits<std::size_t>::max)(),
this->float_prec_, true), item);
}
token += ']';
return token;
}
std::string make_inline_table(const table_type& v) const
{
assert(!has_comment_inside(v));
assert(this->can_be_inlined_);
std::string token;
token += '{';
bool is_first = true;
for(const auto& kv : v)
{
// in inline tables, trailing comma is not allowed (toml-lang #569).
if(is_first) {is_first = false;} else {token += ',';}
token += format_key(kv.first);
token += '=';
token += visit(serializer((std::numeric_limits<std::size_t>::max)(),
this->float_prec_, true), kv.second);
}
token += '}';
return token;
}
std::string make_multiline_table(const table_type& v) const
{
std::string token;
// print non-table stuff first. because after printing [foo.bar], the
// remaining non-table values will be assigned into [foo.bar], not [foo]
for(const auto& kv : v)
{
if(kv.second.is_table() || is_array_of_tables(kv.second))
{
continue;
}
if(!kv.second.comments().empty() && !no_comment_)
{
for(const auto& c : kv.second.comments())
{
token += '#';
token += c;
token += '\n';
}
}
const auto key_and_sep = format_key(kv.first) + " = ";
const auto residual_width = (this->width_ > key_and_sep.size()) ?
this->width_ - key_and_sep.size() : 0;
token += key_and_sep;
token += visit(serializer(residual_width, this->float_prec_, true),
kv.second);
if(token.back() != '\n')
{
token += '\n';
}
}
// normal tables / array of tables
// after multiline table appeared, the other tables cannot be inline
// because the table would be assigned into the table.
// [foo]
// ...
// bar = {...} # <- bar will be a member of [foo].
bool multiline_table_printed = false;
for(const auto& kv : v)
{
if(!kv.second.is_table() && !is_array_of_tables(kv.second))
{
continue; // other stuff are already serialized. skip them.
}
std::vector<toml::key> ks(this->keys_);
ks.push_back(kv.first);
auto tmp = visit(serializer(this->width_, this->float_prec_,
!multiline_table_printed, this->no_comment_, ks),
kv.second);
if((!multiline_table_printed) &&
std::find(tmp.cbegin(), tmp.cend(), '\n') != tmp.cend())
{
multiline_table_printed = true;
}
else
{
// still inline tables only.
tmp += '\n';
}
if(!kv.second.comments().empty() && !no_comment_)
{
for(const auto& c : kv.second.comments())
{
token += '#';
token += c;
token += '\n';
}
}
token += tmp;
}
return token;
}
bool is_array_of_tables(const value_type& v) const
{
if(!v.is_array()) {return false;}
const auto& a = v.as_array();
return !a.empty() && a.front().is_table();
}
private:
bool can_be_inlined_;
bool no_comment_;
int float_prec_;
std::size_t width_;
std::vector<toml::key> keys_;
};
template<typename C,
template<typename ...> class M, template<typename ...> class V>
std::string
format(const basic_value<C, M, V>& v, std::size_t w = 80u,
int fprec = std::numeric_limits<toml::floating>::max_digits10,
bool no_comment = false, bool force_inline = false)
{
using value_type = basic_value<C, M, V>;
// if value is a table, it is considered to be a root object.
// the root object can't be an inline table.
if(v.is_table())
{
std::ostringstream oss;
if(!v.comments().empty())
{
oss << v.comments();
oss << '\n'; // to split the file comment from the first element
}
const auto serialized = visit(serializer<value_type>(w, fprec, no_comment, false), v);
oss << serialized;
return oss.str();
}
return visit(serializer<value_type>(w, fprec, force_inline), v);
}
namespace detail
{
template<typename charT, typename traits>
int comment_index(std::basic_ostream<charT, traits>&)
{
static const int index = std::ios_base::xalloc();
return index;
}
} // detail
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
nocomment(std::basic_ostream<charT, traits>& os)
{
// by default, it is zero. and by defalut, it shows comments.
os.iword(detail::comment_index(os)) = 1;
return os;
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
showcomment(std::basic_ostream<charT, traits>& os)
{
// by default, it is zero. and by defalut, it shows comments.
os.iword(detail::comment_index(os)) = 0;
return os;
}
template<typename charT, typename traits, typename C,
template<typename ...> class M, template<typename ...> class V>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const basic_value<C, M, V>& v)
{
using value_type = basic_value<C, M, V>;
// get status of std::setw().
const auto w = static_cast<std::size_t>(os.width());
const int fprec = static_cast<int>(os.precision());
os.width(0);
// by defualt, iword is initialized byl 0. And by default, toml11 outputs
// comments. So `0` means showcomment. 1 means nocommnet.
const bool no_comment = (1 == os.iword(detail::comment_index(os)));
if(!no_comment && v.is_table() && !v.comments().empty())
{
os << v.comments();
os << '\n'; // to split the file comment from the first element
}
// the root object can't be an inline table. so pass `false`.
const auto serialized = visit(serializer<value_type>(w, fprec, no_comment, false), v);
os << serialized;
// if v is a non-table value, and has only one comment, then
// put a comment just after a value. in the following way.
//
// ```toml
// key = "value" # comment.
// ```
//
// Since the top-level toml object is a table, one who want to put a
// non-table toml value must use this in a following way.
//
// ```cpp
// toml::value v;
// std::cout << "user-defined-key = " << v << std::endl;
// ```
//
// In this case, it is impossible to put comments before key-value pair.
// The only way to preserve comments is to put all of them after a value.
if(!no_comment && !v.is_table() && !v.comments().empty())
{
os << " #";
for(const auto& c : v.comments()) {os << c;}
}
return os;
}
} // toml
#endif// TOML11_SERIALIZER_HPP

87
toml/source_location.hpp Normal file
View File

@@ -0,0 +1,87 @@
// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_SOURCE_LOCATION_HPP
#define TOML11_SOURCE_LOCATION_HPP
#include <cstdint>
#include "region.hpp"
namespace toml
{
// A struct to contain location in a toml file.
// The interface imitates std::experimental::source_location,
// but not completely the same.
//
// It would be constructed by toml::value. It can be used to generate
// user-defined error messages.
//
// - std::uint_least32_t line() const noexcept
// - returns the line number where the region is on.
// - std::uint_least32_t column() const noexcept
// - returns the column number where the region starts.
// - std::uint_least32_t region() const noexcept
// - returns the size of the region.
//
// +-- line() +-- region of interest (region() == 9)
// v .---+---.
// 12 | value = "foo bar"
// ^
// +-- column()
//
// - std::string const& file_name() const noexcept;
// - name of the file.
// - std::string const& line_str() const noexcept;
// - the whole line that contains the region of interest.
//
struct source_location
{
public:
source_location()
: line_num_(0), column_num_(0), region_size_(0),
file_name_("unknown file"), line_str_("")
{}
explicit source_location(const detail::region_base* reg)
: line_num_(0), column_num_(0), region_size_(0),
file_name_("unknown file"), line_str_("")
{
if(reg)
{
if(reg->line_num() != detail::region_base().line_num())
{
line_num_ = static_cast<std::uint_least32_t>(
std::stoul(reg->line_num()));
}
column_num_ = static_cast<std::uint_least32_t>(reg->before() + 1);
region_size_ = static_cast<std::uint_least32_t>(reg->size());
file_name_ = reg->name();
line_str_ = reg->line();
}
}
~source_location() = default;
source_location(source_location const&) = default;
source_location(source_location &&) = default;
source_location& operator=(source_location const&) = default;
source_location& operator=(source_location &&) = default;
std::uint_least32_t line() const noexcept {return line_num_;}
std::uint_least32_t column() const noexcept {return column_num_;}
std::uint_least32_t region() const noexcept {return region_size_;}
std::string const& file_name() const noexcept {return file_name_;}
std::string const& line_str() const noexcept {return line_str_;}
private:
std::uint_least32_t line_num_;
std::uint_least32_t column_num_;
std::uint_least32_t region_size_;
std::string file_name_;
std::string line_str_;
};
} // toml
#endif// TOML11_SOURCE_LOCATION_HPP

43
toml/storage.hpp Normal file
View File

@@ -0,0 +1,43 @@
// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_STORAGE_HPP
#define TOML11_STORAGE_HPP
#include "utility.hpp"
namespace toml
{
namespace detail
{
// this contains pointer and deep-copy the content if copied.
// to avoid recursive pointer.
template<typename T>
struct storage
{
using value_type = T;
explicit storage(value_type const& v): ptr(toml::make_unique<T>(v)) {}
explicit storage(value_type&& v): ptr(toml::make_unique<T>(std::move(v))) {}
~storage() = default;
storage(const storage& rhs): ptr(toml::make_unique<T>(*rhs.ptr)) {}
storage& operator=(const storage& rhs)
{
this->ptr = toml::make_unique<T>(*rhs.ptr);
return *this;
}
storage(storage&&) = default;
storage& operator=(storage&&) = default;
bool is_ok() const noexcept {return static_cast<bool>(ptr);}
value_type& value() & noexcept {return *ptr;}
value_type const& value() const& noexcept {return *ptr;}
value_type&& value() && noexcept {return std::move(*ptr);}
private:
std::unique_ptr<value_type> ptr;
};
} // detail
} // toml
#endif// TOML11_STORAGE_HPP

224
toml/string.hpp Normal file
View File

@@ -0,0 +1,224 @@
// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_STRING_HPP
#define TOML11_STRING_HPP
#include <cstdint>
#include <algorithm>
#include <string>
#if __cplusplus >= 201703L
#if __has_include(<string_view>)
#include <string_view>
#endif
#endif
namespace toml
{
enum class string_t : std::uint8_t
{
basic = 0,
literal = 1,
};
struct string
{
string() = default;
~string() = default;
string(const string& s) = default;
string(string&& s) = default;
string& operator=(const string& s) = default;
string& operator=(string&& s) = default;
string(const std::string& s): kind(string_t::basic), str(s){}
string(const std::string& s, string_t k): kind(k), str(s){}
string(const char* s): kind(string_t::basic), str(s){}
string(const char* s, string_t k): kind(k), str(s){}
string(std::string&& s): kind(string_t::basic), str(std::move(s)){}
string(std::string&& s, string_t k): kind(k), str(std::move(s)){}
string& operator=(const std::string& s)
{kind = string_t::basic; str = s; return *this;}
string& operator=(std::string&& s)
{kind = string_t::basic; str = std::move(s); return *this;}
operator std::string& () & noexcept {return str;}
operator std::string const& () const& noexcept {return str;}
operator std::string&& () && noexcept {return std::move(str);}
string& operator+=(const char* rhs) {str += rhs; return *this;}
string& operator+=(const char rhs) {str += rhs; return *this;}
string& operator+=(const std::string& rhs) {str += rhs; return *this;}
string& operator+=(const string& rhs) {str += rhs.str; return *this;}
#if __cplusplus >= 201703L
explicit string(std::string_view s): kind(string_t::basic), str(s){}
string(std::string_view s, string_t k): kind(k), str(s){}
string& operator=(std::string_view s)
{kind = string_t::basic; str = s; return *this;}
explicit operator std::string_view() const noexcept
{return std::string_view(str);}
string& operator+=(const std::string_view& rhs) {str += rhs; return *this;}
#endif
string_t kind;
std::string str;
};
inline bool operator==(const string& lhs, const string& rhs)
{
return lhs.kind == rhs.kind && lhs.str == rhs.str;
}
inline bool operator!=(const string& lhs, const string& rhs)
{
return !(lhs == rhs);
}
inline bool operator<(const string& lhs, const string& rhs)
{
return (lhs.kind == rhs.kind) ? (lhs.str < rhs.str) : (lhs.kind < rhs.kind);
}
inline bool operator>(const string& lhs, const string& rhs)
{
return rhs < lhs;
}
inline bool operator<=(const string& lhs, const string& rhs)
{
return !(rhs < lhs);
}
inline bool operator>=(const string& lhs, const string& rhs)
{
return !(lhs < rhs);
}
inline bool
operator==(const string& lhs, const std::string& rhs) {return lhs.str == rhs;}
inline bool
operator!=(const string& lhs, const std::string& rhs) {return lhs.str != rhs;}
inline bool
operator< (const string& lhs, const std::string& rhs) {return lhs.str < rhs;}
inline bool
operator> (const string& lhs, const std::string& rhs) {return lhs.str > rhs;}
inline bool
operator<=(const string& lhs, const std::string& rhs) {return lhs.str <= rhs;}
inline bool
operator>=(const string& lhs, const std::string& rhs) {return lhs.str >= rhs;}
inline bool
operator==(const std::string& lhs, const string& rhs) {return lhs == rhs.str;}
inline bool
operator!=(const std::string& lhs, const string& rhs) {return lhs != rhs.str;}
inline bool
operator< (const std::string& lhs, const string& rhs) {return lhs < rhs.str;}
inline bool
operator> (const std::string& lhs, const string& rhs) {return lhs > rhs.str;}
inline bool
operator<=(const std::string& lhs, const string& rhs) {return lhs <= rhs.str;}
inline bool
operator>=(const std::string& lhs, const string& rhs) {return lhs >= rhs.str;}
inline bool
operator==(const string& lhs, const char* rhs) {return lhs.str == std::string(rhs);}
inline bool
operator!=(const string& lhs, const char* rhs) {return lhs.str != std::string(rhs);}
inline bool
operator< (const string& lhs, const char* rhs) {return lhs.str < std::string(rhs);}
inline bool
operator> (const string& lhs, const char* rhs) {return lhs.str > std::string(rhs);}
inline bool
operator<=(const string& lhs, const char* rhs) {return lhs.str <= std::string(rhs);}
inline bool
operator>=(const string& lhs, const char* rhs) {return lhs.str >= std::string(rhs);}
inline bool
operator==(const char* lhs, const string& rhs) {return std::string(lhs) == rhs.str;}
inline bool
operator!=(const char* lhs, const string& rhs) {return std::string(lhs) != rhs.str;}
inline bool
operator< (const char* lhs, const string& rhs) {return std::string(lhs) < rhs.str;}
inline bool
operator> (const char* lhs, const string& rhs) {return std::string(lhs) > rhs.str;}
inline bool
operator<=(const char* lhs, const string& rhs) {return std::string(lhs) <= rhs.str;}
inline bool
operator>=(const char* lhs, const string& rhs) {return std::string(lhs) >= rhs.str;}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const string& s)
{
if(s.kind == string_t::basic)
{
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend())
{
// it contains newline. make it multiline string.
os << "\"\"\"\n";
for(auto i=s.str.cbegin(), e=s.str.cend(); i!=e; ++i)
{
switch(*i)
{
case '\\': {os << "\\\\"; break;}
case '\"': {os << "\\\""; break;}
case '\b': {os << "\\b"; break;}
case '\t': {os << "\\t"; break;}
case '\f': {os << "\\f"; break;}
case '\n': {os << '\n'; break;}
case '\r':
{
// since it is a multiline string,
// CRLF is not needed to be escaped.
if(std::next(i) != e && *std::next(i) == '\n')
{
os << "\r\n";
++i;
}
else
{
os << "\\r";
}
break;
}
default: {os << *i; break;}
}
}
os << "\\\n\"\"\"";
return os;
}
// no newline. make it inline.
os << "\"";
for(const auto c : s.str)
{
switch(c)
{
case '\\': {os << "\\\\"; break;}
case '\"': {os << "\\\""; break;}
case '\b': {os << "\\b"; break;}
case '\t': {os << "\\t"; break;}
case '\f': {os << "\\f"; break;}
case '\n': {os << "\\n"; break;}
case '\r': {os << "\\r"; break;}
default : {os << c; break;}
}
}
os << "\"";
return os;
}
// the string `s` is literal-string.
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend() ||
std::find(s.str.cbegin(), s.str.cend(), '\'') != s.str.cend() )
{
// contains newline or single quote. make it multiline.
os << "'''\n" << s.str << "'''";
return os;
}
// normal literal string
os << '\'' << s.str << '\'';
return os;
}
} // toml
#endif// TOML11_STRING_H

View File

@@ -1,52 +0,0 @@
#ifndef TOML11_TO_TOML
#define TOML11_TO_TOML
#include "value.hpp"
namespace toml
{
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT != toml::value_t::Unknown &&
vT != value_t::Empty), std::nullptr_t>::type = nullptr>
inline toml::value to_toml(T&& x)
{
return toml::value(std::forward<T>(x));
}
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT == toml::value_t::Unknown) &&
(!toml::detail::is_map<T>::value) &&
toml::detail::is_container<T>::value, std::nullptr_t>::type = nullptr>
toml::value to_toml(T&& x)
{
toml::Array tmp; tmp.reserve(std::distance(std::begin(x), std::end(x)));
for(auto iter = std::begin(x); iter != std::end(x); ++iter)
tmp.emplace_back(*iter);
return toml::value(std::move(tmp));
}
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT == toml::value_t::Unknown) &&
toml::detail::is_map<T>::value, std::nullptr_t>::type = nullptr>
toml::value to_toml(T&& x)
{
toml::Table tmp;
for(auto iter = std::begin(x); iter != std::end(x); ++iter)
tmp.emplace(iter->first, to_toml(iter->second));
return toml::value(std::move(tmp));
}
template<typename T>
inline toml::value to_toml(std::initializer_list<T> init)
{
return toml::value(std::move(init));
}
inline toml::value
to_toml(std::initializer_list<std::pair<std::string, toml::value>> init)
{
return toml::value(std::move(init));
}
} // toml
#endif // TOML11_TO_TOML

View File

@@ -1,14 +1,29 @@
#ifndef TOML11_TRAITS
#define TOML11_TRAITS
// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_TRAITS_HPP
#define TOML11_TRAITS_HPP
#include <chrono>
#include <forward_list>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#if __cplusplus >= 201703L
#if __has_include(<string_view>)
#include <string_view>
#endif // has_include(<string_view>)
#endif // cplusplus >= C++17
namespace toml
{
template<typename C, template<typename ...> class T, template<typename ...> class A>
class basic_value;
namespace detail
{
template<typename T>
using unwrap_t = typename std::decay<T>::type;
// ---------------------------------------------------------------------------
// check whether type T is a kind of container/map class
struct has_iterator_impl
{
@@ -30,11 +45,43 @@ struct has_mapped_type_impl
template<typename T> static std::true_type check(typename T::mapped_type*);
template<typename T> static std::false_type check(...);
};
struct has_resize_method_impl
struct has_reserve_method_impl
{
constexpr static std::size_t dummy=0;
template<typename T> static std::true_type check(decltype(std::declval<T>().resize(dummy))*);
template<typename T> static std::false_type check(...);
template<typename T> static std::true_type check(
decltype(std::declval<T>().reserve(std::declval<std::size_t>()))*);
};
struct has_push_back_method_impl
{
template<typename T> static std::false_type check(...);
template<typename T> static std::true_type check(
decltype(std::declval<T>().push_back(std::declval<typename T::value_type>()))*);
};
struct is_comparable_impl
{
template<typename T> static std::false_type check(...);
template<typename T> static std::true_type check(
decltype(std::declval<T>() < std::declval<T>())*);
};
struct has_from_toml_method_impl
{
template<typename T, typename C,
template<typename ...> class Tb, template<typename ...> class A>
static std::true_type check(
decltype(std::declval<T>().from_toml(
std::declval<::toml::basic_value<C, Tb, A>>()))*);
template<typename T, typename C,
template<typename ...> class Tb, template<typename ...> class A>
static std::false_type check(...);
};
struct has_into_toml_method_impl
{
template<typename T>
static std::true_type check(decltype(std::declval<T>().into_toml())*);
template<typename T>
static std::false_type check(...);
};
/// Intel C++ compiler can not use decltype in parent class declaration, here
@@ -52,20 +99,201 @@ struct has_key_type : decltype(has_key_type_impl::check<T>(nullptr)){};
template<typename T>
struct has_mapped_type : decltype(has_mapped_type_impl::check<T>(nullptr)){};
template<typename T>
struct has_resize_method : decltype(has_resize_method_impl::check<T>(nullptr)){};
struct has_reserve_method : decltype(has_reserve_method_impl::check<T>(nullptr)){};
template<typename T>
struct has_push_back_method : decltype(has_push_back_method_impl::check<T>(nullptr)){};
template<typename T>
struct is_comparable : decltype(is_comparable_impl::check<T>(nullptr)){};
template<typename T, typename C,
template<typename ...> class Tb, template<typename ...> class A>
struct has_from_toml_method
: decltype(has_from_toml_method_impl::check<T, C, Tb, A>(nullptr)){};
template<typename T>
struct has_into_toml_method
: decltype(has_into_toml_method_impl::check<T>(nullptr)){};
#ifdef __INTEL_COMPILER
#undef decltype(...)
#undef decltype
#endif
template<typename T>
struct is_container : std::integral_constant<bool,
has_iterator<T>::value && has_value_type<T>::value>{};
// ---------------------------------------------------------------------------
// C++17 and/or/not
#if __cplusplus >= 201703L
using std::conjunction;
using std::disjunction;
using std::negation;
#else
template<typename ...> struct conjunction : std::true_type{};
template<typename T> struct conjunction<T> : T{};
template<typename T, typename ... Ts>
struct conjunction<T, Ts...> :
std::conditional<static_cast<bool>(T::value), conjunction<Ts...>, T>::type
{};
template<typename ...> struct disjunction : std::false_type{};
template<typename T> struct disjunction<T> : T {};
template<typename T, typename ... Ts>
struct disjunction<T, Ts...> :
std::conditional<static_cast<bool>(T::value), T, disjunction<Ts...>>::type
{};
template<typename T>
struct is_map : std::integral_constant<bool,
has_iterator<T>::value && has_key_type<T>::value &&
has_mapped_type<T>::value>{};
struct negation : std::integral_constant<bool, !static_cast<bool>(T::value)>{};
#endif
// ---------------------------------------------------------------------------
// type checkers
template<typename T> struct is_std_pair : std::false_type{};
template<typename T1, typename T2>
struct is_std_pair<std::pair<T1, T2>> : std::true_type{};
template<typename T> struct is_std_tuple : std::false_type{};
template<typename ... Ts>
struct is_std_tuple<std::tuple<Ts...>> : std::true_type{};
template<typename T> struct is_std_forward_list : std::false_type{};
template<typename T>
struct is_std_forward_list<std::forward_list<T>> : std::true_type{};
template<typename T> struct is_chrono_duration: std::false_type{};
template<typename Rep, typename Period>
struct is_chrono_duration<std::chrono::duration<Rep, Period>>: std::true_type{};
template<typename T>
struct is_map : conjunction< // map satisfies all the following conditions
has_iterator<T>, // has T::iterator
has_value_type<T>, // has T::value_type
has_key_type<T>, // has T::key_type
has_mapped_type<T> // has T::mapped_type
>{};
template<typename T> struct is_map<T&> : is_map<T>{};
template<typename T> struct is_map<T const&> : is_map<T>{};
template<typename T> struct is_map<T volatile&> : is_map<T>{};
template<typename T> struct is_map<T const volatile&> : is_map<T>{};
template<typename T>
struct is_container : conjunction<
negation<is_map<T>>, // not a map
negation<std::is_same<T, std::string>>, // not a std::string
#if __cplusplus >= 201703L
negation<std::is_same<T, std::string_view>>, // not a std::string_view
#endif
has_iterator<T>, // has T::iterator
has_value_type<T> // has T::value_type
>{};
template<typename T> struct is_container<T&> : is_container<T>{};
template<typename T> struct is_container<T const&> : is_container<T>{};
template<typename T> struct is_container<T volatile&> : is_container<T>{};
template<typename T> struct is_container<T const volatile&> : is_container<T>{};
template<typename T>
struct is_basic_value: std::false_type{};
template<typename T> struct is_basic_value<T&> : is_basic_value<T>{};
template<typename T> struct is_basic_value<T const&> : is_basic_value<T>{};
template<typename T> struct is_basic_value<T volatile&> : is_basic_value<T>{};
template<typename T> struct is_basic_value<T const volatile&> : is_basic_value<T>{};
template<typename C, template<typename ...> class M, template<typename ...> class V>
struct is_basic_value<::toml::basic_value<C, M, V>>: std::true_type{};
// ---------------------------------------------------------------------------
// C++14 index_sequence
#if __cplusplus >= 201402L
using std::index_sequence;
using std::make_index_sequence;
#else
template<std::size_t ... Ns> struct index_sequence{};
template<typename IS, std::size_t N> struct push_back_index_sequence{};
template<std::size_t N, std::size_t ... Ns>
struct push_back_index_sequence<index_sequence<Ns...>, N>
{
typedef index_sequence<Ns..., N> type;
};
template<std::size_t N>
struct index_sequence_maker
{
typedef typename push_back_index_sequence<
typename index_sequence_maker<N-1>::type, N>::type type;
};
template<>
struct index_sequence_maker<0>
{
typedef index_sequence<0> type;
};
template<std::size_t N>
using make_index_sequence = typename index_sequence_maker<N-1>::type;
#endif // __cplusplus >= 2014
// ---------------------------------------------------------------------------
// C++14 enable_if_t
#if __cplusplus >= 201402L
using std::enable_if_t;
#else
template<bool B, typename T>
using enable_if_t = typename std::enable_if<B, T>::type;
#endif // __cplusplus >= 2014
// ---------------------------------------------------------------------------
// return_type_of_t
#if __cplusplus >= 201703L
template<typename F, typename ... Args>
using return_type_of_t = std::invoke_result_t<F, Args...>;
#else
// result_of is deprecated after C++17
template<typename F, typename ... Args>
using return_type_of_t = typename std::result_of<F(Args...)>::type;
#endif
// ---------------------------------------------------------------------------
// is_string_literal
//
// to use this, pass `typename remove_reference<T>::type` to T.
template<typename T>
struct is_string_literal:
disjunction<
std::is_same<const char*, T>,
conjunction<
std::is_array<T>,
std::is_same<const char, typename std::remove_extent<T>::type>
>
>{};
// ---------------------------------------------------------------------------
// C++20 remove_cvref_t
template<typename T>
struct remove_cvref
{
using type = typename std::remove_cv<
typename std::remove_reference<T>::type>::type;
};
template<typename T>
using remove_cvref_t = typename remove_cvref<T>::type;
}// detail
}//toml

150
toml/types.hpp Normal file
View File

@@ -0,0 +1,150 @@
// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_TYPES_HPP
#define TOML11_TYPES_HPP
#include <unordered_map>
#include <vector>
#include "comments.hpp"
#include "datetime.hpp"
#include "string.hpp"
#include "traits.hpp"
namespace toml
{
template<typename Comment, // discard/preserve_comment
template<typename ...> class Table, // map-like class
template<typename ...> class Array> // vector-like class
class basic_value;
using character = char;
using key = std::string;
using boolean = bool;
using integer = std::int64_t;
using floating = double; // "float" is a keyward, cannot use it here.
// the following stuffs are structs defined here, so aliases are not needed.
// - string
// - offset_datetime
// - offset_datetime
// - local_datetime
// - local_date
// - local_time
// default toml::value and default array/table. these are defined after defining
// basic_value itself.
// using value = basic_value<discard_comments, std::unordered_map, std::vector>;
// using array = typename value::array_type;
// using table = typename value::table_type;
enum class value_t : std::uint8_t
{
empty = 0,
boolean = 1,
integer = 2,
floating = 3,
string = 4,
offset_datetime = 5,
local_datetime = 6,
local_date = 7,
local_time = 8,
array = 9,
table = 10,
};
template<typename charT, typename traits>
inline std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, value_t t)
{
switch(t)
{
case value_t::boolean : os << "boolean"; return os;
case value_t::integer : os << "integer"; return os;
case value_t::floating : os << "floating"; return os;
case value_t::string : os << "string"; return os;
case value_t::offset_datetime : os << "offset_datetime"; return os;
case value_t::local_datetime : os << "local_datetime"; return os;
case value_t::local_date : os << "local_date"; return os;
case value_t::local_time : os << "local_time"; return os;
case value_t::array : os << "array"; return os;
case value_t::table : os << "table"; return os;
case value_t::empty : os << "empty"; return os;
default : os << "unknown"; return os;
}
}
template<typename charT = char,
typename traits = std::char_traits<charT>,
typename alloc = std::allocator<charT>>
inline std::basic_string<charT, traits, alloc> stringize(value_t t)
{
std::basic_ostringstream<charT, traits, alloc> oss;
oss << t;
return oss.str();
}
namespace detail
{
// helper to define a type that represents a value_t value.
template<value_t V>
using value_t_constant = std::integral_constant<value_t, V>;
// meta-function that convertes from value_t to the exact toml type that corresponds to.
// It takes toml::basic_value type because array and table types depend on it.
template<value_t t, typename Value> struct enum_to_type {using type = void ;};
template<typename Value> struct enum_to_type<value_t::empty , Value>{using type = void ;};
template<typename Value> struct enum_to_type<value_t::boolean , Value>{using type = boolean ;};
template<typename Value> struct enum_to_type<value_t::integer , Value>{using type = integer ;};
template<typename Value> struct enum_to_type<value_t::floating , Value>{using type = floating ;};
template<typename Value> struct enum_to_type<value_t::string , Value>{using type = string ;};
template<typename Value> struct enum_to_type<value_t::offset_datetime, Value>{using type = offset_datetime ;};
template<typename Value> struct enum_to_type<value_t::local_datetime , Value>{using type = local_datetime ;};
template<typename Value> struct enum_to_type<value_t::local_date , Value>{using type = local_date ;};
template<typename Value> struct enum_to_type<value_t::local_time , Value>{using type = local_time ;};
template<typename Value> struct enum_to_type<value_t::array , Value>{using type = typename Value::array_type;};
template<typename Value> struct enum_to_type<value_t::table , Value>{using type = typename Value::table_type;};
// meta-function that converts from an exact toml type to the enum that corresponds to.
template<typename T, typename Value>
struct type_to_enum : std::conditional<
std::is_same<T, typename Value::array_type>::value, // if T == array_type,
value_t_constant<value_t::array>, // then value_t::array
typename std::conditional< // else...
std::is_same<T, typename Value::table_type>::value, // if T == table_type
value_t_constant<value_t::table>, // then value_t::table
value_t_constant<value_t::empty> // else value_t::empty
>::type
>::type {};
template<typename Value> struct type_to_enum<boolean , Value>: value_t_constant<value_t::boolean > {};
template<typename Value> struct type_to_enum<integer , Value>: value_t_constant<value_t::integer > {};
template<typename Value> struct type_to_enum<floating , Value>: value_t_constant<value_t::floating > {};
template<typename Value> struct type_to_enum<string , Value>: value_t_constant<value_t::string > {};
template<typename Value> struct type_to_enum<offset_datetime, Value>: value_t_constant<value_t::offset_datetime> {};
template<typename Value> struct type_to_enum<local_datetime , Value>: value_t_constant<value_t::local_datetime > {};
template<typename Value> struct type_to_enum<local_date , Value>: value_t_constant<value_t::local_date > {};
template<typename Value> struct type_to_enum<local_time , Value>: value_t_constant<value_t::local_time > {};
// meta-function that checks the type T is the same as one of the toml::* types.
template<typename T, typename Value>
struct is_exact_toml_type : disjunction<
std::is_same<T, boolean >,
std::is_same<T, integer >,
std::is_same<T, floating >,
std::is_same<T, string >,
std::is_same<T, offset_datetime>,
std::is_same<T, local_datetime >,
std::is_same<T, local_date >,
std::is_same<T, local_time >,
std::is_same<T, typename Value::array_type>,
std::is_same<T, typename Value::table_type>
>{};
template<typename T, typename V> struct is_exact_toml_type<T&, V> : is_exact_toml_type<T, V>{};
template<typename T, typename V> struct is_exact_toml_type<T const&, V> : is_exact_toml_type<T, V>{};
template<typename T, typename V> struct is_exact_toml_type<T volatile&, V> : is_exact_toml_type<T, V>{};
template<typename T, typename V> struct is_exact_toml_type<T const volatile&, V>: is_exact_toml_type<T, V>{};
} // detail
} // toml
#endif// TOML11_TYPES_H

View File

@@ -1,42 +1,92 @@
#ifndef TOML11_UTILITY
#define TOML11_UTILITY
#include "traits.hpp"
#include <utility>
// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_UTILITY_HPP
#define TOML11_UTILITY_HPP
#include <memory>
#include <sstream>
#include <utility>
#include "traits.hpp"
#if __cplusplus >= 201402L
# define TOML11_MARK_AS_DEPRECATED(msg) [[deprecated(msg)]]
#elif defined(__GNUC__)
# define TOML11_MARK_AS_DEPRECATED(msg) __attribute__((deprecated(msg)))
#elif defined(_MSC_VER)
# define TOML11_MARK_AS_DEPRECATED(msg) __declspec(deprecated(msg))
#else
# define TOML11_MARK_AS_DEPRECATED
#endif
namespace toml
{
#if __cplusplus >= 201402L
using std::make_unique;
#else
template<typename T, typename ... Ts>
inline std::unique_ptr<T> make_unique(Ts&& ... args)
{
return std::unique_ptr<T>(new T(std::forward<Ts>(args)...));
}
#endif // __cplusplus >= 2014
namespace detail
{
template<typename T>
inline void resize_impl(T& container, std::size_t N, std::true_type)
template<typename Container>
void try_reserve_impl(Container& container, std::size_t N, std::true_type)
{
container.resize(N);
return ;
container.reserve(N);
return;
}
template<typename Container>
void try_reserve_impl(Container&, std::size_t, std::false_type) noexcept
{
return;
}
} // detail
template<typename Container>
void try_reserve(Container& container, std::size_t N)
{
if(N <= container.size()) {return;}
detail::try_reserve_impl(container, N, detail::has_reserve_method<Container>{});
return;
}
namespace detail
{
inline std::string concat_to_string_impl(std::ostringstream& oss)
{
return oss.str();
}
template<typename T, typename ... Ts>
std::string concat_to_string_impl(std::ostringstream& oss, T&& head, Ts&& ... tail)
{
oss << std::forward<T>(head);
return concat_to_string_impl(oss, std::forward<Ts>(tail) ... );
}
} // detail
template<typename ... Ts>
std::string concat_to_string(Ts&& ... args)
{
std::ostringstream oss;
oss << std::boolalpha << std::fixed;
return detail::concat_to_string_impl(oss, std::forward<Ts>(args) ...);
}
template<typename T>
inline void resize_impl(T& container, std::size_t N, std::false_type)
T from_string(const std::string& str, T opt)
{
if(container.size() >= N) return;
else throw std::invalid_argument("not resizable type");
}
}
template<typename T>
inline void resize(T& container, std::size_t N)
{
if(container.size() == N) return;
else return detail::resize_impl(container, N, detail::has_resize_method<T>());
T v(opt);
std::istringstream iss(str);
iss >> v;
return v;
}
}// toml

File diff suppressed because it is too large Load Diff