output.cc 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of 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,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "absl/strings/internal/str_format/output.h"
  15. #include <errno.h>
  16. #include <cstring>
  17. namespace absl {
  18. ABSL_NAMESPACE_BEGIN
  19. namespace str_format_internal {
  20. namespace {
  21. struct ClearErrnoGuard {
  22. ClearErrnoGuard() : old_value(errno) { errno = 0; }
  23. ~ClearErrnoGuard() {
  24. if (!errno) errno = old_value;
  25. }
  26. int old_value;
  27. };
  28. } // namespace
  29. void BufferRawSink::Write(string_view v) {
  30. size_t to_write = std::min(v.size(), size_);
  31. std::memcpy(buffer_, v.data(), to_write);
  32. buffer_ += to_write;
  33. size_ -= to_write;
  34. total_written_ += v.size();
  35. }
  36. void FILERawSink::Write(string_view v) {
  37. while (!v.empty() && !error_) {
  38. // Reset errno to zero in case the libc implementation doesn't set errno
  39. // when a failure occurs.
  40. ClearErrnoGuard guard;
  41. if (size_t result = std::fwrite(v.data(), 1, v.size(), output_)) {
  42. // Some progress was made.
  43. count_ += result;
  44. v.remove_prefix(result);
  45. } else {
  46. if (errno == EINTR) {
  47. continue;
  48. } else if (errno) {
  49. error_ = errno;
  50. } else if (std::ferror(output_)) {
  51. // Non-POSIX compliant libc implementations may not set errno, so we
  52. // have check the streams error indicator.
  53. error_ = EBADF;
  54. } else {
  55. // We're likely on a non-POSIX system that encountered EINTR but had no
  56. // way of reporting it.
  57. continue;
  58. }
  59. }
  60. }
  61. }
  62. } // namespace str_format_internal
  63. ABSL_NAMESPACE_END
  64. } // namespace absl