From: Daniel Karbach Date: Fri, 11 Nov 2016 10:04:10 +0000 (+0100) Subject: fix number as bool in TokenStreamReader X-Git-Url: https://git.localhorst.tv/?a=commitdiff_plain;h=5bc84befaa51b81f8f4cfc7d447c553bb471953a;p=blank.git fix number as bool in TokenStreamReader --- diff --git a/src/io/TokenStreamReader.hpp b/src/io/TokenStreamReader.hpp index c702703..7b5a8ff 100644 --- a/src/io/TokenStreamReader.hpp +++ b/src/io/TokenStreamReader.hpp @@ -39,15 +39,23 @@ public: void ReadQuat(glm::quat &); + // the Get* functions advance to the next token + // the As* functions try to cast the current token + // if the value could not be converted, a std::runtime_error is thrown + bool GetBool(); + bool AsBool() const; float GetFloat(); + float AsFloat() const; int GetInt(); + int AsInt() const; unsigned long GetULong(); + unsigned long AsULong() const; private: void SkipComments(); - void Assert(Token::Type); + void Assert(Token::Type) const; Token::Type GetType() const noexcept; const std::string &GetValue() const noexcept; diff --git a/src/io/token.cpp b/src/io/token.cpp index 588c125..a2ad44c 100644 --- a/src/io/token.cpp +++ b/src/io/token.cpp @@ -286,7 +286,7 @@ const Token &TokenStreamReader::Peek() { } -void TokenStreamReader::Assert(Token::Type t) { +void TokenStreamReader::Assert(Token::Type t) const { if (GetType() != t) { stringstream s; s << "unexpected token in input stream: expected " << t << ", but got " << in.Current(); @@ -412,9 +412,13 @@ void TokenStreamReader::ReadQuat(glm::quat &q) { bool TokenStreamReader::GetBool() { Next(); + return AsBool(); +} + +bool TokenStreamReader::AsBool() const { switch (GetType()) { case Token::NUMBER: - return GetInt() != 0; + return AsInt() != 0; case Token::IDENTIFIER: case Token::STRING: if (GetValue() == "true" || GetValue() == "yes" || GetValue() == "on") { @@ -435,18 +439,30 @@ bool TokenStreamReader::GetBool() { float TokenStreamReader::GetFloat() { Next(); + return AsFloat(); +} + +float TokenStreamReader::AsFloat() const { Assert(Token::NUMBER); return stof(GetValue()); } int TokenStreamReader::GetInt() { Next(); + return AsInt(); +} + +int TokenStreamReader::AsInt() const { Assert(Token::NUMBER); return stoi(GetValue()); } unsigned long TokenStreamReader::GetULong() { Next(); + return AsULong(); +} + +unsigned long TokenStreamReader::AsULong() const { Assert(Token::NUMBER); return stoul(GetValue()); }