Line data Source code
1 : /* 2 : * 3 : * Copyright (c) 2023 Project CHIP Authors 4 : * All rights reserved. 5 : * 6 : * Licensed under the Apache License, Version 2.0 (the "License"); 7 : * you may not use this file except in compliance with the License. 8 : * You may obtain a copy of the License at 9 : * 10 : * http://www.apache.org/licenses/LICENSE-2.0 11 : * 12 : * Unless required by applicable law or agreed to in writing, software 13 : * distributed under the License is distributed on an "AS IS" BASIS, 14 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 : * See the License for the specific language governing permissions and 16 : * limitations under the License. 17 : */ 18 : #include "StringBuilder.h" 19 : 20 : namespace chip { 21 : 22 1706 : StringBuilderBase & StringBuilderBase::AddFormat(const char * format, ...) 23 : { 24 : va_list args; 25 1706 : va_start(args, format); 26 : 27 1706 : char * output = nullptr; 28 1706 : if (mWriter.Available() > 0) 29 : { 30 1700 : output = reinterpret_cast<char *>(mWriter.Buffer() + mWriter.Needed()); 31 : } 32 : else 33 : { 34 6 : output = reinterpret_cast<char *>(mWriter.Buffer() + mWriter.Size()); 35 : } 36 : 37 : // the + 1 size here because StringBuilder reserves one byte for final null terminator 38 1706 : int needed = vsnprintf(output, mWriter.Available() + 1, format, args); 39 : 40 : // on invalid formats, printf-style methods return negative numbers 41 1706 : if (needed > 0) 42 : { 43 1706 : mWriter.Skip(static_cast<size_t>(needed)); 44 : } 45 : 46 1706 : va_end(args); 47 1706 : NullTerminate(); 48 1706 : return *this; 49 : } 50 : 51 248 : StringBuilderBase & StringBuilderBase::AddMarkerIfOverflow() 52 : { 53 248 : if (mWriter.Fit()) 54 : { 55 239 : return *this; 56 : } 57 : 58 36 : for (unsigned i = 0; i < 3; i++) 59 : { 60 27 : if (mWriter.Size() >= i + 1) 61 : { 62 21 : mWriter.Buffer()[mWriter.Size() - i - 1] = '.'; 63 : } 64 : } 65 9 : return *this; 66 : } 67 : } // namespace chip