aboutsummaryrefslogtreecommitdiffstats
path: root/library/python/compress/__init__.py
blob: 380ec47dca849ff9f9117f1f23265fe716877895 (plain) (blame)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
from io import open

import struct
import json
import os
import logging

import library.python.par_apply as lpp
import library.python.codecs as lpc


logger = logging.getLogger('compress')


def list_all_codecs():
    return sorted(frozenset(lpc.list_all_codecs()))


def find_codec(ext):
    def ext_compress(x):
        return lpc.dumps(ext, x)

    def ext_decompress(x):
        return lpc.loads(ext, x)

    ext_decompress(ext_compress(b''))

    return {'c': ext_compress, 'd': ext_decompress, 'n': ext}


def codec_for(path):
    for ext in reversed(path.split('.')):
        try:
            return find_codec(ext)
        except Exception as e:
            logger.debug('in codec_for(): %s', e)

    raise Exception('unsupported file %s' % path)


def compress(fr, to, codec=None, fopen=open, threads=1):
    if codec:
        codec = find_codec(codec)
    else:
        codec = codec_for(to)

    func = codec['c']

    def iter_blocks():
        with fopen(fr, 'rb') as f:
            while True:
                chunk = f.read(16 * 1024 * 1024)

                if chunk:
                    yield chunk
                else:
                    yield b''

                    return

    def iter_results():
        info = {
            'codec': codec['n'],
        }

        if fr:
            info['size'] = os.path.getsize(fr)

        yield json.dumps(info, sort_keys=True) + '\n'

        for c in lpp.par_apply(iter_blocks(), func, threads):
            yield c

    with fopen(to, 'wb') as f:
        for c in iter_results():
            logger.debug('complete %s', len(c))
            f.write(struct.pack('<I', len(c)))

            try:
                f.write(c)
            except TypeError:
                f.write(c.encode('utf-8'))


def decompress(fr, to, codec=None, fopen=open, threads=1):
    def iter_chunks():
        with fopen(fr, 'rb') as f:
            cnt = 0

            while True:
                ll = f.read(4)

                if ll:
                    ll = struct.unpack('<I', ll)[0]

                if ll:
                    if ll > 100000000:
                        raise Exception('broken stream')

                    yield f.read(ll)

                    cnt += ll
                else:
                    if not cnt:
                        raise Exception('empty stream')

                    return

    it = iter_chunks()
    extra = []

    for chunk in it:
        hdr = {}

        try:
            hdr = json.loads(chunk)
        except Exception as e:
            logger.info('can not parse header, suspect old format: %s', e)
            extra.append(chunk)

        break

    def resolve_codec():
        if 'codec' in hdr:
            return find_codec(hdr['codec'])

        if codec:
            return find_codec(codec)

        return codec_for(fr)

    dc = resolve_codec()['d']

    def iter_all_chunks():
        for x in extra:
            yield x

        for x in it:
            yield x

    with fopen(to, 'wb') as f:
        for c in lpp.par_apply(iter_all_chunks(), dc, threads):
            if c:
                logger.debug('complete %s', len(c))
                f.write(c)
            else:
                break