Olli Etuaho | 2d8e432 | 2018-01-22 14:12:46 +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 | // ImmutableString.h: Wrapper for static or pool allocated char arrays, that are guaranteed to be |
| 7 | // valid and unchanged for the duration of the compilation. |
| 8 | // |
| 9 | |
| 10 | #ifndef COMPILER_TRANSLATOR_IMMUTABLESTRING_H_ |
| 11 | #define COMPILER_TRANSLATOR_IMMUTABLESTRING_H_ |
| 12 | |
| 13 | #include <string> |
| 14 | |
| 15 | #include "compiler/translator/Common.h" |
| 16 | |
| 17 | namespace sh |
| 18 | { |
| 19 | |
| 20 | namespace |
| 21 | { |
| 22 | constexpr size_t constStrlen(const char *str) |
| 23 | { |
| 24 | if (str == nullptr) |
| 25 | { |
| 26 | return 0u; |
| 27 | } |
| 28 | size_t len = 0u; |
| 29 | while (*(str + len) != '\0') |
| 30 | { |
| 31 | ++len; |
| 32 | } |
| 33 | return len; |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | class ImmutableString |
| 38 | { |
| 39 | public: |
| 40 | // The data pointer passed in must be one of: |
| 41 | // 1. nullptr (only valid with length 0). |
| 42 | // 2. a null-terminated static char array like a string literal. |
| 43 | // 3. a null-terminated pool allocated char array. |
| 44 | explicit constexpr ImmutableString(const char *data) : mData(data), mLength(constStrlen(data)) |
| 45 | { |
| 46 | } |
| 47 | |
Olli Etuaho | 12c0376 | 2018-01-25 12:22:33 +0200 | [diff] [blame^] | 48 | constexpr ImmutableString(const char *data, size_t length) : mData(data), mLength(length) {} |
| 49 | |
Olli Etuaho | 2d8e432 | 2018-01-22 14:12:46 +0200 | [diff] [blame] | 50 | ImmutableString(const ImmutableString &) = default; |
| 51 | ImmutableString &operator=(const ImmutableString &) = default; |
| 52 | |
| 53 | const char *data() const { return mData ? mData : ""; } |
Olli Etuaho | 12c0376 | 2018-01-25 12:22:33 +0200 | [diff] [blame^] | 54 | size_t length() const { return mLength; } |
Olli Etuaho | 2d8e432 | 2018-01-22 14:12:46 +0200 | [diff] [blame] | 55 | |
| 56 | bool operator<(const ImmutableString &b) const |
| 57 | { |
| 58 | if (mLength < b.mLength) |
| 59 | { |
| 60 | return true; |
| 61 | } |
| 62 | if (mLength > b.mLength) |
| 63 | { |
| 64 | return false; |
| 65 | } |
| 66 | return (memcmp(data(), b.data(), mLength) < 0); |
| 67 | } |
| 68 | |
| 69 | private: |
Olli Etuaho | 12c0376 | 2018-01-25 12:22:33 +0200 | [diff] [blame^] | 70 | const char *mData; |
| 71 | size_t mLength; |
Olli Etuaho | 2d8e432 | 2018-01-22 14:12:46 +0200 | [diff] [blame] | 72 | }; |
| 73 | |
| 74 | } // namespace sh |
| 75 | |
Olli Etuaho | 12c0376 | 2018-01-25 12:22:33 +0200 | [diff] [blame^] | 76 | std::ostream &operator<<(std::ostream &os, const sh::ImmutableString &str); |
| 77 | |
Olli Etuaho | 2d8e432 | 2018-01-22 14:12:46 +0200 | [diff] [blame] | 78 | #endif // COMPILER_TRANSLATOR_IMMUTABLESTRING_H_ |