1 /*
2 Copyright (c) 2012-2020 Maarten Baert <maarten-baert@hotmail.com>
3 
4 This file is part of SimpleScreenRecorder.
5 
6 SimpleScreenRecorder is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10 
11 SimpleScreenRecorder is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15 
16 You should have received a copy of the GNU General Public License
17 along with SimpleScreenRecorder.  If not, see <http://www.gnu.org/licenses/>.
18 */
19 
20 #pragma once
21 #include "Global.h"
22 
23 template<typename E>
24 class EnumStrings {
25 
26 private:
27 	static const EnumStrings SINGLETON;
28 
29 private:
30 	std::vector<std::pair<E, QString> > m_to_string, m_from_string;
31 
32 private:
CompareFirst(const std::pair<E,QString> & a,const std::pair<E,QString> & b)33 	inline static bool CompareFirst(const std::pair<E, QString>& a, const std::pair<E, QString>& b) { return (a.first < b.first); }
CompareSecond(const std::pair<E,QString> & a,const std::pair<E,QString> & b)34 	inline static bool CompareSecond(const std::pair<E, QString>& a, const std::pair<E, QString>& b) { return (a.second < b.second); }
35 
36 public:
EnumStrings(std::initializer_list<std::pair<E,QString>> list)37 	EnumStrings(std::initializer_list<std::pair<E, QString> > list) {
38 		m_to_string = m_from_string = list;
39 		std::sort(m_to_string.begin(), m_to_string.end(), CompareFirst);
40 		std::sort(m_from_string.begin(), m_from_string.end(), CompareSecond);
41 	}
ToString(E value)42 	inline static QString ToString(E value) {
43 		auto it = std::lower_bound(SINGLETON.m_to_string.begin(), SINGLETON.m_to_string.end(), std::make_pair(value, QString()), CompareFirst);
44 		if(it == SINGLETON.m_to_string.end() || it->first != value) {
45 			assert(false);
46 			return QString();
47 		}
48 		return it->second;
49 	}
FromString(const QString & string,E fallback)50 	inline static E FromString(const QString& string, E fallback) {
51 		auto it = std::lower_bound(SINGLETON.m_from_string.begin(), SINGLETON.m_from_string.end(), std::make_pair((E) 0, string), CompareSecond);
52 		if(it == SINGLETON.m_from_string.end() || it->second != string)
53 			return fallback;
54 		return it->first;
55 	}
56 
57 };
58 
59 template<typename E>
EnumToString(E value)60 inline QString EnumToString(E value) { return EnumStrings<E>::ToString(value); }
61 template<typename E>
StringToEnum(const QString & string,E fallback)62 inline E StringToEnum(const QString& string, E fallback) { return EnumStrings<E>::FromString(string, fallback); }
63 
64 #define ENUMSTRINGS(E) template<> const EnumStrings<E> EnumStrings<E>::SINGLETON
65