aboutsummaryrefslogtreecommitdiffstats
path: root/util/generic/mem_copy.h
blob: 6f38fdc1ab8a39ef3b0e9af2ee4118efde247432 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#pragma once

#include "typetraits.h"

#include <util/system/types.h>

#include <cstring>

template <class T>
using TIfPOD = std::enable_if_t<TTypeTraits<T>::IsPod, T*>;

template <class T>
using TIfNotPOD = std::enable_if_t<!TTypeTraits<T>::IsPod, T*>;

template <class T>
static inline TIfPOD<T> MemCopy(T* to, const T* from, size_t n) noexcept { 
    if (n) {
        memcpy(to, from, n * sizeof(T));
    }

    return to;
}

template <class T>
static inline TIfNotPOD<T> MemCopy(T* to, const T* from, size_t n) {
    for (size_t i = 0; i < n; ++i) {
        to[i] = from[i];
    }

    return to;
}

template <class T>
static inline TIfPOD<T> MemMove(T* to, const T* from, size_t n) noexcept { 
    if (n) {
        memmove(to, from, n * sizeof(T));
    }

    return to;
}

template <class T>
static inline TIfNotPOD<T> MemMove(T* to, const T* from, size_t n) {
    if (to <= from || to >= from + n) {
        return MemCopy(to, from, n);
    }

    //copy backwards
    while (n) {
        to[n - 1] = from[n - 1];
        --n;
    }

    return to;
}