/*
 * Copyright 2015 - 2025 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#pragma once

#include "def.hpp"
#include "types.hpp"
#include "typetraits.hpp"

#if __has_include(<cstring>)
#include<cstring>
#else
extern "C" {

void *memcpy(void *dest, const void *src, std::size_t size);

void *memmove(void *dest, const void *src, std::size_t size);

void *memset(void *ptr, int val, std::size_t size);

int memcmp(const void *ptr1, const void *ptr2, std::size_t size) noexcept;

}
#endif

OX_CLANG_NOWARN_BEGIN(-Wunsafe-buffer-usage)

namespace ox {

template<typename T1, typename T2>
constexpr T1 *listcpy(T1 *dest, T2 *src, std::size_t maxLen) noexcept {
	using T1Type = typename ox::remove_reference<decltype(dest[0])>::type;
	std::size_t i = 0;
	while (i < maxLen) {
		dest[i] = static_cast<T1Type>(src[i]);
		++i;
	}
	// set null terminator
	dest[i] = 0;
	return dest;
}

void *memmove(void *dest, const void *src, std::size_t size) noexcept;

void *memset(void *ptr, int val, std::size_t size) noexcept;

void *memcpy(void *dest, const void *src, std::size_t size) noexcept;

int memcmp(const void *ptr1, const void *ptr2, std::size_t size) noexcept;

template<typename T>
void *memsetElements(T *ptr, T val, std::size_t elements) noexcept {
	return memset(ptr, val, elements * sizeof(T));
}

}

OX_CLANG_NOWARN_END
