function dist = checkcachesize(dist,cacheSize,mx,dataClass)
%CHECKCACHESIZE Sanity check for argument CacheSize. This helper function
%is used by pdist, pdist2.

%   Copyright 2022 The MathWorks, Inc.

if (statslib.internal.isString(cacheSize))
    cacheSize = convertStringsToChars(cacheSize);
end

if (~statslib.internal.isString(cacheSize) || ~strncmpi(cacheSize,'maximal',length(cacheSize))) ...
        && ( ~isscalar(cacheSize) || ~isfloat(cacheSize) ...
        || cacheSize<=0  || isnan(cacheSize) || ~isreal(cacheSize) )
    error(message('stats:lasso:BadCacheSize'));
end

bytePerElem = bytePerElement(dataClass);

% If numeric, check if it can hold at least M-by-1 vector
if isnumeric(cacheSize)
    if mx*bytePerElem > cacheSize*1e6
        warning(message('stats:pdist2:CacheIsNotEnough'));
        switch dist
            case 'fse'
                dist = 'seu';
            case 'fastseuclidean'
                dist = 'seuclidean';
            case 'fqe'
                dist = 'sqe';
            case 'fastsquaredeuclidean'
                dist = 'squaredeuclidean';
            case 'feu'
                dist = 'euc';
            case 'fasteuclidean'
                dist = 'euclidean';
        end
    end
end

end

function bytePerElem = bytePerElement(outClass)
if strcmpi(outClass, 'double')
    bytePerElem = 8;
else
    bytePerElem = 4;
end
end