slice_fill/
lib.rs

1//! `Slice::fill` prototype.
2//!
3//! C++ ships with
4//! [`std::fill`](https://en.cppreference.com/w/cpp/algorithm/fill) which fills a
5//! range of memory with a given byte. Rust currently doesn't have a standard
6//! library equivalent for that.
7//!
8//! [Issue 2067](https://github.com/rust-lang/rfcs/issues/2067) on the RFCs
9//! repo proposes a safe wrapper around `memset(3)` call. This is a reference
10//! implementation of the API proposed in the issue that optimizes to `memset`
11//! in many cases but leaves the exact performance profile undisclosed.
12//!
13//! As Rust makes progress on specialization this can later be lifted to
14//! guarantee the fastest known implementation is used for any specific type.
15//! But until then it provides a convenient API to fill slices of memory with
16//! repeating patterns, which will generally be optimized to be very fast
17//! already.
18//!
19//! # Examples
20//!
21//! ```
22//! use slice_fill::SliceExt;
23//!
24//! let mut buf = vec![0; 10];
25//! buf.fill(1);
26//! assert_eq!(buf, vec![1; 10]);
27//! ```
28//!
29//! # Further reading
30//! - [The hunt for the fastest zero](https://travisdowns.github.io/blog/2020/01/20/zero.html)
31//! - [Filling large arrays with zeroes quickly in C](https://lemire.me/blog/2020/01/20/filling-large-arrays-with-zeroes-quickly-in-c/)
32//! - [Godbolt ASM output](https://godbolt.org/z/ikyFAo)
33
34#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
35#![deny(missing_debug_implementations, nonstandard_style)]
36#![warn(missing_docs, missing_doc_code_examples, unreachable_pub)]
37
38/// Extension trait for `std::slice`.
39pub trait SliceExt<T: Clone> {
40    /// Fill a slice with an item.
41    fn fill(&mut self, item: T);
42}
43
44impl<T: Clone> SliceExt<T> for [T] {
45    fn fill(&mut self, item: T) {
46        for el in self {
47            *el = item.clone();
48        }
49    }
50}
51
52mod test {
53    #[test]
54    fn fills_vec() {
55        use super::SliceExt;
56        let mut buf = vec![0usize; 10];
57        buf.fill(1);
58        assert_eq!(buf, vec![1usize; 10]);
59    }
60
61    #[test]
62    fn fills_slice() {
63        use super::SliceExt;
64        let mut buf = vec![0usize; 10];
65        buf[0..10].fill(1);
66        assert_eq!(buf, vec![1usize; 10]);
67    }
68}