summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibC
diff options
context:
space:
mode:
authorManuel Palenzuela <manuelpalenzuelamerino@gmail.com>2021-04-04 01:43:55 +0200
committerAndreas Kling <kling@serenityos.org>2021-04-04 16:14:23 +0200
commit13315a6ef1a3a33667e0271106d06b1f753d80f4 (patch)
tree5eca0b5523af519001da042f38660754f2544b26 /Userland/Libraries/LibC
parent4fa59baafeef50d08d3fcac25d3f7785616648cb (diff)
downloadserenity-13315a6ef1a3a33667e0271106d06b1f753d80f4.zip
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.
Diffstat (limited to 'Userland/Libraries/LibC')
-rw-r--r--Userland/Libraries/LibC/inttypes.cpp33
-rw-r--r--Userland/Libraries/LibC/inttypes.h3
2 files changed, 36 insertions, 0 deletions
diff --git a/Userland/Libraries/LibC/inttypes.cpp b/Userland/Libraries/LibC/inttypes.cpp
index 87bbb7d024..eeb5ff11ec 100644
--- a/Userland/Libraries/LibC/inttypes.cpp
+++ b/Userland/Libraries/LibC/inttypes.cpp
@@ -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;
+}
}
diff --git a/Userland/Libraries/LibC/inttypes.h b/Userland/Libraries/LibC/inttypes.h
index fc301d5407..3ceae444d0 100644
--- a/Userland/Libraries/LibC/inttypes.h
+++ b/Userland/Libraries/LibC/inttypes.h
@@ -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