From d7159a9af04d88fa2c741557ec436f08d62ef541 Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Fri, 1 May 2015 18:47:22 +0100 Subject: Add str_to_int_ifp that returns an Optional instead of throwing --- src/string.cc | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'src/string.cc') diff --git a/src/string.cc b/src/string.cc index bc02b4a3..2735f087 100644 --- a/src/string.cc +++ b/src/string.cc @@ -98,7 +98,7 @@ String indent(StringView str, StringView indent) return res; } -int str_to_int(StringView str) +Optional str_to_int_ifp(StringView str) { unsigned int res = 0; bool negative = false; @@ -110,11 +110,18 @@ int str_to_int(StringView str) else if (c >= '0' and c <= '9') res = res * 10 + c - '0'; else - throw runtime_error(str + "is not a number"); + return {}; } return negative ? -(int)res : (int)res; } +int str_to_int(StringView str) +{ + if (auto val = str_to_int_ifp(str)) + return *val; + throw str + " is not a number"; +} + InplaceString<16> to_string(int val) { InplaceString<16> res; -- cgit v1.2.3