From 41cfb47de4c91dd4ba7db981fc4079e1f369c42b Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Wed, 18 Sep 2019 09:49:40 -0700 Subject: [PATCH] ircd: Add strncpy++ tool. --- configure.ac | 2 ++ include/ircd/ircd.h | 1 + include/ircd/strn.h | 57 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 include/ircd/strn.h diff --git a/configure.ac b/configure.ac index eaa8bba0c..f881918c5 100644 --- a/configure.ac +++ b/configure.ac @@ -912,6 +912,8 @@ AC_CHECK_FUNCS([ \ strlcat \ strlcpy \ strnlen \ + strncpy \ + strcpy \ vsnprintf \ ]) diff --git a/include/ircd/ircd.h b/include/ircd/ircd.h index a2ddf4a49..902bd5655 100644 --- a/include/ircd/ircd.h +++ b/include/ircd/ircd.h @@ -37,6 +37,7 @@ #include "base.h" #include "stringops.h" #include "strl.h" +#include "strn.h" #include "cmp.h" #include "globular.h" #include "tokens.h" diff --git a/include/ircd/strn.h b/include/ircd/strn.h new file mode 100644 index 000000000..bf16ba2e9 --- /dev/null +++ b/include/ircd/strn.h @@ -0,0 +1,57 @@ +// Matrix Construct +// +// Copyright (C) Matrix Construct Developers, Authors & Contributors +// Copyright (C) 2016-2019 Jason Volk +// +// Permission to use, copy, modify, and/or distribute this software for any +// purpose with or without fee is hereby granted, provided that the above +// copyright notice and this permission notice is present in all copies. The +// full license for this software is available in the LICENSE file. + +#pragma once +#define HAVE_IRCD_STRN_H + +// Vintage +namespace ircd +{ + struct strncpy; +} + +/// This is a function. It works the same as the standard strncpy() but it has +/// some useful modernizations and may be informally referred to as strncpy++. +/// See ircd::strlcpy() documentation for reasoning details. +/// +struct ircd::strncpy +{ + mutable_buffer ret; + + public: + operator string_view() const + { + return ret; + } + + operator size_t() const + { + return size(ret); + } + + strncpy(char *const &dst, const string_view &src, const size_t &max) + :ret{[&]() -> mutable_buffer + { + const auto len(std::min(src.size(), max)); + buffer::copy(mutable_buffer(dst, len), src); + return { dst, len }; + }()} + {} + + #ifndef HAVE_STRNCPY + strncpy(char *const &dst, const char *const &src, const size_t &max) + :strncpy{dst, string_view{src, strnlen(src, max)}, max} + {} + #endif + + strncpy(const mutable_buffer &dst, const string_view &src) + :strncpy{data(dst), src, size(dst)} + {} +};