Introduce a string_ostream string builder facilty

string_ostream is a safe and efficient string builder that combines opaque
stack storage with a built-in ostream interface.

small_string_ostream<bytes> additionally permits an explicit stack storage size
other than the default 128 bytes to be provided. Beyond that, storage is
transferred to the heap.

This convenient class can be used in most places an
std::string+raw_string_ostream pair or SmallString<>+raw_svector_ostream pair
would previously have been used, in order to guarantee consistent access
without byte truncation.

The patch also converts much of LLVM to use the new facility. These changes
include several probable bug fixes for truncated output, a programming error
that's no longer possible with the new interface.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@211749 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Alp Toker
2014-06-26 00:00:48 +00:00
parent ce6e7c7a59
commit 2559070422
57 changed files with 222 additions and 285 deletions

View File

@@ -15,6 +15,7 @@
#define LLVM_SUPPORT_RAW_OSTREAM_H
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DataTypes.h"
@@ -461,6 +462,14 @@ class raw_svector_ostream : public raw_ostream {
/// current_pos - Return the current position within the stream, not
/// counting the bytes currently in the buffer.
uint64_t current_pos() const override;
protected:
// This constructor is specified not to access \p O provided for storage as it
// may not yet be initialized at construction time.
explicit raw_svector_ostream(SmallVectorImpl<char> &O, std::nullptr_t)
: OS(O){};
void init();
public:
/// Construct a new raw_svector_ostream.
///
@@ -493,6 +502,25 @@ public:
~raw_null_ostream();
};
/// string_ostream - A raw_ostream that builds a string. This is a
/// raw_svector_ostream with storage.
template <unsigned InternalLen>
class small_string_ostream : public raw_svector_ostream {
SmallVector<char, InternalLen> Buffer;
// There's no need to flush explicitly.
using raw_svector_ostream::flush;
public:
small_string_ostream() : raw_svector_ostream(Buffer, nullptr) { init(); }
void clear() {
flush();
Buffer.clear();
}
};
typedef small_string_ostream<128> string_ostream;
} // end llvm namespace
#endif