memcpy() comparison: C, Rust, and D

Walter Bright via Digitalmars-d digitalmars-d at puremagic.com
Mon Jan 30 17:30:48 PST 2017


The C99 Standard says:

   #include <string.h>
   void *memcpy(void * restrict s1, const void * restrict s2, size_t n);

   Description

   The memcpy function copies n characters from the object pointed to by s2
   into the object pointed to by s1. If copying takes place between objects
   that overlap, the behavior is undefined.

   Returns

   The memcpy function returns the value of s1.


Rust says https://doc.rust-lang.org/1.14.0/libc/fn.memcpy.html:

   pub unsafe extern fn memcpy(dest: *mut c_void,
                             src: *const c_void,
                             n: size_t)
                             -> *mut c_void


D says https://github.com/dlang/druntime/blob/master/src/core/stdc/string.d#L32:

   pure void* memcpy(return void* s1, scope const void* s2, size_t n);

---

Just from D's type signature, we can know a lot about memcpy():

1. There are no side effects.
2. The return value is derived from s1.
3. Nothing s2 transitively points to is altered via s2.
4. Copies of s1 or s2 are not saved.

The C declaration does not give us any of that info, although the C description
does give us 2, and the 'restrict' says that s1 and s2 do not overlap.

The Rust declaration does not give us 1, 2 or 4 (because it is marked as 
unsafe). If it was safe, the declaration does not give us 2.

By this information being knowable from the declaration, the compiler knows it 
too and can make use of it.


More information about the Digitalmars-d mailing list