Ticket #11778: 0001-Faster-escapejs-11778.patch

File 0001-Faster-escapejs-11778.patch, 2.0 KB (added by gisle, 6 years ago)

Even faster version without double maintenance of keys

  • django/template/defaultfilters.py

    From e889c4a2b8b4258d788a6e9466b4c0e693918acc Mon Sep 17 00:00:00 2001
    From: Gisle Aas <gisle@aas.no>
    Date: Mon, 22 Feb 2010 08:10:00 -0500
    Subject: [PATCH] Faster escapejs #11778
    
    ---
     django/template/defaultfilters.py |   44 ++++++++++++++++++++----------------
     1 files changed, 24 insertions(+), 20 deletions(-)
    
    diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
    index e6492dc..950cc16 100644
    a b def capfirst(value): 
    6868capfirst.is_safe=True
    6969capfirst = stringfilter(capfirst)
    7070
    71 _base_js_escapes = (
    72     ('\\', r'\x5C'),
    73     ('\'', r'\x27'),
    74     ('"', r'\x22'),
    75     ('>', r'\x3E'),
    76     ('<', r'\x3C'),
    77     ('&', r'\x26'),
    78     ('=', r'\x3D'),
    79     ('-', r'\x2D'),
    80     (';', r'\x3B'),
    81     (u'\u2028', r'\u2028'),
    82     (u'\u2029', r'\u2029')
    83 )
    84 
    85 # Escape every ASCII character with a value less than 32.
    86 _js_escapes = (_base_js_escapes +
    87                tuple([('%c' % z, '\\x%02X' % z) for z in range(32)]))
     71_js_escapes_dict = {
     72    '\\': r'\x5C',
     73    '\'': r'\x27',
     74    '"': r'\x22',
     75    '>': r'\x3E',
     76    '<': r'\x3C',
     77    '&': r'\x26',
     78    '=': r'\x3D',
     79    '-': r'\x2D',
     80    ';': r'\x3B',
     81    u'\u2028': r'\u2028',
     82    u'\u2029': r'\u2029',
     83}
     84
     85# also escape every ASCII character with a value less than 32.
     86for z in range(32):
     87    _js_escapes_dict[chr(z)] = '\\x%02X' % z
     88
     89# construct a Regex object matching the keys in _js_escapes_dict
     90_js_escapes_re = u''.join(sorted(_js_escapes_dict.keys()))
     91_js_escapes_re = re.sub(r'[\\\\\-\]]', r'\\\g<0>', _js_escapes_re) # escape \-]
     92_js_escapes_re = '[' + _js_escapes_re + ']'
     93_js_escapes_re = re.compile(_js_escapes_re)
    8894
    8995def escapejs(value):
    9096    """Hex encodes characters for use in JavaScript strings."""
    91     for bad, good in _js_escapes:
    92         value = value.replace(bad, good)
    93     return value
     97    return _js_escapes_re.sub(lambda m: _js_escapes_dict[m.group(0)], value)
    9498escapejs = stringfilter(escapejs)
    9599
    96100def fix_ampersands(value):
Back to Top