File: safe-atoi.c

package info (click to toggle)
findutils 4.6.0%2Bgit%2B20190209-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 20,276 kB
  • sloc: ansic: 98,553; sh: 8,927; yacc: 1,840; exp: 850; makefile: 813; python: 66; sed: 16
file content (78 lines) | stat: -rw-r--r-- 2,047 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* safe-atoi.c -- checked string-to-int conversion.
   Copyright (C) 2007-2019 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/
/* config.h must be included first. */
#include <config.h>

/* system headers. */
#include <errno.h>
#include <limits.h>
#include <stdlib.h>

/* gnulib headers. */
#include "quotearg.h"

/* find headers. */
#include "system.h"
#include "die.h"
#include "safe-atoi.h"


int
safe_atoi (const char *s, enum quoting_style style)
{
  long lval;
  char *end;

  errno = 0;
  lval = strtol (s, &end, 10);
  if ( (LONG_MAX == lval) || (LONG_MIN == lval) )
    {
      /* max/min possible value, or an error. */
      if (errno == ERANGE)
	{
	  /* too big, or too small. */
	  die (EXIT_FAILURE, errno, "%s", s);
	}
      else
	{
	  /* not a valid number */
	  die (EXIT_FAILURE, errno, "%s", s);
	}
      /* Otherwise, we do a range check against INT_MAX and INT_MIN
       * below.
       */
    }

  if (lval > INT_MAX || lval < INT_MIN)
    {
      /* The number was in range for long, but not int. */
      errno = ERANGE;
      die (EXIT_FAILURE, errno, "%s", s);
    }
  else if (*end)
    {
      die (EXIT_FAILURE, errno, _("Unexpected suffix %s on %s"),
	   quotearg_n_style (0, style, end),
	   quotearg_n_style (1, style, s));
    }
  else if (end == s)
    {
      die (EXIT_FAILURE, errno, _("Expected an integer: %s"),
	   quotearg_n_style (0, style, s));
    }
  return (int)lval;
}