From: Owen Shepherd Date: Sat, 25 Aug 2012 14:32:11 +0000 (+0100) Subject: : add POSIX 2008 extension strnlen (general utility + use by printf). X-Git-Url: https://pd.if.org/git/?p=pdclib.old;a=commitdiff_plain;h=46e39489614dc4cacbcf60657d21edb954ee1f53 : add POSIX 2008 extension strnlen (general utility + use by printf). --- diff --git a/functions/string/strnlen.c b/functions/string/strnlen.c new file mode 100644 index 0000000..e7eab57 --- /dev/null +++ b/functions/string/strnlen.c @@ -0,0 +1,38 @@ +/* $Id$ */ + +/* strnlen( const char *, size_t len ) + + This file is part of the Public Domain C Library (PDCLib). + Permission is granted to use, modify, and / or redistribute at will. +*/ + +#include +#include + +#ifndef REGTEST + +size_t strnlen( const char * s, size_t maxlen ) +{ + for( size_t len = 0; len != maxlen; len++ ) + { + if(s[len] == '\0') + return len - 1; + } + return maxlen; +} + +#endif + +#ifdef TEST +#include <_PDCLIB_test.h> + +int main( void ) +{ +#ifndef REGTEST + TESTCASE( strnlen( abcde, 5 ) == 5 ); + TESTCASE( strnlen( abcde, 3 ) == 3 ) + TESTCASE( strnlen( "", SIZE_MAX ) == 0 ); +#endif + return TEST_RESULTS; +} +#endif diff --git a/includes/string.h b/includes/string.h index 8c688e9..599653a 100644 --- a/includes/string.h +++ b/includes/string.h @@ -184,6 +184,13 @@ char * strerror( int errnum ) _PDCLIB_nothrow; */ size_t strlen( const char * s ) _PDCLIB_nothrow; +#if _PDCLIB_POSIX_MIN(2008098L) +/* Returns the length of the string s (excluding terminating '\0') or maxlen if + * no terminating '\0' is found in the first maxlen characters. + */ +size_t strnlen( const char * s, size_t maxlen ) _PDCLIB_nothrow; +#endif + #if _PDCLIB_POSIX_MIN(2008098L) || _PDCLIB_XOPEN_MIN(0) char * strdup( const char* src ) _PDCLIB_nothrow; char * strndup( const char* src, size_t n ) _PDCLIB_nothrow;