Extended MaximInterface

Dependents:   mbed_DS28EC20_GPIO

Revision:
6:a8c83a2e6fa4
Parent:
0:f77ad7f72d04
--- a/Utilities/HexConversions.cpp	Fri Jan 19 10:25:02 2018 -0600
+++ b/Utilities/HexConversions.cpp	Wed Jan 23 13:11:04 2019 -0600
@@ -30,31 +30,55 @@
 * ownership rights.
 *******************************************************************************/
 
+#include <cctype>
 #include <cstdio>
+#include <cstdlib>
 #include "HexConversions.hpp"
 
+using std::string;
+using std::vector;
+
 namespace MaximInterface {
 
-static const unsigned int charsPerByte = 2;
+static const int charsPerByte = 2;
 
-std::string byteArrayToHexString(const uint_least8_t * byteArray,
-                                 size_t byteArraySize) {
-  std::string hexString;
-  char hexBuf[charsPerByte + 1];
-  for (size_t i = 0; i < byteArraySize; i++) {
+string byteArrayToHexString(span<const uint_least8_t> byteArray) {
+  string hexString;
+  hexString.reserve(byteArray.size() * charsPerByte);
+  for (span<const uint_least8_t>::index_type i = 0; i < byteArray.size(); ++i) {
+    char hexBuf[charsPerByte + 1];
     std::sprintf(hexBuf, "%2.2X", byteArray[i] & 0xFF);
     hexString.append(hexBuf, charsPerByte);
   }
   return hexString;
 }
 
-std::vector<uint_least8_t> hexStringToByteArray(const std::string & hexString) {
-  std::vector<uint_least8_t> byteArray;
-  byteArray.reserve(hexString.size() / charsPerByte + 1);
-  for (std::string::size_type i = 0; i < hexString.size(); i += charsPerByte) {
-    unsigned int byte;
-    std::sscanf(hexString.substr(i, charsPerByte).c_str(), "%2x", &byte);
-    byteArray.push_back(byte);
+optional<vector<uint_least8_t> >
+hexStringToByteArray(const string & hexString) {
+  optional<vector<uint_least8_t> > byteArray = vector<uint_least8_t>();
+  byteArray->reserve(hexString.size() / charsPerByte);
+  char hexBuf[charsPerByte + 1];
+  char * const hexBufEnd = hexBuf + charsPerByte;
+  *hexBufEnd = '\0';
+  char * hexBufIt = hexBuf;
+  for (string::const_iterator hexStringIt = hexString.begin(),
+                              hexStringEnd = hexString.end();
+       hexStringIt != hexStringEnd; ++hexStringIt) {
+    if (!std::isspace(*hexStringIt)) {
+      *hexBufIt = *hexStringIt;
+      if (++hexBufIt == hexBufEnd) {
+        char * hexBufParseEnd;
+        byteArray->push_back(static_cast<uint_least8_t>(
+            std::strtoul(hexBuf, &hexBufParseEnd, 16)));
+        if (hexBufParseEnd != hexBufEnd) {
+          break;
+        }
+        hexBufIt = hexBuf;
+      }
+    }
+  }
+  if (hexBufIt != hexBuf) {
+    byteArray.reset();
   }
   return byteArray;
 }