/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_case_p_bonus.c                                  :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: thrieg <thrieg@student.42mulhouse.fr>      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/10/23 16:22:40 by thrieg            #+#    #+#             */
/*   Updated: 2025/02/16 19:07:47 by thrieg           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "../libft.h"
#include "ft_printf.h"
#include "ft_printf_bonus.h"

int	padding_if_needed_before(
		t_arglist *arglist,
		char caller,
		size_t len,
		t_vector *vec);
int	padding_if_needed_after(
		t_arglist *arglist,
		char caller,
		size_t len,
		t_vector *vec);

//zero and precision flags have undefined behavior here
int	ft_case_p_bonus_utils(t_vector *vec, char *str_to_cat, t_arglist *arglist)
{
	size_t	index;
	size_t	size;

	index = ft_strnonchr(str_to_cat, '0');
	size = ft_strlen(str_to_cat + index);
	if (padding_if_needed_before(arglist, 'p', (size + 2), vec) < 0)
		return (0);
	if (!ft_vector_concat(vec, "0x", 2))
		return (0);
	if (!ft_vector_concat(vec, (str_to_cat + index), size))
		return (0);
	if (padding_if_needed_after(arglist, 'p', (size + 2), vec) < 0)
		return (0);
	return (1);
}

//zero and precision flags have undefined behavior here
int	ft_case_p_bonus(t_vector *vec, va_list *args, t_arglist *arglist)
{
	char	*str_to_cat;
	void	*arg;
	int		ret;

	arg = va_arg(*args, void *);
	if (!arg)
	{
		if (padding_if_needed_before(arglist, 'p', 5, vec) < 0)
			return (0);
		if (!ft_vector_concat(vec, "(nil)", 5))
			return (0);
		if (padding_if_needed_after(arglist, 'p', 5, vec) < 0)
			return (0);
		return (1);
	}
	str_to_cat = ft_addr_to_strhex(arg);
	if (!str_to_cat)
		return (0);
	ret = ft_case_p_bonus_utils(vec, str_to_cat, arglist);
	return (free(str_to_cat), ret);
}
