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 <span>
18 #include <type_traits>
19 
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 // std::span of bytes and returns a Status.
38 class Output {
39  public:
40   StatusWithSize Write(std::span<const std::byte> data) {
41     return DoWrite(data);
42   }
43 
44   // Convenience wrapper for writing data from a pointer and length.
45   StatusWithSize Write(const void* data, size_t size_bytes) {
46     return Write(std::span<const std::byte>(static_cast<const std::byte*>(data),
47                                             size_bytes));
48   }
49 
50  protected:
51   ~Output() = default;
52 
53  private:
54   virtual StatusWithSize DoWrite(std::span<const std::byte> data) = 0;
55 };
56 
57 class Input {
58  public:
59   StatusWithSize Read(std::span<std::byte> data) { return DoRead(data); }
60 
61   // Convenience wrapper for reading data from a pointer and length.
62   StatusWithSize Read(void* data, size_t size_bytes) {
63     return Read(
64         std::span<std::byte>(static_cast<std::byte*>(data), size_bytes));
65   }
66 
67  protected:
68   ~Input() = default;
69 
70  private:
71   virtual StatusWithSize DoRead(std::span<std::byte> data) = 0;
72 };
73 
74 // Output adapter that calls a free function.
75 class OutputToFunction final : public Output {
76  public:
77   OutputToFunction(StatusWithSize (*function)(std::span<const std::byte>))
78       : function_(function) {}
79 
80  private:
81   StatusWithSize DoWrite(std::span<const std::byte> data) override {
82     return function_(data);
83   }
84 
85   StatusWithSize (*function_)(std::span<const std::byte>);
86 };
87 
88 }  // namespace pw
89