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
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]

use std::convert::{TryFrom, TryInto};
use std::iter;

/// Initialize tables for fast Erasure Code encode and decode.
///
/// Generates the expanded tables needed for fast encode or decode for erasure codes on blocks of
/// data. 32 bytes is generated for each input coefficient.
///
/// # Arguments:
///
/// * `k`:             Number of vector sources or rows in the generator matrix for coding.
/// * `rows`:          Number of output vectors to concurrently encode/decode.
/// * `encode_matrix`: Input coefficients used to encode or decode data.
/// * `buf`:           Buffer to write the concatenated output tables generated from input
///                    coefficients to.  Must be of length `32 * k * rows`.
///
/// # Panics:
/// If the length of `encode_matrix` is not `k * rows` or the length of `buf` is not
/// `32 * k * rows`.
pub fn ec_init_tables(
    k: usize,
    rows: usize,
    encode_matrix: impl AsRef<[u8]>,
    mut buf: impl AsMut<[u8]>,
) {
    assert_eq!(encode_matrix.as_ref().len(), k * rows);

    let gftbls_len = k * rows * 32;
    assert_eq!(buf.as_mut().len(), gftbls_len);

    unsafe {
        libisal_sys::ec_init_tables(
            k.try_into().unwrap(),
            rows.try_into().unwrap(),
            encode_matrix.as_ref().as_ptr(),
            buf.as_mut().as_mut_ptr(),
        );
    }
}

/// Initialize tables for fast Erasure Code encode and decode.
///
/// Generates the expanded tables needed for fast encode or decode for erasure codes on blocks of
/// data. 32 bytes is generated for each input coefficient.
///
/// # Arguments:
///
/// * `k`:             The number of vector sources or rows in the generator matrix for coding.
/// * `rows`:          The number of output vectors to concurrently encode/decode.
/// * `encode_matrix`: The input coefficients used to encode or decode data.
///
/// # Panics:
/// If the length of `encode_matrix` is not `k * rows`.
#[must_use]
pub fn ec_init_tables_owned(k: usize, rows: usize, encode_matrix: impl AsRef<[u8]>) -> Vec<u8> {
    assert_eq!(encode_matrix.as_ref().len(), k * rows);
    let gftbls_len = k * rows * 32;
    let mut gftbls = Vec::with_capacity(gftbls_len);
    unsafe {
        libisal_sys::ec_init_tables(
            k.try_into().unwrap(),
            rows.try_into().unwrap(),
            encode_matrix.as_ref().as_ptr(),
            gftbls.as_mut_ptr(),
        );
        gftbls.set_len(gftbls_len);
    }
    gftbls
}

/// Generate or decode erasure codes on blocks of data, runs appropriate version.
///
/// Given a list of source data blocks, generate one or multiple blocks of
/// encoded data as specified by a matrix of `GF(2^8)` coefficients. When given a
/// suitable set of coefficients, this function will perform the fast generation
/// or decoding of Reed-Solomon type erasure codes.
///
/// This function determines what instruction sets are enabled and
/// selects the appropriate version at runtime.
///
/// # Arguments:
///
/// * `len`:    Length of each block of data (vector) of source or dest data.
/// * `k`:      The number of vector sources or rows in the generator matrix for coding.
/// * `rows`:   The number of output vectors to concurrently encode/decode.
/// * `gftbls`: Input tables generated from coding coefficients in `ec_init_tables()`. Must be of
///             size `32 * k * rows`
/// * `data`:   Source input slices.
/// * `bufs`:   Buffers to write coded data to.
pub fn ec_encode_data<T, M>(
    len: usize,
    k: usize,
    rows: usize,
    gftbls: impl AsRef<[u8]>,
    data: impl AsRef<[T]>,
    mut bufs: impl AsMut<[M]>,
) where
    T: AsRef<[u8]>,
    M: AsMut<[u8]>,
{
    assert_eq!(gftbls.as_ref().len(), 32 * k * rows);
    assert_eq!(bufs.as_mut().len(), rows);
    assert!(bufs
        .as_mut()
        .iter_mut()
        .all(|buf| buf.as_mut().len() == len));
    let data_ptrs = data
        .as_ref()
        .iter()
        .map(AsRef::as_ref)
        .map(|s| s.as_ptr())
        .collect::<Vec<_>>();
    let coding_ptrs = bufs
        .as_mut()
        .iter_mut()
        .map(AsMut::as_mut)
        .map(|s| s.as_mut_ptr())
        .collect::<Vec<_>>();
    unsafe {
        libisal_sys::ec_encode_data(
            len.try_into().unwrap(),
            k.try_into().unwrap(),
            rows.try_into().unwrap(),
            gftbls.as_ref().as_ptr(),
            data_ptrs.as_ptr(),
            coding_ptrs.as_ptr() as *mut _,
        );
    }
}

/// Generate or decode erasure codes on blocks of data, runs appropriate version.
///
/// Given a list of source data blocks, generate one or multiple blocks of
/// encoded data as specified by a matrix of `GF(2^8)` coefficients. When given a
/// suitable set of coefficients, this function will perform the fast generation
/// or decoding of Reed-Solomon type erasure codes.
///
/// This function determines what instruction sets are enabled and
/// selects the appropriate version at runtime.
///
/// # Arguments:
///
/// * `len`:    Length of each block of data (vector) of source or dest data.
/// * `k`:      The number of vector sources or rows in the generator matrix
///             for coding.
/// * `rows`:   The number of output vectors to concurrently encode/decode.
/// * `gftbls`: Input tables generated from coding coefficients in `ec_init_tables()`.
///             Must be of size `32 * k * rows`
/// * `data`:   Source input slices.
#[must_use]
pub fn ec_encode_data_owned<T>(
    len: usize,
    k: usize,
    rows: usize,
    gftbls: impl AsRef<[u8]>,
    data: impl AsRef<[T]>,
) -> Vec<Vec<u8>>
where
    T: AsRef<[u8]>,
{
    assert_eq!(gftbls.as_ref().len(), 32 * k * rows);
    let data_ptrs = data
        .as_ref()
        .iter()
        .map(AsRef::as_ref)
        .map(|s| s.as_ptr())
        .collect::<Vec<_>>();
    let mut coding = iter::repeat(len)
        .map(Vec::with_capacity)
        .take(rows)
        .collect::<Vec<_>>();
    let mut coding_ptrs: Vec<*mut u8> = coding.iter_mut().map(Vec::as_mut_ptr).collect();
    unsafe {
        libisal_sys::ec_encode_data(
            len.try_into().unwrap(),
            k.try_into().unwrap(),
            rows.try_into().unwrap(),
            gftbls.as_ref().as_ptr(),
            data_ptrs.as_ptr(),
            coding_ptrs.as_mut_ptr(),
        );
        for c in &mut coding {
            c.set_len(len);
        }
        coding
    }
}

/// Single element `GF(2^8)` multiply.
///
/// Returns the product of a and b in `GF(2^8)`.
#[must_use]
pub fn gf_mul(a: u8, b: u8) -> u8 {
    unsafe { libisal_sys::gf_mul(a, b) }
}

/// Single element `GF(2^8)` inverse.
///
/// Returns field element `b` such that `a x b = {1}`
#[must_use]
pub fn gf_inv(a: u8) -> u8 {
    unsafe { libisal_sys::gf_inv(a) }
}

/// Generate a matrix of coefficients to be used for encoding.
///
/// Vandermonde matrix example of encoding coefficients where high portion of
/// matrix is identity matrix `I` and lower portion is constructed as `2^{i*(j-k+1)}`
/// `i:{0,k-1} j:{k,m-1}`. Commonly used method for choosing coefficients in
/// erasure encoding but does not guarantee invertable for every sub matrix. For
/// large pairs of `m` and `k` it is possible to find cases where the decode matrix
/// chosen from sources and parity is not invertable. Users may want to adjust
/// for certain pairs `m` and `k`. If `m` and `k` satisfy one of the following
/// inequalities, no adjustment is required:
///
///  * `k <= 3`
///  * `k = 4, m <= 25`
///  * `k = 5, m <= 10`
///  * `k <= 21, m-k = 4`
///  * `m - k <= 3`
///
/// # Arguments:
///
/// * `m`: number of rows in matrix corresponding to srcs + parity.
/// * `k`: number of columns in matrix corresponding to srcs.
#[must_use]
pub fn gf_gen_rs_matrix(k: usize, m: usize) -> Vec<u8> {
    let encode_matrix_len = m * k;
    let mut encode_matrix = Vec::with_capacity(encode_matrix_len);
    unsafe {
        libisal_sys::gf_gen_rs_matrix(
            encode_matrix.as_mut_ptr(),
            m.try_into().unwrap(),
            k.try_into().unwrap(),
        );
        encode_matrix.set_len(encode_matrix_len);
        encode_matrix
    }
}

/// Generate a Cauchy matrix of coefficients to be used for encoding.
///
/// Cauchy matrix example of encoding coefficients where high portion of matrix
/// is identity matrix `I` and lower portion is constructed as `1/(i + j) | i != j,
/// i:{0,k-1} j:{k,m-1}`.  Any sub-matrix of a Cauchy matrix should be invertable.
///
/// # Arguments:
///
/// * `m`:  number of rows in matrix corresponding to srcs + parity.
/// * `k`:  number of columns in matrix corresponding to srcs.
#[must_use]
pub fn gf_gen_cauchy1_matrix(k: usize, m: usize) -> Vec<u8> {
    let encode_matrix_len = m * k;
    let mut encode_matrix = Vec::with_capacity(encode_matrix_len);
    unsafe {
        libisal_sys::gf_gen_cauchy1_matrix(
            encode_matrix.as_mut_ptr(),
            m.try_into().unwrap(),
            k.try_into().unwrap(),
        );
        encode_matrix.set_len(encode_matrix_len);
        encode_matrix
    }
}

/// Invert a matrix in `GF(2^8)`.
///
/// Returns `None` on singular input matrix.
///
/// # Panics:
///
/// Panics if the matrix is not square.
#[must_use]
pub fn gf_invert_matrix(mut matrix: Vec<u8>) -> Option<Vec<u8>> {
    let len: f64 = u32::try_from(matrix.len()).unwrap().into();
    let n = len.sqrt();
    // Not using `assert_eq!` because it triggers `clippy::float_cmp`
    assert!(n.fract() == 0_f64, "Matrix must be square");

    // Won't truncate because the square root of u32::max_value is less than i32::max_value()
    #[allow(clippy::cast_possible_truncation)]
    let n = n as i32;

    let inverted_matrix_len = matrix.len();
    let mut inverted_matrix = Vec::with_capacity(inverted_matrix_len);
    unsafe {
        if libisal_sys::gf_invert_matrix(matrix.as_mut_ptr(), inverted_matrix.as_mut_ptr(), n) < 0 {
            None
        } else {
            inverted_matrix.set_len(inverted_matrix_len);
            Some(inverted_matrix)
        }
    }
}

/// Generate decode matrix from encode matrix and erasure list
///
/// Ported to Rust from https://github.com/intel/isa-l/blob/master/examples/ec/ec_simple_example.c
#[must_use]
pub fn gf_gen_decode_matrix_simple(
    encode_matrix: impl AsRef<[u8]>,
    erased_idxs: impl AsRef<[usize]>,
    k: usize,
    m: usize,
) -> Option<Vec<u8>> {
    let encode_matrix = encode_matrix.as_ref();
    let erased_idxs = erased_idxs.as_ref();
    let nerrs = erased_idxs.len();

    if nerrs > m - k {
        return None;
    }

    // Construct b (matrix that encoded remaining frags) by removing erased rows
    let b = encode_matrix
        .chunks_exact(k)
        .enumerate()
        .filter_map(|(i, chunk)| {
            if erased_idxs.contains(&i) {
                None
            } else {
                Some(chunk)
            }
        })
        .take(k)
        .flatten()
        .copied()
        .collect::<Vec<u8>>();

    // Invert matrix to get recovery matrix
    let invert_matrix = gf_invert_matrix(b)?;

    // Get decode matrix with only wanted recovery rows
    let mut decode_matrix: Vec<u8> = vec![0_u8; m * k];
    for i in 0..nerrs {
        if erased_idxs[i] < k {
            for j in 0..k {
                decode_matrix[k * i + j] = invert_matrix[k * erased_idxs[i] + j]
            }
        }
    }

    // For non-src (parity) erasures need to multiply encode matrix * invert
    for p in 0..nerrs {
        if erased_idxs[p] >= k {
            for i in 0..k {
                let mut s = 0;
                for j in 0..k {
                    s ^= gf_mul(
                        invert_matrix[j * k + i],
                        encode_matrix[k * erased_idxs[p] + j],
                    )
                }
                decode_matrix[k * p + i] = s;
            }
        }
    }

    Some(decode_matrix)
}

#[cfg(test)]
mod tests {
    use crate::{
        ec_encode_data, ec_encode_data_owned, ec_init_tables, ec_init_tables_owned,
        gf_gen_cauchy1_matrix, gf_gen_decode_matrix_simple, gf_gen_rs_matrix, gf_inv,
        gf_invert_matrix, gf_mul,
    };
    use std::convert::TryInto;

    #[test]
    fn test_ec_init_tables() {
        let k = 4;
        let p = 2;
        #[rustfmt::skip]
        let encode_matrix: Vec<u8> = vec![
            0x01, 0x00, 0x00, 0x00,
            0x00, 0x01, 0x00, 0x00,
            0x00, 0x00, 0x01, 0x00,
            0x00, 0x00, 0x00, 0x01,
            0x47, 0xA7, 0x7A, 0xBA,
            0xA7, 0x47, 0xBA, 0x7A,
        ];

        #[rustfmt::skip]
            let expected_gftbls: Vec<u8> = vec![
            0x00, 0x47, 0x8E, 0xC9, 0x01, 0x46, 0x8F, 0xC8, 0x02, 0x45, 0x8C, 0xCB, 0x03, 0x44, 0x8D, 0xCA, 0x00, 0x04, 0x08, 0x0C, 0x10, 0x14, 0x18, 0x1C, 0x20, 0x24, 0x28, 0x2C, 0x30, 0x34, 0x38, 0x3C,
            0x00, 0xA7, 0x53, 0xF4, 0xA6, 0x01, 0xF5, 0x52, 0x51, 0xF6, 0x02, 0xA5, 0xF7, 0x50, 0xA4, 0x03, 0x00, 0xA2, 0x59, 0xFB, 0xB2, 0x10, 0xEB, 0x49, 0x79, 0xDB, 0x20, 0x82, 0xCB, 0x69, 0x92, 0x30,
            0x00, 0x7A, 0xF4, 0x8E, 0xF5, 0x8F, 0x01, 0x7B, 0xF7, 0x8D, 0x03, 0x79, 0x02, 0x78, 0xF6, 0x8C, 0x00, 0xF3, 0xFB, 0x08, 0xEB, 0x18, 0x10, 0xE3, 0xCB, 0x38, 0x30, 0xC3, 0x20, 0xD3, 0xDB, 0x28,
            0x00, 0xBA, 0x69, 0xD3, 0xD2, 0x68, 0xBB, 0x01, 0xB9, 0x03, 0xD0, 0x6A, 0x6B, 0xD1, 0x02, 0xB8, 0x00, 0x6F, 0xDE, 0xB1, 0xA1, 0xCE, 0x7F, 0x10, 0x5F, 0x30, 0x81, 0xEE, 0xFE, 0x91, 0x20, 0x4F,
            0x00, 0xA7, 0x53, 0xF4, 0xA6, 0x01, 0xF5, 0x52, 0x51, 0xF6, 0x02, 0xA5, 0xF7, 0x50, 0xA4, 0x03, 0x00, 0xA2, 0x59, 0xFB, 0xB2, 0x10, 0xEB, 0x49, 0x79, 0xDB, 0x20, 0x82, 0xCB, 0x69, 0x92, 0x30,
            0x00, 0x47, 0x8E, 0xC9, 0x01, 0x46, 0x8F, 0xC8, 0x02, 0x45, 0x8C, 0xCB, 0x03, 0x44, 0x8D, 0xCA, 0x00, 0x04, 0x08, 0x0C, 0x10, 0x14, 0x18, 0x1C, 0x20, 0x24, 0x28, 0x2C, 0x30, 0x34, 0x38, 0x3C,
            0x00, 0xBA, 0x69, 0xD3, 0xD2, 0x68, 0xBB, 0x01, 0xB9, 0x03, 0xD0, 0x6A, 0x6B, 0xD1, 0x02, 0xB8, 0x00, 0x6F, 0xDE, 0xB1, 0xA1, 0xCE, 0x7F, 0x10, 0x5F, 0x30, 0x81, 0xEE, 0xFE, 0x91, 0x20, 0x4F,
            0x00, 0x7A, 0xF4, 0x8E, 0xF5, 0x8F, 0x01, 0x7B, 0xF7, 0x8D, 0x03, 0x79, 0x02, 0x78, 0xF6, 0x8C, 0x00, 0xF3, 0xFB, 0x08, 0xEB, 0x18, 0x10, 0xE3, 0xCB, 0x38, 0x30, 0xC3, 0x20, 0xD3, 0xDB, 0x28,
        ];

        let mut actual_gftbls = vec![0; 32 * k * p];
        ec_init_tables(
            k.try_into().unwrap(),
            p.try_into().unwrap(),
            &encode_matrix[k * k..],
            &mut actual_gftbls[..],
        );
        assert_eq!(actual_gftbls, expected_gftbls);

        let actual_gftbls = ec_init_tables_owned(
            k.try_into().unwrap(),
            p.try_into().unwrap(),
            &encode_matrix[k * k..],
        );
        assert_eq!(actual_gftbls, expected_gftbls);
    }

    #[test]
    fn test_ec_encode_data() {
        let len = 1;
        let k = 4;
        let nerrs = 2;

        #[rustfmt::skip]
        let gftbls: Vec<u8> = vec![
            0x00, 0x47, 0x8E, 0xC9, 0x01, 0x46, 0x8F, 0xC8, 0x02, 0x45, 0x8C, 0xCB, 0x03, 0x44, 0x8D, 0xCA, 0x00, 0x04, 0x08, 0x0C, 0x10, 0x14, 0x18, 0x1C, 0x20, 0x24, 0x28, 0x2C, 0x30, 0x34, 0x38, 0x3C,
            0x00, 0xA7, 0x53, 0xF4, 0xA6, 0x01, 0xF5, 0x52, 0x51, 0xF6, 0x02, 0xA5, 0xF7, 0x50, 0xA4, 0x03, 0x00, 0xA2, 0x59, 0xFB, 0xB2, 0x10, 0xEB, 0x49, 0x79, 0xDB, 0x20, 0x82, 0xCB, 0x69, 0x92, 0x30,
            0x00, 0x7A, 0xF4, 0x8E, 0xF5, 0x8F, 0x01, 0x7B, 0xF7, 0x8D, 0x03, 0x79, 0x02, 0x78, 0xF6, 0x8C, 0x00, 0xF3, 0xFB, 0x08, 0xEB, 0x18, 0x10, 0xE3, 0xCB, 0x38, 0x30, 0xC3, 0x20, 0xD3, 0xDB, 0x28,
            0x00, 0xBA, 0x69, 0xD3, 0xD2, 0x68, 0xBB, 0x01, 0xB9, 0x03, 0xD0, 0x6A, 0x6B, 0xD1, 0x02, 0xB8, 0x00, 0x6F, 0xDE, 0xB1, 0xA1, 0xCE, 0x7F, 0x10, 0x5F, 0x30, 0x81, 0xEE, 0xFE, 0x91, 0x20, 0x4F,
            0x00, 0xA7, 0x53, 0xF4, 0xA6, 0x01, 0xF5, 0x52, 0x51, 0xF6, 0x02, 0xA5, 0xF7, 0x50, 0xA4, 0x03, 0x00, 0xA2, 0x59, 0xFB, 0xB2, 0x10, 0xEB, 0x49, 0x79, 0xDB, 0x20, 0x82, 0xCB, 0x69, 0x92, 0x30,
            0x00, 0x47, 0x8E, 0xC9, 0x01, 0x46, 0x8F, 0xC8, 0x02, 0x45, 0x8C, 0xCB, 0x03, 0x44, 0x8D, 0xCA, 0x00, 0x04, 0x08, 0x0C, 0x10, 0x14, 0x18, 0x1C, 0x20, 0x24, 0x28, 0x2C, 0x30, 0x34, 0x38, 0x3C,
            0x00, 0xBA, 0x69, 0xD3, 0xD2, 0x68, 0xBB, 0x01, 0xB9, 0x03, 0xD0, 0x6A, 0x6B, 0xD1, 0x02, 0xB8, 0x00, 0x6F, 0xDE, 0xB1, 0xA1, 0xCE, 0x7F, 0x10, 0x5F, 0x30, 0x81, 0xEE, 0xFE, 0x91, 0x20, 0x4F,
            0x00, 0x7A, 0xF4, 0x8E, 0xF5, 0x8F, 0x01, 0x7B, 0xF7, 0x8D, 0x03, 0x79, 0x02, 0x78, 0xF6, 0x8C, 0x00, 0xF3, 0xFB, 0x08, 0xEB, 0x18, 0x10, 0xE3, 0xCB, 0x38, 0x30, 0xC3, 0x20, 0xD3, 0xDB, 0x28,
        ];
        let data: Vec<Vec<u8>> = vec![vec![1; len], vec![2; len], vec![3; len], vec![4; len]];
        let orig_data = data.clone();
        let data_ptrs = data.iter().map(Vec::as_slice).collect::<Vec<_>>();

        let expected_coding: Vec<Vec<u8>> = vec![vec![0x48], vec![0x0F]];

        let mut actual_coding = vec![vec![0; len], vec![0; len]];
        let mut actual_coding_slices = actual_coding.iter_mut().collect::<Vec<_>>();
        ec_encode_data(
            len,
            k,
            nerrs,
            &gftbls,
            &data_ptrs,
            &mut actual_coding_slices,
        );
        for (actual, expected) in data.iter().zip(orig_data.iter()) {
            assert_eq!(actual, expected)
        }
        for (actual, expected) in actual_coding.iter().zip(expected_coding.iter()) {
            assert_eq!(actual, expected);
        }

        let actual_coding = ec_encode_data_owned(len, k, nerrs, &gftbls, &data_ptrs);
        for (actual, expected) in data.iter().zip(orig_data.iter()) {
            assert_eq!(actual, expected)
        }
        for (actual, expected) in actual_coding.iter().zip(expected_coding.iter()) {
            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn test_gf_mul() {
        let a = 0xBE;
        let b = 0xEF;
        let actual = gf_mul(a, b);
        let expected = 0x03;
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_gf_inv() {
        let a = 0x42;
        let actual = gf_inv(a);
        let expected = 0xF8;
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_gf_gen_rs_matrix() {
        let k = 4;
        let p = 2;
        let m = k + p;
        let actual_encode_matrix = gf_gen_rs_matrix(k, m);
        #[rustfmt::skip]
        let expected_encode_matrix: Vec<u8> = vec![
            0x01, 0x00, 0x00, 0x00,
            0x00, 0x01, 0x00, 0x00,
            0x00, 0x00, 0x01, 0x00,
            0x00, 0x00, 0x00, 0x01,
            0x01, 0x01, 0x01, 0x01,
            0x01, 0x02, 0x04, 0x08
        ];
        assert_eq!(actual_encode_matrix, expected_encode_matrix);
    }

    #[test]
    fn test_gf_gen_cauchy1_matrix() {
        let k = 4;
        let p = 2;
        let m = k + p;
        let actual_encode_matrix = gf_gen_cauchy1_matrix(k, m);
        #[rustfmt::skip]
        let expected_encode_matrix: Vec<u8> = vec![
            0x01, 0x00, 0x00, 0x00,
            0x00, 0x01, 0x00, 0x00,
            0x00, 0x00, 0x01, 0x00,
            0x00, 0x00, 0x00, 0x01,
            0x47, 0xA7, 0x7A, 0xBA,
            0xA7, 0x47, 0xBA, 0x7A,
        ];
        assert_eq!(actual_encode_matrix, expected_encode_matrix);
    }

    #[test]
    fn test_gf_invert_matrix() {
        // Inverse of identity matrix is identity matrix
        #[rustfmt::skip]
        let input: Vec<u8> = vec![
            0x01, 0x00, 0x00, 0x00,
            0x00, 0x01, 0x00, 0x00,
            0x00, 0x00, 0x01, 0x00,
            0x00, 0x00, 0x00, 0x01,
        ];
        let actual = gf_invert_matrix(input.clone());
        let expected: Vec<u8> = input;
        assert_eq!(actual, Some(expected));

        // Cauchy bottom part
        #[rustfmt::skip]
        let input: Vec<u8> = vec![
            0x00, 0x00, 0x01, 0x00,
            0x00, 0x00, 0x00, 0x01,
            0x47, 0xA7, 0x7A, 0xBA,
            0xA7, 0x47, 0xBA, 0x7A,
        ];
        let actual = gf_invert_matrix(input);
        #[rustfmt::skip]
        let expected: Vec<u8> = vec![
            0xD0, 0x6B, 0x44, 0x50,
            0x6B, 0xD0, 0x50, 0x44,
            0x01, 0x00, 0x00, 0x00,
            0x00, 0x01, 0x00, 0x00,
        ];
        assert_eq!(actual, Some(expected));
    }

    #[test]
    fn test_ec_gen_decode_matrix_simple() {
        #[rustfmt::skip]
        let encode_matrix = vec![
            0x01, 0x00, 0x00, 0x00,
            0x00, 0x01, 0x00, 0x00,
            0x00, 0x00, 0x01, 0x00,
            0x00, 0x00, 0x00, 0x01,
            0x47, 0xA7, 0x7A, 0xBA,
            0xA7, 0x47, 0xBA, 0x7A,
        ];

        // Three errors
        let erased_idxs = vec![3, 4, 5];
        let actual_decode_matrix = gf_gen_decode_matrix_simple(&encode_matrix, &erased_idxs, 4, 6);
        assert_eq!(actual_decode_matrix, None);

        // One data and one parity error
        let erased_idxs = vec![3, 4];
        let actual_decode_matrix = gf_gen_decode_matrix_simple(&encode_matrix, &erased_idxs, 4, 6);
        #[rustfmt::skip]
        let expected_decode_matrix: Vec<u8> = vec![
            0xF5, 0x8F, 0xBB, 0x06,
            0x60, 0x40, 0xFE, 0xBB,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
        ];
        assert_eq!(actual_decode_matrix, Some(expected_decode_matrix));

        // One data error
        let erased_idxs = vec![3];
        let actual_decode_matrix = gf_gen_decode_matrix_simple(&encode_matrix, &erased_idxs, 4, 6);
        #[rustfmt::skip]
        let expected_decode_matrix: Vec<u8> = vec![
            0xC8, 0x52, 0x7B, 0x07,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
        ];
        assert_eq!(actual_decode_matrix, Some(expected_decode_matrix));

        // One parity error
        let erased_idxs = vec![4];
        let actual_decode_matrix = gf_gen_decode_matrix_simple(&encode_matrix, &erased_idxs, 4, 6);
        #[rustfmt::skip]
        let expected_decode_matrix: Vec<u8> = vec![
            0x47, 0xA7, 0x7A, 0xBA,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
        ];
        assert_eq!(actual_decode_matrix.unwrap(), expected_decode_matrix);
    }
}