/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_memmove.c                                       :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: thrieg <thrieg@student.42mulhouse.fr>      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/10/14 16:00:16 by thrieg            #+#    #+#             */
/*   Updated: 2025/02/16 19:04:08 by thrieg           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft.h"

static void	*ft_optimised_revcpy(void *dest, const void *src, size_t n)
{
	char				*str;
	unsigned long long	*str_packed;
	char				*str_src;
	unsigned long long	*str_src_packed;

	str = (char *)dest;
	str_src = (char *)src;
	while (n % sizeof(unsigned long long))
	{
		n--;
		str[n] = str_src[n];
	}
	n /= sizeof(unsigned long long);
	str_packed = (unsigned long long *)dest;
	str_src_packed = (unsigned long long *)src;
	while (n > 0)
	{
		n--;
		str_packed[n] = str_src_packed[n];
	}
	return (dest);
}

void	*ft_memmove(void *dest, const void *src, size_t n)
{
	char		*str;
	const char	*str_src;

	if (!dest && !src)
		return (NULL);
	str = (char *)dest;
	str_src = (const char *)src;
	if (str > str_src)
	{
		if ((str + sizeof(unsigned long long)) > str_src)
			return (ft_optimised_revcpy(dest, src, n));
		while (n-- > 0)
			str[n] = str_src[n];
	}
	else
	{
		ft_memcpy(dest, src, n);
	}
	return (dest);
}
