Last active
December 17, 2015 03:28
-
-
Save wichert/5543390 to your computer and use it in GitHub Desktop.
boost::uuids::uuid convertor for boost::python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <boost/uuid/uuid.hpp> | |
#include <boost/uuid/nil_generator.hpp> | |
#include <boost/uuid/string_generator.hpp> | |
#include <boost/uuid/uuid_io.hpp> | |
#include <boost/python.hpp> | |
namespace python = boost::python; | |
namespace { | |
boost::uuids::nil_generator nil_gen; | |
boost::uuids::string_generator parse_uuid; | |
struct uuid_to_python { | |
static PyObject* convert(boost::uuids::uuid const& uuid) { | |
std::string s(boost::uuids::to_string(uuid)); | |
PyObject* result; | |
result=PyString_FromStringAndSize(s.data(), static_cast<Py_ssize_t>(s.length())); | |
Py_INCREF(result); | |
return result; | |
} | |
}; | |
struct uuid_from_python { | |
uuid_from_python() { | |
python::converter::registry::push_back(&convertible, &construct, python::type_id<boost::uuids::uuid> | |
()); | |
} | |
static void* convertible(PyObject *obj) { | |
if (obj==Py_None || PyUnicode_Check(obj) || PyString_Check(obj)) | |
return obj; | |
return 0; | |
} | |
static void construct(PyObject* obj, python::converter::rvalue_from_python_stage1_data *data) { | |
typedef python::converter::rvalue_from_python_storage<boost::uuids::uuid> storage_type; | |
boost::uuids::uuid uuid; | |
if (obj==Py_None) | |
uuid=nil_gen(); | |
else { | |
PyObject *str = 0; | |
const char* value = ""; | |
if (PyUnicode_Check(obj)) { | |
str=PyUnicode_AsUTF8String(obj); | |
if (str==0) | |
python::throw_error_already_set(); | |
obj=str; | |
} | |
value=PyString_AsString(obj); | |
Py_XDECREF(str); | |
if (value==0) | |
python::throw_error_already_set(); | |
try { | |
uuid=parse_uuid(value); | |
} catch (const std::runtime_error &e) { | |
PyErr_SetString(PyExc_ValueError, "Invalid UUID value."); | |
python::throw_error_already_set(); | |
} | |
} | |
void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes; | |
new (storage) boost::uuids::uuid(uuid); | |
data->convertible=storage; | |
} | |
}; | |
} | |
void exportUUUID() { | |
python::to_python_converter<boost::uuids::uuid, uuid_to_python>(); | |
uuid_from_python(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment