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
26
27namespace cuttlefish {
28
29Result<void, int> ReadExact(Reader&, char* buf, size_t size);
30
31template <typename T>
33 T data;
34 char* const data_char = reinterpret_cast<char*>(&data);
35 CF_EXPECT(ReadExact(reader, data_char, sizeof(data)));
36 return data;
37}
38
39Result<void, int> PReadExact(const ReaderSeeker&, char* buf, size_t size,
40 uint64_t offset);
41
42// Similar to ReadExact, but returns false instead of an error if zero bytes are
43// read because of EOF. A partial read is still an error.
44Result<bool, int> ReadExactOrEof(Reader&, char* buf, size_t size);
45
46template <typename T>
47Result<T, int> PReadExactBinary(const ReaderSeeker& reader, uint64_t offset) {
48 T data;
49 char* const data_char = reinterpret_cast<char*>(&data);
50 CF_EXPECT(PReadExact(reader, data_char, sizeof(data), offset));
51 return data;
52}
53
54template <typename T>
56 T data;
57 char* data_char = reinterpret_cast<char*>(&data);
58 if (!CF_EXPECT(ReadExactOrEof(reader, data_char, sizeof(data)))) {
59 return std::nullopt;
60 }
61 return data;
62}
63
64} // namespace cuttlefish
Definition: reader_seeker.h:29
Definition: reader.h:25
#define CF_EXPECT(...)
Definition: expect.h:184
uint32_t size
Definition: io.h:2
char data[Size]
Definition: incremental_server.cpp:1
Definition: alloc_driver.h:21
Result< bool, int > ReadExactOrEof(Reader &reader, char *buf, size_t size)
Definition: read_exact.cc:51
Result< T, int > PReadExactBinary(const ReaderSeeker &reader, uint64_t offset)
Definition: read_exact.h:47
Result< void, int > PReadExact(const ReaderSeeker &reader, char *buf, size_t size, uint64_t offset)
Definition: read_exact.cc:39
ssize_t ReadExact(SharedFD fd, char *buf, size_t size)
Definition: shared_buf.cc:45
Result< std::optional< T >, int > ReadExactBinaryOrEof(Reader &reader)
Definition: read_exact.h:55
ssize_t ReadExactBinary(SharedFD fd, T *binary_data)
Definition: shared_buf.h:81
tl::expected< T, StackTraceError< E > > Result
Definition: result_type.h:30