/*
 * 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"

OX_CLANG_NOWARN_BEGIN(-Wunsafe-buffer-usage)

namespace ox {

template<typename T1, typename T2>
constexpr T1 strncpy(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 && src[i]) {
		dest[i] = static_cast<T1Type>(src[i]);
		++i;
	}
	// set null terminator
	dest[i] = 0;
	return dest;
}

[[nodiscard]]
constexpr size_t strnlen_s(const char *str, size_t const maxLen) noexcept {
	if (!str) [[unlikely]] {
		return 0;
	}
	size_t len = 0;
	for (; len < maxLen && str[len]; len++);
	return len;
}

template<typename T>
[[nodiscard]]
constexpr auto strlen(T const&str1) noexcept {
	std::size_t len = 0;
	for (; str1[len]; len++);
	return len;
}

template<typename T1, typename T2>
[[nodiscard]]
constexpr int strcmp(const T1 &str1, const T2 &str2) noexcept {
	auto retval = 0;
	auto i = 0u;
	while (str1[i] || str2[i]) {
		if (str1[i] < str2[i]) {
			retval = -1;
			break;
		} else if (str1[i] > str2[i]) {
			retval = 1;
			break;
		}
		i++;
	}
	return retval;
}

template<typename T1, typename T2>
[[nodiscard]]
constexpr int strncmp(T1 const&str1, T2 const&str2, const std::size_t maxLen) noexcept {
	auto retval = 0;
	std::size_t i = 0;
	while (i < maxLen && (str1[i] || str2[i])) {
		if (str1[i] < str2[i]) {
			retval = -1;
			break;
		} else if (str1[i] > str2[i]) {
			retval = 1;
			break;
		}
		i++;
	}
	return retval;
}

[[nodiscard]]
constexpr const char *strchr(const char *str, int character, std::size_t maxLen = 0xFFFFFFFF) noexcept {
	for (std::size_t i = 0; i <= maxLen; i++) {
		if (str[i] == character) {
			return &str[i];
		} else if (str[i] == 0) {
			return nullptr;
		}
	}
	return nullptr;
}

[[nodiscard]]
constexpr char *strchr(char *str, int character, std::size_t maxLen = 0xFFFFFFFF) noexcept {
	for (std::size_t i = 0; i < maxLen; i++) {
		if (str[i] == character) {
			return &str[i];
		} else if (str[i] == 0) {
			return nullptr;
		}
	}
	return nullptr;
}

[[nodiscard]]
constexpr int lastIndexOf(const auto &str, int character, std::size_t maxLen = 0xFFFFFFFF) noexcept {
	int retval = -1;
	for (std::size_t i = 0; i < maxLen && str[i]; i++) {
		if (str[i] == character) {
			retval = static_cast<int>(i);
		}
	}
	return retval;
}

}

OX_CLANG_NOWARN_END
