]> git.rkrishnan.org Git - tahoe-lafs/zfec.git/blob - zfec/zfec/easyfec.py
docs: update docs and metadata
[tahoe-lafs/zfec.git] / zfec / zfec / easyfec.py
1 # zfec -- a fast C implementation of Reed-Solomon erasure coding with
2 # command-line, C, and Python interfaces
3
4 import zfec
5
6 # div_ceil() was copied from the pyutil library.
7 def div_ceil(n, d):
8     """
9     The smallest integer k such that k*d >= n.
10     """
11     return (n/d) + (n%d != 0)
12
13 from base64 import b32encode
14 def ab(x): # debuggery
15     if len(x) >= 3:
16         return "%s:%s" % (len(x), b32encode(x[-3:]),)
17     elif len(x) == 2:
18         return "%s:%s" % (len(x), b32encode(x[-2:]),)
19     elif len(x) == 1:
20         return "%s:%s" % (len(x), b32encode(x[-1:]),)
21     elif len(x) == 0:
22         return "%s:%s" % (len(x), "--empty--",)
23
24 class Encoder(object):
25     def __init__(self, k, m):
26         self.fec = zfec.Encoder(k, m)
27
28     def encode(self, data):
29         """
30         @param data: string
31
32         @return: a sequence of m blocks -- any k of which suffice to
33             reconstruct the input data
34         """
35         chunksize = div_ceil(len(data), self.fec.k)
36         l = [ data[i*chunksize:(i+1)*chunksize] + "\x00" * min(chunksize, (((i+1)*chunksize)-len(data))) for i in range(self.fec.k) ]
37         assert len(l) == self.fec.k, (len(l), self.fec.k,)
38         assert (not l) or (not [ x for x in l if len(x) != len(l[0]) ], (len(l), [ ab(x) for x in l ], chunksize, self.fec.k, len(data),))
39         return self.fec.encode(l)
40         
41 class Decoder(object):
42     def __init__(self, k, m):
43         self.fec = zfec.Decoder(k, m)
44
45     def decode(self, blocks, sharenums, padlen):
46         """
47         @param padlen: the number of bytes of padding to strip off;  Note that
48             the padlen is always equal to (blocksize times k) minus the length
49             of data.  (Therefore, padlen can be 0.)
50         """
51         data = ''.join(self.fec.decode(blocks, sharenums))
52         if padlen:
53             return data[:-padlen]
54         else:
55             return data
56
57 # zfec -- fast forward error correction library with Python interface
58
59 # Copyright (C) 2007 Allmydata, Inc.
60 # Author: Zooko Wilcox-O'Hearn
61
62 # This file is part of zfec.
63
64 # See README.rst for licensing information.