Olli Etuaho | 12c0376 | 2018-01-25 12:22:33 +0200 | [diff] [blame] | 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.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 | |
| 15 | namespace sh |
| 16 | { |
| 17 | |
| 18 | class 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 Etuaho | fbb1c79 | 2018-01-19 16:26:59 +0200 | [diff] [blame] | 35 | 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 Etuaho | 5ae64c9 | 2018-04-06 11:27:03 +0300 | [diff] [blame] | 50 | char digitChar = (digit < 10) ? (digit + '0') : (digit + ('a' - 10)); |
Olli Etuaho | fbb1c79 | 2018-01-19 16:26:59 +0200 | [diff] [blame] | 51 | mData[mPos++] = digitChar; |
| 52 | --index; |
| 53 | } |
| 54 | return; |
| 55 | } |
| 56 | |
Olli Etuaho | 12c0376 | 2018-01-25 12:22:33 +0200 | [diff] [blame] | 57 | private: |
| 58 | inline static char *AllocateEmptyPoolCharArray(size_t strLength) |
| 59 | { |
| 60 | size_t requiredSize = strLength + 1u; |
Rafael Cintron | 05a449a | 2018-06-20 18:08:04 -0700 | [diff] [blame^] | 61 | return static_cast<char *>(GetGlobalPoolAllocator()->allocate(requiredSize)); |
Olli Etuaho | 12c0376 | 2018-01-25 12:22:33 +0200 | [diff] [blame] | 62 | } |
| 63 | |
| 64 | size_t mPos; |
| 65 | size_t mMaxLength; |
| 66 | char *mData; |
| 67 | }; |
| 68 | |
| 69 | } // namespace sh |
| 70 | |
| 71 | #endif // COMPILER_TRANSLATOR_IMMUTABLESTRINGBUILDER_H_ |