Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added require methods #23

Merged
merged 2 commits into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ if(CCACHE_PROGRAM)
endif()

project(oxenc
VERSION 1.0.8
VERSION 1.0.9
DESCRIPTION "oxenc - Base 16/32/64 and Bittorrent Encoding/Decoding Header Only Library"
LANGUAGES CXX)

Expand Down
16 changes: 4 additions & 12 deletions oxenc/bt_producer.h
Original file line number Diff line number Diff line change
Expand Up @@ -355,9 +355,7 @@ class bt_dict_producer : bt_list_producer {
/// Returns a string_view into the currently serialized data buffer. Note that the returned
/// view includes the `e` dict end serialization markers which will be overwritten if the dict
/// (or an active sublist/subdict) is appended to.
std::string_view view() const {
return bt_list_producer::view();
}
std::string_view view() const { return bt_list_producer::view(); }

/// Extracts the string, when not using buffer mode. This is only usable on the root
/// list/dict producer, and may only be used in rvalue context, as it destroys the internal
Expand All @@ -375,19 +373,13 @@ class bt_dict_producer : bt_list_producer {
/// Returns a reference to the `std::string`, when in string-builder mode. Unlike `str()`, this
/// method *can* be used on a subdict/sublist, but always returns a reference to the root
/// object's string (unlike `.view()` which just returns the view of the current sub-producer).
const std::string& str_ref() {
return bt_list_producer::str_ref();
}
const std::string& str_ref() { return bt_list_producer::str_ref(); }

/// Calls `.reserve()` on the underlying std::string, if using string-builder mode.
void reserve(size_t new_cap) {
bt_list_producer::reserve(new_cap);
}
void reserve(size_t new_cap) { bt_list_producer::reserve(new_cap); }

/// Returns the end position in the buffer.
const char* end() const {
return bt_list_producer::end();
}
const char* end() const { return bt_list_producer::end(); }

/// Appends a key-value pair with a string or integer value. The key must be > the last key
/// added, but this is only enforced (with an assertion) in debug builds.
Expand Down
72 changes: 72 additions & 0 deletions oxenc/bt_serialize.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <cstring>
#include <functional>
#include <limits>
#include <optional>
#include <ostream>
#include <sstream>
#include <stdexcept>
Expand Down Expand Up @@ -542,6 +543,15 @@ namespace detail {
return os;
}

// True if the type is a std::string, std::string_view, or some a basic_string<Char> for some
// single-byte type Char.
template <typename T>
constexpr bool is_string_like = false;
template <typename Char>
inline constexpr bool is_string_like<std::basic_string<Char>> = sizeof(Char) == 1;
template <typename Char>
inline constexpr bool is_string_like<std::basic_string_view<Char>> = sizeof(Char) == 1;

} // namespace detail

/// Returns a wrapper around a value reference that can serialize the value directly to an output
Expand Down Expand Up @@ -1060,6 +1070,23 @@ class bt_dict_consumer : private bt_list_consumer {
return key_ == find;
}

/// This functions nearly identicalkly to skip_until; it will return if we found an exact match
/// but will throw if the key is not found. If we didn't throw, the next `consumer_*()` call
/// will return the key-value pair we found.
///
/// Two important notes:
///
/// - properly encoded bt dicts must have lexicographically sorted keys, and this method assumes
/// that the input is correctly sorted (and thus if we find a greater value then your key does
/// not exist).
/// - this is irreversible; you cannot returned to skipped values without reparsing. (You *can*
/// however, make a copy of the bt_dict_consumer before calling and use the copy to return to
/// the pre-skipped position).
void required(std::string_view find) {
if (!skip_until(find))
throw std::out_of_range{"Key " + std::string{find} + " not found!"};
}

/// The `consume_*` functions are wrappers around next_whatever that discard the returned key.
///
/// Intended for use with skip_until such as:
Expand Down Expand Up @@ -1104,6 +1131,51 @@ class bt_dict_consumer : private bt_list_consumer {
bt_list_consumer consume_list_consumer() { return consume_list_data(); }
/// Shortcut for wrapping `consume_dict_data()` in a new dict consumer
bt_dict_consumer consume_dict_consumer() { return consume_dict_data(); }

/// Consumes a value into the given type (string_view, string, integer, bt_dict_consumer, etc.).
/// This is a shortcut for calling consume_string, consume_integer, etc. based on the templated
/// type.
template <typename T>
T consume() {
if constexpr (std::is_integral_v<T>)
return consume_integer<T>();
else if constexpr (std::is_same_v<T, std::string_view>)
return consume_string_view();
else if constexpr (detail::is_string_like<T>) {
auto sv = consume_string_view();
return T{reinterpret_cast<const typename T::value_type*>(sv.data()), sv.size()};
} else if constexpr (std::is_same_v<T, bt_dict>)
return consume_dict();
else if constexpr (std::is_same_v<T, bt_list>)
return consume_list();
else if constexpr (std::is_same_v<T, bt_dict_consumer>)
return consume_dict_consumer();
else {
static_assert(std::is_same_v<T, bt_list_consumer>, "Unsupported consume type");
return consume_list_consumer();
}
}

/// Advances to a given key (as if by calling `skip_until`) and then throws if the key was not
/// found; otherwise returns the value parsed into the given type.
template <typename T>
T require(std::string_view key) {
required(key);
if (!skip_until(key))
throw std::out_of_range{"Key " + std::string{key} + " not found!"};
return consume<T>();
}

/// Advances to a given key (as if by calling `skip_until`) and then returns std::nullopt if the
/// key was not found; otherwise returns the value parsed into the given type. Note that this
/// will still throw if the key exists but has an incompatible value (e.g. calling
/// `d.maybe<int>("x")` when the value at "x" is a string).
template <typename T>
std::optional<T> maybe(std::string_view key) {
if (!skip_until(key))
return std::nullopt;
return consume<T>();
}
};

inline bt_dict_consumer bt_list_consumer::consume_dict_consumer() {
Expand Down
50 changes: 48 additions & 2 deletions tests/test_bt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ TEST_CASE("bt streaming list producer", "[bt][list][producer]") {
"l3:abci42ei1ei17ei-999eli0e0:elll3:omgeeed3:foo3:bar1:gi42e1:hld1:ad1:"
"Ali999eeeeeee");

CHECK(lp.str_ref().capacity() < 32); // SSO sizes vary across compilers
CHECK(lp.str_ref().capacity() < 32); // SSO sizes vary across compilers
CHECK(lp.view() == "le");
}
}
Expand Down Expand Up @@ -374,7 +374,7 @@ TEST_CASE("bt streaming dict producer", "[bt][dict][producer]") {
"d3:foo3:bar4:foo\0i-333222111e6:myListl0:i2ei42ee1:pd0:0:e1:qi1e1:ri2e1:~i3e2:~1i4ee"sv);
CHECK(str.capacity() == orig_cap);

CHECK(dp.str_ref().capacity() < 32); // SSO sizes vary across compilers
CHECK(dp.str_ref().capacity() < 32); // SSO sizes vary across compilers
CHECK(dp.view() == "de");
}
}
Expand Down Expand Up @@ -403,6 +403,52 @@ TEST_CASE("bt_producer/bt_value combo", "[bt][dict][value][producer]") {
CHECK(y.view() == "li123ed1:bi1e1:cd1:d1:e1:fli1ei2ei3eeeed1:a0:eld1:a0:ee1:~e");
}

TEST_CASE("Require integer/string methods", "[bt][dict][consumer][require]") {
auto data = bt_serialize(
bt_dict{{"A", 92},
{"C", 64},
{"E", "apple pie"},
{"G", "tomato sauce"},
{"I", 69},
{"K", 420},
{"M", bt_dict{{"Q", "Q"}}}});

bt_dict_consumer btdp{data};

int a, c, i, k;
std::string e, g;
bt_dict bd;

SECTION("Failure case: key does not exist") {
REQUIRE_THROWS(c = btdp.require<int>("B"));
REQUIRE_THROWS(btdp.required("B"));
REQUIRE(btdp.maybe<std::string>("B") == std::nullopt);
}

SECTION("Failure case: key is not a string") {
REQUIRE_THROWS(e = btdp.require<std::string>("C"));
}

SECTION("Failure case: key is not an int") {
REQUIRE_THROWS(c = btdp.require<int>("E"));
}

SECTION("Success cases - direct assignment") {
REQUIRE_NOTHROW(a = btdp.require<int>("A"));
REQUIRE_NOTHROW(c = btdp.require<int>("C"));
REQUIRE_NOTHROW(e = btdp.require<std::string>("E"));
REQUIRE_NOTHROW(g = btdp.require<std::string>("G"));
REQUIRE_NOTHROW(i = btdp.require<int>("I"));
REQUIRE_NOTHROW(k = btdp.require<int>("K"));
REQUIRE_NOTHROW(bd = btdp.consume<bt_dict>());
}

SECTION("Success cases - string conversion types") {
std::basic_string<uint8_t> ustr;
REQUIRE_NOTHROW(ustr = btdp.require<std::basic_string<uint8_t>>("E"));
}
}

#ifdef OXENC_APPLE_TO_CHARS_WORKAROUND
TEST_CASE("apple to_chars workaround test", "[bt][apple][sucks]") {
char buf[20];
Expand Down