aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/string.c
blob: 3a52ab21ce71ee538bd0778b9351091f7dc3e76c (plain) (blame)
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
/*
 * Copyright (c) 2023 Egor Tensin <Egor.Tensin@gmail.com>
 * This file is part of the "cimple" project.
 * For details, see https://github.com/egor-tensin/cimple.
 * Distributed under the MIT License.
 */

#include "string.h"
#include "log.h"

#include <errno.h>
#include <stdlib.h>
#include <string.h>

char *stpecpy(char *dst, char *end, const char *src)
{
	if (!dst)
		return NULL;
	if (dst == end)
		return end;

	char *p = memccpy(dst, src, '\0', end - dst);
	if (p)
		return p - 1;

	end[-1] = '\0';
	return end;
}

int string_to_int(const char *src, int *result)
{
	char *endptr = NULL;

	errno = 0;
	long ret = strtol(src, &endptr, 10);

	if (errno) {
		log_errno("strtol");
		return -1;
	}

	if (endptr == src || *endptr != '\0') {
		log_err("Invalid number: %s\n", src);
		return -1;
	}

	*result = (int)ret;
	return 0;
}