# HG changeset patch # User Yuya Nishihara # Date 1454150915 -32400 # Node ID 69a02b1e947c36fa658e6e1203a6fe0404e2d6fd # Parent d1cc0712324370ebed493440ab757cab6e6f8247 encoding: initialize jsonmap when module is loaded This makes jsonescape() a thread-safe function, which is necessary for hgweb. The initialization stuff isn't that slow: $ python -m timeit -n1000 -s 'from mercurial import encoding as x' 'reload(x)' original: 1000 loops, best of 3: 158 usec per loop this patch: 1000 loops, best of 3: 214 usec per loop compared to loading the commands module: $ python -m timeit -n1000 -s 'from mercurial import commands as x' 'reload(x)' 1000 loops, best of 3: 1.11 msec per loop diff -r d1cc07123243 -r 69a02b1e947c mercurial/encoding.py --- a/mercurial/encoding.py Sat Jan 30 19:41:34 2016 +0900 +++ b/mercurial/encoding.py Sat Jan 30 19:48:35 2016 +0900 @@ -379,6 +379,16 @@ other = 0 _jsonmap = [] +_jsonmap.extend("\\u%04x" % x for x in xrange(32)) +_jsonmap.extend(chr(x) for x in xrange(32, 256)) +_jsonmap[0x7f] = '\\u007f' +_jsonmap[0x09] = '\\t' +_jsonmap[0x0a] = '\\n' +_jsonmap[0x22] = '\\"' +_jsonmap[0x5c] = '\\\\' +_jsonmap[0x08] = '\\b' +_jsonmap[0x0c] = '\\f' +_jsonmap[0x0d] = '\\r' def jsonescape(s): '''returns a string suitable for JSON @@ -407,18 +417,6 @@ '' ''' - if not _jsonmap: - _jsonmap.extend("\\u%04x" % x for x in xrange(32)) - _jsonmap.extend(chr(x) for x in xrange(32, 256)) - _jsonmap[0x7f] = '\\u007f' - _jsonmap[0x09] = '\\t' - _jsonmap[0x0a] = '\\n' - _jsonmap[0x22] = '\\"' - _jsonmap[0x5c] = '\\\\' - _jsonmap[0x08] = '\\b' - _jsonmap[0x0c] = '\\f' - _jsonmap[0x0d] = '\\r' - return ''.join(_jsonmap[x] for x in bytearray(toutf8b(s))) _utf8len = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 4]