Skip to content

Commit 39c8820

Browse files
Rollup merge of rust-lang#87944 - oconnor663:as_array_of_cells, r=scottmcm
add Cell::as_array_of_cells, similar to Cell::as_slice_of_cells I'd like to propose adding `Cell::as_array_of_cells`, as a natural analog to `Cell::as_slice_of_cells`. I don't have a specific use case in mind, other than that supporting slices but not arrays feels like a gap. Do other folks agree with that intuition? Would this addition be substantial enough to need an RFC? --- Previously, converting `&mut [T; N]` to `&[Cell<T>; N]` looks like this: ```rust 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: ```rust let array = &mut [1, 2, 3]; let cells = Cell::from_mut(array).as_array_of_cells(); ```
2 parents dd5d80a + e8ef76d commit 39c8820

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

core/src/cell.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,26 @@ impl<T> Cell<[T]> {
576576
}
577577
}
578578

579+
impl<T, const N: usize> Cell<[T; N]> {
580+
/// Returns a `&[Cell<T>; N]` from a `&Cell<[T; N]>`
581+
///
582+
/// # Examples
583+
///
584+
/// ```
585+
/// #![feature(as_array_of_cells)]
586+
/// use std::cell::Cell;
587+
///
588+
/// let mut array: [i32; 3] = [1, 2, 3];
589+
/// let cell_array: &Cell<[i32; 3]> = Cell::from_mut(&mut array);
590+
/// let array_cell: &[Cell<i32>; 3] = cell_array.as_array_of_cells();
591+
/// ```
592+
#[unstable(feature = "as_array_of_cells", issue = "88248")]
593+
pub fn as_array_of_cells(&self) -> &[Cell<T>; N] {
594+
// SAFETY: `Cell<T>` has the same memory layout as `T`.
595+
unsafe { &*(self as *const Cell<[T; N]> as *const [Cell<T>; N]) }
596+
}
597+
}
598+
579599
/// A mutable memory location with dynamically checked borrow rules
580600
///
581601
/// See the [module-level documentation](self) for more.

0 commit comments

Comments
 (0)