source: src/Common/InternedString.h@ eff03a94

new-env
Last change on this file since eff03a94 was 982f95d, checked in by Aaron Moss <a3moss@…>, 7 years ago

Start of new environment implementation; terribly broken

  • Property mode set to 100644
File size: 2.1 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// InternedString.h --
8//
9// Author : Aaron B. Moss
10// Created On : Thu Jun 14 11:15:00 2018
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Thu Jun 14 11:15:00 2018
13// Update Count : 1
14//
15
16#pragma once
17
18#include <functional>
19#include <string>
20#include <unordered_set>
21#include <utility>
22
23/// Keeps canonical copies of a std::string for quicker comparisons
24class interned_string {
25 /// Shared map of canonical string representations
26 static std::unordered_set< std::string > canonical;
27
28 /// Canonical representation of empty string
29 static const std::string* empty_string() {
30 static const std::string* mt = [](){
31 return &*canonical.emplace( "" ).first;
32 }();
33 return mt;
34 }
35
36 /// Canonicalize string
37 template<typename S>
38 static const std::string* intern( S&& s ) {
39 return &*canonical.emplace( std::forward<S>(s) ).first;
40 }
41
42 /// Pointer to stored string
43 const std::string* s;
44
45public:
46 interned_string() : s{empty_string()} {}
47 interned_string(const char* cs) : s{intern(cs)} {}
48 interned_string(const std::string& ss) : s{intern(ss)} {}
49 /// Invalid string
50 interned_string(std::nullptr_t) : s{nullptr} {}
51
52 operator const std::string& () const { return *s; }
53 const std::string& str() const { return (const std::string&)*this; }
54
55 bool operator== (const interned_string& o) const { return s == o.s; }
56 bool operator!= (const interned_string& o) const { return s != o.s; }
57
58 /// Check for invalid string
59 explicit operator bool () { return s != nullptr; }
60};
61
62inline std::ostream& operator<< (std::ostream& out, const interned_string& s) {
63 return out << (const std::string&)s;
64}
65
66namespace std {
67 template<> struct hash<interned_string> {
68 std::size_t operator() (const interned_string& s) const {
69 return std::hash<const std::string*>{}( &(const std::string&)s );
70 }
71 };
72}
73
74// Local Variables: //
75// tab-width: 4 //
76// mode: c++ //
77// compile-command: "make install" //
78// End: //
Note: See TracBrowser for help on using the repository browser.