added C escape and tb_set_next functions
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 284f200 · Browse files · 4 files·+278 added−20 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+278 added−20 removed
- other:+278 added−20 removed
Provenance
- Commit
bd33f11- Tree
772b36a- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
284f200
4 files changed+278 added−20 removed
added:jinja2/_speedups.c+216 added
1+/**2+ * jinja2._speedups3+ * ~~~~~~~~~~~~~~~~4+ *5+ * This module implements a few functions in C for better performance.6+ *7+ * :copyright: 2008 by Armin Ronacher.8+ * :license: BSD.9+ */10+11+#include <Python.h>12+13+14+static char *samp = "&", *slt = "<", *sgt = ">", *sqt = """;15+static Py_UNICODE *amp, *lt, *gt, *qt;16+static PyObject* markup;17+18+19+static int20+init_constants(void)21+{22+ amp = ((PyUnicodeObject*)PyUnicode_DecodeASCII(samp, 5, NULL))->str;23+ lt = ((PyUnicodeObject*)PyUnicode_DecodeASCII(slt, 4, NULL))->str;24+ gt = ((PyUnicodeObject*)PyUnicode_DecodeASCII(sgt, 4, NULL))->str;25+ qt = ((PyUnicodeObject*)PyUnicode_DecodeASCII(sqt, 6, NULL))->str;26+ 27+ PyObject *module = PyImport_ImportModule("jinja2.utils");28+ if (!module)29+ return 0;30+ markup = PyObject_GetAttrString(module, "Markup");31+ Py_DECREF(module);32+33+ return 1;34+}35+36+static PyObject*37+escape_unicode(PyUnicodeObject *in)38+{39+ PyUnicodeObject *out;40+ Py_UNICODE *outp;41+42+ /* First we need to figure out how long the escaped string will be */43+ int len = 0, erepl = 0, repl = 0;44+ Py_UNICODE *inp = in->str;45+ while (*(inp) || in->length > inp - in->str)46+ switch (*inp++) {47+ case '&':48+ len += 5;49+ erepl++;50+ break;51+ case '"':52+ len += 6;53+ erepl++;54+ break;55+ case '<':56+ case '>':57+ len += 4;58+ erepl++;59+ break;60+ default:61+ len++;62+ }63+64+ /* Do we need to escape anything at all? */65+ if (!erepl) {66+ Py_INCREF(in);67+ return (PyObject*)in;68+ }69+70+ out = (PyUnicodeObject*)PyUnicode_FromUnicode(NULL, len);71+ if (!out)72+ return NULL;73+74+ outp = out->str;75+ inp = in->str;76+ while (*(inp) || in->length > inp - in->str) {77+ /* copy rest of string if we have replaced everything */78+ if (repl == erepl) {79+ Py_UNICODE_COPY(outp, inp, in->length - (inp - in->str));80+ break;81+ }82+ /* regular replacements */83+ switch (*inp) {84+ case '&':85+ Py_UNICODE_COPY(outp, amp, 5);86+ outp += 5;87+ repl++;88+ break;89+ case '"':90+ Py_UNICODE_COPY(outp, qt, 6);91+ outp += 6;92+ repl++;93+ break;94+ case '<':95+ Py_UNICODE_COPY(outp, lt, 4);96+ outp += 4;97+ repl++;98+ break;99+ case '>':100+ Py_UNICODE_COPY(outp, gt, 4);101+ outp += 4;102+ repl++;103+ break;104+ default:105+ *outp++ = *inp;106+ };107+ ++inp;108+ }109+110+ return (PyObject*)out;111+}112+113+114+static PyObject*115+escape(PyObject *self, PyObject *args)116+{117+ PyObject *text = NULL, *s = NULL, *rv = NULL;118+ if (!PyArg_UnpackTuple(args, "escape", 1, 2, &text))119+ return NULL;120+121+ /* we don't have to escape integers, bools or floats */122+ if (PyInt_CheckExact(text) || PyLong_CheckExact(text) ||123+ PyFloat_CheckExact(text) || PyBool_Check(text) ||124+ text == Py_None) {125+ args = PyTuple_New(1);126+ if (!args) {127+ Py_DECREF(s);128+ return NULL;129+ }130+ PyTuple_SET_ITEM(args, 0, text);131+ return PyObject_CallObject(markup, args);132+ }133+134+ /* if the object has an __html__ method that performs the escaping */135+ PyObject *html = PyObject_GetAttrString(text, "__html__");136+ if (html) {137+ rv = PyObject_CallObject(html, NULL);138+ Py_DECREF(html);139+ return rv;140+ }141+142+ /* otherwise make the object unicode if it isn't, then escape */143+ PyErr_Clear();144+ if (!PyUnicode_Check(text)) {145+ PyObject *unicode = PyObject_Unicode(text);146+ if (!unicode)147+ return NULL;148+ s = escape_unicode((PyUnicodeObject*)unicode);149+ Py_DECREF(unicode);150+ }151+ else152+ s = escape_unicode((PyUnicodeObject*)text);153+154+ /* convert the unicode string into a markup object. */155+ args = PyTuple_New(1);156+ if (!args) {157+ Py_DECREF(s);158+ return NULL;159+ }160+ PyTuple_SET_ITEM(args, 0, (PyObject*)s);161+ rv = PyObject_CallObject(markup, args);162+ Py_DECREF(args);163+ return rv;164+}165+166+167+static PyObject *168+tb_set_next(PyObject *self, PyObject *args)169+{170+ PyTracebackObject *tb, *old;171+ PyObject *next;172+173+ if (!PyArg_ParseTuple(args, "O!O:tb_set_next", &PyTraceBack_Type, &tb, &next))174+ return NULL;175+ if (next == Py_None)176+ next = NULL;177+ else if (!PyTraceBack_Check(next)) {178+ PyErr_SetString(PyExc_TypeError,179+ "tb_set_next arg 2 must be traceback or None");180+ return NULL;181+ }182+ else183+ Py_INCREF(next);184+185+ old = tb->tb_next;186+ tb->tb_next = (PyTracebackObject*)next;187+ Py_XDECREF(old);188+189+ Py_INCREF(Py_None);190+ return Py_None;191+}192+193+194+static PyMethodDef module_methods[] = {195+ {"escape", (PyCFunction)escape, METH_VARARGS,196+ "escape(s) -> string\n\n"197+ "Convert the characters &, <, >, and \" in string s to HTML-safe\n"198+ "sequences. Use this if you need to display text that might contain\n"199+ "such characters in HTML."},200+ {"tb_set_next", (PyCFunction)tb_set_next, METH_VARARGS,201+ "Set the tb_next member of a traceback object."},202+ {NULL, NULL, 0, NULL} /* Sentinel */203+};204+205+206+#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */207+#define PyMODINIT_FUNC void208+#endif209+PyMODINIT_FUNC210+init_speedups(void)211+{212+ if (!init_constants())213+ return;214+215+ Py_InitModule3("jinja2._speedups", module_methods, "");216+}modified:jinja2/debug.py+7 added-4 removed
132 unmodified lines133 134 return tb_set_next135 136 137-# no ctypes, no fun137+# try to get a tb_set_next implementation138 try:139+ from jinja2._speedups import tb_set_next140+except ImportError:141+ try:139- tb_set_next = _init_ugly_crap()140-except:141- tb_set_next = None142+ tb_set_next = _init_ugly_crap()143+ except:144+ tb_set_next = None145 del _init_ugly_crapmodified:jinja2/utils.py+20 added-14 removed
14 unmodified lines15 from functools import update_wrapper16 from itertools import imap17 18 19-def escape(obj, attribute=False):20- """HTML escape an object."""21- if obj is None:22- return u''23- elif hasattr(obj, '__html__'):24- return obj.__html__()25- return Markup(unicode(obj)26- .replace('&', '&')27- .replace('>', '>')28- .replace('<', '<')29- .replace('"', '"')30- )31-32-19 def soft_unicode(s):20 """Make a string unicode if it isn't already. That way a markup21 string is not converted back to unicode.22 """279 unmodified lines302 rv = LRUCache(self.capacity)303 rv._mapping = deepcopy(self._mapping)304 rv._queue = deepcopy(self._queue)305 return rv306+307+308+# we have to import it down here as the speedups module imports the309+# markup type which is define above.310+try:311+ from jinja2._speedups import escape312+except ImportError:313+ def escape(obj):314+ """Convert the characters &, <, >, and " in string s to HTML-safe315+ sequences. Use this if you need to display text that might contain316+ such characters in HTML.317+ """318+ if hasattr(obj, '__html__'):319+ return obj.__html__()320+ return Markup(unicode(obj)321+ .replace('&', '&')322+ .replace('>', '>')323+ .replace('<', '<')324+ .replace('"', '"')325+ )modified:setup.py+35 added-2 removed
55 unmodified lines56 import sys57 import ez_setup58 ez_setup.use_setuptools()59 60-from setuptools import setup60+from setuptools import setup, Extension, Feature61+from distutils.command.build_ext import build_ext62+from distutils.errors import CCompilerError, DistutilsPlatformError63 64 65 def list_files(path):66 for fn in os.listdir(path):3 unmodified lines70 if os.path.isfile(fn):71 yield fn72 73 74+class optional_build_ext(build_ext):75+ """This class allows C extension building to fail."""76+77+ def run(self):78+ try:79+ build_ext.run(self)80+ except DistutilsPlatformError:81+ self._unavailable()82+83+ def build_extension(self, ext):84+ try:85+ build_ext.build_extension(self, ext)86+ except CCompilerError, x:87+ self._unavailable()88+89+ def _unavailable(self):90+ print '*' * 7091+ print """WARNING:92+An optional C extension could not be compiled, speedups will not be93+available."""94+ print '*' * 7095+96+97 setup(98 name='Jinja 2',99 version='2.0dev',100 url='http://jinja.pocoo.org/',1 unmodified line102 author='Armin Ronacher',103 author_email='armin.ronacher@active-4.com',104 description='A small but fast and easy to use stand-alone template '105 'engine written in pure python.',81- long_description = __doc__,106+ long_description=__doc__,107 # jinja is egg safe. But because we distribute the documentation108 # in form of html and txt files it's a better idea to extract the files109 zip_safe=False,110 classifiers=[11 unmodified lines122 data_files=[123 ('docs/html', list(list_files('docs/html'))),124 ('docs/txt', list(list_files('docs/src')))125 ],126+ features={127+ 'speedups': Feature("optional C speed-enhancements",128+ standard=True,129+ ext_modules=[130+ Extension('jinja2._speedups', ['jinja2/_speedups.c'])131+ ]132+ )133+ },134 extras_require={'plugin': ['setuptools>=0.6a2']}135 )