[Skiboot] [PATCH 06/15] libc/string: Add strnlen

Stewart Smith stewart at linux.vnet.ibm.com
Thu Sep 1 19:42:07 AEST 2016


Claudio Carvalho <cclaudio at linux.vnet.ibm.com> writes:
> diff --git a/libc/string/strnlen.c b/libc/string/strnlen.c
> new file mode 100644
> index 0000000..904c12e
> --- /dev/null
> +++ b/libc/string/strnlen.c
> @@ -0,0 +1,28 @@
> +/******************************************************************************
> + * Copyright (c) 2004, 2016 IBM Corporation
> + * All rights reserved.
> + * This program and the accompanying materials
> + * are made available under the terms of the BSD License
> + * which accompanies this distribution, and is available at
> + * http://www.opensource.org/licenses/bsd-license.php
> + *
> + * Contributors:
> + *     IBM Corporation - initial implementation
> + *****************************************************************************/
> +
> +#include <string.h>
> +
> +size_t strnlen(const char *s, size_t n)
> +{
> +	size_t len = 0;

Looks good, but I just noticed that our strlen() has int rather than
size_t here, so I've posted a fix for that.

> +
> +	if (n < 1)
> +		return 0;

You don't need this check if you swap the while condition around to be
while( n-- > 0 && *s != '\0')

> +
> +	while (*s != 0 && n-- > 0) {

Using '\0' is slightly better as it implies null character rather than a
zero.

> +		len++;
> +		s++;
> +	}
> +
> +	return len;
> +}

-- 
Stewart Smith
OPAL Architect, IBM.



More information about the Skiboot mailing list