00001 // Copyright 2017 The Abseil Authors. 00002 // 00003 // Licensed under the Apache License, Version 2.0 (the "License"); 00004 // you may not use this file except in compliance with the License. 00005 // You may obtain a copy of the License at 00006 // 00007 // https://www.apache.org/licenses/LICENSE-2.0 00008 // 00009 // Unless required by applicable law or agreed to in writing, software 00010 // distributed under the License is distributed on an "AS IS" BASIS, 00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00012 // See the License for the specific language governing permissions and 00013 // limitations under the License. 00014 00015 #include "absl/strings/internal/str_format/output.h" 00016 00017 #include <errno.h> 00018 #include <cstring> 00019 00020 namespace absl { 00021 namespace str_format_internal { 00022 00023 namespace { 00024 struct ClearErrnoGuard { 00025 ClearErrnoGuard() : old_value(errno) { errno = 0; } 00026 ~ClearErrnoGuard() { 00027 if (!errno) errno = old_value; 00028 } 00029 int old_value; 00030 }; 00031 } // namespace 00032 00033 void BufferRawSink::Write(string_view v) { 00034 size_t to_write = std::min(v.size(), size_); 00035 std::memcpy(buffer_, v.data(), to_write); 00036 buffer_ += to_write; 00037 size_ -= to_write; 00038 total_written_ += v.size(); 00039 } 00040 00041 void FILERawSink::Write(string_view v) { 00042 while (!v.empty() && !error_) { 00043 // Reset errno to zero in case the libc implementation doesn't set errno 00044 // when a failure occurs. 00045 ClearErrnoGuard guard; 00046 00047 if (size_t result = std::fwrite(v.data(), 1, v.size(), output_)) { 00048 // Some progress was made. 00049 count_ += result; 00050 v.remove_prefix(result); 00051 } else { 00052 if (errno == EINTR) { 00053 continue; 00054 } else if (errno) { 00055 error_ = errno; 00056 } else if (std::ferror(output_)) { 00057 // Non-POSIX compliant libc implementations may not set errno, so we 00058 // have check the streams error indicator. 00059 error_ = EBADF; 00060 } else { 00061 // We're likely on a non-POSIX system that encountered EINTR but had no 00062 // way of reporting it. 00063 continue; 00064 } 00065 } 00066 } 00067 } 00068 00069 } // namespace str_format_internal 00070 } // namespace absl