From aee5e46516a6828ebda50a5d8a5e4cb57fa91b20 Mon Sep 17 00:00:00 2001 From: Alibek Omarov Date: Tue, 27 Jun 2023 04:11:13 +0300 Subject: [PATCH] public: rewrite Q_strncpy with standard C functions, make it inlined to allow compiler remove unneeded checks So far, passes all tests. --- public/crtlib.c | 29 ----------------------------- public/crtlib.h | 20 +++++++++++++++++++- 2 files changed, 19 insertions(+), 30 deletions(-) diff --git a/public/crtlib.c b/public/crtlib.c index b88d2c10..5da88167 100644 --- a/public/crtlib.c +++ b/public/crtlib.c @@ -134,35 +134,6 @@ size_t Q_strncat( char *dst, const char *src, size_t size ) return( dlen + ( s - src )); // count does not include NULL } -size_t Q_strncpy( char *dst, const char *src, size_t size ) -{ - register char *d = dst; - register const char *s = src; - register size_t n = size; - - if( !dst || !src || !size ) - return 0; - - // copy as many bytes as will fit - if( n != 0 && --n != 0 ) - { - do - { - if(( *d++ = *s++ ) == 0 ) - break; - } while( --n != 0 ); - } - - // not enough room in dst, add NULL and traverse rest of src - if( n == 0 ) - { - if( size != 0 ) - *d = '\0'; // NULL-terminate dst - while( *s++ ); - } - return ( s - src - 1 ); // count does not include NULL -} - int Q_atoi( const char *str ) { int val = 0; diff --git a/public/crtlib.h b/public/crtlib.h index b90fc182..6152aa80 100644 --- a/public/crtlib.h +++ b/public/crtlib.h @@ -65,7 +65,6 @@ size_t Q_colorstr( const char *string ); char Q_toupper( const char in ); char Q_tolower( const char in ); size_t Q_strncat( char *dst, const char *src, size_t siz ); -size_t Q_strncpy( char *dst, const char *src, size_t siz ); qboolean Q_isdigit( const char *str ); qboolean Q_isspace( const char *str ); int Q_atoi( const char *str ); @@ -123,6 +122,25 @@ static inline char *Q_strstr( const char *s1, const char *s2 ) return unlikely( !s1 || !s2 ) ? NULL : (char*)strstr( s1, s2 ); } +// Q_strncpy is the same as strlcpy +static inline size_t Q_strncpy( char *dst, const char *src, size_t siz ) +{ + size_t len; + + if( unlikely( !dst || !src || !siz )) + return 0; + + len = strlen( src ); + if( len + 1 > siz ) // check if truncate + { + memcpy( dst, src, siz - 1 ); + dst[siz - 1] = 0; + } + else memcpy( dst, src, len + 1 ); + + return len; // count does not include NULL +} + // libc extensions, be careful #if XASH_WIN32