8#include <boost/python/class.hpp>
9#include <boost/python/copy_const_reference.hpp>
10#include <boost/python/make_constructor.hpp>
11#include <boost/python/return_value_policy.hpp>
13#include <boost/scoped_array.hpp>
17#include <unicodeobject.h>
23std::shared_ptr<UnitLabel> createLabel(
const object &ascii,
const object &utf8,
const object &latex) {
24 using Utf8Char = UnitLabel::Utf8String::value_type;
25 if (PyUnicode_Check(utf8.ptr())) {
26 auto length = PyUnicode_GetLength(utf8.ptr());
27 boost::scoped_array<Utf8Char> buffer(
new Utf8Char[length]);
28 PyUnicode_AsWideChar(utf8.ptr(), buffer.get(), length);
29 return std::make_shared<UnitLabel>(extract<std::string>(ascii)(),
31 extract<std::string>(latex)());
33 throw std::invalid_argument(
"utf8 label is not a unicode string object. "
34 "Try prefixing the string with a 'u' character.");
42PyObject *utf8ToUnicode(
const UnitLabel &self) {
43 const auto &label = self.
utf8();
44 return PyUnicode_FromWideChar(label.c_str(), label.size());
49 class_<UnitLabel>(
"UnitLabel", no_init)
51 make_constructor(createLabel, default_call_policies(), (arg(
"ascii"), arg(
"utf8"), arg(
"latex"))),
52 "Construct a label from a unicode object")
54 .def(init<UnitLabel::AsciiString>((arg(
"ascii")),
"Construct a label from a plain-text string"))
56 .def(
"ascii", &
UnitLabel::ascii, arg(
"self"), return_value_policy<copy_const_reference>(),
57 "Return the label as a plain-text string")
59 .def(
"utf8", &utf8ToUnicode, arg(
"self"),
"Return the label as a unicode string")
61 .def(
"latex", &
UnitLabel::latex, return_value_policy<copy_const_reference>(), arg(
"self"),
62 "Return the label as a plain-text string with latex formatting")
65 .def(
"__str__", &
UnitLabel::ascii, return_value_policy<copy_const_reference>(), arg(
"self"))
66 .def(
"__unicode__", &utf8ToUnicode, arg(
"self"));
A base-class for the a class that is able to return unit labels in different representations.
const AsciiString & ascii() const
Return an ascii label for unit.
std::wstring Utf8String
Type that can hold a unicode string.
const Utf8String & utf8() const
Return a utf-8 encoded label for unit.
const AsciiString & latex() const
Return an ascii latex compatible label for unit.