02-05-2026
81 lines
2.1 kB
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* print_diu_bonus.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: mleitao <mleitao@student.42.fr> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2026/03/31 17:51:31 by mleitao #+# #+# */
9/* Updated: 2026/05/02 01:02:23 by mleitao ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "printers_bonus.h"
14#include "utils.h"
15#include <stdlib.h>
16
17static int init_signed(t_data *d, t_numdata *n, long nb)
18{
19 ft_bzero(n, sizeof(t_numdata));
20 n->is_negative = (nb < 0);
21 if (n->is_negative)
22 n->sign = '-';
23 else if (d->format.plus)
24 n->sign = '+';
25 else if (d->format.space)
26 n->sign = ' ';
27 if (n->is_negative)
28 n->num = ltoa(-nb);
29 else
30 n->num = ltoa(nb);
31 if (!n->num)
32 return (-1);
33 if (!d->format.precision && !nb)
34 n->len = 0;
35 else
36 n->len = ft_strlen(n->num);
37 return (0);
38}
39
40static int init_unsigned(t_data *d, t_numdata *n, unsigned long nb)
41{
42 d->format.plus = 0;
43 d->format.space = 0;
44 ft_bzero(n, sizeof(t_numdata));
45 n->num = ultoa_base(nb, 10, 0);
46 if (!n->num)
47 return (-1);
48 if (!d->format.precision && !nb)
49 n->len = 0;
50 else
51 n->len = ft_strlen(n->num);
52 return (0);
53}
54
55int print_diu(t_data *d, long nb, int is_signed)
56{
57 t_numdata n;
58
59 if (is_signed)
60 {
61 if (init_signed(d, &n, nb))
62 return (-1);
63 }
64 else
65 {
66 if (init_unsigned(d, &n, nb))
67 return (-1);
68 }
69 calculate_padding(d, &n);
70 if (d->format.minus)
71 {
72 if (print_left(d, &n) < 0)
73 return (free(n.num), -1);
74 }
75 else
76 {
77 if (print_right(d, &n) < 0)
78 return (free(n.num), -1);
79 }
80 return (free(n.num), 0);
81}