1
0
Fork 0
mirror of https://github.com/luanti-org/luanti.git synced 2025-06-27 16:36:03 +00:00

Add nodiscard attribute to helper functions where it makes sense

This commit is contained in:
sfan5 2025-03-26 21:56:09 +01:00
parent e6acc4e7ed
commit ae0f955a0e
10 changed files with 71 additions and 29 deletions

View file

@ -36,22 +36,23 @@ struct DirListNode
bool dir; bool dir;
}; };
[[nodiscard]]
std::vector<DirListNode> GetDirListing(const std::string &path); std::vector<DirListNode> GetDirListing(const std::string &path);
// Returns true if already exists // Returns true if already exists
bool CreateDir(const std::string &path); bool CreateDir(const std::string &path);
bool PathExists(const std::string &path); [[nodiscard]] bool PathExists(const std::string &path);
bool IsPathAbsolute(const std::string &path); [[nodiscard]] bool IsPathAbsolute(const std::string &path);
bool IsDir(const std::string &path); [[nodiscard]] bool IsDir(const std::string &path);
bool IsExecutable(const std::string &path); [[nodiscard]] bool IsExecutable(const std::string &path);
bool IsFile(const std::string &path); [[nodiscard]] bool IsFile(const std::string &path);
inline bool IsDirDelimiter(char c) [[nodiscard]] inline bool IsDirDelimiter(char c)
{ {
return c == '/' || c == DIR_DELIM_CHAR; return c == '/' || c == DIR_DELIM_CHAR;
} }
@ -64,20 +65,21 @@ bool DeleteSingleFileOrEmptyDirectory(const std::string &path);
/// Returns path to temp directory. /// Returns path to temp directory.
/// You probably don't want to use this directly, see `CreateTempFile` or `CreateTempDir`. /// You probably don't want to use this directly, see `CreateTempFile` or `CreateTempDir`.
/// @return path or "" on error /// @return path or "" on error
std::string TempPath(); [[nodiscard]] std::string TempPath();
/// Returns path to securely-created temporary file (will already exist when this function returns). /// Returns path to securely-created temporary file (will already exist when this function returns).
/// @return path or "" on error /// @return path or "" on error
std::string CreateTempFile(); [[nodiscard]] std::string CreateTempFile();
/// Returns path to securely-created temporary directory (will already exist when this function returns). /// Returns path to securely-created temporary directory (will already exist when this function returns).
/// @return path or "" on error /// @return path or "" on error
std::string CreateTempDir(); [[nodiscard]] std::string CreateTempDir();
/* Returns a list of subdirectories, including the path itself, but excluding /* Returns a list of subdirectories, including the path itself, but excluding
hidden directories (whose names start with . or _) hidden directories (whose names start with . or _)
*/ */
void GetRecursiveDirs(std::vector<std::string> &dirs, const std::string &dir); void GetRecursiveDirs(std::vector<std::string> &dirs, const std::string &dir);
[[nodiscard]]
std::vector<std::string> GetRecursiveDirs(const std::string &dir); std::vector<std::string> GetRecursiveDirs(const std::string &dir);
/* Multiplatform */ /* Multiplatform */
@ -128,16 +130,19 @@ std::string RemoveRelativePathComponents(std::string path);
// Returns the absolute path for the passed path, with "." and ".." path // Returns the absolute path for the passed path, with "." and ".." path
// components and symlinks removed. Returns "" on error. // components and symlinks removed. Returns "" on error.
[[nodiscard]]
std::string AbsolutePath(const std::string &path); std::string AbsolutePath(const std::string &path);
// This is a combination of RemoveRelativePathComponents() and AbsolutePath() // This is a combination of RemoveRelativePathComponents() and AbsolutePath()
// It will resolve symlinks for the leading path components that exist and // It will resolve symlinks for the leading path components that exist and
// still remove "." and ".." in the rest of the path. // still remove "." and ".." in the rest of the path.
// Returns "" on error. // Returns "" on error.
[[nodiscard]]
std::string AbsolutePathPartial(const std::string &path); std::string AbsolutePathPartial(const std::string &path);
// Returns the filename from a path or the entire path if no directory // Returns the filename from a path or the entire path if no directory
// delimiter is found. // delimiter is found.
[[nodiscard]]
const char *GetFilenameFromPath(const char *path); const char *GetFilenameFromPath(const char *path);
// Replace the content of a file on disk in a way that is safe from // Replace the content of a file on disk in a way that is safe from
@ -180,6 +185,7 @@ bool OpenStream(std::filebuf &stream, const char *filename,
* @param mode additional mode bits (e.g. std::ios::app) * @param mode additional mode bits (e.g. std::ios::app)
* @return file stream, will be !good in case of error * @return file stream, will be !good in case of error
*/ */
[[nodiscard]]
inline std::ofstream open_ofstream(const char *name, bool log, inline std::ofstream open_ofstream(const char *name, bool log,
std::ios::openmode mode = std::ios::openmode()) std::ios::openmode mode = std::ios::openmode())
{ {
@ -202,6 +208,7 @@ inline std::ofstream open_ofstream(const char *name, bool log,
* @param mode additional mode bits (e.g. std::ios::ate) * @param mode additional mode bits (e.g. std::ios::ate)
* @return file stream, will be !good in case of error * @return file stream, will be !good in case of error
*/ */
[[nodiscard]]
inline std::ifstream open_ifstream(const char *name, bool log, inline std::ifstream open_ifstream(const char *name, bool log,
std::ios::openmode mode = std::ios::openmode()) std::ios::openmode mode = std::ios::openmode())
{ {

View file

@ -77,7 +77,7 @@ namespace porting
void signal_handler_init(); void signal_handler_init();
// Returns a pointer to a bool. // Returns a pointer to a bool.
// When the bool is true, program should quit. // When the bool is true, program should quit.
bool * signal_handler_killstatus(); [[nodiscard]] bool *signal_handler_killstatus();
/* /*
Path of static data directory. Path of static data directory.
@ -105,11 +105,13 @@ extern std::string path_cache;
/* /*
Gets the path of our executable. Gets the path of our executable.
*/ */
[[nodiscard]]
bool getCurrentExecPath(char *buf, size_t len); bool getCurrentExecPath(char *buf, size_t len);
/* /*
Concatenate subpath to path_share. Concatenate subpath to path_share.
*/ */
[[nodiscard]]
std::string getDataPath(const char *subpath); std::string getDataPath(const char *subpath);
/* /*
@ -280,7 +282,8 @@ inline const char *getPlatformName()
; ;
} }
bool secure_rand_fill_buf(void *buf, size_t len); // Securely fills buffer with bytes from system's random source
[[nodiscard]] bool secure_rand_fill_buf(void *buf, size_t len);
// Call once near beginning of main function. // Call once near beginning of main function.
void osSpecificInit(); void osSpecificInit();
@ -308,10 +311,10 @@ static inline void TriggerMemoryTrim() { (void)0; }
#ifdef _WIN32 #ifdef _WIN32
// Quotes an argument for use in a CreateProcess() commandline (not cmd.exe!!) // Quotes an argument for use in a CreateProcess() commandline (not cmd.exe!!)
std::string QuoteArgv(const std::string &arg); [[nodiscard]] std::string QuoteArgv(const std::string &arg);
// Convert an error code (e.g. from GetLastError()) into a string. // Convert an error code (e.g. from GetLastError()) into a string.
std::string ConvertError(DWORD error_code); [[nodiscard]] std::string ConvertError(DWORD error_code);
#endif #endif
// snprintf wrapper // snprintf wrapper

View file

@ -31,6 +31,6 @@ René Nyffenegger rene.nyffenegger@adp-gmbh.ch
#include <string> #include <string>
#include <string_view> #include <string_view>
bool base64_is_valid(std::string_view s); [[nodiscard]] bool base64_is_valid(std::string_view s);
std::string base64_encode(std::string_view s); [[nodiscard]] std::string base64_encode(std::string_view s);
std::string base64_decode(std::string_view s); [[nodiscard]] std::string base64_decode(std::string_view s);

View file

@ -37,6 +37,6 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
* *
* Throws an exception if the url is invalid. * Throws an exception if the url is invalid.
*/ */
std::string colorize_url(const std::string &url); [[nodiscard]] std::string colorize_url(const std::string &url);
#endif #endif

View file

@ -24,4 +24,4 @@ bool string_to_enum(const EnumString *spec, T &result, std::string_view str)
return ret; return ret;
} }
const char *enum_to_string(const EnumString *spec, int num); [[nodiscard]] const char *enum_to_string(const EnumString *spec, int num);

View file

@ -9,6 +9,7 @@
static const char hex_chars[] = "0123456789abcdef"; static const char hex_chars[] = "0123456789abcdef";
[[nodiscard]]
static inline std::string hex_encode(std::string_view data) static inline std::string hex_encode(std::string_view data)
{ {
std::string ret; std::string ret;
@ -20,6 +21,7 @@ static inline std::string hex_encode(std::string_view data)
return ret; return ret;
} }
[[nodiscard]]
static inline std::string hex_encode(const char *data, size_t data_size) static inline std::string hex_encode(const char *data, size_t data_size)
{ {
if (!data_size) if (!data_size)

View file

@ -13,7 +13,7 @@ enum FloatType
FLOATTYPE_SYSTEM FLOATTYPE_SYSTEM
}; };
f32 u32Tof32Slow(u32 i); [[nodiscard]] f32 u32Tof32Slow(u32 i);
u32 f32Tou32Slow(f32 f); [[nodiscard]] u32 f32Tou32Slow(f32 f);
FloatType getFloatSerializationType(); FloatType getFloatSerializationType();

View file

@ -17,6 +17,7 @@
// Like std::clamp but allows mismatched types // Like std::clamp but allows mismatched types
template <typename T, typename T2, typename T3> template <typename T, typename T2, typename T3>
[[nodiscard]]
inline constexpr T rangelim(const T &d, const T2 &min, const T3 &max) inline constexpr T rangelim(const T &d, const T2 &min, const T3 &max)
{ {
if (d < (T)min) if (d < (T)min)
@ -88,7 +89,6 @@ inline void getContainerPosWithOffset(const v3s16 &p, s16 d, v3s16 &container, v
getContainerPosWithOffset(p.Z, d, container.Z, offset.Z); getContainerPosWithOffset(p.Z, d, container.Z, offset.Z);
} }
inline bool isInArea(v3s16 p, s16 d) inline bool isInArea(v3s16 p, s16 d)
{ {
return ( return (
@ -193,6 +193,7 @@ struct MeshGrid {
* \note This is also used in cases where degrees wrapped to the range [0, 360] * \note This is also used in cases where degrees wrapped to the range [0, 360]
* is innapropriate (e.g. pitch needs negative values) * is innapropriate (e.g. pitch needs negative values)
*/ */
[[nodiscard]]
inline float modulo360f(float f) inline float modulo360f(float f)
{ {
return fmodf(f, 360.0f); return fmodf(f, 360.0f);
@ -201,6 +202,7 @@ inline float modulo360f(float f)
/** Returns \p f wrapped to the range [0, 360] /** Returns \p f wrapped to the range [0, 360]
*/ */
[[nodiscard]]
inline float wrapDegrees_0_360(float f) inline float wrapDegrees_0_360(float f)
{ {
float value = modulo360f(f); float value = modulo360f(f);
@ -210,6 +212,7 @@ inline float wrapDegrees_0_360(float f)
/** Returns \p v3f wrapped to the range [0, 360] /** Returns \p v3f wrapped to the range [0, 360]
*/ */
[[nodiscard]]
inline v3f wrapDegrees_0_360_v3f(v3f v) inline v3f wrapDegrees_0_360_v3f(v3f v)
{ {
v3f value_v3f; v3f value_v3f;
@ -227,6 +230,7 @@ inline v3f wrapDegrees_0_360_v3f(v3f v)
/** Returns \p f wrapped to the range [-180, 180] /** Returns \p f wrapped to the range [-180, 180]
*/ */
[[nodiscard]]
inline float wrapDegrees_180(float f) inline float wrapDegrees_180(float f)
{ {
float value = modulo360f(f + 180); float value = modulo360f(f + 180);
@ -289,6 +293,7 @@ inline u32 calc_parity(u32 v)
* @param seed initial seed value * @param seed initial seed value
* @return hash value * @return hash value
*/ */
[[nodiscard]]
u64 murmur_hash_64_ua(const void *key, size_t len, unsigned int seed); u64 murmur_hash_64_ua(const void *key, size_t len, unsigned int seed);
/** /**
@ -299,7 +304,7 @@ u64 murmur_hash_64_ua(const void *key, size_t len, unsigned int seed);
* @param distance_ptr return location for distance from the camera * @param distance_ptr return location for distance from the camera
*/ */
bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir,
f32 camera_fov, f32 range, f32 *distance_ptr=NULL); f32 camera_fov, f32 range, f32 *distance_ptr=nullptr);
s16 adjustDist(s16 dist, float zoom_fov); s16 adjustDist(s16 dist, float zoom_fov);
@ -307,12 +312,14 @@ s16 adjustDist(s16 dist, float zoom_fov);
Returns nearest 32-bit integer for given floating point number. Returns nearest 32-bit integer for given floating point number.
<cmath> and <math.h> in VC++ don't provide round(). <cmath> and <math.h> in VC++ don't provide round().
*/ */
[[nodiscard]]
inline s32 myround(f32 f) inline s32 myround(f32 f)
{ {
return (s32)(f < 0.f ? (f - 0.5f) : (f + 0.5f)); return (s32)(f < 0.f ? (f - 0.5f) : (f + 0.5f));
} }
template <typename T> template <typename T>
[[nodiscard]]
inline constexpr T sqr(T f) inline constexpr T sqr(T f)
{ {
return f * f; return f * f;
@ -321,6 +328,7 @@ inline constexpr T sqr(T f)
/* /*
Returns integer position of node in given floating point position Returns integer position of node in given floating point position
*/ */
[[nodiscard]]
inline v3s16 floatToInt(v3f p, f32 d) inline v3s16 floatToInt(v3f p, f32 d)
{ {
return v3s16( return v3s16(
@ -332,6 +340,7 @@ inline v3s16 floatToInt(v3f p, f32 d)
/* /*
Returns integer position of node in given double precision position Returns integer position of node in given double precision position
*/ */
[[nodiscard]]
inline v3s16 doubleToInt(v3d p, double d) inline v3s16 doubleToInt(v3d p, double d)
{ {
return v3s16( return v3s16(
@ -343,12 +352,14 @@ inline v3s16 doubleToInt(v3d p, double d)
/* /*
Returns floating point position of node in given integer position Returns floating point position of node in given integer position
*/ */
[[nodiscard]]
inline v3f intToFloat(v3s16 p, f32 d) inline v3f intToFloat(v3s16 p, f32 d)
{ {
return v3f::from(p) * d; return v3f::from(p) * d;
} }
// Random helper. Usually d=BS // Returns box of a node as in-world box. Usually d=BS
[[nodiscard]]
inline aabb3f getNodeBox(v3s16 p, float d) inline aabb3f getNodeBox(v3s16 p, float d)
{ {
return aabb3f( return aabb3f(
@ -368,6 +379,7 @@ public:
@param wanted_interval interval wanted @param wanted_interval interval wanted
@return true if action should be done @return true if action should be done
*/ */
[[nodiscard]]
bool step(float dtime, float wanted_interval) bool step(float dtime, float wanted_interval)
{ {
m_accumulator += dtime; m_accumulator += dtime;
@ -489,12 +501,14 @@ inline video::SColor multiplyColorValue(const video::SColor &color, float mod)
core::clamp<u32>(color.getBlue() * mod, 0, 255)); core::clamp<u32>(color.getBlue() * mod, 0, 255));
} }
template <typename T> constexpr inline T numericAbsolute(T v) template <typename T>
constexpr inline T numericAbsolute(T v)
{ {
return v < 0 ? T(-v) : v; return v < 0 ? T(-v) : v;
} }
template <typename T> constexpr inline T numericSign(T v) template <typename T>
constexpr inline T numericSign(T v)
{ {
return T(v < 0 ? -1 : (v == 0 ? 0 : 1)); return T(v < 0 ? -1 : (v == 0 ? 0 : 1));
} }

View file

@ -435,12 +435,12 @@ MAKE_STREAM_WRITE_FXN(video::SColor, ARGB8, 4);
//// More serialization stuff //// More serialization stuff
//// ////
inline float clampToF1000(float v) [[nodiscard]] inline float clampToF1000(float v)
{ {
return core::clamp(v, F1000_MIN, F1000_MAX); return core::clamp(v, F1000_MIN, F1000_MAX);
} }
inline v3f clampToF1000(v3f v) [[nodiscard]] inline v3f clampToF1000(v3f v)
{ {
return {clampToF1000(v.X), clampToF1000(v.Y), clampToF1000(v.Z)}; return {clampToF1000(v.X), clampToF1000(v.Y), clampToF1000(v.Z)};
} }

View file

@ -72,8 +72,8 @@ struct FlagDesc {
// Try to avoid converting between wide and UTF-8 unless you need to // Try to avoid converting between wide and UTF-8 unless you need to
// input/output stuff via Irrlicht // input/output stuff via Irrlicht
std::wstring utf8_to_wide(std::string_view input); [[nodiscard]] std::wstring utf8_to_wide(std::string_view input);
std::string wide_to_utf8(std::wstring_view input); [[nodiscard]] std::string wide_to_utf8(std::wstring_view input);
void wide_add_codepoint(std::wstring &result, char32_t codepoint); void wide_add_codepoint(std::wstring &result, char32_t codepoint);
@ -287,6 +287,7 @@ MAKE_VARIANT(str_ends_with, std::basic_string_view<T>, const T*)
* @return An std::vector<std::basic_string<T> > of the component parts * @return An std::vector<std::basic_string<T> > of the component parts
*/ */
template <typename T> template <typename T>
[[nodiscard]]
inline std::vector<std::basic_string<T> > str_split( inline std::vector<std::basic_string<T> > str_split(
const std::basic_string<T> &str, const std::basic_string<T> &str,
T delimiter) T delimiter)
@ -306,6 +307,7 @@ inline std::vector<std::basic_string<T> > str_split(
* @param str * @param str
* @return A copy of \p str converted to all lowercase characters. * @return A copy of \p str converted to all lowercase characters.
*/ */
[[nodiscard]]
inline std::string lowercase(std::string_view str) inline std::string lowercase(std::string_view str)
{ {
std::string s2; std::string s2;
@ -331,6 +333,7 @@ inline bool my_isspace(const wchar_t c)
* @return A view of \p str with leading and trailing whitespace removed. * @return A view of \p str with leading and trailing whitespace removed.
*/ */
template<typename T> template<typename T>
[[nodiscard]]
inline std::basic_string_view<T> trim(std::basic_string_view<T> str) inline std::basic_string_view<T> trim(std::basic_string_view<T> str)
{ {
size_t front = 0; size_t front = 0;
@ -354,6 +357,7 @@ inline std::basic_string_view<T> trim(std::basic_string_view<T> str)
* @return A copy of \p str with leading and trailing whitespace removed. * @return A copy of \p str with leading and trailing whitespace removed.
*/ */
template<typename T> template<typename T>
[[nodiscard]]
inline std::basic_string<T> trim(std::basic_string<T> &&str) inline std::basic_string<T> trim(std::basic_string<T> &&str)
{ {
std::basic_string<T> ret(trim(std::basic_string_view<T>(str))); std::basic_string<T> ret(trim(std::basic_string_view<T>(str)));
@ -361,6 +365,7 @@ inline std::basic_string<T> trim(std::basic_string<T> &&str)
} }
template<typename T> template<typename T>
[[nodiscard]]
inline std::basic_string_view<T> trim(const std::basic_string<T> &str) inline std::basic_string_view<T> trim(const std::basic_string<T> &str)
{ {
return trim(std::basic_string_view<T>(str)); return trim(std::basic_string_view<T>(str));
@ -368,6 +373,7 @@ inline std::basic_string_view<T> trim(const std::basic_string<T> &str)
// The above declaration causes ambiguity with char pointers so we have to fix that: // The above declaration causes ambiguity with char pointers so we have to fix that:
template<typename T> template<typename T>
[[nodiscard]]
inline std::basic_string_view<T> trim(const T *str) inline std::basic_string_view<T> trim(const T *str)
{ {
return trim(std::basic_string_view<T>(str)); return trim(std::basic_string_view<T>(str));
@ -556,6 +562,7 @@ std::string wrap_rows(std::string_view from, unsigned row_len, bool has_color_co
* Removes backslashes from an escaped string (FormSpec strings) * Removes backslashes from an escaped string (FormSpec strings)
*/ */
template <typename T> template <typename T>
[[nodiscard]]
inline std::basic_string<T> unescape_string(const std::basic_string<T> &s) inline std::basic_string<T> unescape_string(const std::basic_string<T> &s)
{ {
std::basic_string<T> res; std::basic_string<T> res;
@ -580,6 +587,7 @@ inline std::basic_string<T> unescape_string(const std::basic_string<T> &s)
* @return \p s, with escape sequences removed. * @return \p s, with escape sequences removed.
*/ */
template <typename T> template <typename T>
[[nodiscard]]
std::basic_string<T> unescape_enriched(const std::basic_string<T> &s) std::basic_string<T> unescape_enriched(const std::basic_string<T> &s)
{ {
std::basic_string<T> output; std::basic_string<T> output;
@ -610,6 +618,7 @@ std::basic_string<T> unescape_enriched(const std::basic_string<T> &s)
} }
template <typename T> template <typename T>
[[nodiscard]]
std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim) std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim)
{ {
std::vector<std::basic_string<T> > tokens; std::vector<std::basic_string<T> > tokens;
@ -641,10 +650,13 @@ std::vector<std::basic_string<T> > split(const std::basic_string<T> &s, T delim)
return tokens; return tokens;
} }
[[nodiscard]]
std::wstring translate_string(std::wstring_view s, Translations *translations); std::wstring translate_string(std::wstring_view s, Translations *translations);
[[nodiscard]]
std::wstring translate_string(std::wstring_view s); std::wstring translate_string(std::wstring_view s);
[[nodiscard]]
inline std::wstring unescape_translate(std::wstring_view s) inline std::wstring unescape_translate(std::wstring_view s)
{ {
return unescape_enriched(translate_string(s)); return unescape_enriched(translate_string(s));
@ -730,6 +742,7 @@ inline const std::string duration_to_string(int sec)
* *
* @return A std::string * @return A std::string
*/ */
[[nodiscard]]
inline std::string str_join(const std::vector<std::string> &list, inline std::string str_join(const std::vector<std::string> &list,
std::string_view delimiter) std::string_view delimiter)
{ {
@ -748,6 +761,7 @@ inline std::string str_join(const std::vector<std::string> &list,
/** /**
* Create a UTF8 std::string from an irr::core::stringw. * Create a UTF8 std::string from an irr::core::stringw.
*/ */
[[nodiscard]]
inline std::string stringw_to_utf8(const irr::core::stringw &input) inline std::string stringw_to_utf8(const irr::core::stringw &input)
{ {
std::wstring_view sv(input.c_str(), input.size()); std::wstring_view sv(input.c_str(), input.size());
@ -757,6 +771,7 @@ inline std::string stringw_to_utf8(const irr::core::stringw &input)
/** /**
* Create an irr::core:stringw from a UTF8 std::string. * Create an irr::core:stringw from a UTF8 std::string.
*/ */
[[nodiscard]]
inline irr::core::stringw utf8_to_stringw(std::string_view input) inline irr::core::stringw utf8_to_stringw(std::string_view input)
{ {
std::wstring str = utf8_to_wide(input); std::wstring str = utf8_to_wide(input);
@ -770,6 +785,7 @@ inline irr::core::stringw utf8_to_stringw(std::string_view input)
* and add a prefix to them * and add a prefix to them
* 2. Remove 'unsafe' characters from the name by replacing them with '_' * 2. Remove 'unsafe' characters from the name by replacing them with '_'
*/ */
[[nodiscard]]
std::string sanitizeDirName(std::string_view str, std::string_view optional_prefix); std::string sanitizeDirName(std::string_view str, std::string_view optional_prefix);
/** /**