blob: a33fec9ee907216c0780476b307ec3f34002c929 [file] [log] [blame]
Olli Etuaho2d8e4322018-01-22 14:12:46 +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// 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
17namespace sh
18{
19
20namespace
21{
22constexpr 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
37class 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 Etuaho12c03762018-01-25 12:22:33 +020048 constexpr ImmutableString(const char *data, size_t length) : mData(data), mLength(length) {}
49
Olli Etuaho2d8e4322018-01-22 14:12:46 +020050 ImmutableString(const ImmutableString &) = default;
51 ImmutableString &operator=(const ImmutableString &) = default;
52
53 const char *data() const { return mData ? mData : ""; }
Olli Etuaho12c03762018-01-25 12:22:33 +020054 size_t length() const { return mLength; }
Olli Etuaho2d8e4322018-01-22 14:12:46 +020055
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 Etuaho12c03762018-01-25 12:22:33 +020070 const char *mData;
71 size_t mLength;
Olli Etuaho2d8e4322018-01-22 14:12:46 +020072};
73
74} // namespace sh
75
Olli Etuaho12c03762018-01-25 12:22:33 +020076std::ostream &operator<<(std::ostream &os, const sh::ImmutableString &str);
77
Olli Etuaho2d8e4322018-01-22 14:12:46 +020078#endif // COMPILER_TRANSLATOR_IMMUTABLESTRING_H_