Skip to content

Commit 431b981

Browse files
committed
weighted_string_id_reader can require weights
It makes sense for formats to be able to require a value
1 parent 7d48da4 commit 431b981

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

src/generic_factory.h

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <limits>
1010
#include <list>
1111
#include <map>
12+
#include <optional>
1213
#include <set>
1314
#include <string>
1415
#include <string_view>
@@ -1839,20 +1840,21 @@ class weighted_string_id_reader : public generic_typed_reader<weighted_string_id
18391840
public:
18401841
static constexpr bool read_objects = true;
18411842

1842-
V default_weight;
1843-
explicit weighted_string_id_reader( V default_weight ) : default_weight( default_weight ) {};
1843+
std::optional<V> default_weight;
1844+
explicit weighted_string_id_reader( std::optional<V> default_weight ) : default_weight(
1845+
default_weight ) {};
18441846

18451847
std::pair<K, V> get_next( const JsonValue &val ) const {
18461848
if( val.is_member() ) {
18471849
const JsonMember &jm = dynamic_cast<const JsonMember &>( val );
18481850
return std::pair<K, V>( jm.name(), static_cast<V>( val.get_float() ) );
18491851
} else if( val.test_object() ) {
18501852
JsonObject inline_pair = val.get_object();
1851-
if( !( inline_pair.size() == 1 || inline_pair.size() == 2 ) ) {
1853+
if( !( ( inline_pair.size() == 1 && default_weight.has_value() ) || inline_pair.size() == 2 ) ) {
18521854
inline_pair.throw_error( "weighted_string_id_reader failed to read object" );
18531855
}
18541856
K pair_key;
1855-
V pair_val = default_weight;
1857+
V pair_val = default_weight.value_or( V() );
18561858
for( JsonMember mem : inline_pair ) {
18571859
if( mem.test_string() ) {
18581860
pair_key = K( std::move( mem.get_string() ) );
@@ -1871,12 +1873,14 @@ class weighted_string_id_reader : public generic_typed_reader<weighted_string_id
18711873
return std::pair<K, V>(
18721874
K( std::move( arr[0].get_string() ) ),
18731875
static_cast<V>( arr[1].get_float() ) );
1874-
} else {
1876+
} else if( default_weight.has_value() ) {
18751877
if( val.test_string() ) {
18761878
return std::pair<K, V>(
1877-
K( std::move( val.get_string() ) ), default_weight );
1879+
K( std::move( val.get_string() ) ), *default_weight );
18781880
}
18791881
val.throw_error( "weighted_string_id_reader provided with invalid string_id" );
1882+
} else {
1883+
val.throw_error( "weighted_string_id_reader requires two entries" );
18801884
}
18811885
}
18821886
};

0 commit comments

Comments
 (0)