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
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; }
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.
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;