• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 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 <fstream>
17 
18 #include "pw_stream/stream.h"
19 
20 namespace pw::stream {
21 
22 // Wraps an std::ifstream with the Reader interface.
23 class StdFileReader final : public stream::SeekableReader {
24  public:
StdFileReader(const char * path)25   StdFileReader(const char* path) : stream_(path, std::ios::binary) {}
26 
Close()27   void Close() { stream_.close(); }
28 
29  private:
30   StatusWithSize DoRead(ByteSpan dest) override;
31   Status DoSeek(ptrdiff_t offset, Whence origin) override;
32   size_t DoTell() override;
33   size_t ConservativeLimit(LimitType limit) const override;
34 
35   std::ifstream stream_;
36 };
37 
38 // Wraps an std::ofstream with the Writer interface.
39 class StdFileWriter final : public stream::SeekableWriter {
40  public:
StdFileWriter(const char * path)41   StdFileWriter(const char* path)
42       : stream_(path, std::ios::binary | std::ios::trunc) {}
43 
Close()44   void Close() { stream_.close(); }
45 
46  private:
47   Status DoWrite(ConstByteSpan data) override;
48   Status DoSeek(ptrdiff_t offset, Whence origin) override;
49   size_t DoTell() override;
50 
51   std::ofstream stream_;
52 };
53 
54 }  // namespace pw::stream
55