Subversion Repositories svnkaklik

Rev

Details | Last modification | View Log

Rev Author Line No. Line
36 kaklik 1
# Written by John Hoffman
2
# see LICENSE.txt for license information
3
 
4
from array import array
5
from threading import Lock
6
# import inspect
7
try:
8
    True
9
except:
10
    True = 1
11
    False = 0
12
 
13
DEBUG = False
14
 
15
class SingleBuffer:
16
    def __init__(self, pool):
17
        self.pool = pool
18
        self.buf = array('c')
19
 
20
    def init(self):
21
        if DEBUG:
22
            print self.count
23
            '''
24
            for x in xrange(6,1,-1):
25
                try:
26
                    f = inspect.currentframe(x).f_code
27
                    print (f.co_filename,f.co_firstlineno,f.co_name)
28
                    del f
29
                except:
30
                    pass
31
            print ''
32
            '''
33
        self.length = 0
34
 
35
    def append(self, s):
36
        l = self.length+len(s)
37
        self.buf[self.length:l] = array('c',s)
38
        self.length = l
39
 
40
    def __len__(self):
41
        return self.length
42
 
43
    def __getslice__(self, a, b):
44
        if b > self.length:
45
            b = self.length
46
        if b < 0:
47
            b += self.length
48
        if a == 0 and b == self.length and len(self.buf) == b:
49
            return self.buf  # optimization
50
        return self.buf[a:b]
51
 
52
    def getarray(self):
53
        return self.buf[:self.length]
54
 
55
    def release(self):
56
        if DEBUG:
57
            print -self.count
58
        self.pool.release(self)
59
 
60
 
61
class BufferPool:
62
    def __init__(self):
63
        self.pool = []
64
        self.lock = Lock()
65
        if DEBUG:
66
            self.count = 0
67
 
68
    def new(self):
69
        self.lock.acquire()
70
        if self.pool:
71
            x = self.pool.pop()
72
        else:
73
            x = SingleBuffer(self)
74
            if DEBUG:
75
                self.count += 1
76
                x.count = self.count
77
        x.init()
78
        self.lock.release()
79
        return x
80
 
81
    def release(self, x):
82
        self.pool.append(x)
83
 
84
 
85
_pool = BufferPool()
86
PieceBuffer = _pool.new