Commit e1949632 authored by Xavier Thompson's avatar Xavier Thompson

Add string formatting

parent f68a8341
# distutils: libraries = fmt
from .string cimport Str
# Description:
# This defines a format() function that accepts Str arguments for formatting
# and returns a Str. The format string itself must still be a string literal.
#
# Explanation:
# Cy_Str is a template parameter in this C++ code only because this code is
# inserted before the definition of Cy_Str (C++ name of cypclass Str) in the
# generated C++ output. The actual Cy_Str type is injected at each call site
# of the format function. This is achieved by explicitly setting the C++ name
# of the format function to `format<Cy_Str>`.
cdef extern from * nogil:
"""
#include <fmt/format.h>
#include <string_view>
template <typename T, typename Cy_Str>
struct Cy_Str_Adapter {
constexpr static auto adapt(T t) { return t; }
};
template <typename Cy_Str>
struct Cy_Str_Adapter<Cy_Str*, Cy_Str> {
static std::string_view adapt(Cy_Str* s) {
return s->operator std::string_view();
}
};
template <typename Cy_Str, typename Fmt, typename... T>
Cy_Str * format(const Fmt & fmt, T... args) {
Cy_Str *s = new Cy_Str();
s->_str = fmt::format(fmt, Cy_Str_Adapter<T, Cy_Str>::adapt(args)...);
return s;
}
"""
Str format "format<Cy_Str>" (const char *, ...) except +
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment