Commit 2d15883e authored by Guido van Rossum's avatar Guido van Rossum

added seekable option; save unix from lines; speed up islast()

parent 0b900faf
...@@ -43,29 +43,39 @@ import string ...@@ -43,29 +43,39 @@ import string
import time import time
_blanklines = ('\r\n', '\n') # Optimization for islast()
class Message: class Message:
# Initialize the class instance and read the headers. # Initialize the class instance and read the headers.
def __init__(self, fp): def __init__(self, fp, seekable = 1):
self.fp = fp self.fp = fp
self.seekable = seekable
self.startofheaders = None
self.startofbody = None
# #
try: if self.seekable:
self.startofheaders = self.fp.tell() try:
except IOError: self.startofheaders = self.fp.tell()
self.startofheaders = None except IOError:
self.seekable = 0
# #
self.readheaders() self.readheaders()
# #
try: if self.seekable:
self.startofbody = self.fp.tell() try:
except IOError: self.startofbody = self.fp.tell()
self.startofbody = None except IOError:
self.seekable = 0
# Rewind the file to the start of the body (if seekable). # Rewind the file to the start of the body (if seekable).
def rewindbody(self): def rewindbody(self):
if not self.seekable:
raise IOError, "unseekable file"
self.fp.seek(self.startofbody) self.fp.seek(self.startofbody)
...@@ -83,6 +93,7 @@ class Message: ...@@ -83,6 +93,7 @@ class Message:
# reproduce the header exactly as it appears in the file). # reproduce the header exactly as it appears in the file).
def readheaders(self): def readheaders(self):
self.unixfrom = ''
self.headers = list = [] self.headers = list = []
self.status = '' self.status = ''
headerseen = 0 headerseen = 0
...@@ -94,6 +105,7 @@ class Message: ...@@ -94,6 +105,7 @@ class Message:
break break
# Skip unix From name time lines # Skip unix From name time lines
if firstline and line[:5] == 'From ': if firstline and line[:5] == 'From ':
self.unixfrom = self.unixfrom + line
continue continue
firstline = 0 firstline = 0
if self.islast(line): if self.islast(line):
...@@ -112,9 +124,9 @@ class Message: ...@@ -112,9 +124,9 @@ class Message:
else: else:
self.status = 'Bad header' self.status = 'Bad header'
# Try to undo the read. # Try to undo the read.
try: if self.seekable:
self.fp.seek(-len(line), 1) self.fp.seek(-len(line), 1)
except IOError: else:
self.status = \ self.status = \
self.status + '; bad seek' self.status + '; bad seek'
break break
...@@ -128,7 +140,7 @@ class Message: ...@@ -128,7 +140,7 @@ class Message:
# sockets) a line consisting of \r\n also matches. # sockets) a line consisting of \r\n also matches.
def islast(self, line): def islast(self, line):
return line == '\n' or line == '\r\n' return line in _blanklines
# Look through the list of headers and find all lines matching # Look through the list of headers and find all lines matching
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment