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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
//! This crate providers an encoder/decoder for Reed-Solomon erasure code
//!
//! Please note that erasure coding means errors are not directly detected or corrected,
//! but missing data pieces(shards) can be reconstructed given that
//! the configuration provides high enough redundancy.
//!
//! You will have to implement error detection separately(e.g. via checksums)
//! and simply leave out the corrupted shards when attempting to reconstruct
//! the missing data.

#![allow(dead_code)]
mod galois;
mod matrix;

use std::rc::Rc;
use std::cell::RefCell;
use std::ops::Deref;

use matrix::Matrix;

#[derive(Debug)]
pub enum Error {
    NotEnoughShards
}

/// Base unit of data processing
pub type Shard = Rc<RefCell<Box<[u8]>>>;

/// Constructs a shard
///
/// # Example
/// ```rust
/// # #[macro_use] extern crate reed_solomon_erasure;
/// # use reed_solomon_erasure::*;
/// # fn main () {
/// let shard = shard!(1, 2, 3);
/// # }
/// ```
#[macro_export]
macro_rules! shard {
    (
        $( $x:expr ),*
    ) => {
        boxed_u8_into_shard(Box::new([ $( $x ),* ]))
    }
}

/// Constructs vector of shards
///
/// # Example
/// ```rust
/// # #[macro_use] extern crate reed_solomon_erasure;
/// # use reed_solomon_erasure::*;
/// # fn main () {
/// let shards = shards!([1, 2, 3],
///                      [4, 5, 6]);
/// # }
/// ```
#[macro_export]
macro_rules! shards {
    (
        $( [ $( $x:expr ),* ] ),*
    ) => {{
        vec![ $( boxed_u8_into_shard(Box::new([ $( $x ),* ])) ),* ]
    }}
}

mod helper {
    use super::*;

    pub fn calc_offset(offset : Option<usize>) -> usize {
        match offset {
            Some(x) => x,
            None    => 0
        }
    }

    pub fn calc_byte_count(shards     : &[Shard],
                           byte_count : Option<usize>) -> usize {
        match byte_count {
            Some(x) => x,
            None    => shards[0].borrow().len()
        }
    }

    pub fn calc_byte_count_option_shards(shards     : &[Option<Shard>],
                                         offset     : usize,
                                         byte_count : Option<usize>) -> usize {
        match byte_count {
            Some(x) => x,
            None    => {
                for v in shards.iter() {
                    match *v {
                        Some(ref x) => return x.borrow().len() - offset,
                        None    => {},
                    }
                };
                0
            }
        }
    }
}


pub fn boxed_u8_into_shard(b : Box<[u8]>) -> Shard {
    Rc::new(RefCell::new(b))
}

/// Make shard with byte array of zero length
pub fn make_zero_len_shard() -> Shard {
    boxed_u8_into_shard(Box::new([]))
}

pub fn make_zero_len_shards(count : usize) -> Vec<Shard> {
    let mut result = Vec::with_capacity(count);
    for _ in 0..count {
        result.push(make_zero_len_shard());
    }
    result
}

/// Make shard with byte array filled with zeros of some length
pub fn make_blank_shard(size : usize) -> Shard {
    boxed_u8_into_shard(vec![0; size].into_boxed_slice())
}

pub fn make_blank_shards(size : usize, count : usize) -> Vec<Shard> {
    let mut result = Vec::with_capacity(count);
    for _ in 0..count {
        result.push(make_blank_shard(size));
    }
    result
}

/// Transforms vector of shards to vector of option shards
///
/// # Remarks
///
/// Each shard is cloned rather than moved, which may be slow.
///
/// This is mainly useful when you want to repair a vector
/// of shards using `decode_missing`.
pub fn shards_to_option_shards(shards : &Vec<Shard>)
                               -> Vec<Option<Shard>> {
    let mut result = Vec::with_capacity(shards.len());

    for v in shards.iter() {
        let inner : RefCell<Box<[u8]>> = v.deref().clone();
        result.push(Some(Rc::new(inner)));
    }
    result
}

/// Transforms vector of shards into vector of option shards
///
/// # Remarks
///
/// Each shard is moved rather than cloned.
///
/// This is mainly useful when you want to repair a vector
/// of shards using `decode_missing`.
pub fn shards_into_option_shards(shards : Vec<Shard>)
                                 -> Vec<Option<Shard>> {
    let mut result = Vec::with_capacity(shards.len());

    for v in shards.into_iter() {
        result.push(Some(v));
    }
    result
}

/// Transforms a section of vector of option shards to vector of shards
///
/// # Arguments
///
/// * `start` - start of range of option shards you want to use
/// * `count` - number of option shards you want to use
///
/// # Remarks
///
/// Each shard is cloned rather than moved, which may be slow.
///
/// This is mainly useful when you want to convert result of
/// `decode_missing` to the normal and more usable arrangement.
///
/// Panics when any of the shards is missing or the range exceeds number of shards provided.
pub fn option_shards_to_shards(shards : &Vec<Option<Shard>>,
                               start  : Option<usize>,
                               count  : Option<usize>)
                               -> Vec<Shard> {
    let offset = helper::calc_offset(start);
    let count  = match count {
        None    => shards.len(),
        Some(x) => x
    };

    if shards.len() < offset + count {
        panic!("Too few shards, number of shards : {}, offset + count : {}", shards.len(), offset + count);
    }

    let mut result = Vec::with_capacity(shards.len());

    for i in offset..offset + count {
        let shard = match shards[i] {
            Some(ref x) => x,
            None        => panic!("Missing shard, index : {}", i),
        };
        let inner : RefCell<Box<[u8]>> = shard.deref().clone();
        result.push(Rc::new(inner));
    }
    result
}

/// Transforms vector of option shards into vector of shards
///
/// # Remarks
///
/// Each shard is moved rather than cloned.
///
/// This is mainly useful when you want to convert result of
/// `decode_missing` to the normal and more usable arrangement.
pub fn option_shards_into_shards(shards : Vec<Option<Shard>>)
                                 -> Vec<Shard> {
    let mut result = Vec::with_capacity(shards.len());

    for shard in shards.into_iter() {
        let shard = match shard {
            Some(x) => x,
            None    => panic!("Missing shard"),
        };
        result.push(shard);
    }
    result
}

/// Reed-Solomon erasure code encoder/decoder
///
/// # Remarks
/// Notes about usage of `offset` and `byte_count` for all methods/functions below
///
/// `offset` refers to start of the shard you want to as starting point for encoding/decoding.
///
/// `offset` defaults to 0 if it is `None`
///
///  `byte_count` refers to number of bytes, starting from `offset` to use for encoding/decoding.
///
///  `byte_count` defaults to length of shard if it is `None`
pub struct ReedSolomon {
    data_shard_count   : usize,
    parity_shard_count : usize,
    total_shard_count  : usize,
    matrix             : Matrix,
    parity_rows        : Vec<Shard>,
}

impl Clone for ReedSolomon {
    fn clone(&self) -> ReedSolomon {
        let mut parity_rows =
            Vec::with_capacity(self.parity_rows.len());

        for shard in self.parity_rows.iter() {
            let inner : RefCell<Box<[u8]>> = shard.deref().clone();
            parity_rows.push(Rc::new(inner));
        }

        ReedSolomon {
            data_shard_count   : self.data_shard_count,
            parity_shard_count : self.parity_shard_count,
            total_shard_count  : self.total_shard_count,
            matrix             : Matrix::clone(&self.matrix),
            parity_rows
        }
    }
}

impl ReedSolomon {
    fn build_matrix(data_shards : usize, total_shards : usize) -> Matrix {
        let vandermonde = Matrix::vandermonde(total_shards, data_shards);

        let top = vandermonde.sub_matrix(0, 0, data_shards, data_shards);

        vandermonde.multiply(&top.invert().unwrap())
    }

    /// Creates a new instance of Reed-Solomon erasure code encoder/decoder
    pub fn new(data_shards : usize, parity_shards : usize) -> ReedSolomon {
        if 256 < data_shards + parity_shards {
            panic!("Too many shards, max is 256")
        }

        let total_shards = data_shards + parity_shards;
        let matrix       = Self::build_matrix(data_shards, total_shards);
        let mut parity_rows  = Vec::with_capacity(parity_shards);
        for i in 0..parity_shards {
            parity_rows.push(
                Rc::new(
                    RefCell::new(matrix.get_row(data_shards + i))));
        }

        ReedSolomon {
            data_shard_count   : data_shards,
            parity_shard_count : parity_shards,
            total_shard_count  : total_shards,
            matrix,
            parity_rows
        }
    }

    pub fn data_shard_count(&self) -> usize {
        self.data_shard_count
    }

    pub fn parity_shard_count(&self) -> usize {
        self.parity_shard_count
    }

    pub fn total_shard_count(&self) -> usize {
        self.total_shard_count
    }

    fn check_buffer_and_sizes(&self,
                              shards : &Vec<Shard>,
                              offset : usize, byte_count : usize) {
        if shards.len() != self.total_shard_count {
            panic!("Incorrect number of shards : {}", shards.len())
        }

        let shard_length = shards[0].borrow().len();
        for shard in shards.iter() {
            if shard.borrow().len() != shard_length {
                panic!("Shards are of different sizes");
            }
        }

        if shard_length < offset + byte_count {
            panic!("Shards too small, shard length : Some({}), offset + byte_count : {}", shard_length, offset + byte_count);
        }
    }

    fn check_buffer_and_sizes_option_shards(&self,
                                            shards : &Vec<Option<Shard>>,
                                            offset : usize, byte_count : usize) {
        if shards.len() != self.total_shard_count {
            panic!("Incorrect number of shards : {}", shards.len())
        }

        let mut shard_length = None;
        for shard in shards.iter() {
            if let Some(ref s) = *shard {
                match shard_length {
                    None    => shard_length = Some(s.borrow().len()),
                    Some(x) => {
                        if s.borrow().len() != x {
                            panic!("Shards are of different sizes");
                        }
                    }
                }
            }
        }

        if let Some(x) = shard_length {
            if x < offset + byte_count {
                panic!("Shards too small, shard length : Some({}), offset + byte_count : {}", x, offset + byte_count);
            }
        }
    }

    #[inline]
    fn code_first_input_shard(matrix_rows  : &Vec<Shard>,
                              outputs      : &mut [Shard],
                              output_count : usize,
                              offset       : usize,
                              byte_count   : usize,
                              i_input      : usize,
                              input_shard  : &Box<[u8]>) {
        let table = &galois::MULT_TABLE;

        for i_output in 0..output_count {
            let mut output_shard =
                outputs[i_output].borrow_mut();
            let matrix_row       = matrix_rows[i_output].borrow();
            let mult_table_row   = table[matrix_row[i_input] as usize];
            for i_byte in offset..offset + byte_count {
                output_shard[i_byte] =
                    mult_table_row[input_shard[i_byte] as usize];
            }
        }
    }

    #[inline]
    fn code_other_input_shard(matrix_rows  : &Vec<Shard>,
                              outputs      : &mut [Shard],
                              output_count : usize,
                              offset       : usize,
                              byte_count   : usize,
                              i_input      : usize,
                              input_shard  : &Box<[u8]>) {
        let table = &galois::MULT_TABLE;

        for i_output in 0..output_count {
            let mut output_shard = outputs[i_output].borrow_mut();
            let matrix_row       = matrix_rows[i_output].borrow();
            let mult_table_row   = &table[matrix_row[i_input] as usize];
            for i_byte in offset..offset + byte_count {
                output_shard[i_byte] ^= mult_table_row[input_shard[i_byte] as usize];
            }
        }
    }

    // Translated from InputOutputByteTableCodingLoop.java
    fn code_some_shards(matrix_rows  : &Vec<Shard>,
                        inputs       : &[Shard],
                        input_count  : usize,
                        outputs      : &mut [Shard],
                        output_count : usize,
                        offset       : usize,
                        byte_count   : usize) {
        {
            let i_input = 0;
            let input_shard = inputs[i_input].borrow();
            Self::code_first_input_shard(matrix_rows,
                                         outputs, output_count,
                                         offset,  byte_count,
                                         i_input, &input_shard);
        }

        for i_input in 1..input_count {
            let input_shard = inputs[i_input].borrow();
            Self::code_other_input_shard(matrix_rows,
                                         outputs, output_count,
                                         offset, byte_count,
                                         i_input, &input_shard);
        }
    }

    fn code_some_option_shards(matrix_rows  : &Vec<Shard>,
                               inputs       : &[Option<Shard>],
                               input_count  : usize,
                               outputs      : &mut [Shard],
                               output_count : usize,
                               offset       : usize,
                               byte_count   : usize) {
        {
            let i_input = 0;
            let input_shard = match inputs[i_input] {
                Some(ref x) => x.borrow(),
                None        => panic!()
            };
            Self::code_first_input_shard(matrix_rows,
                                         outputs, output_count,
                                         offset,  byte_count,
                                         i_input, &input_shard);
        }

        for i_input in 1..input_count {
            let input_shard = match inputs[i_input] {
                Some(ref x) => x.borrow(),
                None        => panic!()
            };
            Self::code_other_input_shard(matrix_rows,
                                         outputs, output_count,
                                         offset, byte_count,
                                         i_input, &input_shard);
        }
    }

    /// Constructs parity shards
    ///
    /// # Remarks
    ///
    /// This overwrites data in the parity shard slots
    ///
    /// Panics when the shards are of different sizes, number of shards does not match codec's configuration, or when the shards' length is shorter than required
    pub fn encode_parity(&self,
                         shards     : &mut Vec<Shard>,
                         offset     : Option<usize>,
                         byte_count : Option<usize>) {
        let offset     = helper::calc_offset(offset);
        let byte_count = helper::calc_byte_count(shards, byte_count);

        self.check_buffer_and_sizes(shards, offset, byte_count);

        let (inputs, outputs) = shards.split_at_mut(self.data_shard_count);

        Self::code_some_shards(&self.parity_rows,
                               inputs,  self.data_shard_count,
                               outputs, self.parity_shard_count,
                               offset, byte_count);
    }

    // Translated from CodingLoopBase.java
    fn check_some_shards(matrix_rows : &Vec<Shard>,
                         inputs      : &[Shard],
                         input_count : usize,
                         to_check    : &[Shard],
                         check_count : usize,
                         offset      : usize,
                         byte_count  : usize)
                         -> bool {
        let table = &galois::MULT_TABLE;

        for i_byte in offset..offset + byte_count {
            for i_output in 0..check_count {
                let matrix_row = matrix_rows[i_output as usize].borrow();
                let mut value = 0;
                for i_input in 0..input_count {
                    value ^=
                        table
                        [matrix_row[i_input]     as usize]
                        [inputs[i_input].borrow()[i_byte] as usize];
                }
                if to_check[i_output].borrow()[i_byte] != value {
                    return false
                }
            }
        }
        true
    }

    /// Verify correctness of parity shards
    pub fn is_parity_correct(&self,
                             shards     : &Vec<Shard>,
                             offset     : Option<usize>,
                             byte_count : Option<usize>) -> bool {
        let offset     = helper::calc_offset(offset);
        let byte_count = helper::calc_byte_count(shards, byte_count);

        self.check_buffer_and_sizes(shards, offset, byte_count);

        let (data_shards, to_check) = shards.split_at(self.data_shard_count);

        Self::check_some_shards(&self.parity_rows,
                                data_shards, self.data_shard_count,
                                to_check,    self.parity_shard_count,
                                offset, byte_count)
    }

    /// Reconstruct missing shards
    ///
    /// # Remarks
    ///
    /// Panics when the shards are of different sizes, number of shards does not match codec's configuration, or when the shards' length is shorter than required
    pub fn decode_missing(&self,
                          shards     : &mut Vec<Option<Shard>>,
                          offset     : Option<usize>,
                          byte_count : Option<usize>)
                          -> Result<(), Error> {
        let offset     = helper::calc_offset(offset);
        let byte_count = helper::calc_byte_count_option_shards(shards,
                                                               offset,
                                                               byte_count);

        self.check_buffer_and_sizes_option_shards(shards, offset, byte_count);

        // Quick check: are all of the shards present?  If so, there's
        // nothing to do.
        let mut number_present = 0;
        for v in shards.iter() {
            if let Some(_) = *v { number_present += 1; }
        }
        if number_present == self.total_shard_count {
            // Cool.  All of the shards data data.  We don't
            // need to do anything.
            return Ok(())
        }

        // More complete sanity check
        if number_present < self.data_shard_count {
            return Err(Error::NotEnoughShards)
        }

        // Pull out the rows of the matrix that correspond to the
        // shards that we have and build a square matrix.  This
        // matrix could be used to generate the shards that we have
        // from the original data.
        //
        // Also, pull out an array holding just the shards that
        // correspond to the rows of the submatrix.  These shards
        // will be the input to the decoding process that re-creates
        // the missing data shards.
        let mut sub_matrix =
            Matrix::new(self.data_shard_count, self.data_shard_count);
        let mut sub_shards : Vec<Shard> =
            Vec::with_capacity(self.data_shard_count);
        {
            for matrix_row in 0..self.total_shard_count {
                let sub_matrix_row = sub_shards.len();

                if sub_matrix_row >= self.data_shard_count { break; }

                if let Some(ref shard) = shards[matrix_row] {
                    for c in 0..self.data_shard_count {
                        sub_matrix.set(sub_matrix_row, c,
                                       self.matrix.get(matrix_row, c));
                    }
                    sub_shards.push(Rc::clone(shard));
                }
            }
        }

        // Invert the matrix, so we can go from the encoded shards
        // back to the original data.  Then pull out the row that
        // generates the shard that we want to decode.  Note that
        // since this matrix maps back to the orginal data, it can
        // be used to create a data shard, but not a parity shard.
        let data_decode_matrix = sub_matrix.invert().unwrap();

        // Re-create any data shards that were missing.
        //
        // The input to the coding is all of the shards we actually
        // have, and the output is the missing data shards.  The computation
        // is done using the special decode matrix we just built.
        let mut matrix_rows : Vec<Shard> =
            make_zero_len_shards(self.parity_shard_count);
        {
            let mut outputs : Vec<Shard> =
                make_blank_shards(offset + byte_count,
                                  self.parity_shard_count);
            let mut output_count = 0;
            for i_shard in 0..self.data_shard_count {
                if let None = shards[i_shard] {
                    // link slot in outputs to the missing slot in shards
                    shards[i_shard] =
                        Some(Rc::clone(&outputs[output_count]));
                    matrix_rows[output_count] =
                        boxed_u8_into_shard(
                            data_decode_matrix.get_row(i_shard));
                    output_count += 1;
                }
            }
            Self::code_some_shards(&matrix_rows,
                                   &sub_shards,  self.data_shard_count,
                                   &mut outputs, output_count,
                                   offset, byte_count);
        }

        // Now that we have all of the data shards intact, we can
        // compute any of the parity that is missing.
        //
        // The input to the coding is ALL of the data shards, including
        // any that we just calculated.  The output is whichever of the
        // data shards were missing.
        {
            let mut outputs : Vec<Shard> =
                make_blank_shards(offset + byte_count,
                                  self.parity_shard_count);
            let mut output_count = 0;
            for i_shard in self.data_shard_count..self.total_shard_count {
                if let None = shards[i_shard] {
                    // link slot in outputs to the missing slot in shards
                    shards[i_shard] =
                        Some(Rc::clone(&outputs[output_count]));
                    matrix_rows[output_count] =
                        Rc::clone(
                            &self.parity_rows[i_shard
                                              - self.data_shard_count]);
                    output_count += 1;
                }
            }
            Self::code_some_option_shards(&matrix_rows,
                                          &shards, self.data_shard_count,
                                          &mut outputs, output_count,
                                          offset, byte_count);
        }

        Ok (())
    }
}

#[cfg(test)]
mod tests {
    extern crate rand;

    use super::*;

    macro_rules! make_random_shards {
        ($size:expr, $per_shard:expr) => {{
            let mut shards = Vec::with_capacity(13);
            for _ in 0..$size {
                shards.push(make_blank_shard($per_shard));
            }

            for s in shards.iter_mut() {
                fill_random(s);
            }

            shards
        }}
    }

    fn is_increasing_and_contains_data_row(indices : &Vec<usize>) -> bool {
        let cols = indices.len();
        for i in 0..cols-1 {
            if indices[i] >= indices[i+1] {
                return false
            }
        }
        return indices[0] < cols
    }

    fn increment_indices(indices : &mut Vec<usize>,
                         index_bound : usize) -> bool {
        for i in (0..indices.len()).rev() {
            indices[i] += 1;
            if indices[i] < index_bound {
                break;
            }

            if i == 0 {
                return false
            }

            indices[i] = 0
        }

        return true
    }

    fn increment_indices_until_increasing_and_contains_data_row(indices : &mut Vec<usize>, max_index : usize) -> bool {
        loop {
            let valid = increment_indices(indices, max_index);
            if !valid {
                return false
            }

            if is_increasing_and_contains_data_row(indices) {
                return true
            }
        }
    }

    fn find_singular_sub_matrix(m : Matrix) -> Option<Matrix> {
        let rows = m.row_count();
        let cols = m.column_count();
        let mut row_indices = Vec::with_capacity(cols);
        while increment_indices_until_increasing_and_contains_data_row(&mut row_indices, rows) {
            let mut sub_matrix = Matrix::new(cols, cols);
            for i in 0..row_indices.len() {
                let r = row_indices[i];
                for c in 0..cols {
                    sub_matrix.set(i, c, m.get(r, c));
                }
            }

            match sub_matrix.invert() {
                Err(matrix::Error::SingularMatrix) => return Some(sub_matrix),
                whatever => whatever.unwrap()
            };
        }
        None
    }

    fn fill_random(arr : &mut Shard) {
        for a in arr.borrow_mut().iter_mut() {
            *a = rand::random::<u8>();
        }
    }

    #[test]
    fn test_encoding() {
        let per_shard = 50_000;

        let r = ReedSolomon::new(10, 3);

        let mut shards = make_random_shards!(13, per_shard);

        r.encode_parity(&mut shards, None, None);
        assert!(r.is_parity_correct(&shards, None, None));
    }

    #[test]
    fn test_decode_missing() {
        let per_shard = 100_000;

        let r = ReedSolomon::new(8, 5);

        let mut shards = make_random_shards!(13, per_shard);

        r.encode_parity(&mut shards, None, None);

        let master_copy = shards.clone();

        let mut shards = shards_to_option_shards(&shards);

        // Try to decode with all shards present
        r.decode_missing(&mut shards,
                         None, None).unwrap();
        {
            let shards = option_shards_to_shards(&shards, None, None);
            assert!(r.is_parity_correct(&shards, None, None));
            assert_eq!(shards, master_copy);
        }

        // Try to decode with 10 shards
        shards[0] = None;
        shards[2] = None;
        //shards[4] = None;
        r.decode_missing(&mut shards,
                         None, None).unwrap();
        {
            let shards = option_shards_to_shards(&shards, None, None);
            assert!(r.is_parity_correct(&shards, None, None));
            assert_eq!(shards, master_copy);
        }

        // Try to deocde with 6 data and 4 parity shards
        shards[0] = None;
        shards[2] = None;
        shards[12] = None;
        r.decode_missing(&mut shards,
                         None, None).unwrap();
        {
            let shards = option_shards_to_shards(&shards, None, None);
            assert!(r.is_parity_correct(&shards, None, None));
            assert_eq!(shards, master_copy);
        }

        // Try to decode with 7 data and 1 parity shards
        shards[0] = None;
        shards[1] = None;
        shards[9] = None;
        shards[10] = None;
        shards[11] = None;
        shards[12] = None;
        match r.decode_missing(&mut shards,
                               None, None) {
            Err(Error::NotEnoughShards) => {},
            Ok(()) => panic!("Should fail due to not enough shards"),
        }
    }

    #[test]
    fn test_is_parity_correct() {
        let per_shard = 33_333;

        let r = ReedSolomon::new(10, 4);

        let mut shards = make_random_shards!(14, per_shard);

        r.encode_parity(&mut shards, None, None);
        assert!(r.is_parity_correct(&shards, None, None));

        // corrupt shards
        fill_random(&mut shards[5]);
        assert!(!r.is_parity_correct(&shards, None, None));

        // Re-encode
        r.encode_parity(&mut shards, None, None);
        fill_random(&mut shards[1]);
        assert!(!r.is_parity_correct(&shards, None, None));
    }

    #[test]
    fn test_one_encode() {
        let r = ReedSolomon::new(5, 5);

        let mut shards = shards!([0, 1],
                                 [4, 5],
                                 [2, 3],
                                 [6, 7],
                                 [8, 9],
                                 [0, 0],
                                 [0, 0],
                                 [0, 0],
                                 [0, 0],
                                 [0, 0]);

        r.encode_parity(&mut shards, None, None);
        { assert_eq!(shards[5].borrow()[0], 12);
          assert_eq!(shards[5].borrow()[1], 13); }
        { assert_eq!(shards[6].borrow()[0], 10);
          assert_eq!(shards[6].borrow()[1], 11); }
        { assert_eq!(shards[7].borrow()[0], 14);
          assert_eq!(shards[7].borrow()[1], 15); }
        { assert_eq!(shards[8].borrow()[0], 90);
          assert_eq!(shards[8].borrow()[1], 91); }
        { assert_eq!(shards[9].borrow()[0], 94);
          assert_eq!(shards[9].borrow()[1], 95); }

        assert!(r.is_parity_correct(&shards, None, None));

        shards[8].borrow_mut()[0] += 1;
        assert!(!r.is_parity_correct(&shards, None, None));
    }
}