forked from beached/daw_json_link
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcookbook_kv2_test.cpp
86 lines (75 loc) · 2.42 KB
/
cookbook_kv2_test.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright (c) Darrell Wright
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/beached/daw_json_link
//
#include "defines.h"
#include "daw/json/daw_json_link.h"
#include <daw/daw_read_file.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <unordered_map>
namespace daw::cookbook_kv2 {
struct MyKeyValue2 {
std::unordered_map<intmax_t, std::string> kv;
};
bool operator==( MyKeyValue2 const &lhs, MyKeyValue2 const &rhs ) {
return lhs.kv == rhs.kv;
}
} // namespace daw::cookbook_kv2
namespace daw::json {
template<>
struct json_data_contract<daw::cookbook_kv2::MyKeyValue2> {
#ifdef DAW_JSON_CNTTP_JSON_NAME
using type = json_member_list<
json_key_value_array<"kv", std::unordered_map<intmax_t, std::string>>>;
#else
static constexpr char const kv[] = "kv";
static constexpr char const value[] = "value";
using type = json_member_list<
json_key_value_array<kv, std::unordered_map<intmax_t, std::string>>>;
#endif
static inline auto to_json_data( daw::cookbook_kv2::MyKeyValue2 const &v ) {
return std::forward_as_tuple( v.kv );
}
};
} // namespace daw::json
int main( int argc, char **argv )
#ifdef DAW_USE_EXCEPTIONS
try
#endif
{
if( argc <= 1 ) {
puts( "Must supply path to cookbook_kv2.json file\n" );
exit( EXIT_FAILURE );
}
auto data = *daw::read_file( argv[1] );
auto kv = daw::json::from_json<daw::cookbook_kv2::MyKeyValue2>(
std::string_view( data.data( ), data.size( ) ) );
test_assert( kv.kv.size( ) == 2, "Expected data to have 2 items" );
test_assert( kv.kv[0] == "test_001", "Unexpected value" );
test_assert( kv.kv[1] == "test_002", "Unexpected value" );
auto const str = daw::json::to_json( kv );
puts( str.c_str( ) );
auto const kv2 = daw::json::from_json<daw::cookbook_kv2::MyKeyValue2>(
std::string_view( str.data( ), str.size( ) ) );
test_assert( kv == kv2, "Unexpected round trip error" );
}
#ifdef DAW_USE_EXCEPTIONS
catch( daw::json::json_exception const &jex ) {
std::cerr << "Exception thrown by parser: " << jex.reason( ) << '\n';
exit( 1 );
} catch( std::exception const &ex ) {
std::cerr << "Unknown exception thrown during testing: " << ex.what( )
<< '\n';
exit( 1 );
} catch( ... ) {
std::cerr << "Unknown exception thrown during testing\n";
throw;
}
#endif