Search code examples
c++cmemset

Are there memset function implementations that fill the buffer in reverse order?


I know that there are implementations of memcpy, which copied memory in reverse order to optimize for some processors. At one time, a bug "Strange sound on mp3 flash website" was connected with that. Well, it was an interesting story, but my question is about another function.

I am wondering, there is a memset function in the world, which fills the buffer, starting from the end. It is clear that in theory nothing prevents doing such an implementation of a function. But I am interested exactly in the fact that this function was done in practice by someone somewhere. I would be especially grateful on the link on the library with such a function.

P.S. I understand that in terms of applications programming it has completely no difference whether the buffer is filled in the ascending or descending order. However, it is important for me to find out whether there was any "reverse" function implementation. I need it for writing an article.


Solution

  • The Linux kernel's memset for the SuperH architecture has this property:

    https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/sh/lib/memset.S?id=v4.14

    Presumably it's done this way because the mov instruction exists in predecrement form (mov.l Rm,@-Rn) but not postincrement form. See:

    http://shared-ptr.com/sh_insns.html

    If you want something that's not technically kernel internals on a freestanding implementation, but an actual hosted C implementation that application code could get linked to, musl libc also has an example:

    https://git.musl-libc.org/cgit/musl/tree/src/string/memset.c?id=v1.1.18

    Here, the C version of memset (used on many but not all target archs) does not actually fill the whole buffer backwards, but rather starts from both the beginning and end in a manner that reduces the number of conditional branches and makes them all predictable for very small memsets. See the commit message where it was added for details:

    https://git.musl-libc.org/cgit/musl/commit/src/string/memset.c?id=a543369e3b06a51eacd392c738fc10c5267a195f

    Some of the arch-specific asm versions of memset also have this property:

    https://git.musl-libc.org/cgit/musl/tree/src/string/x86_64/memset.s?id=v1.1.18