text: /*
   * Base64 encoding/decoding (RFC1341)
   * Copyright (c) 2005-2011, Jouni Malinen <j@w1.fi>
   *
   * This software may be distributed under the terms of the BSD license.
   */
  
  // 2016-12-12 - Gaspard Petit : Slightly modified to return a std::string
  // instead of a buffer allocated with malloc.
  
  #include "simulator/ui/base64_encoder.h"
  
  #include <string>
  
  static const unsigned char base64_table[65] =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  
  /**
   * base64_encode - Base64 encode
   * @src: Data to be encoded
   * @len: Length of the data to be encoded
   * Returns: string containing encoded data
   */
  std::string base64::encode(const unsigned char *src, size_t len) {
      unsigned char *out, *pos;
      const unsigned char *end, *in;
  
      size_t olen;
  
      olen = 4 * ((len + 2) / 3); /* 3-byte blocks to 4-byte */
  
      if(olen < len)
          return std::string(); /* integer overflow */
  
      std::string outStr;
      outStr.resize(olen);
      out = (unsigned char *)&outStr[0];
  
      end = src + len;
      in = src;
      pos = out;
      while(end - in >= 3) {
          *pos++ = base64_table[in[0] >> 2];
          *pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
          *pos++ = base64_table[((in[1] & 0x0f) << 2) | (in[2] >> 6)];
          *pos++ = base64_table[in[2] & 0x3f];
          in += 3;
      }
  
      if(end - in) {
          *pos++ = base64_table[in[0] >> 2];
          if(end - in == 1) {
              *pos++ = base64_table[(in[0] & 0x03) << 4];
              *pos++ = '=';
          } else {
              *pos++ = base64_table[((in[0] & 0x03) << 4) | (in[1] >> 4)];
              *pos++ = base64_table[(in[1] & 0x0f) << 2];
          }
          *pos++ = '=';
      }
  
      return outStr;
  }
  