/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_va_escape.c                                     :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: gbaconni@student.42lausanne.ch             +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/04/17 22:35:03 by gbaconni          #+#    #+#             */
/*   Updated: 2022/04/29 14:34:51 by gbaconni         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "ft_printf.h"

static char		ft_unescape_char(const char c);
static size_t	ft_unescape_len(const char *str);

int	ft_va_escape(const char *format, va_list ap)
{
	int	ret;

	(void) ap;
	ret = ft_putchar(ft_unescape_char(*format));
	return (ret);
}

char	*ft_unescape(const char *str)
{
	char	*s;
	void	*ptr;

	s = (char *) ft_calloc(ft_unescape_len(str) + 1, sizeof(char));
	if (s == NULL)
		return (NULL);
	ptr = s;
	while (*str != '\0')
	{
		if (*str == '\\')
			*s++ = ft_unescape_char(*++str);
		else
			*s++ = *str;
		str++;
	}
	*s = '\0';
	s = ptr;
	return (s);
}

static char	ft_unescape_char(const char c)
{
	if (c == 'a')
		return ('\a');
	else if (c == 'b')
		return ('\b');
	else if (c == 't')
		return ('\t');
	else if (c == 'n')
		return ('\n');
	else if (c == 'v')
		return ('\v');
	else if (c == 'f')
		return ('\f');
	else if (c == 'r')
		return ('\r');
	else if (c == 'e')
		return ('\033');
	else
		return (c);
}

static size_t	ft_unescape_len(const char *str)
{
	size_t	len;

	len = 0;
	while (*str != '\0')
	{
		if (*str == '\\')
			str++;
		len++;
		str++;
	}
	return (len);
}
