/*
********************************************************
/* Public API, typed binary (base64) access
********************************************************
165515
@Override
    public byte[] getBinaryValue(Base64Variant b64variant) throws IOException {
        Object n = currentNode();
        if (n instanceof byte[]) {
            return (byte[]) n;
        } else if (n instanceof org.bson.types.ObjectId) {
            return ((org.bson.types.ObjectId) n).toByteArray();
        }
        return null;
    }

    @Override
    public Object getEmbeddedObject() throws IOException, JsonParseException {
        return currentNode();
    }

    /*
   /**********************************************************
   /* Internal methods
   /**********************************************************
    */

    protected Object currentNode() {
        if (closed || nodeCursor == null) {
            return null;
        }
        return nodeCursor.currentNode();
    }
274180
public String getPublicKeyBase64() {
		final PublicKey publicKey = getPublicKey();
		return (null == publicKey) ? null : Base64.encode(publicKey.getEncoded());
	}
776667
function urlB64ToUint8Array(base64String) {
    const padding = '='.repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');

    const rawData = self.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
}
686140
function convertBinaryToBase36(binary)
{
	var result = '';
	for (var i = 0; i < 25; i++)
	{
		var c;
		if (typeof binary == 'string')
		{
			c = binary.charCodeAt(i) % 36;
		}
		else
		{
			c = binary[i] % 36;
		}
		if (c < 10)
		{
			result += String.fromCharCode(48 + c);
		}
		else
		{
			result += String.fromCharCode(87 + c);
		}
	}
	return result;
}
777103
function access(cb, force){
						_this.login(function(login_result, login_accesskey){
							// console.log(login_result, login_accesskey);
							if( login_result === false && login_accesskey === false ){
								cb(null, false, 0, {});
								return;
							}
							_this.httpRequest(
								url,
								{
									'params': options ,
									'method': apiSettings.method
								},
								function(bin, status, responseHeaders){
									if( !status ){
										cb(false, false, 0, {});
										return;
									}
									try {
										bin = JSON.parse(bin);
									} catch (e) {
									}
									// console.log(bin);
									if( bin.return_code !== 0 ){
										if(force){
											cb(null, bin, status, responseHeaders);
											return;
										}
										setTimeout(function(){
											access(cb, true);
										}, 1000);
										return;
									}
									cb(bin.list, bin, status, responseHeaders);
									return;
								}
							);
						}, force);

					}
139670
function parseBinaryDataMessage(msg, data, bigNumberRequested) {
  var offset = extractBinaryFields(msg, binaryDataMessageFormats[msg['version']], data);

  msg.logicalTimestampMs = (msg.timestampMs1 * hiMult) + msg.timestampMs2;
  delete msg.timestampMs1;
  delete msg.timestampMs2;

  if (typeof msg.maxDelayMs1 !== 'undefined' && typeof msg.maxDelayMs2 !== 'undefined') {
    msg.maxDelayMs = (msg.maxDelayMs1 * hiMult) + msg.maxDelayMs2;
    delete msg.maxDelayMs1;
    delete msg.maxDelayMs2;
  }

  var values = [];
  msg.data = values;

  for (var dataPointCount = 0; dataPointCount < msg.count; dataPointCount++) {
    var type = data.getUint8(offset);
    offset++;

    var tsidBytes = [];
    for (var tsidByteIndex = 0; tsidByteIndex < 8; tsidByteIndex++) {
      tsidBytes.push(data.getUint8(offset));
      offset++;
    }
    var tsId = getSnowflakeIdFromUint8Array(tsidBytes);

    var val = null;
    if (type === 0) {
      // NULL_TYPE, nothing to do
    } else if (type === 1) {
      // LONG_TYPE

      // get MSB for twos complement to determine sign
      var isNegative = data.getUint32(offset) >>> 31 > 0;
      if (isNegative) {
        // twos complement manual handling, because we cannot do Int64.
        // must do >>> 0 to prevent bit flips from turning into signed integers.
        val = (new BigNumber(hiMult)
               .times(~data.getUint32(offset) >>> 0)
               .plus(~data.getUint32(offset + 4) >>> 0)
               .plus(1)
               .times(-1));
      } else {
        val = (new BigNumber(data.getUint32(offset))
               .times(hiMult)
               .plus(data.getUint32(offset + 4)));
      }

      if (!bigNumberRequested) {
        val = val.toNumber();
      }
    } else if (type === 2) {
      // DOUBLE_TYPE
      val = data.getFloat64(offset);
      if (bigNumberRequested) {
        val = new BigNumber(val);
      }
    } else if (type === 3) {
      // INT_TYPE
      val = data.getUint32(offset + 4);
      if (bigNumberRequested) {
        val = new BigNumber(val);
      }
    }

    offset += 8;
    values.push({tsId: tsId, value: val});
  }

  delete msg.count;
  return msg;
}
951358
function licenseBinaryBlob(blobType) {
	blobType = blobType || BinaryBlobType.BB_ANY_BLOB;
	var self = {
		wBlobType : new type.UInt16Le(blobType, { constant : (blobType === BinaryBlobType.BB_ANY_BLOB)?false:true }),
        wBlobLen : new type.UInt16Le(function() {
        	return self.blobData.size();
        }),
        blobData : new type.BinaryString(null, { readLength : new type.CallableValue(function() {
        	return self.wBlobLen.value;
        })})
	};
	
	return new type.Component(self);
}
37710
public static byte[] decodeBase64(String base64) {
    if (base64 == null)
      throw new NullPointerException("Parameter 'base64' cannot be null.");

    String fixedBase64 = padBase64(base64);
    return Base64.getDecoder().decode(fixedBase64);
  }
99604
function _get_binary_packet()
    {
        if (!is_resource($this->fsock) || feof($this->fsock)) {
            user_error('Connection closed prematurely');
            $this->bitmap = 0;
            return false;
        }

        $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
        $raw = fread($this->fsock, $this->decrypt_block_size);

        if (!strlen($raw)) {
            return '';
        }

        if ($this->decrypt !== false) {
            $raw = $this->decrypt->decrypt($raw);
        }
        if ($raw === false) {
            user_error('Unable to decrypt content');
            return false;
        }

        if (strlen($raw) < 5) {
            return false;
        }
        extract(unpack('Npacket_length/Cpadding_length', $this->_string_shift($raw, 5)));

        $remaining_length = $packet_length + 4 - $this->decrypt_block_size;

        // quoting <http://tools.ietf.org/html/rfc4253#section-6.1>,
        // "implementations SHOULD check that the packet length is reasonable"
        // PuTTY uses 0x9000 as the actual max packet size and so to shall we
        if ($remaining_length < -$this->decrypt_block_size || $remaining_length > 0x9000 || $remaining_length % $this->decrypt_block_size != 0) {
            user_error('Invalid size');
            return false;
        }

        $buffer = '';
        while ($remaining_length > 0) {
            $temp = fread($this->fsock, $remaining_length);
            if ($temp === false || feof($this->fsock)) {
                user_error('Error reading from socket');
                $this->bitmap = 0;
                return false;
            }
            $buffer.= $temp;
            $remaining_length-= strlen($temp);
        }
        $stop = strtok(microtime(), ' ') + strtok('');
        if (strlen($buffer)) {
            $raw.= $this->decrypt !== false ? $this->decrypt->decrypt($buffer) : $buffer;
        }

        $payload = $this->_string_shift($raw, $packet_length - $padding_length - 1);
        $padding = $this->_string_shift($raw, $padding_length); // should leave $raw empty

        if ($this->hmac_check !== false) {
            $hmac = fread($this->fsock, $this->hmac_size);
            if ($hmac === false || strlen($hmac) != $this->hmac_size) {
                user_error('Error reading socket');
                $this->bitmap = 0;
                return false;
            } elseif ($hmac != $this->hmac_check->hash(pack('NNCa*', $this->get_seq_no, $packet_length, $padding_length, $payload . $padding))) {
                user_error('Invalid HMAC');
                return false;
            }
        }

        //if ($this->decompress) {
        //    $payload = gzinflate(substr($payload, 2));
        //}

        $this->get_seq_no++;

        if (defined('NET_SSH2_LOGGING')) {
            $current = strtok(microtime(), ' ') + strtok('');
            $message_number = isset($this->message_numbers[ord($payload[0])]) ? $this->message_numbers[ord($payload[0])] : 'UNKNOWN (' . ord($payload[0]) . ')';
            $message_number = '<- ' . $message_number .
                              ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)';
            $this->_append_log($message_number, $payload);
            $this->last_packet = $current;
        }

        return $this->_filter($payload);
    }
343244
public function parseEncodedBinary()
    {
        $f = ord($this->read(1));
        if ($f <= 250) {
            return $f;
        }
        if ($f === 251) {
            return null;
        }
        if ($f === 255) {
            return false;
        }
        if ($f === 252) {
            return Binary::bytes2int($this->read(2), true);
        }
        if ($f === 253) {
            return Binary::bytes2int($this->read(3), true);
        }
        return Binary::bytes2int($this->read(8), true);
    }
736563
function getRowBytesFromTransactionBase64(base64Data) {
  let bytesDecode = base64DecodeFromString(base64Data);
  let transaction = proto.protocol.Transaction.deserializeBinary(bytesDecode);
  let raw = transaction.getRawData();
  return raw.serializeBinary();
}
798226
function(base64) {
      // Remove non-base-64 characters
      base64 = base64.replace(/[^A-Z0-9+\/]/ig, '');

      for (var bytes = [], i = 0, imod4 = 0; i < base64.length;
          imod4 = ++i % 4) {
        if (imod4 == 0) continue;
        bytes.push(((base64map.indexOf(base64.charAt(i - 1))
            & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2))
            | (base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2)));
      }
      return bytes;
    }
334494
function write_binary_type(out, opts) {
	switch(opts.type) {
		case "string":
		case "base64":
		case "binary":
			var bstr = "";
			// $FlowIgnore
			for(var i = 0; i < out.length; ++i) bstr += String.fromCharCode(out[i]);
			return opts.type == 'base64' ? Base64.encode(bstr) : opts.type == 'string' ? utf8read(bstr) : bstr;
		case "file": return write_dl(opts.file, out);
		case "buffer": return out;
		default: throw new Error("Unrecognized type " + opts.type);
	}
}
845652
function byteswap64(buf) {
  var swap = new Buffer(buf.length);
  for (var i = 0; i < buf.length; i++) {
    swap[i] = buf[buf.length -1 - i];
  }
  return swap;
}
392363
function hash(input, algo, type){
    // string or buffer input ? => keep it
    if (typeof input !== 'string' && !(input instanceof Buffer)){
        input = JSON.stringify(input);
    }

    // create hash algo
    var sum = _crypto.createHash(algo);

    // set content
    sum.update(input);

    // binary output ?
    if (type && type.toLowerCase().trim() == 'binary'){
        // calculate hashsum
        return sum.digest();

    // base 64 urlsafe ?
    }else if (type==='base64-urlsafe'){
        return base64urlsafe(sum.digest('base64'));

    // string output
    }else{
        // calculate hashsum
        return sum.digest(type);
    }
}
320823
function _decodeBlob(encodedBlob) {
    var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
    return createBlob([arrayBuff], { type: encodedBlob.type });
}
3949
function encodeArrayBuffer(packet, supportsBinary, callback) {
  if (!supportsBinary) {
    return exports.encodeBase64Packet(packet, callback);
  }

  var data = packet.data;
  var contentArray = new Uint8Array(data);
  var resultBuffer = new Uint8Array(1 + data.byteLength);

  resultBuffer[0] = packets[packet.type];
  for (var i = 0; i < contentArray.length; i++) {
    resultBuffer[i+1] = contentArray[i];
  }

  return callback(resultBuffer.buffer);
}