42_cub3d/stream.c
2024-10-15 18:23:16 +02:00

89 lines
2.1 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* stream.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mcolonna <mcolonna@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/02 14:08:10 by mcolonna #+# #+# */
/* Updated: 2024/10/02 17:31:34 by mcolonna ### ########.fr */
/* */
/* ************************************************************************** */
#include "stream.h"
#include <stdlib.h>
void read_expected_string(const char *str, t_stream *stream, bool *err)
{
int i;
if (*err)
return ;
i = 0;
while (str[i])
{
if (str[i] != stream->str[stream->i])
{
*err = true;
return ;
}
i++;
stream->i++;
}
return ;
}
/// @brief Check if a character is a digit.
/// @param c Character to check.
/// @return true if the character is a digit, false if not.
/// false if the character is '\0'.
static bool is_digit(char c)
{
return (c >= '0' && c <= '9');
}
void read_unsigned(unsigned int *dest, t_stream *stream, bool *err)
{
int r;
if (*err)
return ;
if (!is_digit(stream->str[stream->i]))
{
*err = true;
return ;
}
r = 0;
while (is_digit(stream->str[stream->i]))
{
r = r * 10 + stream->str[stream->i] - '0';
stream->i++;
}
*dest = r;
}
void read_until(char c, char **dest, t_stream *stream, bool *err)
{
int len;
int i;
if (*err)
return ;
len = 0;
while (stream->str[stream->i + len] && stream->str[stream->i + len] != c)
len++;
*dest = malloc((len + 1) * sizeof(char));
if (!*dest)
{
*err = true;
return ;
}
i = 0;
while (stream->str[stream->i] && stream->str[stream->i] != c)
{
(*dest)[i] = stream->str[stream->i];
i++;
stream->i++;
}
(*dest)[i] = '\0';
}