Skip to content
datastructures.py 1.67 KiB
Newer Older
Antoine Millet's avatar
Antoine Millet committed
#!/usr/bin/env python
#coding:utf8

import threading

class BytesBuffer(object):
    '''
    BytesBuffers objects are useful to create socket buffers.
    
    Its behavior is pretty simple and looks like a FIFO queue: you can push data
    on it with push method, and pull a specified amount of data.
    
    .. note::
       All calls to :class:`BytesBuffer` objects are thread-safe.
    '''
    
    def __init__(self, data=None):
        if data is None:
            self._buf = ''
        else:
            self._buf = data
        self._lock = threading.Lock()
    
    def push(self, data):
        '''
        Push data on buffer.
        
        :param data: the data to push on the buffer
        :type data: :class:`str` object
        '''
        
        self._lock.acquire()
        self._buf += data
        self._lock.release()
    
    def pull(self, size=0):
        '''
        Pull the specified amount of data on the buffer.
        
        If size is equal to 0, will return the entire content. If buffer 
        contains less of data than asked, :meth:`pull` will return all the 
        available data.
        
        :param size: size (in bytes) of data to pull on the buffer
        :type size: 0 or positive integer
        :return: asked data
        :rtype: :class:`str` object
        '''
        
        self._lock.acquire()
        if size == 0:
            buf = self._buf
            self._buf = ''
        else:
            buf = self._buf[:size]
            self._buf = self._buf[size:]
        self._lock.release()
        return buf
    
    def __len__(self):
        '''
        Return the size of the buffer.
        '''
        
        return len(self._buf)