# Memcpy()ing into a slice of cells

**URL:** <https://internals.rust-lang.org/t/memcpy-ing-into-a-slice-of-cells/14682>\
**Category:** libs\
**Created:** [May 11, 2021, 4:41pm UTC](https://internals.rust-lang.org/t/memcpy-ing-into-a-slice-of-cells/14682 "2021-05-11T16:41:32Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![mcy](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mcy/32/6512_2.png) [@mcy](https://internals.rust-lang.org/u/mcy)\
**Post date:** [May 11, 2021, 4:41pm UTC](https://internals.rust-lang.org/t/memcpy-ing-into-a-slice-of-cells/14682/1 "2021-05-11T16:41:32Z")

</div>

Simple API:

```rust
impl<T: Copy> [Cell<T>] {
  fn copy_cells_from_slice(&self, src: &[T]);
}

```

Maybe also a version that takes `src: &[Cell<T>]`? Notionally this would just call `set()` on every element, but compile down a memcpy. Thoughts?

---

<div class="post-metadata">

**Author:** ![kornel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kornel/32/2711_2.png) [@kornel](https://internals.rust-lang.org/u/kornel)\
**Post date:** [May 11, 2021, 5:00pm UTC](https://internals.rust-lang.org/t/memcpy-ing-into-a-slice-of-cells/14682/2 "2021-05-11T17:00:43Z")

</div>

`.set()` on every element in a loop already optimizes to `memcpy`:

> **[Compiler Explorer - Rust (rustc 1.52.0)](https://rust.godbolt.org/z/7Yhesq4s8)**
>
> use std::cell::Cell;
> 
> pub fn to\_slice(dst: &\[Cell\], src: &\[u8\]) {
> for (d, s) in dst.iter().zip(src) {
> d.set(\*s);
> }
> }

---

<div class="post-metadata">

**Author:** ![mcy](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mcy/32/6512_2.png) [@mcy](https://internals.rust-lang.org/u/mcy)\
**Post date:** [May 11, 2021, 5:02pm UTC](https://internals.rust-lang.org/t/memcpy-ing-into-a-slice-of-cells/14682/3 "2021-05-11T17:02:37Z")

</div>

I mean yes, LLVM is smart. But we have `copy_from_slice`, might as well advertise a well-lit path for safely-aliased mutation of byte buffers.

(This is how you wind up with people using `ptr::copy_nonoverlapping` because they think the for loop won't work. This isn't speculation, kernel programmers absolutely do this.)

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/system/32/14092_2.png) [@system](https://internals.rust-lang.org/u/system)\
**Post date:** [August 9, 2021, 5:03pm UTC](https://internals.rust-lang.org/t/memcpy-ing-into-a-slice-of-cells/14682/4 "2021-08-09T17:03:22Z")

</div>

Closed on August 9, 2021, 5:03pm UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
