LLVM 17.0.0git
BinaryStreamWriter.h
Go to the documentation of this file.
1//===- BinaryStreamWriter.h - Writes objects to a BinaryStream ---*- C++-*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_SUPPORT_BINARYSTREAMWRITER_H
10#define LLVM_SUPPORT_BINARYSTREAMWRITER_H
11
12#include "llvm/ADT/ArrayRef.h"
13#include "llvm/ADT/StringRef.h"
17#include "llvm/Support/Endian.h"
18#include "llvm/Support/Error.h"
19#include <cstdint>
20#include <type_traits>
21#include <utility>
22
23namespace llvm {
24
25/// Provides write only access to a subclass of `WritableBinaryStream`.
26/// Provides bounds checking and helpers for writing certain common data types
27/// such as null-terminated strings, integers in various flavors of endianness,
28/// etc. Can be subclassed to provide reading and writing of custom datatypes,
29/// although no methods are overridable.
31public:
32 BinaryStreamWriter() = default;
37
39
41
42 virtual ~BinaryStreamWriter() = default;
43
44 /// Write the bytes specified in \p Buffer to the underlying stream.
45 /// On success, updates the offset so that subsequent writes will occur
46 /// at the next unwritten position.
47 ///
48 /// \returns a success error code if the data was successfully written,
49 /// otherwise returns an appropriate error code.
51
52 /// Write the integer \p Value to the underlying stream in the
53 /// specified endianness. On success, updates the offset so that
54 /// subsequent writes occur at the next unwritten position.
55 ///
56 /// \returns a success error code if the data was successfully written,
57 /// otherwise returns an appropriate error code.
58 template <typename T> Error writeInteger(T Value) {
59 static_assert(std::is_integral_v<T>,
60 "Cannot call writeInteger with non-integral value!");
61 uint8_t Buffer[sizeof(T)];
62 llvm::support::endian::write<T, llvm::support::unaligned>(
63 Buffer, Value, Stream.getEndian());
64 return writeBytes(Buffer);
65 }
66
67 /// Similar to writeInteger
68 template <typename T> Error writeEnum(T Num) {
69 static_assert(std::is_enum<T>::value,
70 "Cannot call writeEnum with non-Enum type");
71
72 using U = std::underlying_type_t<T>;
73 return writeInteger<U>(static_cast<U>(Num));
74 }
75
76 /// Write the unsigned integer Value to the underlying stream using ULEB128
77 /// encoding.
78 ///
79 /// \returns a success error code if the data was successfully written,
80 /// otherwise returns an appropriate error code.
82
83 /// Write the unsigned integer Value to the underlying stream using ULEB128
84 /// encoding.
85 ///
86 /// \returns a success error code if the data was successfully written,
87 /// otherwise returns an appropriate error code.
88 Error writeSLEB128(int64_t Value);
89
90 /// Write the string \p Str to the underlying stream followed by a null
91 /// terminator. On success, updates the offset so that subsequent writes
92 /// occur at the next unwritten position. \p Str need not be null terminated
93 /// on input.
94 ///
95 /// \returns a success error code if the data was successfully written,
96 /// otherwise returns an appropriate error code.
98
99 /// Write the string \p Str to the underlying stream without a null
100 /// terminator. On success, updates the offset so that subsequent writes
101 /// occur at the next unwritten position.
102 ///
103 /// \returns a success error code if the data was successfully written,
104 /// otherwise returns an appropriate error code.
106
107 /// Efficiently reads all data from \p Ref, and writes it to this stream.
108 /// This operation will not invoke any copies of the source data, regardless
109 /// of the source stream's implementation.
110 ///
111 /// \returns a success error code if the data was successfully written,
112 /// otherwise returns an appropriate error code.
114
115 /// Efficiently reads \p Size bytes from \p Ref, and writes it to this stream.
116 /// This operation will not invoke any copies of the source data, regardless
117 /// of the source stream's implementation.
118 ///
119 /// \returns a success error code if the data was successfully written,
120 /// otherwise returns an appropriate error code.
122
123 /// Writes the object \p Obj to the underlying stream, as if by using memcpy.
124 /// It is up to the caller to ensure that type of \p Obj can be safely copied
125 /// in this fashion, as no checks are made to ensure that this is safe.
126 ///
127 /// \returns a success error code if the data was successfully written,
128 /// otherwise returns an appropriate error code.
129 template <typename T> Error writeObject(const T &Obj) {
130 static_assert(!std::is_pointer<T>::value,
131 "writeObject should not be used with pointers, to write "
132 "the pointed-to value dereference the pointer before calling "
133 "writeObject");
134 return writeBytes(
135 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(&Obj), sizeof(T)));
136 }
137
138 /// Writes an array of objects of type T to the underlying stream, as if by
139 /// using memcpy. It is up to the caller to ensure that type of \p Obj can
140 /// be safely copied in this fashion, as no checks are made to ensure that
141 /// this is safe.
142 ///
143 /// \returns a success error code if the data was successfully written,
144 /// otherwise returns an appropriate error code.
145 template <typename T> Error writeArray(ArrayRef<T> Array) {
146 if (Array.empty())
147 return Error::success();
148 if (Array.size() > UINT32_MAX / sizeof(T))
149 return make_error<BinaryStreamError>(
151
152 return writeBytes(
153 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Array.data()),
154 Array.size() * sizeof(T)));
155 }
156
157 /// Writes all data from the array \p Array to the underlying stream.
158 ///
159 /// \returns a success error code if the data was successfully written,
160 /// otherwise returns an appropriate error code.
161 template <typename T, typename U>
163 return writeStreamRef(Array.getUnderlyingStream());
164 }
165
166 /// Writes all elements from the array \p Array to the underlying stream.
167 ///
168 /// \returns a success error code if the data was successfully written,
169 /// otherwise returns an appropriate error code.
170 template <typename T> Error writeArray(FixedStreamArray<T> Array) {
171 return writeStreamRef(Array.getUnderlyingStream());
172 }
173
174 /// Splits the Writer into two Writers at a given offset.
175 std::pair<BinaryStreamWriter, BinaryStreamWriter> split(uint64_t Off) const;
176
177 void setOffset(uint64_t Off) { Offset = Off; }
178 uint64_t getOffset() const { return Offset; }
179 uint64_t getLength() const { return Stream.getLength(); }
180 uint64_t bytesRemaining() const { return getLength() - getOffset(); }
182
183protected:
186};
187
188} // end namespace llvm
189
190#endif // LLVM_SUPPORT_BINARYSTREAMWRITER_H
Lightweight arrays that are backed by an arbitrary BinaryStream.
uint64_t Size
#define T
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
llvm::support::endianness getEndian() const
uint64_t getLength() const
BinaryStreamRef is to BinaryStream what ArrayRef is to an Array.
Provides write only access to a subclass of WritableBinaryStream.
Error writeCString(StringRef Str)
Write the string Str to the underlying stream followed by a null terminator.
Error writeArray(FixedStreamArray< T > Array)
Writes all elements from the array Array to the underlying stream.
Error writeArray(ArrayRef< T > Array)
Writes an array of objects of type T to the underlying stream, as if by using memcpy.
Error writeInteger(T Value)
Write the integer Value to the underlying stream in the specified endianness.
Error writeSLEB128(int64_t Value)
Write the unsigned integer Value to the underlying stream using ULEB128 encoding.
uint64_t bytesRemaining() const
Error writeArray(VarStreamArray< T, U > Array)
Writes all data from the array Array to the underlying stream.
BinaryStreamWriter & operator=(const BinaryStreamWriter &Other)=default
std::pair< BinaryStreamWriter, BinaryStreamWriter > split(uint64_t Off) const
Splits the Writer into two Writers at a given offset.
Error writeStreamRef(BinaryStreamRef Ref)
Efficiently reads all data from Ref, and writes it to this stream.
Error writeBytes(ArrayRef< uint8_t > Buffer)
Write the bytes specified in Buffer to the underlying stream.
Error writeFixedString(StringRef Str)
Write the string Str to the underlying stream without a null terminator.
void setOffset(uint64_t Off)
Error writeEnum(T Num)
Similar to writeInteger.
Error writeULEB128(uint64_t Value)
Write the unsigned integer Value to the underlying stream using ULEB128 encoding.
WritableBinaryStreamRef Stream
Error writeObject(const T &Obj)
Writes the object Obj to the underlying stream, as if by using memcpy.
BinaryStreamWriter(const BinaryStreamWriter &Other)=default
virtual ~BinaryStreamWriter()=default
Error padToAlignment(uint32_t Align)
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
static ErrorSuccess success()
Create a success value.
Definition: Error.h:330
FixedStreamArray is similar to VarStreamArray, except with each record having a fixed-length.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:305
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
LLVM Value Representation.
Definition: Value.h:74
A BinaryStream which can be read from as well as written to.
Definition: BinaryStream.h:73
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Ref
The access may reference the value stored in memory.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39