messages.py 文件源码

python
阅读 51 收藏 0 点赞 0 评论 0

项目:py2p 作者: p2p-today 项目源码 文件源码
def compress(msg, method):
    # type: (bytes, int) -> bytes
    """Shortcut method for compression

    Args:
        msg:    The message you wish to compress, the type required is
                    defined by the requested method
        method: The compression method you wish to use. Supported
                    (assuming installed):

                    - :py:data:`~py2p.flags.gzip`
                    - :py:data:`~py2p.flags.zlib`
                    - :py:data:`~py2p.flags.bz2`
                    - :py:data:`~py2p.flags.lzma`
                    - :py:data:`~py2p.flags.snappy`

    Returns:
        Defined by the compression method, but typically the bytes of the
        compressed message

    Warning:
        The types fed are dependent on which compression method you use.
        Best to assume most values are :py:class:`bytes` or
        :py:class:`bytearray`

    Raises:
        ValueError: if there is an unknown compression method, or a
            method-specific error
    """
    if method in (flags.gzip, flags.zlib):
        wbits = 15 + (16 * (method == flags.gzip))
        compressor = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
                                      zlib.DEFLATED, wbits)
        return compressor.compress(msg) + compressor.flush()
    elif method == flags.bz2:
        return bz2.compress(msg)
    elif method == flags.lzma:
        return lzma.compress(msg)
    elif method == flags.snappy:
        return snappy.compress(msg)
    else:  # pragma: no cover
        raise ValueError('Unknown compression method')
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号