forked from mia/Aegisub
Add a strtoi function. (with unit tests)
Originally committed to SVN as r5340.
This commit is contained in:
parent
6615d3981f
commit
3522c0b4bd
3 changed files with 48 additions and 1 deletions
|
@ -19,9 +19,15 @@
|
|||
/// @ingroup libaegisub
|
||||
|
||||
#ifndef LAGI_PRE
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include <errno.h>
|
||||
|
||||
#include <climits>
|
||||
#include <locale>
|
||||
#endif
|
||||
|
||||
#include <locale>
|
||||
|
||||
#include "libaegisub/util.h"
|
||||
|
||||
|
@ -35,5 +41,17 @@ void str_lower(std::string &str) {
|
|||
}
|
||||
}
|
||||
|
||||
int strtoi(std::string &str) {
|
||||
long l = strtol(str.c_str(), NULL, 10);
|
||||
|
||||
if (errno == ERANGE)
|
||||
throw("Cannot convert to long (invalid range)");
|
||||
|
||||
if ((l < INT_MIN) || (l > INT_MAX))
|
||||
throw("Cannot convert to int (invalid range)");
|
||||
|
||||
return (int)l;
|
||||
}
|
||||
|
||||
} // namespace util
|
||||
} // namespace agi
|
||||
|
|
|
@ -38,6 +38,7 @@ namespace agi {
|
|||
void Rename(const std::string& from, const std::string& to);
|
||||
void time_log(agi_timeval &tv);
|
||||
void str_lower(std::string &str);
|
||||
int strtoi(std::string &str);
|
||||
|
||||
struct delete_ptr {
|
||||
template<class T>
|
||||
|
|
|
@ -71,5 +71,33 @@ TEST_F(lagi_util, Utilstr_lower) {
|
|||
EXPECT_STREQ(str.c_str(), "-!abcdefghijklmnopqrstuvwxyz123");
|
||||
}
|
||||
|
||||
TEST_F(lagi_util, UtilstrtoiInvalidRange) {
|
||||
std::string str("2147483650");
|
||||
EXPECT_ANY_THROW(util::strtoi(str));
|
||||
|
||||
str.assign("-2147483650");
|
||||
EXPECT_ANY_THROW(util::strtoi(str));
|
||||
}
|
||||
|
||||
TEST_F(lagi_util, UtilstrtoiInvalidString) {
|
||||
std::string str("bottles of beer on the wall");
|
||||
EXPECT_EQ(util::strtoi(str), 0);
|
||||
}
|
||||
|
||||
TEST_F(lagi_util, UtilstrtoiNumberWithString) {
|
||||
std::string str("24 bottles of beer on the wall");
|
||||
EXPECT_EQ(util::strtoi(str), 24);
|
||||
}
|
||||
|
||||
TEST_F(lagi_util, UtilstrtoiValidString) {
|
||||
std::string str("24");
|
||||
int i;
|
||||
|
||||
EXPECT_NO_THROW(i = util::strtoi(str));
|
||||
EXPECT_EQ(i, 24);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
} // namespace agi
|
||||
|
|
Loading…
Reference in a new issue