1 | // |
---|---|
2 | // Copyright (c) 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 <stdio.h> |
13 | |
14 | namespace sh |
15 | { |
16 | |
17 | ImmutableStringBuilder &ImmutableStringBuilder::operator<<(const ImmutableString &str) |
18 | { |
19 | ASSERT(mData != nullptr); |
20 | ASSERT(mPos + str.length() <= mMaxLength); |
21 | memcpy(mData + mPos, str.data(), str.length()); |
22 | mPos += str.length(); |
23 | return *this; |
24 | } |
25 | |
26 | ImmutableStringBuilder &ImmutableStringBuilder::operator<<(const char *str) |
27 | { |
28 | ASSERT(mData != nullptr); |
29 | size_t len = strlen(str); |
30 | ASSERT(mPos + len <= mMaxLength); |
31 | memcpy(mData + mPos, str, len); |
32 | mPos += len; |
33 | return *this; |
34 | } |
35 | |
36 | ImmutableStringBuilder &ImmutableStringBuilder::operator<<(const char &c) |
37 | { |
38 | ASSERT(mData != nullptr); |
39 | ASSERT(mPos + 1 <= mMaxLength); |
40 | mData[mPos++] = c; |
41 | return *this; |
42 | } |
43 | |
44 | void ImmutableStringBuilder::appendDecimal(const uint32_t &u) |
45 | { |
46 | int numChars = snprintf(mData + mPos, mMaxLength - mPos, "%d", u); |
47 | ASSERT(numChars >= 0); |
48 | ASSERT(mPos + numChars <= mMaxLength); |
49 | mPos += numChars; |
50 | } |
51 | |
52 | ImmutableStringBuilder::operator ImmutableString() |
53 | { |
54 | mData[mPos] = '\0'; |
55 | ImmutableString str(static_cast<const char *>(mData), mPos); |
56 | #if defined(ANGLE_ENABLE_ASSERTS) |
57 | // Make sure that nothing is added to the string after it is finalized. |
58 | mData = nullptr; |
59 | #endif |
60 | return str; |
61 | } |
62 | |
63 | } // namespace sh |
64 |