Back to home page

LXR

 
 

    


File indexing completed on 2025-05-11 08:24:19

0001 /**
0002  * @file
0003  *
0004  * @ingroup libmisc_conv_help Conversion Helpers
0005  *
0006  * @brief Convert String to Int (with validation)
0007  */
0008 
0009 /*
0010  *  COPYRIGHT (c) 2009.
0011  *  On-Line Applications Research Corporation (OAR).
0012  *
0013  *  Copyright (c) 2011  Ralf Corsépius, Ulm, Germany.
0014  *
0015  *  The license and distribution terms for this file may be
0016  *  found in the file LICENSE in this distribution or at
0017  *  http://www.rtems.org/license/LICENSE.
0018  */
0019 
0020 #ifdef HAVE_CONFIG_H
0021 #include "config.h"
0022 #endif
0023 
0024 #include <errno.h>
0025 #include <stdlib.h>
0026 #include <limits.h>
0027 
0028 #include <rtems/stringto.h>
0029 
0030 /*
0031  *  Instantiate an error checking wrapper for strtol (int)
0032  */
0033 
0034 rtems_status_code rtems_string_to_int (
0035   const char *s,
0036   int *n,
0037   char **endptr,
0038   int base
0039 )
0040 {
0041   long result;
0042   char *end;
0043 
0044   if ( !n )
0045     return RTEMS_INVALID_ADDRESS;
0046 
0047   errno = 0;
0048   *n = 0;
0049 
0050   result = strtol( s, &end, base );
0051 
0052   if ( endptr )
0053     *endptr = end;
0054 
0055   if ( end == s )
0056     return RTEMS_NOT_DEFINED;
0057 
0058   if ( ( errno == ERANGE ) &&
0059     (( result == 0 ) || ( result == LONG_MAX ) || ( result == LONG_MIN )))
0060       return RTEMS_INVALID_NUMBER;
0061 
0062 #if (INT_MAX < LONG_MAX)
0063   if ( result > INT_MAX ) {
0064     errno = ERANGE;
0065     return RTEMS_INVALID_NUMBER;
0066   }
0067 #endif
0068 
0069 #if (INT_MIN < LONG_MIN)
0070   if ( result < INT_MIN ) {
0071     errno = ERANGE;
0072     return RTEMS_INVALID_NUMBER;
0073   }
0074 #endif
0075 
0076   *n = result;
0077 
0078   return RTEMS_SUCCESSFUL;
0079 }