diff options
-rw-r--r-- | include/osmocom/core/utils.h | 2 | ||||
-rw-r--r-- | src/utils.c | 22 |
2 files changed, 24 insertions, 0 deletions
diff --git a/include/osmocom/core/utils.h b/include/osmocom/core/utils.h index 01d55205..3c6fc98e 100644 --- a/include/osmocom/core/utils.h +++ b/include/osmocom/core/utils.h @@ -82,4 +82,6 @@ int osmo_constant_time_cmp(const uint8_t *exp, const uint8_t *rel, const int cou uint64_t osmo_decode_big_endian(const uint8_t *data, size_t data_len); uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len); +size_t osmo_strlcpy(char *dst, const char *src, size_t siz); + /*! @} */ diff --git a/src/utils.c b/src/utils.c index 4a548022..1bb2be8b 100644 --- a/src/utils.c +++ b/src/utils.c @@ -339,3 +339,25 @@ uint8_t *osmo_encode_big_endian(uint64_t value, size_t data_len) return buf; } /*! @} */ + +/*! \brief Copy a C-string into a sized buffer + * \param[in] src source string + * \param[out] dst destination string + * \param[in] siz size of the \a dst string + * \returns length of source string + * + * Copies up to \a siz characters from \a src to \a dst, but ensures + * that the last character of \a dst is always a NUL character. May + * truncate \a src to do achieve this. + */ +size_t osmo_strlcpy(char *dst, const char *src, size_t siz) +{ + size_t ret = strlen(src); + + if (siz) { + size_t len = (ret >= siz) ? siz - 1 : ret; + memcpy(dst, src, len); + dst[len] = '\0'; + } + return ret; +} |