LLVM 24.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/APSInt.h"
13#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/StringRef.h"
20#include "llvm/Support/Endian.h"
21#include "llvm/Support/Error.h"
22#include <cstdint>
23#include <type_traits>
24#include <utility>
25
26namespace llvm {
27
28/// Provides write only access to a subclass of `WritableBinaryStream`.
29/// Provides bounds checking and helpers for writing certain common data types
30/// such as null-terminated strings, integers in various flavors of endianness,
31/// etc. Can be subclassed to provide reading and writing of custom datatypes,
32/// although no methods are overridable.
34public:
35 BinaryStreamWriter() = default;
39 llvm::endianness Endian);
40
42
44
45 virtual ~BinaryStreamWriter() = default;
46
47 /// Write the bytes specified in \p Buffer to the underlying stream.
48 /// On success, updates the offset so that subsequent writes will occur
49 /// at the next unwritten position.
50 ///
51 /// \returns a success error code if the data was successfully written,
52 /// otherwise returns an appropriate error code.
54
55 /// Write the integer \p Value to the underlying stream in the
56 /// specified endianness. On success, updates the offset so that
57 /// subsequent writes occur at the next unwritten position.
58 ///
59 /// \returns a success error code if the data was successfully written,
60 /// otherwise returns an appropriate error code.
61 template <typename T> Error writeInteger(T Value) {
62 static_assert(std::is_integral_v<T>,
63 "Cannot call writeInteger with non-integral value!");
64 uint8_t Buffer[sizeof(T)];
65 llvm::support::endian::write<T>(Buffer, Value, Stream.getEndian());
66 return writeBytes(Buffer);
67 }
68
69 /// Write \p Value as a 128 bit integer (possibly truncated).
70 ///
71 /// \p Value is expected to be in native endian as it is byte swapped if
72 /// needed.
73 ///
74 /// \returns a success error code if the data was successfully written,
75 /// otherwise returns an appropriate error code.
77
78 /// Similar to writeInteger
79 template <typename T> Error writeEnum(T Num) {
80 static_assert(std::is_enum<T>::value,
81 "Cannot call writeEnum with non-Enum type");
82
84 }
85
86 /// Write the unsigned integer Value to the underlying stream using ULEB128
87 /// encoding.
88 ///
89 /// \returns a success error code if the data was successfully written,
90 /// otherwise returns an appropriate error code.
92
93 /// Write the unsigned integer Value to the underlying stream using ULEB128
94 /// encoding.
95 ///
96 /// \returns a success error code if the data was successfully written,
97 /// otherwise returns an appropriate error code.
99
100 /// Write the string \p Str to the underlying stream followed by a null
101 /// terminator. On success, updates the offset so that subsequent writes
102 /// occur at the next unwritten position. \p Str need not be null terminated
103 /// on input.
104 ///
105 /// \returns a success error code if the data was successfully written,
106 /// otherwise returns an appropriate error code.
108
109 /// Write the string \p Str to the underlying stream without a null
110 /// terminator. On success, updates the offset so that subsequent writes
111 /// occur at the next unwritten position.
112 ///
113 /// \returns a success error code if the data was successfully written,
114 /// otherwise returns an appropriate error code.
116
117 /// Efficiently reads all data from \p Ref, and writes it to this stream.
118 /// This operation will not invoke any copies of the source data, regardless
119 /// of the source stream's implementation.
120 ///
121 /// \returns a success error code if the data was successfully written,
122 /// otherwise returns an appropriate error code.
124
125 /// Efficiently reads \p Size bytes from \p Ref, and writes it to this stream.
126 /// This operation will not invoke any copies of the source data, regardless
127 /// of the source stream's implementation.
128 ///
129 /// \returns a success error code if the data was successfully written,
130 /// otherwise returns an appropriate error code.
132
133 /// Writes the object \p Obj to the underlying stream, as if by using memcpy.
134 /// It is up to the caller to ensure that type of \p Obj can be safely copied
135 /// in this fashion, as no checks are made to ensure that this is safe.
136 ///
137 /// \returns a success error code if the data was successfully written,
138 /// otherwise returns an appropriate error code.
139 template <typename T> Error writeObject(const T &Obj) {
140 static_assert(!std::is_pointer<T>::value,
141 "writeObject should not be used with pointers, to write "
142 "the pointed-to value dereference the pointer before calling "
143 "writeObject");
144 return writeBytes(
145 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(&Obj), sizeof(T)));
146 }
147
148 /// Writes an array of objects of type T to the underlying stream, as if by
149 /// using memcpy. It is up to the caller to ensure that type of \p Obj can
150 /// be safely copied in this fashion, as no checks are made to ensure that
151 /// this is safe.
152 ///
153 /// \returns a success error code if the data was successfully written,
154 /// otherwise returns an appropriate error code.
155 template <typename T> Error writeArray(ArrayRef<T> Array) {
156 if (Array.empty())
157 return Error::success();
158 if (Array.size() > UINT32_MAX / sizeof(T))
161
162 return writeBytes(
163 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Array.data()),
164 Array.size() * sizeof(T)));
165 }
166
167 /// Writes all data from the array \p Array to the underlying stream.
168 ///
169 /// \returns a success error code if the data was successfully written,
170 /// otherwise returns an appropriate error code.
171 template <typename T, typename U>
173 return writeStreamRef(Array.getUnderlyingStream());
174 }
175
176 /// Writes all elements from the array \p Array to the underlying stream.
177 ///
178 /// \returns a success error code if the data was successfully written,
179 /// otherwise returns an appropriate error code.
180 template <typename T> Error writeArray(FixedStreamArray<T> Array) {
181 return writeStreamRef(Array.getUnderlyingStream());
182 }
183
184 /// Splits the Writer into two Writers at a given offset.
185 LLVM_ABI std::pair<BinaryStreamWriter, BinaryStreamWriter>
186 split(uint64_t Off) const;
187
189 uint64_t getOffset() const { return Offset; }
190 uint64_t getLength() const { return Stream.getLength(); }
191 uint64_t bytesRemaining() const { return getLength() - getOffset(); }
193
194protected:
197};
198
199} // end namespace llvm
200
201#endif // LLVM_SUPPORT_BINARYSTREAMWRITER_H
uint64_t uint64_t
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Lightweight arrays that are backed by an arbitrary BinaryStream.
#define LLVM_ABI
Definition Compiler.h:211
#define T
This file contains library features backported from future STL versions.
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
BinaryStreamRef is to BinaryStream what ArrayRef is to an Array.
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.
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 Error writeInt128(const APSInt &Value)
Write Value as a 128 bit integer (possibly truncated).
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.
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.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
LLVM Value Representation.
Definition Value.h:75
A BinaryStream which can be read from as well as written to.
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition Endian.h:82
This is an optimization pass for GlobalISel generic memory operations.
@ Off
Use window algorithm after SMS algorithm fails.
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ Other
Any other memory.
Definition ModRef.h:68
endianness
Definition bit.h:71
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39