1 | // Scintilla source code edit control |
---|---|
2 | /** @file UniqueString.cxx |
3 | ** Define an allocator for UniqueString. |
4 | **/ |
5 | // Copyright 2017 by Neil Hodgson <neilh@scintilla.org> |
6 | // The License.txt file describes the conditions under which this software may be distributed. |
7 | |
8 | #include <string_view> |
9 | #include <vector> |
10 | #include <algorithm> |
11 | #include <memory> |
12 | |
13 | #include "UniqueString.h" |
14 | |
15 | namespace Scintilla::Internal { |
16 | |
17 | /// Equivalent to strdup but produces a std::unique_ptr<const char[]> allocation to go |
18 | /// into collections. |
19 | UniqueString UniqueStringCopy(const char *text) { |
20 | if (!text) { |
21 | return UniqueString(); |
22 | } |
23 | const std::string_view sv(text); |
24 | std::unique_ptr<char[]> upcNew = std::make_unique<char[]>(sv.length() + 1); |
25 | sv.copy(upcNew.get(), sv.length()); |
26 | return UniqueString(upcNew.release()); |
27 | } |
28 | |
29 | // A set of strings that always returns the same pointer for each string. |
30 | |
31 | UniqueStringSet::UniqueStringSet() = default; |
32 | |
33 | UniqueStringSet::~UniqueStringSet() noexcept = default; |
34 | |
35 | void UniqueStringSet::Clear() noexcept { |
36 | strings.clear(); |
37 | } |
38 | |
39 | const char *UniqueStringSet::Save(const char *text) { |
40 | if (!text) |
41 | return nullptr; |
42 | |
43 | const std::string_view sv(text); |
44 | for (const UniqueString &us : strings) { |
45 | if (sv == us.get()) { |
46 | return us.get(); |
47 | } |
48 | } |
49 | |
50 | strings.push_back(UniqueStringCopy(text)); |
51 | return strings.back().get(); |
52 | } |
53 | |
54 | } |
55 |