blob: 7c6d6f17b1516d8365b66abb94a176904483b0c3 [file] [log] [blame]
Steven Morelandf183fdd2020-10-27 00:12:12 +00001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Steven Morelandf183fdd2020-10-27 00:12:12 +000017#include <stddef.h>
Andrei Homescu7c0b79f2022-06-30 02:00:46 +000018#include <sys/uio.h>
Frederick Mayledc07cf82022-05-26 20:30:12 +000019#include <cstdint>
20#include <optional>
Steven Morelandf183fdd2020-10-27 00:12:12 +000021
Yifan Hong18ac9472021-09-09 19:55:38 -070022#include <log/log.h>
Andrei Homescuc24c8792022-04-19 00:24:51 +000023#include <utils/Errors.h>
Yifan Hong18ac9472021-09-09 19:55:38 -070024
25#define TEST_AND_RETURN(value, expr) \
26 do { \
27 if (!(expr)) { \
28 ALOGE("Failed to call: %s", #expr); \
29 return value; \
30 } \
31 } while (0)
Yifan Hongb675ffe2021-08-05 16:37:17 -070032
Steven Morelandf183fdd2020-10-27 00:12:12 +000033namespace android {
34
35// avoid optimizations
36void zeroMemory(uint8_t* data, size_t size);
37
Frederick Mayledc07cf82022-05-26 20:30:12 +000038// View of contiguous sequence. Similar to std::span.
39template <typename T>
40struct Span {
41 T* data = nullptr;
42 size_t size = 0;
43
44 size_t byteSize() { return size * sizeof(T); }
45
46 iovec toIovec() { return {const_cast<std::remove_const_t<T>*>(data), byteSize()}; }
47
48 // Truncates `this` to a length of `offset` and returns a span with the
49 // remainder.
50 //
51 // Aborts if offset > size.
52 Span<T> splitOff(size_t offset) {
53 LOG_ALWAYS_FATAL_IF(offset > size);
54 Span<T> rest = {data + offset, size - offset};
55 size = offset;
56 return rest;
57 }
Frederick Mayle69a0c992022-05-26 20:38:39 +000058
59 // Returns nullopt if the byte size of `this` isn't evenly divisible by sizeof(U).
60 template <typename U>
61 std::optional<Span<U>> reinterpret() const {
62 // Only allow casting from bytes for simplicity.
63 static_assert(std::is_same_v<std::remove_const_t<T>, uint8_t>);
64 if (size % sizeof(U) != 0) {
65 return std::nullopt;
66 }
67 return Span<U>{reinterpret_cast<U*>(data), size / sizeof(U)};
68 }
Frederick Mayledc07cf82022-05-26 20:30:12 +000069};
70
Steven Morelandf183fdd2020-10-27 00:12:12 +000071} // namespace android