summaryrefslogtreecommitdiffstats
path: root/src/StringUtils.h
diff options
context:
space:
mode:
authorHownaer <franzi.moos@googlemail.com>2014-08-28 18:58:58 +0200
committerHownaer <franzi.moos@googlemail.com>2014-08-28 18:58:58 +0200
commitc2260addf4ede896695ad1212592912b2f3e1ed4 (patch)
treeb4e4943d4b3df7febf9d53a1ec5d54b61298ca0b /src/StringUtils.h
parentFixed anvil placing. (diff)
parentMerge pull request #1323 from mc-server/CraftingFixes (diff)
downloadcuberite-c2260addf4ede896695ad1212592912b2f3e1ed4.tar
cuberite-c2260addf4ede896695ad1212592912b2f3e1ed4.tar.gz
cuberite-c2260addf4ede896695ad1212592912b2f3e1ed4.tar.bz2
cuberite-c2260addf4ede896695ad1212592912b2f3e1ed4.tar.lz
cuberite-c2260addf4ede896695ad1212592912b2f3e1ed4.tar.xz
cuberite-c2260addf4ede896695ad1212592912b2f3e1ed4.tar.zst
cuberite-c2260addf4ede896695ad1212592912b2f3e1ed4.zip
Diffstat (limited to '')
-rw-r--r--src/StringUtils.h63
1 files changed, 63 insertions, 0 deletions
diff --git a/src/StringUtils.h b/src/StringUtils.h
index 3d4379352..4a4c267c7 100644
--- a/src/StringUtils.h
+++ b/src/StringUtils.h
@@ -9,6 +9,7 @@
#pragma once
#include <string>
+#include <limits>
@@ -98,6 +99,68 @@ extern int GetBEInt(const char * a_Mem);
/// Writes four bytes to the specified memory location so that they interpret as BigEndian int
extern void SetBEInt(char * a_Mem, Int32 a_Value);
+/// Parses any integer type. Checks bounds and returns errors out of band.
+template <class T>
+bool StringToInteger(const AString& a_str, T& a_Num)
+{
+ size_t i = 0;
+ bool positive = true;
+ T result = 0;
+ if (a_str[0] == '+')
+ {
+ i++;
+ }
+ else if (a_str[0] == '-')
+ {
+ i++;
+ positive = false;
+ }
+ if (positive)
+ {
+ for (size_t size = a_str.size(); i < size; i++)
+ {
+ if ((a_str[i] <= '0') || (a_str[i] >= '9'))
+ {
+ return false;
+ }
+ if (std::numeric_limits<T>::max() / 10 < result)
+ {
+ return false;
+ }
+ result *= 10;
+ T digit = a_str[i] - '0';
+ if (std::numeric_limits<T>::max() - digit < result)
+ {
+ return false;
+ }
+ result += digit;
+ }
+ }
+ else
+ {
+ for (size_t size = a_str.size(); i < size; i++)
+ {
+ if ((a_str[i] <= '0') || (a_str[i] >= '9'))
+ {
+ return false;
+ }
+ if (std::numeric_limits<T>::min() / 10 > result)
+ {
+ return false;
+ }
+ result *= 10;
+ T digit = a_str[i] - '0';
+ if (std::numeric_limits<T>::min() + digit > result)
+ {
+ return false;
+ }
+ result -= digit;
+ }
+ }
+ a_Num = result;
+ return true;
+}
+
// If you have any other string helper functions, declare them here