Commit e3a49e3d authored by Louis Brandy's avatar Louis Brandy Committed by Peter Griess

add functions to return string's internal pointers

Summary: See title. This avoids unnecessary copies when needing to access string data directly. These will throw if the dynamic isn't a string.

@override-unit-failures

Test Plan: Unit test.

Reviewed By: delong.j@fb.com

FB internal diff: D986331
parent 524d0e74
......@@ -374,6 +374,9 @@ inline double dynamic::asDouble() const { return asImpl<double>(); }
inline int64_t dynamic::asInt() const { return asImpl<int64_t>(); }
inline bool dynamic::asBool() const { return asImpl<bool>(); }
inline const char* dynamic::data() const { return get<fbstring>().data(); }
inline const char* dynamic::c_str() const { return get<fbstring>().c_str(); }
template<class T>
struct dynamic::CompareOp {
static bool comp(T const& a, T const& b) { return a < b; }
......
......@@ -272,6 +272,15 @@ public:
int64_t asInt() const;
bool asBool() const;
/*
* It is occasionally useful to access a string's internal pointer
* directly, without the type conversion of `asString()`.
*
* These will throw a TypeError if the dynamic is not a string.
*/
const char* data() const;
const char* c_str() const;
/*
* Returns: true if this dynamic is null, an empty array, an empty
* object, or an empty string.
......
......@@ -222,6 +222,17 @@ TEST(Dynamic, Conversions) {
EXPECT_EQ(12.0, num.asDouble());
}
TEST(Dynamic, StringPtrs) {
dynamic str = "12.0";
dynamic num = 12.0;
EXPECT_EQ(0, strcmp(str.c_str(), "12.0"));
EXPECT_EQ(0, strncmp(str.data(), "12.0", str.asString().length()));
EXPECT_ANY_THROW(num.c_str());
EXPECT_ANY_THROW(num.data());
}
TEST(Dynamic, FormattedIO) {
std::ostringstream out;
dynamic doubl = 123.33;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment