xref: /aosp_15_r20/external/angle/src/compiler/translator/ImmutableStringBuilder.cpp (revision 8975f5c5ed3d1c378011245431ada316dfb6f244)
1 //
2 // Copyright 2018 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 // ImmutableStringBuilder.cpp: Stringstream-like utility for building pool allocated strings where
7 // the maximum length is known in advance.
8 //
9 
10 #include "compiler/translator/ImmutableStringBuilder.h"
11 
12 #include <inttypes.h>
13 #include <stdio.h>
14 
15 namespace sh
16 {
17 
operator <<(const ImmutableString & str)18 ImmutableStringBuilder &ImmutableStringBuilder::operator<<(const ImmutableString &str)
19 {
20     ASSERT(mData != nullptr);
21     ASSERT(mPos + str.length() <= mMaxLength);
22     memcpy(mData + mPos, str.data(), str.length());
23     mPos += str.length();
24     return *this;
25 }
26 
operator <<(char c)27 ImmutableStringBuilder &ImmutableStringBuilder::operator<<(char c)
28 {
29     ASSERT(mData != nullptr);
30     ASSERT(mPos + 1 <= mMaxLength);
31     mData[mPos++] = c;
32     return *this;
33 }
34 
operator <<(uint64_t v)35 ImmutableStringBuilder &ImmutableStringBuilder::operator<<(uint64_t v)
36 {
37     // + 1 is because snprintf writes at most bufsz - 1 and then \0.
38     // Our bufsz is mMaxLength + 1.
39     int numChars = snprintf(mData + mPos, mMaxLength - mPos + 1, "%" PRIu64, v);
40     ASSERT(numChars >= 0);
41     ASSERT(mPos + numChars <= mMaxLength);
42     mPos += numChars;
43     return *this;
44 }
45 
operator <<(int64_t v)46 ImmutableStringBuilder &ImmutableStringBuilder::operator<<(int64_t v)
47 {
48     // + 1 is because snprintf writes at most bufsz - 1 and then \0.
49     // Our bufsz is mMaxLength + 1.
50     int numChars = snprintf(mData + mPos, mMaxLength - mPos + 1, "%" PRId64, v);
51     ASSERT(numChars >= 0);
52     ASSERT(mPos + numChars <= mMaxLength);
53     mPos += numChars;
54     return *this;
55 }
56 
operator ImmutableString()57 ImmutableStringBuilder::operator ImmutableString()
58 {
59     mData[mPos] = '\0';
60     ImmutableString str(mData, mPos);
61 #if defined(ANGLE_ENABLE_ASSERTS)
62     // Make sure that nothing is added to the string after it is finalized.
63     mData = nullptr;
64 #endif
65     return str;
66 }
67 
68 }  // namespace sh
69