File: compress.py

package info (click to toggle)
python-bitarray 0.8.0-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 320 kB
  • sloc: ansic: 2,493; python: 2,269; makefile: 52; sh: 7
file content (40 lines) | stat: -rw-r--r-- 952 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""
Demonstrates how the bz2 module may be used to create a compressed object
which represents a bitarray.
"""
import bz2

from bitarray import bitarray


def compress(ba):
    """
    Given a bitarray, return an object which represents all information
    within the bitarray in a compresed form.
    The function `decompress` can be used to restore the bitarray from the
    compresed object.
    """
    assert isinstance(ba, bitarray)
    return ba.length(), bz2.compress(ba.tobytes()), ba.endian()


def decompress(obj):
    """
    Given an object (created by `compress`), return the a copy of the
    original bitarray.
    """
    n, data, endian = obj
    res = bitarray(endian=endian)
    res.frombytes(bz2.decompress(data))
    del res[n:]
    return res


if __name__ == '__main__':
    a = bitarray(12345)
    a.setall(0)
    a[::10] = True
    c = compress(a)
    print c
    b = decompress(c)
    assert a == b, a.endian() == b.endian()