Merge branch 'dev' of gitlab.cri.epita.fr:guillem.george/42sh into dev

This commit is contained in:
Jean Herail 2026-01-22 16:49:12 +01:00
commit f2e44d93f4
14 changed files with 89 additions and 46 deletions

View file

@ -1,6 +1,7 @@
#include "string_utils.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@ -42,3 +43,11 @@ char *insert_into(char *dest, const char *src, size_t pos, size_t len)
return realloc(dest, new_len + 1);
return dest;
}
void int_to_str(int value, char *buffer)
{
if (buffer == NULL)
return;
snprintf(buffer, 11, "%d", value);
}

View file

@ -18,4 +18,13 @@ char *trim_blank_left(char *str);
*/
char *insert_into(char *dest, const char *src, size_t pos, size_t len);
/**
* Converts an integer to its string representation.
* @param value The integer value to convert.
* @param buffer A character array where the resulting string will be stored.
* The buffer must be at least 11 bytes long to accommodate the largest
* 32-bit integer and the null terminator.
*/
void int_to_str(int value, char *buffer);
#endif /* STRING_UTILS_H */

View file

@ -9,23 +9,27 @@
#include <unistd.h>
#include "../hash_map/hash_map.h"
#include "../string_utils/string_utils.h"
#define VARS_INITIAL_SIZE 16
struct hash_map *vars_init(void)
{
return hash_map_init(VARS_INITIAL_SIZE);
}
void vars_default(struct hash_map *vars)
static void vars_default(struct hash_map *vars)
{
set_var_copy(vars, "?", "0");
pid_t pid = getpid();
char pid_str[20];
snprintf(pid_str, sizeof(pid_str), "%d", pid);
char pid_str[11];
int_to_str(pid, pid_str);
set_var_copy(vars, "$", pid_str);
}
struct hash_map *vars_init(void)
{
struct hash_map *vars = hash_map_init(VARS_INITIAL_SIZE);
if (vars != NULL)
vars_default(vars);
return vars;
}
short short_random(void)
{
static bool seeded = false;
@ -68,3 +72,10 @@ bool set_var_copy(struct hash_map *vars, const char *key, const char *value)
free(value_copy);
return res;
}
bool set_var_int(struct hash_map *vars, const char *key, int value)
{
char value_str[11];
int_to_str(value, value_str);
return set_var_copy(vars, key, value_str);
}

View file

@ -10,11 +10,6 @@
*/
struct hash_map *vars_init(void);
/**
* Set default variables.
*/
void vars_default(struct hash_map *vars);
/**
* Generate a random short integer (16 bits positive [0-32767]).
*/
@ -45,4 +40,10 @@ bool set_var(struct hash_map *vars, const char *key, const char *value,
*/
bool set_var_copy(struct hash_map *vars, const char *key, const char *value);
/**
* Set the value of a variable to an integer. Behavior is similar to
* set_var_copy.
*/
bool set_var_int(struct hash_map *vars, const char *key, int value);
#endif /* ! VARS_H */