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
use crate::mem::{size_of, transmute_copy};
use crate::ptr::write_bytes;

pub(super) trait SpecFill<T> {
    fn spec_fill(&mut self, value: T);
}

impl<T: Clone> SpecFill<T> for [T] {
    default fn spec_fill(&mut self, value: T) {
        if let Some((last, elems)) = self.split_last_mut() {
            for el in elems {
                el.clone_from(&value);
            }

            *last = value
        }
    }
}

impl<T: Copy> SpecFill<T> for [T] {
    fn spec_fill(&mut self, value: T) {
        if size_of::<T>() == 1 {
            // SAFETY: 上述检查的大小确保值为 1 字节宽,这是转换和写入字节所需要的
            //
            unsafe {
                let value: u8 = transmute_copy(&value);
                write_bytes(self.as_mut_ptr(), value, self.len());
            }
        } else {
            for item in self.iter_mut() {
                *item = value;
            }
        }
    }
}