Best interface for memcpy() (and the string.h family of functions)

Stefanos Baziotis sdi1600105 at di.uoa.gr
Wed May 29 17:35:03 UTC 2019


On Wednesday, 29 May 2019 at 15:41:42 UTC, Jonathan Marler wrote:
>
> The default memcpy signature is still pretty useful in many 
> cases.  The original signature should still be implemented and 
> available as a non-template function:
>
> void memcpy(void* dst, void* src, size_t length);
>
> For D, you should also create a template so developer's don't 
> have to cast to `void*` all the time, but it just forwards all 
> calls to the real memcpy function like this:
>
> void memcpy(T,U)(T* dst, U* src, size_t length)
> {
>     pragma(inline, true);
>     memcpy(cast(void*)dst, cast(void*)src, length);
> }
>
> And there's no need to have a different name like `memcpyD`. 
> The function behaves the same as libc's memcpy, and when you 
> have libc available, you should use that implementation instead 
> so you can leverages other people's work when you can.
>

I'm not sure about that. Does it really make sense to have such an
interface in the case where you don't have libc memcpy available?
Although, there is a discussion about such fallback functions. 
But I don't
know, I feel like it will encourage bad practices.

In the same way, I don't know about whether it should accept two 
different types.

> However, we also want to get type-safety and bounds-checking 
> when when can.  So we should also provide a set of templates 
> that accept D arrays, verifies type-safety and bounds checking, 
> then forwards the call to memcpy.
>

Those are good ideas. But I think all this could be done 
explicitly with
(ref T[] dst, ref T[] source). This makes a specific-to-arrays 
version,
which again I'm unsure if it is good to make specific cases.

Generally, all those things are up for discussion, I don't pretend
to have some definitive answer.

The thing with all this code depending on libc memcpy is that to 
my understanding,
the prospect is that libc will be removed. And this project is a 
step towards that
by making some better D versions (meaning, leveraging D features).
If the better version calls libc, then when libc
is finally removed, all this code will break. And because we 
encouraged
this bad practice, _a lot_ of code will break.
Which will then force people to write their D-version of 
memcpy(void *dst, const void *src, size_t len);
Which of course is bad because suddenly, we lost all the D 
benefits + we lost
all the work that has been put on libc.

Best regards,
Stefanos




More information about the Digitalmars-d mailing list