• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <stdio.h>
13 
14 namespace sh
15 {
16 
operator <<(const ImmutableString & str)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 
operator <<(char c)26 ImmutableStringBuilder &ImmutableStringBuilder::operator<<(char c)
27 {
28     ASSERT(mData != nullptr);
29     ASSERT(mPos + 1 <= mMaxLength);
30     mData[mPos++] = c;
31     return *this;
32 }
33 
appendDecimal(uint32_t u)34 void ImmutableStringBuilder::appendDecimal(uint32_t u)
35 {
36     // + 1 is because snprintf writes at most bufsz - 1 and then \0.
37     // Our bufsz is mMaxLength + 1.
38     int numChars = snprintf(mData + mPos, mMaxLength - mPos + 1, "%d", u);
39     ASSERT(numChars >= 0);
40     ASSERT(mPos + numChars <= mMaxLength);
41     mPos += numChars;
42 }
43 
operator ImmutableString()44 ImmutableStringBuilder::operator ImmutableString()
45 {
46     mData[mPos] = '\0';
47     ImmutableString str(mData, mPos);
48 #if defined(ANGLE_ENABLE_ASSERTS)
49     // Make sure that nothing is added to the string after it is finalized.
50     mData = nullptr;
51 #endif
52     return str;
53 }
54 
55 }  // namespace sh
56