xref: /aosp_15_r20/external/pigweed/pw_kvs/public/pw_kvs/io.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2020 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15 
16 #include <cstddef>
17 #include <type_traits>
18 
19 #include "pw_span/span.h"
20 #include "pw_status/status_with_size.h"
21 
22 namespace pw {
23 namespace internal {
24 
25 template <typename T>
26 struct FunctionTraits;
27 
28 template <typename T, typename ReturnType, typename... Args>
29 struct FunctionTraits<ReturnType (T::*)(Args...)> {
30   using Class = T;
31   using Return = ReturnType;
32 };
33 
34 }  // namespace internal
35 
36 // Writes bytes to an unspecified output. Provides a Write function that takes a
37 // span of bytes and returns a Status.
38 class Output {
39  public:
40   StatusWithSize Write(span<const std::byte> data) { return DoWrite(data); }
41 
42   // Convenience wrapper for writing data from a pointer and length.
43   StatusWithSize Write(const void* data, size_t size_bytes) {
44     return Write(
45         span<const std::byte>(static_cast<const std::byte*>(data), size_bytes));
46   }
47 
48  protected:
49   ~Output() = default;
50 
51  private:
52   virtual StatusWithSize DoWrite(span<const std::byte> data) = 0;
53 };
54 
55 class Input {
56  public:
57   StatusWithSize Read(span<std::byte> data) { return DoRead(data); }
58 
59   // Convenience wrapper for reading data from a pointer and length.
60   StatusWithSize Read(void* data, size_t size_bytes) {
61     return Read(span<std::byte>(static_cast<std::byte*>(data), size_bytes));
62   }
63 
64  protected:
65   ~Input() = default;
66 
67  private:
68   virtual StatusWithSize DoRead(span<std::byte> data) = 0;
69 };
70 
71 // Output adapter that calls a free function.
72 class OutputToFunction final : public Output {
73  public:
74   OutputToFunction(StatusWithSize (*function)(span<const std::byte>))
75       : function_(function) {}
76 
77  private:
78   StatusWithSize DoWrite(span<const std::byte> data) override {
79     return function_(data);
80   }
81 
82   StatusWithSize (*function_)(span<const std::byte>);
83 };
84 
85 }  // namespace pw
86