Cursor.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright 2014-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <folly/io/Cursor.h>
  17. #include <cstdio>
  18. #include <folly/ScopeGuard.h>
  19. namespace folly {
  20. namespace io {
  21. void Appender::printf(const char* fmt, ...) {
  22. va_list ap;
  23. va_start(ap, fmt);
  24. vprintf(fmt, ap);
  25. va_end(ap);
  26. }
  27. void Appender::vprintf(const char* fmt, va_list ap) {
  28. // Make a copy of ap in case we need to retry.
  29. // We use ap on the first attempt, so it always gets advanced
  30. // passed the used arguments. We'll only use apCopy if we need to retry.
  31. va_list apCopy;
  32. va_copy(apCopy, ap);
  33. SCOPE_EXIT {
  34. va_end(apCopy);
  35. };
  36. // First try writing into our available data space.
  37. int ret =
  38. vsnprintf(reinterpret_cast<char*>(writableData()), length(), fmt, ap);
  39. if (ret < 0) {
  40. throw std::runtime_error("error formatting printf() data");
  41. }
  42. auto len = size_t(ret);
  43. // vsnprintf() returns the number of characters that would be printed,
  44. // not including the terminating nul.
  45. if (len < length()) {
  46. // All of the data was successfully written.
  47. append(len);
  48. return;
  49. }
  50. // There wasn't enough room for the data.
  51. // Allocate more room, and then retry.
  52. ensure(len + 1);
  53. ret =
  54. vsnprintf(reinterpret_cast<char*>(writableData()), length(), fmt, apCopy);
  55. if (ret < 0) {
  56. throw std::runtime_error("error formatting printf() data");
  57. }
  58. len = size_t(ret);
  59. if (len >= length()) {
  60. // This shouldn't ever happen.
  61. throw std::runtime_error(
  62. "unexpectedly out of buffer space on second "
  63. "vsnprintf() attmept");
  64. }
  65. append(len);
  66. }
  67. } // namespace io
  68. } // namespace folly