• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <algorithm>
17 #include <cstddef>
18 #include <cstring>
19 #include <initializer_list>
20 #include <span>
21 #include <utility>
22 
23 #include "pw_bytes/span.h"
24 #include "pw_kvs/io.h"
25 #include "pw_status/status_with_size.h"
26 
27 namespace pw {
28 
29 // Returns the value rounded down to the nearest multiple of alignment.
AlignDown(size_t value,size_t alignment)30 constexpr size_t AlignDown(size_t value, size_t alignment) {
31   return (value / alignment) * alignment;
32 }
33 
34 // Returns the value rounded up to the nearest multiple of alignment.
AlignUp(size_t value,size_t alignment)35 constexpr size_t AlignUp(size_t value, size_t alignment) {
36   return (value + alignment - 1) / alignment * alignment;
37 }
38 
39 // Returns the number of padding bytes required to align the provided length.
Padding(size_t length,size_t alignment)40 constexpr size_t Padding(size_t length, size_t alignment) {
41   return AlignUp(length, alignment) - length;
42 }
43 
44 // Class for managing aligned writes. Stores data in an intermediate buffer and
45 // calls an output function with aligned data as the buffer becomes full. Any
46 // bytes remaining in the buffer are written to the output when Flush() is
47 // called or the AlignedWriter goes out of scope.
48 class AlignedWriter {
49  public:
AlignedWriter(std::span<std::byte> buffer,size_t alignment_bytes,Output & writer)50   AlignedWriter(std::span<std::byte> buffer,
51                 size_t alignment_bytes,
52                 Output& writer)
53       : buffer_(buffer.data()),
54         write_size_(AlignDown(buffer.size(), alignment_bytes)),
55         alignment_bytes_(alignment_bytes),
56         output_(writer),
57         bytes_written_(0),
58         bytes_in_buffer_(0) {
59     // TODO(hepler): Add DCHECK to ensure that buffer.size() >= alignment_bytes.
60   }
61 
~AlignedWriter()62   ~AlignedWriter() {
63     Flush().IgnoreError();  // TODO(pwbug/387): Handle Status properly
64   }
65 
66   // Writes bytes to the AlignedWriter. The output may be called if the internal
67   // buffer is filled.
68   //
69   // The size in the return value is the total number of bytes for which a write
70   // has been attempted since Flush or Reset. The size is set for both
71   // successful and failed Write calls. On a failed write call, knowing the
72   // bytes attempted may be important when working with flash memory, since it
73   // can only be written once between erases.
74   StatusWithSize Write(std::span<const std::byte> data);
75 
Write(const void * data,size_t size)76   StatusWithSize Write(const void* data, size_t size) {
77     return Write(
78         std::span<const std::byte>(static_cast<const std::byte*>(data), size));
79   }
80 
81   // Reads size bytes from the input and writes them to the output.
82   StatusWithSize Write(Input& input, size_t size);
83 
84   // Flush and reset the AlignedWriter. Any remaining bytes in the buffer are
85   // zero-padded to an alignment boundary and written to the output. Flush is
86   // automatically called when the AlignedWriter goes out of scope.
87   StatusWithSize Flush();
88 
89  private:
90   static constexpr std::byte kPadByte = static_cast<std::byte>(0);
91 
92   StatusWithSize AddBytesToBuffer(size_t bytes_added);
93 
94   std::byte* const buffer_;
95   const size_t write_size_;
96   const size_t alignment_bytes_;
97 
98   Output& output_;
99   size_t bytes_written_;
100   size_t bytes_in_buffer_;
101 };
102 
103 // Declares an AlignedWriter with a built-in buffer.
104 template <size_t kBufferSize>
105 class AlignedWriterBuffer : public AlignedWriter {
106  public:
107   template <typename... Args>
AlignedWriterBuffer(Args &&...aligned_writer_args)108   AlignedWriterBuffer(Args&&... aligned_writer_args)
109       : AlignedWriter(buffer_, std::forward<Args>(aligned_writer_args)...) {}
110 
111  private:
112   std::byte buffer_[kBufferSize];
113 };
114 
115 // Writes data from multiple buffers using an AlignedWriter.
116 template <size_t kBufferSize>
AlignedWrite(Output & output,size_t alignment_bytes,std::span<const std::span<const std::byte>> data)117 StatusWithSize AlignedWrite(Output& output,
118                             size_t alignment_bytes,
119                             std::span<const std::span<const std::byte>> data) {
120   // TODO: This should convert to PW_CHECK once that is available for use in
121   // host tests.
122   if (alignment_bytes > kBufferSize) {
123     return StatusWithSize::Internal();
124   }
125 
126   AlignedWriterBuffer<kBufferSize> buffer(alignment_bytes, output);
127 
128   for (const std::span<const std::byte>& chunk : data) {
129     StatusWithSize result = buffer.Write(chunk);
130     if (!result.ok()) {
131       return result;
132     }
133   }
134 
135   return buffer.Flush();
136 }
137 
138 // Calls AlignedWrite with an initializer list.
139 template <size_t kBufferSize>
AlignedWrite(Output & output,size_t alignment_bytes,std::initializer_list<std::span<const std::byte>> data)140 StatusWithSize AlignedWrite(
141     Output& output,
142     size_t alignment_bytes,
143     std::initializer_list<std::span<const std::byte>> data) {
144   return AlignedWrite<kBufferSize>(
145       output,
146       alignment_bytes,
147       std::span<const ConstByteSpan>(data.begin(), data.size()));
148 }
149 
150 }  // namespace pw
151