1 //===- BinaryStreamWriter.cpp - Writes objects to a BinaryStream ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Support/BinaryStreamWriter.h"
12 #include "llvm/Support/BinaryStreamError.h"
13 #include "llvm/Support/BinaryStreamReader.h"
14 #include "llvm/Support/BinaryStreamRef.h"
18 BinaryStreamWriter::BinaryStreamWriter(WritableBinaryStreamRef S)
19 : Stream(S), Offset(0) {}
21 Error BinaryStreamWriter::writeBytes(ArrayRef<uint8_t> Buffer) {
22 if (auto EC = Stream.writeBytes(Offset, Buffer))
24 Offset += Buffer.size();
25 return Error::success();
28 Error BinaryStreamWriter::writeCString(StringRef Str) {
29 if (auto EC = writeFixedString(Str))
31 if (auto EC = writeObject('\0'))
34 return Error::success();
37 Error BinaryStreamWriter::writeFixedString(StringRef Str) {
38 return writeBytes(ArrayRef<uint8_t>(Str.bytes_begin(), Str.bytes_end()));
41 Error BinaryStreamWriter::writeStreamRef(BinaryStreamRef Ref) {
42 return writeStreamRef(Ref, Ref.getLength());
45 Error BinaryStreamWriter::writeStreamRef(BinaryStreamRef Ref, uint32_t Length) {
46 BinaryStreamReader SrcReader(Ref.slice(0, Length));
47 // This is a bit tricky. If we just call readBytes, we are requiring that it
48 // return us the entire stream as a contiguous buffer. There is no guarantee
49 // this can be satisfied by returning a reference straight from the buffer, as
50 // an implementation may not store all data in a single contiguous buffer. So
51 // we iterate over each contiguous chunk, writing each one in succession.
52 while (SrcReader.bytesRemaining() > 0) {
53 ArrayRef<uint8_t> Chunk;
54 if (auto EC = SrcReader.readLongestContiguousChunk(Chunk))
56 if (auto EC = writeBytes(Chunk))
59 return Error::success();
62 Error BinaryStreamWriter::padToAlignment(uint32_t Align) {
63 uint32_t NewOffset = alignTo(Offset, Align);
64 if (NewOffset > getLength())
65 return make_error<BinaryStreamError>(stream_error_code::stream_too_short);
67 return Error::success();