Serenity Operating System
at hosted 96 lines 2.8 kB view raw
1/* 2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright notice, this 9 * list of conditions and the following disclaimer. 10 * 11 * 2. Redistributions in binary form must reproduce the above copyright notice, 12 * this list of conditions and the following disclaimer in the documentation 13 * and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 */ 26 27#include <AK/PrintfImplementation.h> 28#include <AK/StdLibExtras.h> 29#include <KBufferBuilder.h> 30#include <stdarg.h> 31 32namespace Kernel { 33 34inline bool KBufferBuilder::can_append(size_t size) const 35{ 36 bool has_space = ((m_size + size) < m_buffer.size()); 37 ASSERT(has_space); 38 return has_space; 39} 40 41KBuffer KBufferBuilder::build() 42{ 43 m_buffer.set_size(m_size); 44 return m_buffer; 45} 46 47KBufferBuilder::KBufferBuilder() 48 : m_buffer(KBuffer::create_with_size(4 * MB, Region::Access::Read | Region::Access::Write)) 49{ 50} 51 52void KBufferBuilder::append(const StringView& str) 53{ 54 if (str.is_empty()) 55 return; 56 if (!can_append(str.length())) 57 return; 58 memcpy(insertion_ptr(), str.characters_without_null_termination(), str.length()); 59 m_size += str.length(); 60} 61 62void KBufferBuilder::append(const char* characters, int length) 63{ 64 if (!length) 65 return; 66 if (!can_append(length)) 67 return; 68 memcpy(insertion_ptr() + m_size, characters, length); 69 m_size += length; 70} 71 72void KBufferBuilder::append(char ch) 73{ 74 if (!can_append(1)) 75 return; 76 insertion_ptr()[0] = ch; 77 m_size += 1; 78} 79 80void KBufferBuilder::appendvf(const char* fmt, va_list ap) 81{ 82 printf_internal([this](char*&, char ch) { 83 append(ch); 84 }, 85 nullptr, fmt, ap); 86} 87 88void KBufferBuilder::appendf(const char* fmt, ...) 89{ 90 va_list ap; 91 va_start(ap, fmt); 92 appendvf(fmt, ap); 93 va_end(ap); 94} 95 96}