LPVOID AplCopyMemory()

in src/native/windows/src/mclib.c [177:240]


LPVOID AplCopyMemory(PVOID Destination, const VOID* Source, SIZE_T Length)
{
    char *dst = Destination;
    const char *src = Source;
    SIZE_T t;

    if (Length == 0 || dst == src)      /* nothing to do */
        goto done;

    /*
     * Macros: loop-t-times; and loop-t-times, t>0
     */
#define TLOOP(s) if (t) TLOOP1(s)
#define TLOOP1(s) do { s; } while (--t)

    if ((SIZE_T)dst < (SIZE_T)src) {
        /*
         * Copy forward.
         */
        t = (int)(SIZE_T)src;   /* only need low bits */
        if ((t | (int)(SIZE_T)dst) & wmask) {
            /*
             * Try to align operands.  This cannot be done
             * unless the low bits match.
             */
            if ((t ^ (int)(SIZE_T)dst) & wmask || Length < wsize)
                t = Length;
            else
                t = wsize - (t & wmask);
            Length -= t;
            TLOOP1(*dst++ = *src++);
        }
        /*
         * Copy whole words, then mop up any trailing bytes.
         */
        t = Length / wsize;
        TLOOP(*(word *)dst = *(word *)src; src += wsize; dst += wsize);
        t = Length & wmask;
        TLOOP(*dst++ = *src++);
    } else {
        /*
         * Copy backwards.  Otherwise essentially the same.
         * Alignment works as before, except that it takes
         * (t&wmask) bytes to align, not wsize-(t&wmask).
         */
        src += Length;
        dst += Length;
        t = (int)(SIZE_T)src;
        if ((t | (int)(SIZE_T)dst) & wmask) {
            if ((t ^ (int)(SIZE_T)dst) & wmask || Length <= wsize)
                t = Length;
            else
                t &= wmask;
            Length -= t;
            TLOOP1(*--dst = *--src);
        }
        t = Length / wsize;
        TLOOP(src -= wsize; dst -= wsize; *(word *)dst = *(word *)src);
        t = Length & wmask;
        TLOOP(*--dst = *--src);
    }
done:
    return (Destination);
}