start using global, 100% generic enum to/from string object
[ardour.git] / libs / pbd / pbd / enumwriter.h
1 /* 
2     Copyright (C) 2006 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18     $Id$
19 */
20
21 #include <map>
22 #include <string>
23 #include <vector>
24 #include <exception>
25
26
27 namespace PBD {
28
29 class unknown_enumeration : public std::exception {
30   public:
31         virtual const char *what() const throw() { return "unknown enumerator in PBD::EnumWriter"; }
32 };
33
34 class EnumWriter {
35   public:
36         EnumWriter ();
37         ~EnumWriter ();
38
39         static EnumWriter& instance() { return *_instance; }
40
41         void register_distinct (std::string type, std::vector<int>, std::vector<std::string>);
42         void register_bits     (std::string type, std::vector<int>, std::vector<std::string>);
43
44         std::string write (std::string type, int value);
45         int         read  (std::string type, std::string value);
46
47   private:
48         struct EnumRegistration {
49             std::vector<int> values;
50             std::vector<std::string> names;
51             bool bitwise;
52
53             EnumRegistration() {}
54             EnumRegistration (std::vector<int>& v, std::vector<std::string>& s, bool b) 
55                     : values (v), names (s), bitwise (b) {}
56         };
57
58         typedef std::map<std::string, EnumRegistration> Registry;
59         Registry registry;
60
61         std::string write_bits (EnumRegistration&, int value);
62         std::string write_distinct (EnumRegistration&, int value);
63
64         int read_bits (EnumRegistration&, std::string value);
65         int read_distinct (EnumRegistration&, std::string value);
66
67         static EnumWriter* _instance;
68 };
69
70 }
71
72 #define enum_2_string(e) (PBD::EnumWriter::instance().write (typeid(e).name(), e))
73 #define string_2_enum(str,e) (PBD::EnumWriter::instance().read (typeid(e).name(), (str)))
74