Skip to content
Myr

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

4 files+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 */1011#include <Python.h>121314static char *samp = "&amp;", *slt = "&lt;", *sgt = "&gt;", *sqt = "&quot;";15static Py_UNICODE *amp, *lt, *gt, *qt;16static PyObject* markup;171819static int20init_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);3233 return 1;34}3536static PyObject*37escape_unicode(PyUnicodeObject *in)38{39 PyUnicodeObject *out;40 Py_UNICODE *outp;4142 /* 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 }6364 /* Do we need to escape anything at all? */65 if (!erepl) {66 Py_INCREF(in);67 return (PyObject*)in;68 }6970 out = (PyUnicodeObject*)PyUnicode_FromUnicode(NULL, len);71 if (!out)72 return NULL;7374 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 }109110 return (PyObject*)out;111}112113114static PyObject*115escape(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;120121 /* 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 }133134 /* 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 }141142 /* 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);153154 /* 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}165166167static PyObject *168tb_set_next(PyObject *self, PyObject *args)169{170 PyTracebackObject *tb, *old;171 PyObject *next;172173 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);184185 old = tb->tb_next;186 tb->tb_next = (PyTracebackObject*)next;187 Py_XDECREF(old);188189 Py_INCREF(Py_None);190 return Py_None;191}192193194static 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};204205206#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */207#define PyMODINIT_FUNC void208#endif209PyMODINIT_FUNC210init_speedups(void)211{212 if (!init_constants())213 return;214215 Py_InitModule3("jinja2._speedups", module_methods, "");216}
modified:jinja2/debug.py+7 added-4 removed
132 unmodified lines
133134 return tb_set_next135136137# no ctypes, no fun137# try to get a tb_set_next implementation138try:139 from jinja2._speedups import tb_set_next140except ImportError:141 try:139 tb_set_next = _init_ugly_crap()140except:141 tb_set_next = None142 tb_set_next = _init_ugly_crap()143 except:144 tb_set_next = None145del _init_ugly_crap
modified:jinja2/utils.py+20 added-14 removed
14 unmodified lines
15from functools import update_wrapper16from itertools import imap171819def 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('&', '&amp;')27 .replace('>', '&gt;')28 .replace('<', '&lt;')29 .replace('"', '&quot;')30 )313219def 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 lines
302 rv = LRUCache(self.capacity)303 rv._mapping = deepcopy(self._mapping)304 rv._queue = deepcopy(self._queue)305 return rv306307308# we have to import it down here as the speedups module imports the309# markup type which is define above.310try:311 from jinja2._speedups import escape312except 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('&', '&amp;')322 .replace('>', '&gt;')323 .replace('<', '&lt;')324 .replace('"', '&quot;')325 )
modified:setup.py+35 added-2 removed
55 unmodified lines
56import sys57import ez_setup58ez_setup.use_setuptools()5960from setuptools import setup60from setuptools import setup, Extension, Feature61from distutils.command.build_ext import build_ext62from distutils.errors import CCompilerError, DistutilsPlatformError636465def list_files(path):66 for fn in os.listdir(path):
3 unmodified lines
70 if os.path.isfile(fn):71 yield fn727374class optional_build_ext(build_ext):75 """This class allows C extension building to fail."""7677 def run(self):78 try:79 build_ext.run(self)80 except DistutilsPlatformError:81 self._unavailable()8283 def build_extension(self, ext):84 try:85 build_ext.build_extension(self, ext)86 except CCompilerError, x:87 self._unavailable()8889 def _unavailable(self):90 print '*' * 7091 print """WARNING:92An optional C extension could not be compiled, speedups will not be93available."""94 print '*' * 70959697setup(98 name='Jinja 2',99 version='2.0dev',100 url='http://jinja.pocoo.org/',
1 unmodified line
102 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 lines
122 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)