/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   memorybook.c                                       :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: pblagoje <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/05/04 13:56:30 by pblagoje          #+#    #+#             */
/*   Updated: 2022/05/04 19:47:54 by hulamy           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "cube3d.h"

void	mb_set_params_exit(void (*f)(void *), void *param);
void	mb_exec_exit_func(void);
t_list	**mb_get_lst(void);
int		mb_comp_addr(void *to_find, void *to_compare);

void	mb_init(void (*f)(void *), void *param)
{
	mb_set_params_exit(f, param);
}

void	*mb_alloc(size_t size)
{
	void	*tmp;
	t_list	**lst;

	lst = mb_get_lst();
	tmp = ft_memalloc(size);
	if (!tmp)
		mb_exit(B_RED"mb: failed create new allocation"RESET"\n", EXIT_FAILURE);
	if (!ft_lstpush_back(lst, ft_lstcreate(tmp)))
		mb_exit(B_RED"mb: failed add new elmnt to list"RESET"\n", EXIT_FAILURE);
	return (tmp);
}

void	mb_add(void *addr)
{
	t_list	**lst;

	lst = mb_get_lst();
	if (!ft_lstpush_back(lst, ft_lstcreate(addr)))
		mb_exit(B_RED"mb: failed add new elmnt to list"RESET"\n", EXIT_FAILURE);
}

void	mb_free(void *addr)
{
	t_list	**lst;
	t_list	*tmp;

	lst = mb_get_lst();
	tmp = ft_lstfind((*lst), addr, mb_comp_addr);
	if (!tmp)
		ft_putstr_fd(B_RED"mb: try to free not allocated address"RESET"\n", 2);
	ft_lsterase(tmp, free);
}

void	mb_exit(char *str, int status)
{
	t_list	**lst;

	lst = mb_get_lst();
	mb_exec_exit_func();
	ft_putstr_fd(str, 2);
	ft_lstfree((*lst), free);
	exit(status);
}
