Debian Codegraph @

Source/Core/Common/SpanUtils.h

raw symbols SCIP
1 // Copyright 2024 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #pragma once
5
6 #include <algorithm>
7 #include <cstddef>
8 #include <cstring>
9 #include <span>
10
11 #include "Common/CommonTypes.h"
12
13 namespace Common
14 {
15
16 // Like std::span::subspan, except undefined behavior is replaced with returning a 0-length span.
17 template <class T>
18 [[nodiscard]] constexpr std::span<T> SafeSubspan(std::span<T> span, size_t offset,
19 size_t count = std::dynamic_extent)
20 {
21 if (count == std::dynamic_extent || offset > span.size())
22 return span.subspan(std::min(offset, span.size()));
23 else
24 return span.subspan(offset, std::min(count, span.size() - offset));
25 }
26
27 // Default-constructs an object of type T, then copies data into it from the specified offset in
28 // the specified span. Out-of-bounds reads will be skipped, meaning that specifying a too large
29 // offset results in the object partially or entirely remaining default constructed.
30 template <class T>
31 [[nodiscard]] T SafeSpanRead(std::span<const u8> span, size_t offset)
32 {
33 static_assert(std::is_trivially_copyable<T>());
34
35 const std::span<const u8> subspan = SafeSubspan(span, offset);
36 T result{};
37 std::memcpy(&result, subspan.data(), std::min(subspan.size(), sizeof(result)));
38 return result;
39 }
40
41 } // namespace Common