blob: f7ed515673988d47b2298e54f1b1cef76c7e1a0f [file] [log] [blame]
Olli Etuaho12c03762018-01-25 12:22:33 +02001//
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.h: Stringstream-like utility for building pool allocated strings where the
7// maximum length is known in advance.
8//
9
10#ifndef COMPILER_TRANSLATOR_IMMUTABLESTRINGBUILDER_H_
11#define COMPILER_TRANSLATOR_IMMUTABLESTRINGBUILDER_H_
12
13#include "compiler/translator/ImmutableString.h"
14
15namespace sh
16{
17
18class ImmutableStringBuilder
19{
20 public:
21 ImmutableStringBuilder(size_t maxLength)
22 : mPos(0u), mMaxLength(maxLength), mData(AllocateEmptyPoolCharArray(maxLength))
23 {
24 }
25
26 ImmutableStringBuilder &operator<<(const ImmutableString &str);
27
28 ImmutableStringBuilder &operator<<(const char *str);
29
30 ImmutableStringBuilder &operator<<(const char &c);
31
32 // This invalidates the ImmutableStringBuilder, so it should only be called once.
33 operator ImmutableString();
34
Olli Etuahofbb1c792018-01-19 16:26:59 +020035 template <typename T>
36 void appendHex(T number)
37 {
38 ASSERT(mData != nullptr);
39 ASSERT(mPos + sizeof(T) * 2u <= mMaxLength);
40 int index = static_cast<int>(sizeof(T)) * 2 - 1;
41 // Loop through leading zeroes.
42 while (((number >> (index * 4)) & 0xfu) == 0 && index > 0)
43 {
44 --index;
45 }
46 // Write the rest of the hex digits.
47 while (index >= 0)
48 {
49 char digit = static_cast<char>((number >> (index * 4)) & 0xfu);
Olli Etuaho5ae64c92018-04-06 11:27:03 +030050 char digitChar = (digit < 10) ? (digit + '0') : (digit + ('a' - 10));
Olli Etuahofbb1c792018-01-19 16:26:59 +020051 mData[mPos++] = digitChar;
52 --index;
53 }
54 return;
55 }
56
Olli Etuaho12c03762018-01-25 12:22:33 +020057 private:
58 inline static char *AllocateEmptyPoolCharArray(size_t strLength)
59 {
60 size_t requiredSize = strLength + 1u;
Rafael Cintron05a449a2018-06-20 18:08:04 -070061 return static_cast<char *>(GetGlobalPoolAllocator()->allocate(requiredSize));
Olli Etuaho12c03762018-01-25 12:22:33 +020062 }
63
64 size_t mPos;
65 size_t mMaxLength;
66 char *mData;
67};
68
69} // namespace sh
70
71#endif // COMPILER_TRANSLATOR_IMMUTABLESTRINGBUILDER_H_