mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-30 03:20:28 +00:00
LibC: Added strtoimax() and strtoumax()
They are the same as strtol() and strtoul() but if there is overflow/underflow then the maximum integer val/lower integer val/maximum uint val will be returned while also setting errno to ERANGE.
This commit is contained in:
parent
4fa59baafe
commit
13315a6ef1
Notes:
sideshowbarker
2024-07-18 20:49:37 +09:00
Author: https://github.com/Baitinq Commit: https://github.com/SerenityOS/serenity/commit/13315a6ef1a Pull-request: https://github.com/SerenityOS/serenity/pull/6098
2 changed files with 36 additions and 0 deletions
|
@ -24,7 +24,10 @@
|
|||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <AK/NumericLimits.h>
|
||||
#include <errno.h>
|
||||
#include <inttypes.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
extern "C" {
|
||||
|
||||
|
@ -41,4 +44,34 @@ imaxdiv_t imaxdiv(intmax_t numerator, intmax_t denominator)
|
|||
|
||||
return result;
|
||||
}
|
||||
|
||||
intmax_t strtoimax(const char* str, char** endptr, int base)
|
||||
{
|
||||
long long_value = strtoll(str, endptr, base);
|
||||
|
||||
intmax_t max_int_value = NumericLimits<intmax_t>::max();
|
||||
intmax_t min_int_value = NumericLimits<intmax_t>::min();
|
||||
if (long_value > max_int_value) {
|
||||
errno = -ERANGE;
|
||||
return max_int_value;
|
||||
} else if (long_value < min_int_value) {
|
||||
errno = -ERANGE;
|
||||
return min_int_value;
|
||||
}
|
||||
|
||||
return long_value;
|
||||
}
|
||||
|
||||
uintmax_t strtoumax(const char* str, char** endptr, int base)
|
||||
{
|
||||
unsigned long ulong_value = strtoull(str, endptr, base);
|
||||
|
||||
uintmax_t max_uint_value = NumericLimits<uintmax_t>::max();
|
||||
if (ulong_value > max_uint_value) {
|
||||
errno = -ERANGE;
|
||||
return max_uint_value;
|
||||
}
|
||||
|
||||
return ulong_value;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -78,4 +78,7 @@ typedef struct imaxdiv_t {
|
|||
} imaxdiv_t;
|
||||
imaxdiv_t imaxdiv(intmax_t, intmax_t);
|
||||
|
||||
intmax_t strtoimax(const char*, char** endptr, int base);
|
||||
uintmax_t strtoumax(const char*, char** endptr, int base);
|
||||
|
||||
__END_DECLS
|
||||
|
|
Loading…
Reference in a new issue