Skip to content

Instantly share code, notes, and snippets.

@shadedyin
Created August 31, 2011 02:04
Show Gist options
  • Save shadedyin/1182654 to your computer and use it in GitHub Desktop.
Save shadedyin/1182654 to your computer and use it in GitHub Desktop.
#include <Python.h>
#include <ctype.h>
#include <stdbool.h>
#define MAX_STRING_LENGTH 500
#define UPPER(c) (((c)>='a' && (c) <= 'z') ? ((c)+('A'-'a')) : (c) )
char* CAP(char *txt)
{
*txt = UPPER(*txt);
return txt;
}
static PyObject* cutils_format(PyObject *self, PyObject *args);
static PyMethodDef CutilsMethods[] = {
{"format", cutils_format, METH_VARARGS,
"Format string for output."},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef cutils = {
PyModuleDef_HEAD_INIT,
"cutils",
NULL,
-1,
CutilsMethods
};
static PyObject *FormatError;
PyMODINIT_FUNC PyInit_cutils(void) {
PyObject *m;
m = PyModule_Create(&cutils);
if(!m)
return NULL;
FormatError = PyErr_NewException("cutils.format.error", NULL, NULL);
Py_INCREF(FormatError);
PyModule_AddObject(m, "error", FormatError);
return m;
}
static PyObject* cutils_format(PyObject *self, PyObject *args) {
char *str;
PyObject *sender;
if(!PyArg_ParseTuple(args, "sO", &str, &sender))
return NULL;
const char *i = NULL;
char lbuf[MAX_STRING_LENGTH], *buf, *j;
bool uppercasenext = false;
buf = lbuf;
while(1) {
if (*str == '$') {
switch (*(++str)) {
case 'n':
// obviously won't work
i = PyObject_GetAttrString(sender, "__name");
break;
case 'u': // uppercase previous word
for (j=buf; j > lbuf && !isspace((int) *(j-1)); j--);
if (j != buf)
*j = UPPER(*j);
i = "";
break;
case 'U': // uppercase next word
uppercasenext = true;
i = "";
break;
case '$':
i = "$";
break;
default:
return PyErr_Format(FormatError, "Invalid code %c in format string", *str);
i = "";
break;
} // switch
while ((*buf = *(i++))) {
if (uppercasenext && !isspace((int) *buf)) {
*buf = UPPER(*buf);
uppercasenext = false;
}
buf++;
}
str++;
}
else if (!(*(buf++) = *(str++))) {
break;
}
else if (uppercasenext && !isspace((int) *(buf-1))) {
*(buf-1) = UPPER(*(buf-1));
uppercasenext = false;
}
}
*(--buf) = '\r';
*(++buf) = '\n';
*(++buf) = '\0';
return PyUnicode_FromString(CAP(lbuf));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment