slice-fill 1.0.1

Slice::fill prototype
Documentation
//! `Slice::fill` prototype.
//!
//! C++ ships with
//! [`std::fill`](https://en.cppreference.com/w/cpp/algorithm/fill) which fills a
//! range of memory with a given byte. Rust currently doesn't have a standard
//! library equivalent for that.
//!
//! [Issue 2067](https://github.com/rust-lang/rfcs/issues/2067) on the RFCs
//! repo proposes a safe wrapper around `memset(3)` call. This is a reference
//! implementation of the API proposed in the issue that optimizes to `memset`
//! in many cases but leaves the exact performance profile undisclosed.
//!
//! As Rust makes progress on specialization this can later be lifted to
//! guarantee the fastest known implementation is used for any specific type.
//! But until then it provides a convenient API to fill slices of memory with
//! repeating patterns, which will generally be optimized to be very fast
//! already.
//!
//! # Examples
//!
//! ```
//! use slice_fill::SliceExt;
//!
//! let mut buf = vec![0; 10];
//! buf.fill(1);
//! assert_eq!(buf, vec![1; 10]);
//! ```
//!
//! # Further reading
//! - [The hunt for the fastest zero](https://travisdowns.github.io/blog/2020/01/20/zero.html)
//! - [Filling large arrays with zeroes quickly in C](https://lemire.me/blog/2020/01/20/filling-large-arrays-with-zeroes-quickly-in-c/)
//! - [Godbolt ASM output](https://godbolt.org/z/ikyFAo)

#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![warn(missing_docs, missing_doc_code_examples, unreachable_pub)]

/// Extension trait for `std::slice`.
pub trait SliceExt<T: Clone> {
    /// Fill a slice with an item.
    fn fill(&mut self, item: T);
}

impl<T: Clone> SliceExt<T> for [T] {
    fn fill(&mut self, item: T) {
        for el in self {
            *el = item.clone();
        }
    }
}

mod test {
    #[test]
    fn fills_vec() {
        use super::SliceExt;
        let mut buf = vec![0usize; 10];
        buf.fill(1);
        assert_eq!(buf, vec![1usize; 10]);
    }

    #[test]
    fn fills_slice() {
        use super::SliceExt;
        let mut buf = vec![0usize; 10];
        buf[0..10].fill(1);
        assert_eq!(buf, vec![1usize; 10]);
    }
}