append_truncated.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2022 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. #ifndef ABSL_LOG_INTERNAL_APPEND_TRUNCATED_H_
  15. #define ABSL_LOG_INTERNAL_APPEND_TRUNCATED_H_
  16. #include <cstddef>
  17. #include <cstring>
  18. #include "absl/base/config.h"
  19. #include "absl/strings/string_view.h"
  20. #include "absl/types/span.h"
  21. namespace absl {
  22. ABSL_NAMESPACE_BEGIN
  23. namespace log_internal {
  24. // Copies into `dst` as many bytes of `src` as will fit, then truncates the
  25. // copied bytes from the front of `dst` and returns the number of bytes written.
  26. inline size_t AppendTruncated(absl::string_view src, absl::Span<char> &dst) {
  27. if (src.size() > dst.size()) src = src.substr(0, dst.size());
  28. memcpy(dst.data(), src.data(), src.size());
  29. dst.remove_prefix(src.size());
  30. return src.size();
  31. }
  32. // Likewise, but `n` copies of `c`.
  33. inline size_t AppendTruncated(char c, size_t n, absl::Span<char> &dst) {
  34. if (n > dst.size()) n = dst.size();
  35. memset(dst.data(), c, n);
  36. dst.remove_prefix(n);
  37. return n;
  38. }
  39. } // namespace log_internal
  40. ABSL_NAMESPACE_END
  41. } // namespace absl
  42. #endif // ABSL_LOG_INTERNAL_APPEND_TRUNCATED_H_