function url = urlencode( url )
%URLENCODE Replace special characters with escape characters URLs need
%
% Example:
%   encodedUrl = parallel.internal.urlencode( url )
%
%   decodedUrl = parallel.internal.urldecode( encodedUrl );
%
% See also parallel.internal.urldecode

% Copyright 2010-2020 The MathWorks, Inc.

% This encodes more characters than Java URLEncoder. This is fine, as the
% encoded string is typically treated as opaque until urldecode /
% URLDecoder, both which will interpret this fine.
url = char(unicode2native(char(url), 'UTF-8'));
isAlphaNum = (url >= 'a' & url <= 'z') | (url >= 'A' & url <= 'Z') | (url >= '0' & url <= '9');
% Any character that isn't in the allowed set must be percent encoded. We
% now insert %XX for each such character where XX is equivalent to
% dec2hex(c). Characters are guaranteed < 256 because of UTF-8 encoding.
valsToEncode = unique(url(~isAlphaNum));
if ~isempty(valsToEncode)
    % This format string is effectively %XX where XX is a hexidecimal number.
    valsEncoded = sprintf('%%%02X', valsToEncode);
    % The above sprintf generates a single character vector. We need to
    % split that into N character vectors each of length numel('%xx').
    valsEncoded = mat2cell(valsEncoded, 1, 3*ones(1, numel(valsToEncode)));
    valsToEncode = num2cell(valsToEncode);
    url = replace(url, valsToEncode, valsEncoded);
end
