aboutsummaryrefslogtreecommitdiff
path: root/common/src/args.c
blob: 333852f3917400eaa1564211cca0ad4c691c9f93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   args.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/08 23:12:55 by cacharle          #+#    #+#             */
/*   Updated: 2021/01/10 11:12:26 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "common.h"

static int		st_err(int ret, const char *format, char *str)
{
	while (*format != '\0')
	{
		if (format[0] == '%' && format[1] == 's')
		{
			if (str != NULL)
			{
				while (*str != '\0')
					write(STDERR_FILENO, str++, 1);
			}
			format += 2;
		}
		else
		{
			write(STDERR_FILENO, format, 1);
			format++;
		}
	}
	write(STDERR_FILENO, "\n", 1);
	return (ret);
}

static long int	st_atou_strict(char *s)
{
	long int	num;
	char		*origin;

	origin = s;
	if (*s < '0' || *s > '9')
		return (st_err(-1, "Error: %s: is not a number", origin));
	num = 0;
	while (*s >= '0' && *s <= '9')
	{
		num *= 10;
		if (num > UINT_MAX)
			return (st_err(-1, "Error: %s: is too big", origin));
		num += *s - '0';
		if (num > UINT_MAX)
			return (st_err(-1, "Error: %s: is too big", origin));
		s++;
	}
	if (*s != '\0')
		return (st_err(-1, "Error: %s: is not a number", origin));
	return (num);
}

bool			parse_args(t_philo_args *args, int argc, char **argv)
{
	if (argc != 5 && argc != 6)
	{
		return (st_err(false, "Usage: %s philosophers_num deatst_timeout"
			"eat_timeout sleep_timeout [meal_num]", argv[0]));
	}
	if ((args->philo_num = st_atou_strict(argv[1])) == -1
		|| (args->timeout_death = st_atou_strict(argv[2])) == -1
		|| (args->timeout_eat = st_atou_strict(argv[3])) == -1
		|| (args->timeout_sleep = st_atou_strict(argv[4])) == -1)
		return (false);
	if (argc == 6)
	{
		if ((args->meal_num = st_atou_strict(argv[5])) == -1)
			return (false);
	}
	else
		args->meal_num = -1;
	return (true);
}