iocp / iocp.py

'''iocp tries to mimic Go's `io.Copy`_ function which copies from everything
that is an io.Reader to anything that is an io.Writer.

The Python world of things is not that organized, so iocp.copy will try to do a
best guess about which are the right function to call when reading and writing.

For example, checking md5 signature of a file::

    md5 = hashlib.md5()
    with open('/path/to/file') as fo:
        iocp(fo, md5)
    print md5.hexdigest()

.. _`io.Copy`:  http://golang.org/pkg/io/#Copy
'''

__version__ = '0.1.0'

READ_FNS = [
    'read',  # file, StringIO ...
    'recv',  # socket
]

WRITE_FNS = [
    'write',  # file, StringIO, ...
    'send',  # socket
    'update',  # hashlib ...
]

# Default buffer size
BUFSIZE = 32 * 1024


def find_fn(obj, names, name):
    '''Find function in from list of names, raise ValueError not found.'''
    for name in names:
        fn = getattr(obj, name, None)
        if fn:
            return fn

    raise ValueError('cannot find {} function for {}'.format(name, obj))


def copy(src, dest, bufsize=BUFSIZE):
    '''Copy from source to destination, return number of bytes read.

    Since Python's "write" functions don't return number of bytes written, we
    return number of bytes read as best estimation.
    '''
    write = find_fn(dest, WRITE_FNS, 'write')
    read = find_fn(src, READ_FNS, 'read')

    nwritten = 0
    while True:
            try:
                buf = read(bufsize)
            except EOFError:
                buf = ''

            if not buf:
                break

            nwritten += len(buf)
            write(buf)

    return nwritten
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.