pencil_box/array/
fill_value.rs

1/// Creates a `Vec<T>` of a given size, filled with the provided value.
2///
3/// # Type Parameters
4/// - `T`: The element type of the vector. Must implement [`Clone`].
5///
6/// # Arguments
7/// - `value`: A reference to the value to fill the vector with. This value is cloned into each slot.
8/// - `size`: The number of elements in the resulting vector.
9///
10/// # Returns
11/// A new `Vec<T>` of length `size`, where every element is a clone of `value`.
12///
13/// # Examples
14///
15/// ## Scalar Types
16/// ```
17/// use pencil_box::array::fill_value;
18///
19/// let vec = fill_value(&42, 4);
20/// assert_eq!(vec, vec![42, 42, 42, 42]);
21///
22/// let vec = fill_value(&true, 3);
23/// assert_eq!(vec, vec![true, true, true]);
24/// ```
25///
26/// ## Complex Types
27/// ```
28/// use pencil_box::array::fill_value;
29///
30/// let vec = fill_value(&String::from("hi"), 2);
31/// assert_eq!(vec, vec!["hi".to_string(), "hi".to_string()]);
32///
33/// let vec = fill_value(&vec![1, 2], 3);
34/// assert_eq!(vec, vec![vec![1, 2], vec![1, 2], vec![1, 2]]);
35/// ```
36///
37/// ## Enum Type
38/// ```
39/// use pencil_box::array::fill_value;
40///
41/// #[derive(Debug, PartialEq, Clone)]
42/// enum Status {
43///     Ready,
44///     Error(String),
45/// }
46///
47/// let vec = fill_value(&Status::Error("x".into()), 2);
48/// assert_eq!(
49///     vec,
50///     vec![Status::Error("x".into()), Status::Error("x".into())]
51/// );
52/// ```
53///
54/// # Behavior
55/// - Returns an empty vector if `size` is `0`.
56/// - Clones `value` `size` times into a new vector.
57/// - Useful for initializing vectors with a specific repeated value.
58///
59/// # Time Complexity
60/// - **O(n)** where `n` is the `size` of the vector.
61///
62/// # Memory
63/// - Allocates memory for `size` elements on the heap.
64///
65/// # Panics
66/// - Never panics under valid input.
67///
68/// # Features
69/// - Works with any type that implements [`Clone`], including scalars, strings, vectors, and enums.
70pub fn fill_value<T: Clone>(value: &T, size: usize) -> Vec<T> {
71    vec![value.clone(); size]
72}