Skip to content
converter.cc 9.1 KiB
Newer Older
YannGarcia's avatar
YannGarcia committed
#include "converter.hh"
YannGarcia's avatar
YannGarcia committed

YannGarcia's avatar
YannGarcia committed
#include <stdexcept>
YannGarcia's avatar
YannGarcia committed

YannGarcia's avatar
YannGarcia committed
converter *converter::instance = NULL;

uint16_t converter::swap(const uint16_t p_value) {
  uint8_t *ptr = (uint8_t *)&p_value;
  return (ptr[0] << 8) | ptr[1];
}

uint32_t converter::swap(const uint32_t p_value) {
  uint8_t *ptr = (uint8_t *)&p_value;
  return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
}

const std::string converter::lut_u = "0123456789ABCDEF";
const std::string converter::lut_l = "0123456789abcdef";
YannGarcia's avatar
YannGarcia committed
std::string       converter::string_to_hexa(const std::string& p_value, const bool p_uppercase) {
YannGarcia's avatar
YannGarcia committed

  std::string input(p_value);
  std::for_each(input.begin(), input.end(), [](char &c) { c = std::toupper(c); });

  std::string output;
  uint32_t    length = p_value.length();
  output.reserve(2 * length);
  if (p_uppercase) { // TODO Use pointer to reduce code size
    for (uint32_t i = 0; i < length; ++i) {
      const uint8_t c = input[i];
      output.push_back(lut_u[c >> 4]);
      output.push_back(lut_u[c & 15]);
    } // End of 'for' statement
  } else {
    for (uint32_t i = 0; i < length; ++i) {
      const uint8_t c = input[i];
      output.push_back(lut_l[c >> 4]);
      output.push_back(lut_l[c & 15]);
    } // End of 'for' statement
  }

  return output;
}

std::string converter::bytes_to_hexa(const std::vector<uint8_t> &p_value, const bool p_uppercase) {
YannGarcia's avatar
YannGarcia committed
  std::string out;
  out.assign(p_value.size() * 2, ' ');
YannGarcia's avatar
YannGarcia committed
  if (p_uppercase) { // TODO Use pointer to reduce code size
    for (size_t i = 0; i < p_value.size(); i++) {
      uint8_t c      = p_value[i];
YannGarcia's avatar
YannGarcia committed
      out[i * 2]     = lut_u[c >> 4];
      out[i * 2 + 1] = lut_u[c & 0xF];
YannGarcia's avatar
YannGarcia committed
    }
  } else {
    for (size_t i = 0; i < p_value.size(); i++) {
      uint8_t c      = p_value[i];
YannGarcia's avatar
YannGarcia committed
      out[i * 2]     = lut_l[c >> 4];
      out[i * 2 + 1] = lut_l[c & 0xF];
YannGarcia's avatar
YannGarcia committed
  return out;
YannGarcia's avatar
YannGarcia committed
}

inline uint8_t char2byte(const char p_ch) {
  size_t s = converter::lut_l.find(p_ch);
  if (s == std::string::npos) {
    if ((s = converter::lut_u.find(p_ch)) == std::string::npos) {
      throw(std::length_error(""));
    }
  }
  return s;
}

YannGarcia's avatar
YannGarcia committed
std::vector<uint8_t> converter::hexa_to_bytes(const std::string& p_value) {
YannGarcia's avatar
YannGarcia committed
  // Sanity check
  std::vector<uint8_t> output;
  size_t               i = 0, idx = 0, outlen = (p_value.length() + 1) / 2;

  output.assign(outlen, 0x00);
  try {
    if (p_value.length() & 1)
      output[idx++] = char2byte(p_value[i++]);
    for (; idx < outlen; idx++) {
      uint8_t b0  = char2byte(p_value[i++]);
      uint8_t b1  = char2byte(p_value[i++]);
      output[idx] = (b0 << 4) | b1;
    }
  } catch (const std::length_error &le) {
    output.clear();
  }
  return output;
}

std::string converter::time_to_string(const time_t p_time) {
  struct tm *t = std::localtime(&p_time);
  return time_to_string(*t);
}

std::string converter::time_to_string(const struct tm &p_time) {
  char buffer[64] = {0};
  // Format: RFC 822, 1036, 1123, 2822
  std::strftime(buffer, 64, "%a, %d %b %Y %H:%M:%S %z", &p_time);
  return std::string(buffer);
}

YannGarcia's avatar
YannGarcia committed
std::string converter::trim(const std::string& str, const std::string& whitespace) {
YannGarcia's avatar
YannGarcia committed
  size_t strBegin = str.find_first_not_of(whitespace);
  if (strBegin == std::string::npos)
    return ""; // no content

  size_t strEnd   = str.find_last_not_of(whitespace);
  size_t strRange = strEnd - strBegin + 1;

  return str.substr(strBegin, strRange);
}

YannGarcia's avatar
YannGarcia committed
std::vector<std::string> converter::split(const std::string& p_value, const std::string& p_separator) {
YannGarcia's avatar
YannGarcia committed
  std::vector<std::string> output;
  std::size_t              current, previous = 0;
  current = p_value.find(p_separator);
  while (current != std::string::npos) {
    output.push_back(p_value.substr(previous, current - previous));
    previous = current + 1;
    current  = p_value.find(p_separator, previous);
  }
  output.push_back(p_value.substr(previous, current - previous));

  return output;
}

YannGarcia's avatar
YannGarcia committed
std::vector<std::string> converter::split_arguments_line(const std::string& p_value) {
YannGarcia's avatar
YannGarcia committed
  std::vector<std::string> output;
  std::string              line = trim(p_value);
  if (!line.empty() && (line[0] == '-')) { // Valid command line
    size_t current = 0;
    size_t next    = (size_t)-1;
    size_t pos     = 0;
    do {
      if (line[pos + 1] == '-') { // --
        current = pos + 2;
      } else {
        current = pos + 1;
      }
      next = line.find("-", current);
      std::string str(line.substr(pos, next - pos));
      output.push_back(str);
      pos = next;
    } while (next != std::string::npos);
  } // else, invalid command line
  return output;
}

YannGarcia's avatar
YannGarcia committed
const std::string converter::base64_enc_map[2] = {
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  };

/**
 * @brief Return the position of chr within base64_encode()
 * @param[in] chr 
 * @return Return the position of chr within base64_encode()
 */
static unsigned char pos_of_char(const unsigned char chr) {
  if ((chr >= 'A' && chr <= 'Z')) {
    return static_cast<unsigned char>(chr - 'A');
  } else if ((chr >= 'a' && chr <= 'z')) {
    return static_cast<unsigned char>(chr - 'a' + ('Z' - 'A') + 1);
  } else if ((chr >= '0' && chr <= '9')) {
    return static_cast<unsigned char>(chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2);
  } else if ((chr == '+' || chr == '-')) {
    return 62; // Be liberal with input and accept both url ('-') and non-url ('+') base 64 characters (
  } else if ((chr == '/' || chr == '_')) {
    return 63; // Idem for '/' and '_'
  } else {
    throw std::runtime_error("Input is not valid base64-encoded data.");
  }
}

static std::string insert_linebreaks(std::string str, size_t distance) {
    if (!str.length()) {
        return "";
    }
    size_t pos = distance;
    while (pos < str.size()) {
        str.insert(pos, "\n");
        pos += distance + 1;
    }
    return str;
}

std::string converter::replace(const std::string& p_value, const std::string& p_from, const std::string& p_to) {
  size_t start_pos = 0;
  std::string str(p_value);
  while((start_pos = str.find(p_from, start_pos)) != std::string::npos) {
      str.replace(start_pos, p_from.length(), p_to);
      start_pos += p_to.length(); // Handles case where 'p_to' is a substring of 'p_from'
  }
  return str; 
}

YannGarcia's avatar
YannGarcia committed
std::vector<unsigned char> converter::buffer_to_base64(const std::vector<unsigned char> &p_value, const bool p_is_url) {
  const std::string& base64_enc_map_ = converter::base64_enc_map[(p_is_url) ? 1 : 0];
  const unsigned char trailing_char = (p_is_url) ? '.' : '=';
YannGarcia's avatar
YannGarcia committed

  std::vector<unsigned char> out;
YannGarcia's avatar
YannGarcia committed
  //out.resize((p_value.size() + 2) / 3 * 4);
YannGarcia's avatar
YannGarcia committed
  unsigned int pos = 0;
  while (pos < p_value.size()) {
      out.push_back(base64_enc_map_[(p_value[pos + 0] & 0xfc) >> 2]);

      if (pos+1 < p_value.size()) {
          out.push_back(base64_enc_map_[((p_value[pos + 0] & 0x03) << 4) + ((p_value[pos + 1] & 0xf0) >> 4)]);

          if (pos+2 < p_value.size()) {
            out.push_back(base64_enc_map_[((p_value[pos + 1] & 0x0f) << 2) + ((p_value[pos + 2] & 0xc0) >> 6)]);
            out.push_back(base64_enc_map_[  p_value[pos + 2] & 0x3f]);
          } else {
            out.push_back(base64_enc_map_[(p_value[pos + 1] & 0x0f) << 2]);
            out.push_back(trailing_char);
          }
      } else {
          out.push_back(base64_enc_map_[(p_value[pos + 0] & 0x03) << 4]);
          out.push_back(trailing_char);
          out.push_back(trailing_char);
      }
      pos += 3;
YannGarcia's avatar
YannGarcia committed
    } // End of 'while' statement

  return out;
}

YannGarcia's avatar
YannGarcia committed
std::vector<unsigned char> converter::base64_to_buffer(const std::vector<unsigned char> &p_value, const bool p_remove_crlf) {
YannGarcia's avatar
YannGarcia committed
  if (p_value.size() == 0) {
    return std::vector<unsigned char>();
YannGarcia's avatar
YannGarcia committed
  std::vector<unsigned char> value(p_value);
  if (p_remove_crlf) {
    value.erase(std::remove(value.begin(), value.end(), '\r'), value.end());
    value.erase(std::remove(value.begin(), value.end(), '\n'), value.end());
  }

  std::vector<unsigned char> out;
  //out.resize(value.size() / 4 * 3);

  size_t pos = 0;
  while (pos < value.size()) {
    size_t pos_of_char_1 = pos_of_char(value[pos + 1]);
    out.push_back(((pos_of_char(value[pos])) << 2 ) + ( (pos_of_char_1 & 0x30 ) >> 4));

    if ((pos + 2 < value.size()) &&  // Check for data that is not padded with equal signs (which is allowed by RFC 2045)
        value[pos + 2] != '=' &&
        value[pos + 2] != '.' // accept URL-safe base 64 strings, too, so check for '.' also.
        ) {
      //Emit a chunk's second byte (which might not be produced in the last chunk).
      unsigned int pos_of_char_2 = pos_of_char(value[pos + 2]);
      out.push_back(((pos_of_char_1 & 0x0f) << 4) + ((pos_of_char_2 & 0x3c) >> 2));

      if ((pos + 3 < value.size()) && value[pos + 3] != '='  && value[pos + 3] != '.' ) {
        // Emit a chunk's third byte (which might not be produced in the last chunk).
        out.push_back(((pos_of_char_2 & 0x03 ) << 6) + pos_of_char(value[pos + 3]));
      }
YannGarcia's avatar
YannGarcia committed

    pos += 4;
  } // End of 'while' statement

YannGarcia's avatar
YannGarcia committed
  return out;
}