Make rocksdb::Slice more interoperable with std::string_view (#4242)

Summary:
This change allows using std::string_view objects directly in the
DB API:

    db->Get(some_string_view_object, ...);

The conversion from std::string_view to rocksdb::Slice is done
automatically, thanks to the added constructor.

I'm stopping short of adding an implicit conversion operator
from rocksdb::Slice to std::string_view, as I don't think that's
a good idea for PinnableSlices.
Pull Request resolved: https://github.com/facebook/rocksdb/pull/4242

Differential Revision: D9224134

Pulled By: anand1976

fbshipit-source-id: f50aad04dd0b01737907c0fb88d495c83a81f4e4
This commit is contained in:
Georgios Bitzes 2018-08-09 14:30:38 -07:00 committed by Facebook Github Bot
parent ab22cf349e
commit 1b813a9b2e

View File

@ -25,6 +25,10 @@
#include <string.h>
#include <string>
#ifdef __cpp_lib_string_view
#include <string_view>
#endif
#include "rocksdb/cleanable.h"
namespace rocksdb {
@ -41,6 +45,12 @@ class Slice {
/* implicit */
Slice(const std::string& s) : data_(s.data()), size_(s.size()) { }
#ifdef __cpp_lib_string_view
// Create a slice that refers to the same contents as "sv"
/* implicit */
Slice(std::string_view sv) : data_(sv.data()), size_(sv.size()) { }
#endif
// Create a slice that refers to s[0,strlen(s)-1]
/* implicit */
Slice(const char* s) : data_(s) {
@ -86,6 +96,13 @@ class Slice {
// when hex is true, returns a string of twice the length hex encoded (0-9A-F)
std::string ToString(bool hex = false) const;
#ifdef __cpp_lib_string_view
// Return a string_view that references the same data as this slice.
std::string_view ToStringView() const {
return std::string_view(data_, size_);
}
#endif
// Decodes the current slice interpreted as an hexadecimal string into result,
// if successful returns true, if this isn't a valid hex string
// (e.g not coming from Slice::ToString(true)) DecodeHex returns false.