1 # zfec -- a fast C implementation of Reed-Solomon erasure coding with
2 # command-line, C, and Python interfaces
6 # div_ceil() was copied from the pyutil library.
9 The smallest integer k such that k*d >= n.
11 return (n/d) + (n%d != 0)
13 from base64 import b32encode
14 def ab(x): # debuggery
16 return "%s:%s" % (len(x), b32encode(x[-3:]),)
18 return "%s:%s" % (len(x), b32encode(x[-2:]),)
20 return "%s:%s" % (len(x), b32encode(x[-1:]),)
22 return "%s:%s" % (len(x), "--empty--",)
24 class Encoder(object):
25 def __init__(self, k, m):
26 self.fec = zfec.Encoder(k, m)
28 def encode(self, data):
32 @return: a sequence of m blocks -- any k of which suffice to
33 reconstruct the input data
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)
41 class Decoder(object):
42 def __init__(self, k, m):
43 self.fec = zfec.Decoder(k, m)
45 def decode(self, blocks, sharenums, padlen):
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.)
51 data = ''.join(self.fec.decode(blocks, sharenums))
57 # zfec -- fast forward error correction library with Python interface
59 # Copyright (C) 2007 Allmydata, Inc.
60 # Author: Zooko Wilcox-O'Hearn
62 # This file is part of zfec.
64 # See README.rst for licensing information.