xref: /aosp_15_r20/external/pigweed/pw_sys_io_stdio/sys_io.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2019 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_sys_io/sys_io.h"
16 
17 #include <cstdio>
18 
19 namespace pw::sys_io {
20 
ReadByte(std::byte * dest)21 Status ReadByte(std::byte* dest) {
22   if (dest == nullptr) {
23     return Status::FailedPrecondition();
24   }
25 
26   int value = std::getchar();
27   if (value == EOF) {
28     return Status::ResourceExhausted();
29   }
30   *dest = static_cast<std::byte>(value);
31   return OkStatus();
32 }
33 
TryReadByte(std::byte *)34 Status TryReadByte(std::byte*) {
35   // TryReadByte() is not (yet) supported on hosts.
36   return Status::Unimplemented();
37 }
38 
WriteByte(std::byte b)39 Status WriteByte(std::byte b) {
40   if (std::putchar(static_cast<char>(b)) == EOF) {
41     return Status::Internal();
42   }
43   return OkStatus();
44 }
45 
WriteLine(std::string_view s)46 StatusWithSize WriteLine(std::string_view s) {
47   size_t chars_written = 0;
48   StatusWithSize size_result = WriteBytes(as_bytes(span(s)));
49   if (!size_result.ok()) {
50     return size_result;
51   }
52   chars_written += size_result.size();
53 
54   // Write trailing newline character.
55   Status result = WriteByte(static_cast<std::byte>('\n'));
56   if (result.ok()) {
57     chars_written++;
58   }
59 
60   return StatusWithSize(result, chars_written);
61 }
62 
63 }  // namespace pw::sys_io
64