LLVM 22.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"
18#include "llvm/Support/Endian.h"
19#include "llvm/Support/Error.h"
20#include <cstdint>
21#include <type_traits>
22#include <utility>
23
24namespace llvm {
25
26/// Provides write only access to a subclass of `WritableBinaryStream`.
27/// Provides bounds checking and helpers for writing certain common data types
28/// such as null-terminated strings, integers in various flavors of endianness,
29/// etc. Can be subclassed to provide reading and writing of custom datatypes,
30/// although no methods are overridable.
32public:
33 BinaryStreamWriter() = default;
38
40
42
43 virtual ~BinaryStreamWriter() = default;
44
45 /// Write the bytes specified in \p Buffer to the underlying stream.
46 /// On success, updates the offset so that subsequent writes will occur
47 /// at the next unwritten position.
48 ///
49 /// \returns a success error code if the data was successfully written,
50 /// otherwise returns an appropriate error code.
52
53 /// Write the integer \p Value to the underlying stream in the
54 /// specified endianness. On success, updates the offset so that
55 /// subsequent writes occur at the next unwritten position.
56 ///
57 /// \returns a success error code if the data was successfully written,
58 /// otherwise returns an appropriate error code.
59 template <typename T> Error writeInteger(T Value) {
60 static_assert(std::is_integral_v<T>,
61 "Cannot call writeInteger with non-integral value!");
62 uint8_t Buffer[sizeof(T)];
63 llvm::support::endian::write<T>(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.
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 LLVM_ABI std::pair<BinaryStreamWriter, BinaryStreamWriter>
176 split(uint64_t Off) const;
177
178 void setOffset(uint64_t Off) { Offset = Off; }
179 uint64_t getOffset() const { return Offset; }
180 uint64_t getLength() const { return Stream.getLength(); }
181 uint64_t bytesRemaining() const { return getLength() - getOffset(); }
183
184protected:
187};
188
189} // end namespace llvm
190
191#endif // LLVM_SUPPORT_BINARYSTREAMWRITER_H
Lightweight arrays that are backed by an arbitrary BinaryStream.
#define LLVM_ABI
Definition: Compiler.h:213
uint64_t Size
#define T
endianness Endian
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
llvm::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.
LLVM_ABI 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.
LLVM_ABI 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
LLVM_ABI std::pair< BinaryStreamWriter, BinaryStreamWriter > split(uint64_t Off) const
Splits the Writer into two Writers at a given offset.
LLVM_ABI Error writeStreamRef(BinaryStreamRef Ref)
Efficiently reads all data from Ref, and writes it to this stream.
LLVM_ABI Error writeBytes(ArrayRef< uint8_t > Buffer)
Write the bytes specified in Buffer to the underlying stream.
LLVM_ABI 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.
LLVM_ABI 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
LLVM_ABI Error padToAlignment(uint32_t Align)
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
static ErrorSuccess success()
Create a success value.
Definition: Error.h:336
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:303
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
LLVM Value Representation.
Definition: Value.h:75
A BinaryStream which can be read from as well as written to.
Definition: BinaryStream.h:72
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Ref
The access may reference the value stored in memory.
@ Other
Any other memory.
endianness
Definition: bit.h:71
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39