blob: 5b06f922d489fd9f449dd361eb7cfee299c9a999 [file] [log] [blame]
Guido van Rossum5c971671996-07-22 15:23:25 +00001"""File-like objects that read/write an array buffer.
2
3This implements (nearly) all stdio methods.
4
5f = ArrayIO() # ready for writing
6f = ArrayIO(buf) # ready for reading
7f.close() # explicitly release resources held
8flag = f.isatty() # always false
9pos = f.tell() # get current position
10f.seek(pos) # set current position
11f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
12buf = f.read() # read until EOF
13buf = f.read(n) # read up to n bytes
14buf = f.readline() # read until end of line ('\n') or EOF
15list = f.readlines()# list of f.readline() results until EOF
16f.write(buf) # write at current position
17f.writelines(list) # for line in list: f.write(line)
18f.getvalue() # return whole file's contents as a string
19
20Notes:
21- This is very similar to StringIO. StringIO is faster for reading,
22 but ArrayIO is faster for writing.
23- ArrayIO uses an array object internally, but all its interfaces
24 accept and return strings.
25- Using a real file is often faster (but less convenient).
26- fileno() is left unimplemented so that code which uses it triggers
27 an exception early.
28- Seeking far beyond EOF and then writing will insert real null
29 bytes that occupy space in the buffer.
30- There's a simple test set (see end of this file).
31"""
32
33import string
34from array import array
35
36class ArrayIO:
37 def __init__(self, buf = ''):
38 self.buf = array('c', buf)
39 self.pos = 0
40 self.closed = 0
41 self.softspace = 0
42 def close(self):
43 if not self.closed:
44 self.closed = 1
45 del self.buf, self.pos
46 def isatty(self):
47 return 0
48 def seek(self, pos, mode = 0):
49 if mode == 1:
50 pos = pos + self.pos
51 elif mode == 2:
52 pos = pos + len(self.buf)
53 self.pos = max(0, pos)
54 def tell(self):
55 return self.pos
56 def read(self, n = -1):
57 if n < 0:
58 newpos = len(self.buf)
59 else:
60 newpos = min(self.pos+n, len(self.buf))
61 r = self.buf[self.pos:newpos].tostring()
62 self.pos = newpos
63 return r
64 def readline(self):
65 i = string.find(self.buf[self.pos:].tostring(), '\n')
66 if i < 0:
67 newpos = len(self.buf)
68 else:
69 newpos = self.pos+i+1
70 r = self.buf[self.pos:newpos].tostring()
71 self.pos = newpos
72 return r
73 def readlines(self):
74 lines = string.splitfields(self.read(), '\n')
75 if not lines:
76 return lines
77 for i in range(len(lines)-1):
78 lines[i] = lines[i] + '\n'
79 if not lines[-1]:
80 del lines[-1]
81 return lines
82 def write(self, s):
83 if not s: return
84 a = array('c', s)
85 n = self.pos - len(self.buf)
86 if n > 0:
87 self.buf[len(self.buf):] = array('c', '\0')*n
88 newpos = self.pos + len(a)
89 self.buf[self.pos:newpos] = a
90 self.pos = newpos
91 def writelines(self, list):
92 self.write(string.joinfields(list, ''))
93 def flush(self):
94 pass
95 def getvalue(self):
96 return self.buf.tostring()
97
98
99# A little test suite
100
101def test():
102 import sys
103 if sys.argv[1:]:
104 file = sys.argv[1]
105 else:
106 file = '/etc/passwd'
107 lines = open(file, 'r').readlines()
108 text = open(file, 'r').read()
109 f = ArrayIO()
110 for line in lines[:-2]:
111 f.write(line)
112 f.writelines(lines[-2:])
113 if f.getvalue() != text:
114 raise RuntimeError, 'write failed'
115 length = f.tell()
116 print 'File length =', length
117 f.seek(len(lines[0]))
118 f.write(lines[1])
119 f.seek(0)
120 print 'First line =', `f.readline()`
121 here = f.tell()
122 line = f.readline()
123 print 'Second line =', `line`
124 f.seek(-len(line), 1)
125 line2 = f.read(len(line))
126 if line != line2:
127 raise RuntimeError, 'bad result after seek back'
128 f.seek(len(line2), 1)
129 list = f.readlines()
130 line = list[-1]
131 f.seek(f.tell() - len(line))
132 line2 = f.read()
133 if line != line2:
134 raise RuntimeError, 'bad result after seek back from EOF'
135 print 'Read', len(list), 'more lines'
136 print 'File length =', f.tell()
137 if f.tell() != length:
138 raise RuntimeError, 'bad length'
139 f.close()
140
141if __name__ == '__main__':
142 test()