From e67fc33ec0f18a1772bfc3f46ecad834abba66b3 Mon Sep 17 00:00:00 2001 From: Menno Smits Date: Tue, 21 Jul 2015 23:03:00 +1200 Subject: [PATCH] Speed up message id list parsing (dramatically) Use a fast, specialised function when parsing message id lists. Fixes #162. --- NEWS.rst | 9 +++++ imapclient/imapclient.py | 12 ++----- imapclient/response_parser.py | 46 +++++++++++++++++++++++-- imapclient/test/test_response_parser.py | 29 +++++++++++++++- 4 files changed, 83 insertions(+), 13 deletions(-) diff --git a/NEWS.rst b/NEWS.rst index 4361bd5..b9474ec 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -1,3 +1,12 @@ +======= + 1.0.0 +======= + +Performance optimsation for parsing message id lists +---------------------------------------------------- +A short circuit is now used when parsing a list of message ids which +greatly speeds up parsing time. + ====== 0.13 ====== diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py index 705d418..a6417ff 100644 --- a/imapclient/imapclient.py +++ b/imapclient/imapclient.py @@ -22,7 +22,6 @@ except ImportError: from . import response_lexer from .datetime_util import datetime_to_INTERNALDATE from .imap_utf7 import encode as encode_utf7, decode as decode_utf7 -from .response_types import SearchIds from .six import moves, iteritems, text_type, integer_types, PY3, binary_type, string_types xrange = moves.xrange @@ -32,7 +31,7 @@ if PY3: __all__ = ['IMAPClient', 'DELETED', 'SEEN', 'ANSWERED', 'FLAGGED', 'DRAFT', 'RECENT'] -from .response_parser import parse_response, parse_fetch_response +from .response_parser import parse_response, parse_message_list, parse_fetch_response # We also offer the gmail-specific XLIST command... if 'XLIST' not in imaplib.Commands: @@ -654,14 +653,7 @@ class IMAPClient(object): typ, data = self._imap.search(charset, *criteria) self._checkok('search', typ, data) - - ids = SearchIds() - for item in parse_response(data): - if isinstance(item, int): - ids.append(item) - elif isinstance(item, tuple) and len(item) == 2 and item[0].lower() == b'modseq': - ids.modseq = item[1] - return ids + return parse_message_list(data) def thread(self, algorithm='REFERENCES', criteria='ALL', charset='UTF-8'): """Return a list of messages threads matching *criteria*. diff --git a/imapclient/response_parser.py b/imapclient/response_parser.py index 29021e0..0bc15fb 100644 --- a/imapclient/response_parser.py +++ b/imapclient/response_parser.py @@ -13,6 +13,7 @@ Initially inspired by http://effbot.org/zone/simple-iterator-parser.htm from __future__ import unicode_literals +import re import sys from collections import defaultdict @@ -21,10 +22,10 @@ xrange = six.moves.xrange from .datetime_util import parse_to_datetime from .response_lexer import TokenSource -from .response_types import BodyData, Envelope, Address +from .response_types import BodyData, Envelope, Address, SearchIds -__all__ = ['parse_response', 'ParseError'] +__all__ = ['parse_response', 'parse_message_list', 'ParseError'] class ParseError(ValueError): @@ -41,6 +42,47 @@ def parse_response(data): return tuple(gen_parsed_response(data)) +_msg_id_pattern = re.compile("(\d+(?: +\d+)*)") + +def parse_message_list(data): + """Parse a list of message ids and return them as a list. + + parse_response is also capable of doing this but this is + faster. This also has special handling of the optional MODSEQ part + of a SEARCH response. + + The returned list is a SearchIds instance which has a *modseq* + attribute which contains the MODSEQ response (if returned by the + server). + """ + if len(data) != 1: + raise ValueError("unexpected message list data") + + data = data[0] + if not data: + return SearchIds() + + if six.PY3 and isinstance(data, six.binary_type): + data = data.decode('ascii') + + m = _msg_id_pattern.match(data) + if not m: + raise ValueError("unexpected message list format") + + ids = SearchIds(int(n) for n in m.group(1).split()) + + # Parse any non-numeric part on th end using parse_response (this + # is likely to be the MODSEQ section). + extra = data[m.end(1):] + if extra: + for item in parse_response([extra.encode('ascii')]): + if isinstance(item, tuple) and len(item) == 2 and item[0].lower() == b'modseq': + ids.modseq = item[1] + elif isinstance(item, int): + ids.append(item) + return ids + + def gen_parsed_response(text): if not text: return diff --git a/imapclient/test/test_response_parser.py b/imapclient/test/test_response_parser.py index bc66cc6..cc40e43 100644 --- a/imapclient/test/test_response_parser.py +++ b/imapclient/test/test_response_parser.py @@ -12,7 +12,7 @@ from datetime import datetime from imapclient.datetime_util import datetime_to_native from imapclient.fixed_offset import FixedOffset -from imapclient.response_parser import parse_response, parse_fetch_response, ParseError +from imapclient.response_parser import parse_response, parse_message_list, parse_fetch_response, ParseError from imapclient.response_types import Envelope, Address from imapclient.test.util import unittest @@ -159,6 +159,33 @@ class TestParseResponse(unittest.TestCase): parse_response, to_parse) +class TestParseMessageList(unittest.TestCase): + + def test_basic(self): + out = parse_message_list([b'1 2 3']) + self.assertSequenceEqual(out, [1, 2, 3]) + self.assertEqual(out.modseq, None) + + def test_one_id(self): + self.assertSequenceEqual(parse_message_list([b'4']), [4]) + + def test_modseq(self): + out = parse_message_list([b'1 2 3 (modseq 999)']) + self.assertSequenceEqual(out, [1, 2, 3]) + self.assertEqual(out.modseq, 999) + + def test_modseq_no_space(self): + out = parse_message_list([b'1 2 3(modseq 999)']) + self.assertSequenceEqual(out, [1, 2, 3]) + self.assertEqual(out.modseq, 999) + + def test_modseq_interleaved(self): + # Unlikely but test it anyway. + out = parse_message_list([b'1 2 (modseq 9) 3 4']) + self.assertSequenceEqual(out, [1, 2, 3, 4]) + self.assertEqual(out.modseq, 9) + + class TestParseFetchResponse(unittest.TestCase): def test_basic(self): -- 2.43.0