memcpy() comparison: C, Rust, and D
Cody Laeder via Digitalmars-d
digitalmars-d at puremagic.com
Wed Feb 1 06:39:15 PST 2017
On Wednesday, 1 February 2017 at 08:17:45 UTC, Walter Bright
wrote:
> I'm not very familiar with Rust. Can you post what a Rust
> declaration for memcpy would look like with all the guarantees?
The memcpy you have linked [1] is just a wrapper around the LLVM
intrinsic [2] function. This is not stabilized therefore not part
of the standard library, as Rust doesn't want to force permanent
dependence on the LLVM (or emulating the LLVM on other future
backends).
The _traditional_ C-like memcpy [3] in the stdlib. It is unsafe,
and carries no side effects for the src buffer. It enforces type
safety, but it cannot enforce memory safety as you can blow past
the allocation side on your dst buffer (hence why it is unsafe).
The simplest _safe_ memcpy [4] is just doing a range check before
calling the unsafe memcpy in stdlib. This ensure type and memory
safety (returning Err on non-equal length buffers). While this
may seem limiting one can still archive non-aligned copies via
the Rust sub-slice operator Example: mempy( &src[0..4], &mut
dst[20..24]);
Which would copy the first 3 bytes of src, into the 20th to 23rd
bytes of dst.
[1] https://doc.rust-lang.org/1.14.0/libc/fn.memcpy.html
[2] http://llvm.org/docs/LangRef.html#llvm-memcpy-intrinsic
[3] https://doc.rust-lang.org/std/ptr/fn.copy_nonoverlapping.html
[4] https://gist.github.com/1f34331b2cae6ba9e624c5f9f4f2a458
More information about the Digitalmars-d
mailing list