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
//! Utility and debugging functions.
//!
//! ## Stability
//!
//! Printing functions may be moved/renamed/removed at any time.
use std::ops::Range;
use std::mem;
use std::ptr;
use std::iter;
use num::{Integer, FromPrimitive};
use rand;
use rand::distributions::{IndependentSample, Range as RandRange};
use error::{Result as OclResult, Error as OclError};

use ::{OclPrm, OclScl};

//=============================================================================
//================================= MACROS ====================================
//=============================================================================



//=============================================================================
//================================ STATICS ====================================
//=============================================================================

pub mod colors {
    //! ASCII Color Palette
    //!
    //! Used for printing functions.

    pub static TAB: &'static str = "    ";

    pub static C_DEFAULT: &'static str = "\x1b[0m";
    pub static C_UNDER: &'static str = "\x1b[1m";

    // 30–37
    pub static C_RED: &'static str = "\x1b[31m";
    pub static C_BRED: &'static str = "\x1b[1;31m";
    pub static C_GRN: &'static str = "\x1b[32m";
    pub static C_BGRN: &'static str = "\x1b[1;32m";
    pub static C_ORA: &'static str = "\x1b[33m";
    pub static C_DBL: &'static str = "\x1b[34m";
    pub static C_PUR: &'static str = "\x1b[35m";
    pub static C_CYA: &'static str = "\x1b[36m";
    pub static C_LGR: &'static str = "\x1b[37m";
    // [ADDME] 38: Extended Colors
    // pub static C_EXT38: &'static str = "\x1b[38m";
    pub static C_DFLT: &'static str = "\x1b[39m";

    // 90-97
    pub static C_DGR: &'static str = "\x1b[90m";
    pub static C_LRD: &'static str = "\x1b[91m";
    pub static C_YEL: &'static str = "\x1b[93m";
    pub static C_BLU: &'static str = "\x1b[94m";
    pub static C_LBL: &'static str = "\x1b[94m";
    pub static C_MAG: &'static str = "\x1b[95m";
    // [ADDME] 38: Extended Colors
    // pub static C_EXT38: &'static str = "\x1b[38m";

    pub static BGC_DEFAULT: &'static str = "\x1b[49m";
    pub static BGC_GRN: &'static str = "\x1b[42m";
    pub static BGC_PUR: &'static str = "\x1b[45m";
    pub static BGC_LGR: &'static str = "\x1b[47m";
    pub static BGC_DGR: &'static str = "\x1b[100m";
}


//=============================================================================
//=========================== UTILITY FUNCTIONS ===============================
//=============================================================================

/// Copies a byte slice to a new `u32`.
///
/// ### Stability
///
/// May depricate in favor of `bytes_to`
///
pub fn bytes_to_u32(bytes: &[u8]) -> u32 {
    debug_assert!(bytes.len() == 4);

    bytes[0] as u32 |
    ((bytes[1] as u32) << 8) |
    ((bytes[2] as u32) << 16) |
    ((bytes[3] as u32) << 24)
}

/// Copies a slice of bytes to a new value of arbitrary type.
///
/// ### Safety
///
/// You may want to wear a helmet.
///
pub unsafe fn bytes_to<T>(bytes: &[u8]) -> OclResult<T> {
    if mem::size_of::<T>() == bytes.len() {
        let mut new_val: T = mem::uninitialized();
        ptr::copy(bytes.as_ptr(), &mut new_val as *mut _ as *mut u8, bytes.len());
        Ok(new_val)
    } else {
        OclError::err_string(format!("The size of the source byte slice ({} bytes) \
        does not match the size of the destination type ({} bytes).", bytes.len(),
        mem::size_of::<T>()))
    }
}

/// Converts a vector of bytes into a value of arbitrary type.
///
/// ### Safety
///
/// Roughly equivalent to a weekend in Tijuana.
///
// [NOTE]: Not sure this is the best or simplest way to do this but whatever.
// Would be nice to not even have to copy anything and just basically
// transmute the vector into the result type. [TODO]: Fiddle with this
// at some point.
//
pub unsafe fn bytes_into<T>(vec: Vec<u8>) -> OclResult<T> {
    if mem::size_of::<T>() == vec.len() {
        let mut new_val: T = mem::uninitialized();
        ptr::copy(vec.as_ptr(), &mut new_val as *mut _ as *mut u8, vec.len());
        Ok(new_val)
    } else {
        OclError::err_string(format!("The size of the source byte vector ({} bytes) \
        does not match the size of the destination type ({} bytes).", vec.len(),
        mem::size_of::<T>()))
    }
}

/// Converts a vector of bytes into a vector of arbitrary type.
///
/// ### Safety
///
/// Ummm... Say what?
///
/// TODO: Consider using `alloc::heap::reallocate_inplace` equivalent.
///
pub unsafe fn bytes_into_vec<T>(mut vec: Vec<u8>) -> OclResult<Vec<T>> {
    // debug_assert!(vec.len() % mem::size_of::<T>() == 0);
    if vec.len() % mem::size_of::<T>() == 0 {
        let new_len = vec.len() / mem::size_of::<T>();
        let new_cap = vec.capacity() / mem::size_of::<T>();
        let ptr = vec.as_mut_ptr();
        mem::forget(vec);
        let mut new_vec: Vec<T> = Vec::from_raw_parts(ptr as *mut T, new_len, new_cap);
        new_vec.shrink_to_fit();
        Ok(new_vec)
    } else {
        OclError::err_conversion(format!("The size of the source byte vector ({} bytes) is not \
            evenly divisible by the size of the destination type ({} bytes).", vec.len(),
            mem::size_of::<T>()))
    }
}

/// Copies a slice of bytes into a vector of arbitrary type.
///
/// ### Safety
///
/// Negative.
///
pub unsafe fn bytes_to_vec<T>(bytes: &[u8]) -> OclResult<Vec<T>> {
    // debug_assert!(bytes.len() % mem::size_of::<T>() == 0);
    if bytes.len() % mem::size_of::<T>() == 0 {
        let new_len = bytes.len() / mem::size_of::<T>();
        let mut new_vec: Vec<T> = Vec::with_capacity(new_len);
        ptr::copy(bytes.as_ptr(), new_vec.as_mut_ptr() as *mut _ as *mut u8, bytes.len());
        new_vec.set_len(new_len);
        Ok(new_vec)
    } else {
        OclError::err_conversion(format!("The size of the source byte slice ({} bytes) is not \
            evenly divisible by the size of the destination type ({} bytes).", bytes.len(),
            mem::size_of::<T>()))
    }
}


/// Converts a byte Vec into a string, removing the trailing null byte if it
/// exists.
pub fn bytes_into_string(mut bytes: Vec<u8>) -> OclResult<String> {
    if bytes.last() == Some(&0u8) {
        bytes.pop();
    }

    String::from_utf8(bytes).map_err(OclError::from)
}


/// Converts a byte Vec into a string, removing the trailing null byte if it
/// exists, then removes leading and trailing whitespace.
pub fn bytes_into_trimmed_string(mut bytes: Vec<u8>) -> OclResult<String> {
    if bytes.last() == Some(&0u8) {
        bytes.pop();
    }

    let string = String::from_utf8(bytes).map_err(OclError::from)?;
    Ok(String::from(string.trim()))
}



/// [UNTESTED] Copies an arbitrary primitive or struct into core bytes.
///
/// ### Depth
///
/// This is not a deep copy, will only copy the surface of primitives, structs,
/// etc. Not 100% sure about what happens with other types but should copy
/// everything zero levels deep.
///
/// ### Endianness
///
/// 98% sure (speculative) this will always be correct due to the driver
/// automatically taking it into account.
///
/// ### Safety
///
/// Don't ask.
///
/// [FIXME]: Evaluate the ins and outs of this and lock this down a bit.
pub unsafe fn into_bytes<T>(val: T) -> Vec<u8> {
    // let big_endian = false;
    let size = mem::size_of::<T>();
    let mut new_vec: Vec<u8> = iter::repeat(0).take(size).collect();

    ptr::copy(&val as *const _ as *const u8, new_vec.as_mut_ptr(), size);

    // if big_endian {
    //     new_vec = new_vec.into_iter().rev().collect();
    // }

    new_vec
}

/// Pads `len` to make it evenly divisible by `incr`.
pub fn padded_len(len: usize, incr: usize) -> usize {
    let len_mod = len % incr;

    if len_mod == 0 {
        len
    } else {
        let pad = incr - len_mod;
        let padded_len = len + pad;
        debug_assert_eq!(padded_len % incr, 0);
        padded_len
    }
}

/// Batch removes elements from a vector using a list of indices to remove.
///
/// Will create a new vector and do a streamlined rebuild if
/// `remove_list.len()` > `rebuild_threshold`. Threshold should typically be
/// set very low (less than probably 5 or 10) as it's expensive to remove one
/// by one.
///
/// ### Safety
///
/// Should be perfectly safe, just need to test it a bit.
///
pub fn vec_remove_rebuild<T: Clone + Copy>(orig_vec: &mut Vec<T>, remove_list: &[usize],
                rebuild_threshold: usize) -> OclResult<()> {
    if remove_list.len() > orig_vec.len() {
        return OclError::err_string("ocl::util::vec_remove_rebuild: Remove list is longer than source
            vector.");
    }
    let orig_len = orig_vec.len();

    // If the list is below threshold
    if remove_list.len() <= rebuild_threshold {
        for &idx in remove_list.iter().rev() {
            if idx < orig_len {
                 orig_vec.remove(idx);
            } else {
                return OclError::err_string(format!("ocl::util::remove_rebuild_vec: 'remove_list' \
                    contains at least one out of range index: [{}] ('orig_vec.len()': {}).",
                    idx, orig_len));
            }
        }
    } else {
        unsafe {
            let mut remove_markers: Vec<bool> = iter::repeat(true).take(orig_len).collect();

            // Build a sparse list of which elements to remove:
            for &idx in remove_list.iter() {
                if idx < orig_len {
                    *remove_markers.get_unchecked_mut(idx) = false;
                } else {
                    return OclError::err_string(format!("ocl::util::remove_rebuild_vec: 'remove_list' \
                        contains at least one out of range index: [{}] ('orig_vec.len()': {}).",
                        idx, orig_len));
                }
            }

            let mut new_len = 0usize;

            // Iterate through remove_markers and orig_vec, pushing when the marker is false:
            for idx in 0..orig_len {
                if *remove_markers.get_unchecked(idx) {
                    *orig_vec.get_unchecked_mut(new_len) = *orig_vec.get_unchecked(idx);
                    new_len += 1;
                }
            }

            debug_assert_eq!(new_len, orig_len - remove_list.len());
            orig_vec.set_len(new_len);
        }
    }

    Ok(())
}

/// Wraps (`%`) each value in the list `vals` if it equals or exceeds `val_n`.
pub fn wrap_vals<T: OclPrm + Integer>(vals: &[T], val_n: T) -> Vec<T> {
    vals.iter().map(|&v| v % val_n).collect()
}



/// Returns a vector with length `size` containing random values in the (half-open)
/// range `[vals.0, vals.1)`.
#[cfg(feature = "rand")]
pub fn scrambled_vec<T: OclScl>(vals: (T, T), size: usize) -> Vec<T> {
    assert!(size > 0, "\nbuffer::shuffled_vec(): Vector size must be greater than zero.");
    assert!(vals.0 < vals.1, "\nbuffer::shuffled_vec(): Minimum value must be less than maximum.");
    let mut rng = rand::weak_rng();
    let range = RandRange::new(vals.0, vals.1);

    (0..size).map(|_| range.ind_sample(&mut rng)).take(size as usize).collect()
}

/// Returns a vector with length `size` which is first filled with each integer value
/// in the (inclusive) range `[vals.0, vals.1]`. If `size` is greater than the
/// number of integers in the aforementioned range, the integers will repeat. After
/// being filled with `size` values, the vector is shuffled and the order of its
/// values is randomized.
#[cfg(feature = "rand")]
pub fn shuffled_vec<T: OclScl>(vals: (T, T), size: usize) -> Vec<T> {
    let mut vec: Vec<T> = Vec::with_capacity(size);
    assert!(size > 0, "\nbuffer::shuffled_vec(): Vector size must be greater than zero.");
    assert!(vals.0 < vals.1, "\nbuffer::shuffled_vec(): Minimum value must be less than maximum.");
    let min = vals.0.to_i64().expect("\nbuffer::shuffled_vec(), min");
    let max = vals.1.to_i64().expect("\nbuffer::shuffled_vec(), max") + 1;
    let mut range = (min..max).cycle();

    for _ in 0..size {
        vec.push(FromPrimitive::from_i64(range.next().expect("\nbuffer::shuffled_vec(), range"))
            .expect("\nbuffer::shuffled_vec(), from_usize"));
    }

    shuffle(&mut vec);
    vec
}


/// Shuffles the values in a vector using a single pass of Fisher-Yates with a
/// weak (not cryptographically secure) random number generator.
pub fn shuffle<T: OclScl>(vec: &mut [T]) {
    let len = vec.len();
    let mut rng = rand::weak_rng();
    let mut ridx: usize;
    let mut tmp: T;

    for i in 0..len {
        ridx = RandRange::new(i, len).ind_sample(&mut rng);
        tmp = vec[i];
        vec[i] = vec[ridx];
        vec[ridx] = tmp;
    }
}


// /// Converts a length in `T` to a size in bytes.
// #[inline]
// pub fn len_to_size<T>(len: usize) -> usize {
//     len * mem::size_of::<T>()
// }

// /// Converts lengths in `T` to sizes in bytes for a `[usize; 3]`.
// #[inline]
// pub fn len3_to_size3<T>(lens: [usize; 3]) -> [usize; 3] {
//     [len_to_size::<T>(lens[0]), len_to_size::<T>(lens[1]), len_to_size::<T>(lens[2])]
// }

// /// Converts lengths in `T` to sizes in bytes for a `&[usize]`.
// pub fn lens_to_sizes<T>(lens: &[usize]) -> Vec<usize> {
//     lens.iter().map(|len| len * mem::size_of::<T>()).collect()
// }

//=============================================================================
//=========================== PRINTING FUNCTIONS ==============================
//=============================================================================

/// Does what is says it's gonna.
pub fn print_bytes_as_hex(bytes: &[u8]) {
    print!("0x");

    for &byte in bytes.iter() {
        print!("{:x}", byte);
    }
}


#[allow(unused_assignments, unused_variables)]
/// [UNSTABLE]: MAY BE REMOVED AT ANY TIME
/// Prints a vector to stdout. Used for debugging.
pub fn print_slice<T: OclScl>(
            vec: &[T],
            every: usize,
            val_range: Option<(T, T)>,
            idx_range: Option<Range<usize>>,
            show_zeros: bool,
            ) {
    print!( "{cdgr}[{cg}{}{cdgr}/{}", vec.len(), every, cg = colors::C_GRN, cdgr = colors::C_DGR);

    let (vr_start, vr_end) = match val_range {
        Some(vr) => {
            print!( ";({}-{})", vr.0, vr.1);
            vr
        },

        None => (Default::default(), Default::default()),
    };

    let (ir_start, ir_end) = match idx_range {
        Some(ref ir) => {
            print!( ";[{}..{}]", ir.start, ir.end);
            (ir.start, ir.end)
        },

        None => (0usize, 0usize),
    };

    print!( "]:{cd} ", cd = colors::C_DEFAULT,);

    let mut ttl_nz = 0usize;
    let mut ttl_ir = 0usize;
    let mut within_idx_range = true;
    let mut within_val_range = true;
    let mut hi: T = vr_start;
    let mut lo: T = vr_end;
    let mut sum: i64 = 0;
    let mut ttl_prntd: usize = 0;
    let len = vec.len();


    let mut color: &'static str = colors::C_DEFAULT;
    let mut prnt: bool = false;

    // Yes, this clusterfuck needs rewriting someday
    for (i, item) in vec.iter().enumerate() {

        prnt = false;

        if every != 0 {
            if i % every == 0 {
                prnt = true;
            } else {
                prnt = false;
            }
        }

        if idx_range.is_some() {
            let ir = idx_range.as_ref().expect("ocl::buffer::print_vec()");

            if i < ir_start || i >= ir_end {
                prnt = false;
                within_idx_range = false;
            } else {
                within_idx_range = true;
            }
        } else {
            within_idx_range = true;
        }

        if val_range.is_some() {
            if *item < vr_start || *item > vr_end {
                prnt = false;
                within_val_range = false;
            } else {
                if within_idx_range {
                    // if *item == Default::default() {
                    //     ttl_ir += 1;
                    // } else {
                    //     ttl_ir += 1;
                    // }
                    ttl_ir += 1;
                }

                within_val_range = true;
            }
        }

        if within_idx_range && within_val_range {
            sum += item.to_i64().expect("ocl::buffer::print_vec(): vec[i]");

            if *item > hi { hi = *item };

            if *item < lo { lo = *item };

            if vec[i] != Default::default() {
                ttl_nz += 1usize;
                color = colors::C_ORA;
            } else if show_zeros {
                color = colors::C_DEFAULT;
            } else {
                prnt = false;
            }
        }

        if prnt {
            print!( "{cg}[{cd}{}{cg}:{cc}{}{cg}]{cd}", i, vec[i], cc = color, cd = colors::C_DEFAULT, cg = colors::C_DGR);
            ttl_prntd += 1;
        }
    }

    let mut anz: f32 = 0f32;
    let mut nz_pct: f32 = 0f32;

    let mut ir_pct: f32 = 0f32;
    let mut avg_ir: f32 = 0f32;

    if ttl_nz > 0 {
        anz = sum as f32 / ttl_nz as f32;
        nz_pct = (ttl_nz as f32 / len as f32) * 100f32;
        //print!( "[ttl_nz: {}, nz_pct: {:.0}%, len: {}]", ttl_nz, nz_pct, len);
    }

    if ttl_ir > 0 {
        avg_ir = sum as f32 / ttl_ir as f32;
        ir_pct = (ttl_ir as f32 / len as f32) * 100f32;
        //print!( "[ttl_nz: {}, nz_pct: {:.0}%, len: {}]", ttl_nz, nz_pct, len);
    }


    println!("{cdgr}; (nz:{clbl}{}{cdgr}({clbl}{:.2}%{cdgr}),\
        ir:{clbl}{}{cdgr}({clbl}{:.2}%{cdgr}),hi:{},lo:{},anz:{:.2},prntd:{}){cd} ",
        ttl_nz, nz_pct, ttl_ir, ir_pct, hi, lo, anz, ttl_prntd, cd = colors::C_DEFAULT, clbl = colors::C_LBL, cdgr = colors::C_DGR);
}


pub fn print_simple<T: OclScl>(slice: &[T]) {
    print_slice(slice, 1, None, None, true);
}



pub fn print_val_range<T: OclScl>(slice: &[T], every: usize, val_range: Option<(T, T)>) {
    print_slice(slice, every, val_range, None, true);
}


#[cfg(test)]
mod tests {
    // use std::iter;

    #[test]
    fn remove_rebuild() {
        let mut primary_vals: Vec<u32> = (0..(1 << 18)).map(|v| v).collect();
        let orig_len = primary_vals.len();

        let mut bad_indices: Vec<usize> = Vec::<usize>::with_capacity(1 << 16);
        let mut idx = 0;

        // Mark every whateverth value 'bad':
        for &val in primary_vals.iter() {
            if (val % 19 == 0) || (val % 31 == 0) || (val % 107 == 0) {
                bad_indices.push(idx);
            }

            idx += 1;
        }

        println!("util::tests::remove_rebuild(): bad_indices: {}", bad_indices.len());

        // Remove the bad values:
        super::vec_remove_rebuild(&mut primary_vals, &bad_indices[..], 3)
            .expect("util::tests::remove_rebuild()");

        // Check:
        for &val in primary_vals.iter() {
            if (val % 19 == 0) || (val % 31 == 0) || (val % 107 == 0) {
                panic!("util::tests::remove_rebuild(): Value: '{}' found in list!", val);
            }
        }

        assert_eq!(orig_len, primary_vals.len() + bad_indices.len());
    }
}