diff options
author | Jiakai Zhang <jiakaiz@google.com> | 2023-09-14 23:53:18 +0100 |
---|---|---|
committer | Jiakai Zhang <jiakaiz@google.com> | 2023-09-15 22:16:49 +0100 |
commit | 0f96cc0441c626c6172d5c9dfe12c4c6be70873f (patch) | |
tree | 777113adfb95f6dfd39535412e14b7ef2ac4d4a8 | |
parent | 4be05051ef76b2c24d8385732a892401eb45d911 (diff) | |
download | libnativehelper-0f96cc0441c626c6172d5c9dfe12c4c6be70873f.tar.gz |
Add an implicit cast from `ScopedUtfChars` to `std::string_view`.
Bug: 298183834
Test: Presubmit
Change-Id: Iab8f78cb186fe454a69d3248826ffdf797a8760c
-rw-r--r-- | header_only_include/nativehelper/scoped_utf_chars.h | 10 | ||||
-rw-r--r-- | header_only_include/nativehelper/utils.h | 8 |
2 files changed, 17 insertions, 1 deletions
diff --git a/header_only_include/nativehelper/scoped_utf_chars.h b/header_only_include/nativehelper/scoped_utf_chars.h index 8f9fc70..25de0fc 100644 --- a/header_only_include/nativehelper/scoped_utf_chars.h +++ b/header_only_include/nativehelper/scoped_utf_chars.h @@ -23,6 +23,11 @@ #include "nativehelper_utils.h" +// Protect this with __has_include to cope with `stl: "none"` users. +#if __has_include(<string_view>) +#include <string_view> +#endif + // A smart pointer that provides read-only access to a Java string's UTF chars. // Unlike GetStringUTFChars, we throw NullPointerException rather than abort if // passed a null jstring, and c_str will return nullptr. @@ -86,6 +91,10 @@ class ScopedUtfChars { return utf_chars_[n]; } +#if __has_include(<string_view>) + operator std::string_view() const { return utf_chars_; } +#endif + private: JNIEnv* env_; jstring string_; @@ -93,4 +102,3 @@ class ScopedUtfChars { DISALLOW_COPY_AND_ASSIGN(ScopedUtfChars); }; - diff --git a/header_only_include/nativehelper/utils.h b/header_only_include/nativehelper/utils.h index b01c060..30f239e 100644 --- a/header_only_include/nativehelper/utils.h +++ b/header_only_include/nativehelper/utils.h @@ -89,6 +89,14 @@ class JniDefaultValue { // ScopedUtfChars str = GET_UTF_OR_RETURN_VOID(env, j_str); // // Safely use `str` here... // } +// +// The idiomatic way to construct an `std::string` using this macro (an additional string copy is +// performed): +// +// jobject MyJniMethod(JNIEnv* env, jstring j_str) { +// std::string str(GET_UTF_OR_RETURN(env, j_str)); +// // Safely use `str` here... +// } #define GET_UTF_OR_RETURN(env, expr) \ GET_UTF_OR_RETURN_IMPL_((env), (expr), android::jnihelp::JniDefaultValue()) #define GET_UTF_OR_RETURN_VOID(env, expr) GET_UTF_OR_RETURN_IMPL_((env), (expr)) |