KBufferBuilder.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <AK/PrintfImplementation.h>
  2. #include <AK/StdLibExtras.h>
  3. #include <KBufferBuilder.h>
  4. #include <stdarg.h>
  5. inline bool KBufferBuilder::can_append(size_t size) const
  6. {
  7. bool has_space = ((m_size + size) < m_buffer.size());
  8. ASSERT(has_space);
  9. return has_space;
  10. }
  11. KBuffer KBufferBuilder::build()
  12. {
  13. m_buffer.set_size(m_size);
  14. return m_buffer;
  15. }
  16. KBufferBuilder::KBufferBuilder()
  17. : m_buffer(KBuffer::create_with_size(4 * MB, Region::Access::Read | Region::Access::Write))
  18. {
  19. }
  20. void KBufferBuilder::append(const StringView& str)
  21. {
  22. if (str.is_empty())
  23. return;
  24. if (!can_append(str.length()))
  25. return;
  26. memcpy(insertion_ptr(), str.characters_without_null_termination(), str.length());
  27. m_size += str.length();
  28. }
  29. void KBufferBuilder::append(const char* characters, int length)
  30. {
  31. if (!length)
  32. return;
  33. if (!can_append(length))
  34. return;
  35. memcpy(insertion_ptr() + m_size, characters, length);
  36. m_size += length;
  37. }
  38. void KBufferBuilder::append(char ch)
  39. {
  40. if (!can_append(1))
  41. return;
  42. insertion_ptr()[0] = ch;
  43. m_size += 1;
  44. }
  45. void KBufferBuilder::appendvf(const char* fmt, va_list ap)
  46. {
  47. printf_internal([this](char*&, char ch) {
  48. append(ch);
  49. },
  50. nullptr, fmt, ap);
  51. }
  52. void KBufferBuilder::appendf(const char* fmt, ...)
  53. {
  54. va_list ap;
  55. va_start(ap, fmt);
  56. appendvf(fmt, ap);
  57. va_end(ap);
  58. }