[libc] Add wcsnlen()

Signed-off-by: Michael Brown <mcb30@ipxe.org>
This commit is contained in:
Michael Brown
2025-08-28 15:12:41 +01:00
parent 61b4585e2a
commit 5bec2604a3
3 changed files with 35 additions and 3 deletions

View File

@@ -36,12 +36,25 @@ FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
* Calculate length of wide-character string
*
* @v string String
* @ret len Length (excluding terminating NUL)
* @v max Maximum length (in wide characters)
* @ret len Length (in wide characters, excluding terminating NUL)
*/
size_t wcslen ( const wchar_t *string ) {
size_t wcsnlen ( const wchar_t *string, size_t max ) {
size_t len = 0;
while ( *(string++) )
while ( max-- && *(string++) )
len++;
return len;
}
/**
* Calculate length of wide-character string
*
* @v string String
* @ret len Length (in wide characters, excluding terminating NUL)
*/
size_t wcslen ( const wchar_t *string ) {
return wcsnlen ( string, ( ( ~( ( size_t ) 0 ) ) /
sizeof ( string[0] ) ) );
}

View File

@@ -24,6 +24,7 @@ size_t wcrtomb ( char *buf, wchar_t wc, mbstate_t *ps __unused ) {
return 1;
}
extern size_t wcsnlen ( const wchar_t *string, size_t max );
extern size_t wcslen ( const wchar_t *string );
#endif /* WCHAR_H */

View File

@@ -38,6 +38,7 @@ FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <wchar.h>
#include <ipxe/string.h>
#include <ipxe/test.h>
@@ -322,6 +323,23 @@ static void string_test_exec ( void ) {
+ 17 ) * 26 + 10 ) );
ok ( endp == &string[6] );
}
/* Test wcslen() */
ok ( wcslen ( L"" ) == 0 );
ok ( wcslen ( L"Helloo" ) == 6 );
ok ( wcslen ( L"Helloo woorld!" ) == 14 );
ok ( wcslen ( L"Helloo\0woorld!" ) == 6 );
/* Test wcsnlen() */
ok ( wcsnlen ( L"", 0 ) == 0 );
ok ( wcsnlen ( L"", 10 ) == 0 );
ok ( wcsnlen ( L"Helloo", 0 ) == 0 );
ok ( wcsnlen ( L"Helloo", 3 ) == 3 );
ok ( wcsnlen ( L"Helloo", 5 ) == 5 );
ok ( wcsnlen ( L"Helloo", 16 ) == 6 );
ok ( wcsnlen ( L"Helloo woorld!", 5 ) == 5 );
ok ( wcsnlen ( L"Helloo woorld!", 11 ) == 11 );
ok ( wcsnlen ( L"Helloo woorld!", 16 ) == 14 );
}
/** String self-test */