From e3a49e3d201be73c383fceb5e226f4ed54461d4b Mon Sep 17 00:00:00 2001 From: Louis Brandy Date: Wed, 11 Sep 2013 09:15:59 -0700 Subject: [PATCH] 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 --- folly/dynamic-inl.h | 3 +++ folly/dynamic.h | 9 +++++++++ folly/test/DynamicTest.cpp | 11 +++++++++++ 3 files changed, 23 insertions(+) diff --git a/folly/dynamic-inl.h b/folly/dynamic-inl.h index 1893f051..b9c91369 100644 --- a/folly/dynamic-inl.h +++ b/folly/dynamic-inl.h @@ -374,6 +374,9 @@ inline double dynamic::asDouble() const { return asImpl(); } inline int64_t dynamic::asInt() const { return asImpl(); } inline bool dynamic::asBool() const { return asImpl(); } +inline const char* dynamic::data() const { return get().data(); } +inline const char* dynamic::c_str() const { return get().c_str(); } + template struct dynamic::CompareOp { static bool comp(T const& a, T const& b) { return a < b; } diff --git a/folly/dynamic.h b/folly/dynamic.h index 41680543..882cd6b5 100644 --- a/folly/dynamic.h +++ b/folly/dynamic.h @@ -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. diff --git a/folly/test/DynamicTest.cpp b/folly/test/DynamicTest.cpp index 8cfe0b55..faf04bf9 100644 --- a/folly/test/DynamicTest.cpp +++ b/folly/test/DynamicTest.cpp @@ -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; -- 2.34.1