]> git.lizzy.rs Git - rust.git/commitdiff
add Cell::as_array_of_cells, similar to Cell::as_slice_of_cells
authorJack O'Connor <oconnor663@gmail.com>
Wed, 11 Aug 2021 18:38:20 +0000 (14:38 -0400)
committerJack O'Connor <oconnor663@gmail.com>
Mon, 23 Aug 2021 05:00:34 +0000 (01:00 -0400)
Previously, converting `&mut [T; N]` to `&[Cell<T>; N]` looks like this:

    let array = &mut [1, 2, 3];
    let cells: &[Cell<i32>; 3] = Cell::from_mut(&mut array[..])
        .as_slice_of_cells()
        .try_into()
        .unwrap();

With this new helper method, it looks like this:

    let array = &mut [1, 2, 3];
    let cells: &[Cell<i32>; 3] = Cell::from_mut(array).as_array_of_cells();

library/core/src/cell.rs
src/test/ui/rfcs/rfc-1789-as-cell/from-mut.rs

index f0c934edf3977b0856671d8d10e5106a2927771a..85b43f48847608a4708b2464ce71ba5d4c3d66ac 100644 (file)
@@ -576,6 +576,26 @@ pub fn as_slice_of_cells(&self) -> &[Cell<T>] {
     }
 }
 
+impl<T, const N: usize> Cell<[T; N]> {
+    /// Returns a `&[Cell<T>; N]` from a `&Cell<[T; N]>`
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(as_array_of_cells)]
+    /// use std::cell::Cell;
+    ///
+    /// let mut array: [i32; 3] = [1, 2, 3];
+    /// let cell_array: &Cell<[i32; 3]> = Cell::from_mut(&mut array);
+    /// let array_cell: &[Cell<i32>; 3] = cell_array.as_array_of_cells();
+    /// ```
+    #[unstable(feature = "as_array_of_cells", issue = "88248")]
+    pub fn as_array_of_cells(&self) -> &[Cell<T>; N] {
+        // SAFETY: `Cell<T>` has the same memory layout as `T`.
+        unsafe { &*(self as *const Cell<[T; N]> as *const [Cell<T>; N]) }
+    }
+}
+
 /// A mutable memory location with dynamically checked borrow rules
 ///
 /// See the [module-level documentation](self) for more.
index ea3ad7aed492666b10b7e68985b215089e6fb926..329fadb150fcd9586e5f39e60e5f34e881ced254 100644 (file)
@@ -1,5 +1,7 @@
 // run-pass
 
+#![feature(as_array_of_cells)]
+
 use std::cell::Cell;
 
 fn main() {
@@ -8,4 +10,11 @@ fn main() {
     let slice_cell: &[Cell<i32>] = cell_slice.as_slice_of_cells();
 
     assert_eq!(slice_cell.len(), 3);
+
+    let mut array: [i32; 3] = [1, 2, 3];
+    let cell_array: &Cell<[i32; 3]> = Cell::from_mut(&mut array);
+    let array_cell: &[Cell<i32>; 3] = cell_array.as_array_of_cells();
+
+    array_cell[0].set(99);
+    assert_eq!(array, [99, 2, 3]);
 }