瀏覽代碼

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.
Manuel Palenzuela 4 年之前
父節點
當前提交
13315a6ef1
共有 2 個文件被更改,包括 36 次插入0 次删除
  1. 33 0
      Userland/Libraries/LibC/inttypes.cpp
  2. 3 0
      Userland/Libraries/LibC/inttypes.h

+ 33 - 0
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;
+}
 }

+ 3 - 0
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