some support for Integers – improved v_0
authorFrantišek Kučera <franta-hg@frantovo.cz>
Sat, 26 Jun 2021 20:26:29 +0200
branchv_0
changeset 18 cb85500c4a30
parent 17 f5281ab3e68f
child 19 b7431bc6069b
some support for Integers – improved
src/lib/ASN1ContentHandler.h
--- a/src/lib/ASN1ContentHandler.h	Sat Jun 26 20:04:52 2021 +0200
+++ b/src/lib/ASN1ContentHandler.h	Sat Jun 26 20:26:29 2021 +0200
@@ -54,6 +54,8 @@
 
 	class Integer {
 	private:
+		// TODO: use std::string (of octets, not ASCII) instead of std::vector?
+		// TODO: use this class as BigInteger across Relational pipes?
 		std::vector<uint8_t> data;
 	public:
 
@@ -85,8 +87,9 @@
 			try {
 				return std::to_string(toInt64());
 			} catch (...) {
+				// integer has more than 64 bits → only HEX form value will be available
 				// TODO: support longer values than 64 bits
-				// integer has more than 64 bits → only HEX form value will be available
+				// TODO: do not ignore zero-length error?
 				return "";
 			}
 		}
@@ -94,14 +97,15 @@
 		const int64_t toInt64() const {
 			int64_t value = 0;
 
-			if (data.size() > sizeof (value)) throw std::invalid_argument("integer is too long");
+			if (data.size() > sizeof (value)) throw std::invalid_argument("Integer is too long");
+			else if (data.size() == 0) throw std::invalid_argument("Integer has zero length");
 
-			for (size_t i = 0, limit = data.size(), negative = 0; i < limit; i++) {
-				uint8_t b = data[i];
-				if (i == 0 && b & 0x80) negative = true;
-				value = (value << 8) | b;
-				if (i == (limit - 1) && negative) value -= std::pow(256, data.size());
-			}
+			value = data[0];
+			bool negative = data[0] & 0x80;
+
+			for (size_t i = 1, limit = data.size(); i < limit; i++) value = (value << 8) | data[i];
+
+			if (negative) value -= std::pow(256, data.size());
 
 			return value;
 		}