[PATCH] D25255: Add a c_str() method to StringRef, similar to data() but asserting if the string isn't null terminated (NFC)
Mehdi AMINI via llvm-commits
llvm-commits at lists.llvm.org
Tue Oct 4 14:57:40 PDT 2016
mehdi_amini created this revision.
mehdi_amini added reviewers: dexonsmith, kimgr.
mehdi_amini added a subscriber: llvm-commits.
As I'm trying to replace our uses of raw "const char *"
with StringRef, one issue that came up is that calling .data()
on a StringRef is seen as "dangerous": there is no guarantee
that the String will be null terminated.
This is an attempt to alleviate this issue: instead of calling
data(), users that knows (because of an API contract) that a
StringRef must be null terminated can call c_str() instead.
https://reviews.llvm.org/D25255
Files:
llvm/include/llvm/ADT/StringRef.h
Index: llvm/include/llvm/ADT/StringRef.h
===================================================================
--- llvm/include/llvm/ADT/StringRef.h
+++ llvm/include/llvm/ADT/StringRef.h
@@ -13,6 +13,7 @@
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/Compiler.h"
+#include "llvm/Support/ErrorHandling.h"
#include <algorithm>
#include <cassert>
#include <cstring>
@@ -126,6 +127,18 @@
LLVM_ATTRIBUTE_ALWAYS_INLINE
const char *data() const { return Data; }
+ /// Get a pointer to the start of the string, enforcing that it is null
+ /// terminated. This is intended to be used when the contract of the API is
+ /// to return a null terminated string.
+ const char *c_str() const {
+#if !defined(NDEBUG) || LLVM_ADDRESS_SANITIZER_BUILD || \
+ LLVM_MEMORY_SANITIZER_BUILD
+ if (Data[size()] != '\0')
+ report_fatal_error("c_str() called on a non-null terminated string");
+#endif
+ return Data;
+ }
+
/// empty - Check if the string is empty.
LLVM_ATTRIBUTE_ALWAYS_INLINE
bool empty() const { return Length == 0; }
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D25255.73558.patch
Type: text/x-patch
Size: 1146 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20161004/5ea0b606/attachment.bin>
More information about the llvm-commits
mailing list