piecebuffer.py 1.8 KB

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