f735bffe5c184f41ac3b2a507a86ab2ebf9a2bba
[gnulib.git] / lib / strnlen1.c
1 /* Find the length of STRING + 1, but scan at most MAXLEN bytes.
2    Copyright (C) 2005-2006, 2009-2011 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include <config.h>
18
19 /* Specification.  */
20 #include "strnlen1.h"
21
22 #include <string.h>
23
24 /* The attribute __pure__ was added in gcc 2.96.  */
25 #undef _GL_ATTRIBUTE_PURE
26 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
27 # define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
28 #else
29 # define _GL_ATTRIBUTE_PURE /* empty */
30 #endif
31
32 /* Find the length of STRING + 1, but scan at most MAXLEN bytes.
33    If no '\0' terminator is found in that many characters, return MAXLEN.  */
34 /* This is the same as strnlen (string, maxlen - 1) + 1.  */
35 size_t _GL_ATTRIBUTE_PURE
36 strnlen1 (const char *string, size_t maxlen)
37 {
38   const char *end = (const char *) memchr (string, '\0', maxlen);
39   if (end != NULL)
40     return end - string + 1;
41   else
42     return maxlen;
43 }