• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 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 <filesystem>
17 #include <string>
18 #include <string_view>
19 #include <variant>
20 
21 #include "pw_status/status.h"
22 #include "pw_stream/std_file_stream.h"
23 #include "pw_transfer/handler.h"
24 
25 namespace pw::transfer {
26 
27 // The AtomicFileTransferHandler is intended to be used as a transfer
28 // handler for files. It ensures that the target file of the transfer is always
29 // in a correct state. In particular, the transfer is first done to a temporary
30 // file and once complete, the original targeted file is updated.
31 class AtomicFileTransferHandler : public ReadWriteHandler {
32  public:
AtomicFileTransferHandler(uint32_t resource_id,std::string_view file_path)33   AtomicFileTransferHandler(uint32_t resource_id, std::string_view file_path)
34       : ReadWriteHandler(resource_id), path_(file_path) {}
35 
36   AtomicFileTransferHandler(const AtomicFileTransferHandler& rhs) = delete;
37   AtomicFileTransferHandler& operator=(const AtomicFileTransferHandler&) =
38       delete;
39   ~AtomicFileTransferHandler() override = default;
40 
41   // Function called prior to initializing a read transfer.
42   Status PrepareRead() override;
43   // Function called after a read transfer is done.
44   // Status indicates whether transfer was done successfully.
45   void FinalizeRead(Status) override;
46   // Function called prior to initializing a write transfer.
47   Status PrepareWrite() override;
48   // Function called after a write transfer is done.
49   // Status indicates whether transfer was done successfully.
50   Status FinalizeWrite(Status) override;
51 
52  private:
53   std::string path_;
54   std::variant<std::monostate, stream::StdFileReader, stream::StdFileWriter>
55       stream_{};
56 };
57 
58 }  // namespace pw::transfer
59