blob: 2957944eb333946b919caf971af147ee1b7db163 [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
48 ImmutableString(const ImmutableString &) = default;
49 ImmutableString &operator=(const ImmutableString &) = default;
50
51 const char *data() const { return mData ? mData : ""; }
52
53 bool operator<(const ImmutableString &b) const
54 {
55 if (mLength < b.mLength)
56 {
57 return true;
58 }
59 if (mLength > b.mLength)
60 {
61 return false;
62 }
63 return (memcmp(data(), b.data(), mLength) < 0);
64 }
65
66 private:
67 const char *const mData;
68 const size_t mLength;
69};
70
71} // namespace sh
72
73#endif // COMPILER_TRANSLATOR_IMMUTABLESTRING_H_