]> sigrok.org Git - libsigrok.git/blobdiff - bindings/cxx/enums.py
bindings: Better error handling in enumeration get() function.
[libsigrok.git] / bindings / cxx / enums.py
index fdc8e8e3dcda46a68c0afeb3cdaf41a3b01e4227..9eddd1ad9631fe61344b7ec13068bf5cc0adb29c 100644 (file)
@@ -26,6 +26,10 @@ index_file = sys.argv[1]
 # Get directory this script is in.
 dirname = os.path.dirname(os.path.realpath(__file__))
 
+outdirname = "bindings/cxx"
+if not os.path.exists(os.path.join(outdirname, 'include/libsigrok')):
+    os.makedirs(os.path.join(outdirname, 'include/libsigrok'))
+
 mapping = dict([
     ('sr_loglevel', ('LogLevel', 'Log verbosity level')),
     ('sr_packettype', ('PacketType', 'Type of datafeed packet')),
@@ -60,8 +64,8 @@ for compound in index.findall('compound'):
             if name in mapping:
                 classes[member] = mapping[name]
 
-header = open(os.path.join(dirname, 'include/libsigrok/enums.hpp'), 'w')
-code = open(os.path.join(dirname, 'enums.cpp'), 'w')
+header = open(os.path.join(outdirname, 'include/libsigrok/enums.hpp'), 'w')
+code = open(os.path.join(outdirname, 'enums.cpp'), 'w')
 
 for file in (header, code):
     print >> file, "/* Generated file - edit enums.py instead! */"
@@ -78,7 +82,7 @@ public:
 # Template for beginning of private members.
 header_private_template = """
 private:
-    static const std::map<enum {enumname}, const {classname} *> values;
+    static const std::map<enum {enumname}, const {classname} *> _values;
     {classname}(enum {enumname} id, const char name[]);
 """
 
@@ -91,7 +95,10 @@ code_template = """
 
 const {classname} *{classname}::get(int id)
 {{
-    return {classname}::values.at(static_cast<{enumname}>(id));
+    if (_values.find(static_cast<{enumname}>(id)) == _values.end())
+        throw Error(SR_ERR_ARG);
+
+    return {classname}::_values.at(static_cast<{enumname}>(id));
 }}
 """
 
@@ -149,7 +156,7 @@ for enum, (classname, classbrief) in classes.items():
             classname, classname, trimmed_name, classname, trimmed_name)
 
     # Define map of enum values to constants
-    print >> code, 'const std::map<enum %s, const %s *> %s::values = {' % (
+    print >> code, 'const std::map<enum %s, const %s *> %s::_values = {' % (
         enum_name, classname, classname)
     for name, trimmed_name in zip(member_names, trimmed_names):
         print >> code, '\t{%s, %s::%s},' % (name, classname, trimmed_name)