1
0
mirror of https://github.com/RIOT-OS/RIOT.git synced 2024-12-29 04:50:03 +01:00

sys/string_utils: add strscpy()

This commit is contained in:
Benjamin Valentin 2022-09-21 16:26:32 +02:00
parent 6db9960741
commit cdaf715a84
5 changed files with 76 additions and 1 deletions

View File

@ -37,6 +37,7 @@ rsource "fs/Kconfig"
rsource "hashes/Kconfig"
rsource "iolist/Kconfig"
rsource "isrpipe/Kconfig"
rsource "libc/Kconfig"
menu "Libc"

View File

@ -22,11 +22,13 @@
* @author Marian Buschsieweke <marian.buschsieweke@ovgu.de>
*/
#include <errno.h>
#include <stdint.h>
/* if explicit_bzero() is provided by standard C lib, it may be defined in
* either `string.h` or `strings.h`, so just include both here */
#include <stdint.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include "kernel_defines.h"
@ -70,6 +72,26 @@ static inline void explicit_bzero(void *dest, size_t n_bytes)
}
#endif
/**
* @brief Copy the string, or as much of it as fits, into the dest buffer.
*
* Preferred to `strncpy` since it always returns a valid string, and doesn't
* unnecessarily force the tail of the destination buffer to be zeroed.
* If the zeroing is desired, it's likely cleaner to use `strscpy` with an
* overflow test, then just memset the tail of the dest buffer.
*
* @param[out] dest Where to copy the string to
* @param[in] src Where to copy the string from
* @param[in] count Size of destination buffer
*
* @pre The destination buffer is at least one byte large, as
* otherwise the terminating zero byte won't fit
*
* @return the number of characters copied (not including the trailing zero)
* @retval -E2BIG the destination buffer wasn't big enough
*/
ssize_t strscpy(char *dest, const char *src, size_t count);
#ifdef __cplusplus
}
#endif

11
sys/libc/Kconfig Normal file
View File

@ -0,0 +1,11 @@
# Copyright (c) 2021 HAW Hamburg
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.
#
config MODULE_LIBC
bool "C Library helper functions"
default y
depends on TEST_KCONFIG

1
sys/libc/Makefile Normal file
View File

@ -0,0 +1 @@
include $(RIOTBASE)/Makefile.base

40
sys/libc/string.c Normal file
View File

@ -0,0 +1,40 @@
/*
* Copyright (C) 2022 ML!PA Consulting GmbH
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @{
*
* @file
*
* @author Benjamin Valentin <benjamin.valentin@ml-pa.com>
*/
#include <errno.h>
#include "string_utils.h"
ssize_t strscpy(char *dest, const char *src, size_t count)
{
const char *start = dest;
if (!count) {
return -E2BIG;
}
while (--count && *src) {
*dest++ = *src++;
}
*dest = 0;
if (*src == 0) {
return dest - start;
} else {
return -E2BIG;
}
}
/** @} */