mirror of
https://github.com/apple/swift.git
synced 2025-12-21 12:14:44 +01:00
[CodeCompletion] Make all result's string fields null terminated
This is convenient for clients to pass these fields values to C functions. Introduce NullTerminatedStringRef to guarantee that.
This commit is contained in:
@@ -469,6 +469,52 @@ bool omitNeedlessWords(StringRef &baseName,
|
||||
/// If the name has a completion-handler suffix, strip off that suffix.
|
||||
Optional<StringRef> stripWithCompletionHandlerSuffix(StringRef name);
|
||||
|
||||
/// Represents a string that can be efficiently retrieved either as a StringRef
|
||||
/// or as a null-terminated C string.
|
||||
class NullTerminatedStringRef {
|
||||
StringRef Ref;
|
||||
|
||||
public:
|
||||
/// Create a \c NullTerminatedStringRef from a null-terminated C string with
|
||||
/// size \p Size (excluding the null character).
|
||||
NullTerminatedStringRef(const char *Data, size_t Size) : Ref(Data, Size) {
|
||||
assert(Data != nullptr && Data[Size] == '\0' &&
|
||||
"Data should be null-terminated");
|
||||
}
|
||||
|
||||
/// Create an empty null-terminated string. \c data() is not a \c nullptr.
|
||||
constexpr NullTerminatedStringRef() : Ref("") {}
|
||||
|
||||
/// Create an null terminated string with a C string.
|
||||
constexpr NullTerminatedStringRef(const char *Data) : Ref(Data) {}
|
||||
|
||||
/// Create a null-terminated string, copying \p Str into \p A .
|
||||
template <typename Allocator>
|
||||
NullTerminatedStringRef(StringRef Str, Allocator &A) : Ref("") {
|
||||
if (Str.empty())
|
||||
return;
|
||||
|
||||
size_t size = Str.size();
|
||||
char *memory = A.template Allocate<char>(size + 1);
|
||||
memcpy(memory, Str.data(), size);
|
||||
memory[size] = '\0';
|
||||
Ref = {memory, size};
|
||||
}
|
||||
|
||||
/// Returns the string as a `StringRef`. The `StringRef` does not include the
|
||||
/// null character.
|
||||
operator StringRef() const { return Ref; }
|
||||
|
||||
/// Returns the string as a null-terminated C string.
|
||||
const char *data() const { return Ref.data(); }
|
||||
|
||||
/// The size of the string, excluding the null character.
|
||||
size_t size() const { return Ref.size(); }
|
||||
|
||||
bool empty() const { return Ref.empty(); }
|
||||
int compare(NullTerminatedStringRef RHS) const { return Ref.compare(RHS); }
|
||||
};
|
||||
|
||||
} // end namespace swift
|
||||
|
||||
#endif // SWIFT_BASIC_STRINGEXTRAS_H
|
||||
|
||||
Reference in New Issue
Block a user