From: Louis Brandy Date: Wed, 11 Sep 2013 16:15:59 +0000 (-0700) Subject: add functions to return string's internal pointers X-Git-Tag: v0.22.0~857 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=e3a49e3d201be73c383fceb5e226f4ed54461d4b;p=folly.git 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 --- 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;