Android-cuttlefish cvd tool
read_exact.h
Go to the documentation of this file.
1//
2// Copyright (C) 2026 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#pragma once
17
18#include <stdint.h>
19
20#include <optional>
21
22#include "cuttlefish/io/io.h"
25
26namespace cuttlefish {
27
28Result<void> ReadExact(Reader&, char* buf, size_t size);
29
30template <typename T>
32 T data;
33 char* const data_char = reinterpret_cast<char*>(&data);
34 CF_EXPECT(ReadExact(reader, data_char, sizeof(data)));
35 return data;
36}
37
38Result<void> PReadExact(const ReaderSeeker&, char* buf, size_t size,
39 uint64_t offset);
40
41// Similar to ReadExact, but returns false instead of an error if zero bytes are
42// read because of EOF. A partial read is still an error.
43Result<bool> ReadExactOrEof(Reader&, char* buf, size_t size);
44
45template <typename T>
46Result<T> PReadExactBinary(const ReaderSeeker& reader, uint64_t offset) {
47 T data;
48 char* const data_char = reinterpret_cast<char*>(&data);
49 CF_EXPECT(PReadExact(reader, data_char, sizeof(data), offset));
50 return data;
51}
52
53template <typename T>
55 T data;
56 char* data_char = reinterpret_cast<char*>(&data);
57 if (!CF_EXPECT(ReadExactOrEof(reader, data_char, sizeof(data)))) {
58 return std::nullopt;
59 }
60 return data;
61}
62
63} // namespace cuttlefish
Definition: io.h:60
Definition: io.h:29
#define data
Definition: dict.c:56
#define CF_EXPECT(...)
Definition: expect.h:149
uint32_t size
Definition: io.h:2
Definition: alloc_driver.h:20
Result< bool > ReadExactOrEof(Reader &reader, char *buf, size_t size)
Definition: read_exact.cc:49
ssize_t ReadExact(SharedFD fd, char *buf, size_t size)
Definition: shared_buf.cc:44
tl::expected< T, StackTraceError > Result
Definition: result_type.h:30
ssize_t ReadExactBinary(SharedFD fd, T *binary_data)
Definition: shared_buf.h:80
Result< T > PReadExactBinary(const ReaderSeeker &reader, uint64_t offset)
Definition: read_exact.h:46
Result< void > PReadExact(const ReaderSeeker &reader, char *buf, size_t size, uint64_t offset)
Definition: read_exact.cc:37
Result< std::optional< T > > ReadExactBinaryOrEof(Reader &reader)
Definition: read_exact.h:54