Index: include/llvm/Support/MemoryBuffer.h =================================================================== --- include/llvm/Support/MemoryBuffer.h +++ include/llvm/Support/MemoryBuffer.h @@ -134,6 +134,13 @@ std::unique_ptr &Result, int64_t FileSize = -1); + /// \brief Returns a slice of the given MemoryBuffer, to which ownership is + /// transferred. Note that the slice must be null terminated if + /// RequiresNullTerminator is true. + static MemoryBuffer *getSlice(std::unique_ptr Underlying, + uint64_t Offset, uint64_t Len, + bool RequiresNullTerminator); + //===--------------------------------------------------------------------===// // Provided for performance analysis. //===--------------------------------------------------------------------===// Index: lib/Support/MemoryBuffer.cpp =================================================================== --- lib/Support/MemoryBuffer.cpp +++ lib/Support/MemoryBuffer.cpp @@ -168,6 +168,45 @@ //===----------------------------------------------------------------------===// +// MemoryBufferSlice implementation. +//===----------------------------------------------------------------------===// + +namespace { +/// MemoryBufferSlice - slice of an owned underlying MemoryBuffer. +class MemoryBufferSlice : public MemoryBuffer { + std::unique_ptr Underlying; + +public: + MemoryBufferSlice(std::unique_ptr U, uint64_t Offset, + uint64_t Len, bool RequiresNullTerminator) + : Underlying(std::move(U)) { + init(Underlying->getBufferStart() + Offset, + Underlying->getBufferStart() + Offset + Len, RequiresNullTerminator); + } + + const char *getBufferIdentifier() const override { + return Underlying->getBufferIdentifier(); + } + + BufferKind getBufferKind() const override { + return Underlying->getBufferKind(); + } +}; +} + +/// getSlice - returns a slice of the given MemoryBuffer, to which ownership is +/// transferred. Note that the slice must be null terminated if +/// RequiresNullTerminator is true! +MemoryBuffer *MemoryBuffer::getSlice(std::unique_ptr Underlying, + uint64_t Offset, uint64_t Len, + bool RequiresNullTerminator) { + assert(Offset + Len < Underlying->getBufferSize()); + return new MemoryBufferSlice(std::move(Underlying), Offset, Len, + RequiresNullTerminator); +} + + +//===----------------------------------------------------------------------===// // MemoryBuffer::getFile implementation. //===----------------------------------------------------------------------===//