xref: /llvm-project/llvm/lib/Support/BinaryStreamWriter.cpp (revision d9dc2829ea28a065115203ebc648b3be4846aae4)
1 //===- BinaryStreamWriter.cpp - Writes objects to a BinaryStream ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/Support/BinaryStreamWriter.h"
11 
12 #include "llvm/Support/BinaryStreamReader.h"
13 #include "llvm/Support/BinaryStreamRef.h"
14 
15 using namespace llvm;
16 
17 BinaryStreamWriter::BinaryStreamWriter(WritableBinaryStreamRef S)
18     : Stream(S), Offset(0) {}
19 
20 Error BinaryStreamWriter::writeBytes(ArrayRef<uint8_t> Buffer) {
21   if (auto EC = Stream.writeBytes(Offset, Buffer))
22     return EC;
23   Offset += Buffer.size();
24   return Error::success();
25 }
26 
27 Error BinaryStreamWriter::writeCString(StringRef Str) {
28   if (auto EC = writeFixedString(Str))
29     return EC;
30   if (auto EC = writeObject('\0'))
31     return EC;
32 
33   return Error::success();
34 }
35 
36 Error BinaryStreamWriter::writeFixedString(StringRef Str) {
37   return writeBytes(ArrayRef<uint8_t>(Str.bytes_begin(), Str.bytes_end()));
38 }
39 
40 Error BinaryStreamWriter::writeStreamRef(BinaryStreamRef Ref) {
41   return writeStreamRef(Ref, Ref.getLength());
42 }
43 
44 Error BinaryStreamWriter::writeStreamRef(BinaryStreamRef Ref, uint32_t Length) {
45   BinaryStreamReader SrcReader(Ref.slice(0, Length));
46   // This is a bit tricky.  If we just call readBytes, we are requiring that it
47   // return us the entire stream as a contiguous buffer.  There is no guarantee
48   // this can be satisfied by returning a reference straight from the buffer, as
49   // an implementation may not store all data in a single contiguous buffer.  So
50   // we iterate over each contiguous chunk, writing each one in succession.
51   while (SrcReader.bytesRemaining() > 0) {
52     ArrayRef<uint8_t> Chunk;
53     if (auto EC = SrcReader.readLongestContiguousChunk(Chunk))
54       return EC;
55     if (auto EC = writeBytes(Chunk))
56       return EC;
57   }
58   return Error::success();
59 }
60