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
15 #include "pw_stream/std_file_stream.h"
16
17 namespace pw::stream {
18 namespace {
19
WhenceToSeekDir(Stream::Whence whence)20 std::ios::seekdir WhenceToSeekDir(Stream::Whence whence) {
21 switch (whence) {
22 case Stream::Whence::kBeginning:
23 return std::ios::beg;
24 case Stream::Whence::kCurrent:
25 return std::ios::cur;
26 case Stream::Whence::kEnd:
27 return std::ios::end;
28 }
29 }
30
31 } // namespace
32
DoRead(ByteSpan dest)33 StatusWithSize StdFileReader::DoRead(ByteSpan dest) {
34 stream_.peek(); // Peek to set EOF if at the end of the file.
35 if (stream_.eof()) {
36 return StatusWithSize::OutOfRange();
37 }
38
39 stream_.read(reinterpret_cast<char*>(dest.data()), dest.size());
40 if (stream_.bad()) {
41 return StatusWithSize::Unknown();
42 }
43
44 return StatusWithSize(stream_.gcount());
45 }
46
DoSeek(ptrdiff_t offset,Whence origin)47 Status StdFileReader::DoSeek(ptrdiff_t offset, Whence origin) {
48 if (!stream_.seekg(offset, WhenceToSeekDir(origin))) {
49 return Status::Unknown();
50 }
51 return OkStatus();
52 }
53
DoWrite(ConstByteSpan data)54 Status StdFileWriter::DoWrite(ConstByteSpan data) {
55 if (stream_.eof()) {
56 return Status::OutOfRange();
57 }
58
59 if (stream_.write(reinterpret_cast<const char*>(data.data()), data.size())) {
60 return OkStatus();
61 }
62
63 return Status::Unknown();
64 }
65
DoSeek(ptrdiff_t offset,Whence origin)66 Status StdFileWriter::DoSeek(ptrdiff_t offset, Whence origin) {
67 if (!stream_.seekp(offset, WhenceToSeekDir(origin))) {
68 return Status::Unknown();
69 }
70 return OkStatus();
71 }
72
73 } // namespace pw::stream
74